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
985
A
Chess Placing
You are given a chessboard of size $1 × n$. It is guaranteed that \textbf{$n$ is even}. The chessboard is painted like this: "BWBW$...$BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to $\frac{n t}{2}$. In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied. Your task is to place all the pieces in the cells of the same color \textbf{using the minimum number of moves} (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Firstly let's sort our array $p$ (pay the attention that there are $\frac{n t}{2}$ elements in this array, not $n$). Then for 0-indexed array $p$ answer will be equal to $m i n{\Bigl(}\sum_{i=0}^{n/2-1}|p_{i}-(i\cdot2+1)|,\sum_{i=0}^{n/2-1}|p_{i}-(i\cdot2+2)|{\Bigr)}$, where $|a - b|$ is an absolute value of difference between $a$ and $b$.
[ "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> pos(n / 2); for (int i = 0; i < n / 2; ++i) cin >> pos[i]; sort(pos.begin(), pos.end()); int ans1 = 0, ans2 = 0; for (int i = 0; i < n / 2; ++i) { ans1 += abs(pos[i] - (i * 2 + 1)); ans2 += abs(pos[i] - (i * 2 + 2)); } cout << min(ans1, ans2) << endl; return 0; }
985
B
Switches and Lamps
You are given $n$ switches and $m$ lamps. The $i$-th switch turns on some subset of the lamps. This information is given as the matrix $a$ consisting of $n$ rows and $m$ columns where $a_{i, j} = 1$ if the $i$-th switch turns on the $j$-th lamp and $a_{i, j} = 0$ if the $i$-th switch is not connected to the $j$-th lamp. Initially all $m$ lamps are turned off. Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards. It is guaranteed that if you push all $n$ switches then \textbf{all $m$ lamps will be turned on}. Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other $n - 1$ switches then all the $m$ lamps will be turned on.
Let's maintain an array $cnt$ of size $m$, where $cnt_{i}$ will be equal to the number of switches that are connected to the $i$-th lamp. Then answer will be "YES" if and only if there exists some switch such that for each lamp $i$ that is connected to this switch $cnt_{i} > 1$. Otherwise the answer will be "NO".
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<string> s(n); vector<int> cnt(m); for (int i = 0; i < n; ++i) { cin >> s[i]; for (int j = 0; j < m; ++j) if (s[i][j] == '1') ++cnt[j]; } for (int i = 0; i < n; ++i) { bool ok = true; for (int j = 0; j < m; ++j) { if (s[i][j] == '1' && cnt[j] == 1) ok = false; } if (ok) { puts("YES"); return 0; } } puts("NO"); return 0; }
985
C
Liebig's Barrels
You have $m = n·k$ wooden staves. The $i$-th stave has length $a_{i}$. You have to assemble $n$ barrels consisting of $k$ staves each, you can use any $k$ staves to construct a barrel. Each stave must belong to exactly one barrel. Let volume $v_{j}$ of barrel $j$ be equal to the length of the \textbf{minimal} stave in it. You want to assemble exactly $n$ barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed $l$, i.e. $|v_{x} - v_{y}| ≤ l$ for any $1 ≤ x ≤ n$ and $1 ≤ y ≤ n$. Print maximal total sum of volumes of equal enough barrels or $0$ if it's impossible to satisfy the condition above.
At first, sort all $a_{i}$ in non-decreasing order. Let $rg$ be first position that $a_{rg} > a_{1} + l$ (if $a_{m} \le a_{1} + l$, $rg = m + 1$). Then each barrel should have at least one stave from segment $[1, rg)$. So if $rg - 1 < n$ answer is $0$. Otherwise, for each $i$ from $1$ to $n$ let's take no more than $k$ smallest staves from this segment in the $i$-th barrel, but in such way, that there are at least $n - i$ staves left for next barrels.
[ "greedy" ]
1,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) typedef long long li; int n, k, l, m; vector<li> a; inline bool read() { if(!(cin >> n >> k >> l)) return false; m = n * k; a.assign(m, 0); fore(i, 0, m) assert(scanf("%lld", &a[i]) == 1); return true; } inline void solve() { sort(a.begin(), a.end()); int rg = int(upper_bound(a.begin(), a.end(), a[0] + l) - a.begin()); if(rg < n) { puts("0"); return; } li ans = 0; int u = 0; fore(i, 0, n) { ans += a[u++]; fore(j, 0, k - 1) { if(rg - u > n - i - 1) u++; else break; } } cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif cerr << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
985
D
Sand Fortress
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered $1$ through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought $n$ packs of sand with you. Let height $h_{i}$ of the sand pillar on some spot $i$ be the number of sand packs you spent on it. \textbf{You can't split a sand pack to multiple pillars, all the sand from it should go to a single one.} There is a fence of height equal to the height of pillar with $H$ sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: - $h_{1} ≤ H$: no sand from the leftmost spot should go over the fence; - For any $i\in[1;\infty)$ $|h_{i} - h_{i + 1}| ≤ 1$: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; - $\sum_{i=1}^{\infty}h_{i}=n$: you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.
Let's consider the optimal answer to always look like $h_{1} \le h_{2} \le ... \le h_{k} \ge h_{k + 1} \ge ...$ $k$ will be the leftmost position of a pillar with maximum height. We will heavily use the fact that all integers from $1$ to $h_{k} - 1$ appear in this sequence to the right of $k$. If you are able to construct any answer, it is easy to rearrange it to this pattern: select the leftmost maximum $k$, sort $[1..k - 1]$ in non-decreasing order and $[k + 1.. \infty )$ in non-increasing order. Sorted sequence will also be valid. Let a pyramid of height $k$ be such a valid castle that it occupies exactly $2k - 1$ consecutive spots and $1 = h_{1} < h_{2} < ... < h_{k} > h_{k + 1} > ... > h_{2k - 1} = 1$. Exactly $k^{2}$ sand packs are required to build it. At first let's solve the problem without even touching the fence. This won't always give the minimal answer but it'll help us further. Given some $k$ you can build the pyramid of height $k$ and get $n - k^{2}$ sand packs left over. This can fit in exactly $\textstyle{\left[\!\!leftfrac{n-k^{2}}{k}\right]}$ pillars (you can place any pillar of height $ \le k$ next to some pillar of the same height). That way we see that $a n s(k)=2k-1+\textstyle{\lceil{\frac{n-k^{2}}{k}}}\rfloor$. This function is non-increasing, let's show that for any $k$ from $2$ to $\lfloor{\sqrt{n}}\rfloor$ $ans(k) - ans(k - 1)$ is non-positive. $ans(k) - ans(k - 1)$ = $2k-1+\lceil{\frac{n-k^{2}}{k}}\rceil-2\cdot(k-1)+1-\lceil{\frac{n-(k-1)^{2}}{k-1}}\rceil$ = $\nabla_{\frac{n}{2}}=\frac{M_{s}(k)}{k}+\sum_{p=1}^{\pi_{s}(k)}\d t=1\d t$ = $2+\left\lceil{\frac{n}{k}}\right\rceil-k-\left\lceil{\frac{n}{k-1}}\right\rceil+\left(k-1\right)$ = $\textstyle{{1}+{\left[{\frac{n}{k}}\right]}}-{{\left[{\frac{n}{k-1}}\right]}}$ = $\lceil{\frac{n+k}{k}}\rceil-\lceil{\frac{n}{k-1}}\rfloor$ = $\textstyle{\left[\frac{(n+k)(k-1)}{k(k-1)}\right]}-\left[\frac{n k}{k(k-1)}\right]$. $\lceil{\frac{(n+k)(k-1)}{k(k-1)}}\rceil\leq\lceil{\frac{n k}{k(k-1)}}\rceil$ $\stackrel{\longrightarrow}{\longleftrightarrow}$ $(n + k)(k - 1) \le nk + k(k - 1) - 1$ $\stackrel{\longrightarrow}{\longleftrightarrow}$ $nk - n + k^{2} - k \le nk + k^{2} - k - 1$ $\stackrel{\longrightarrow}{\longleftrightarrow}$ $n \ge 1$. Now we can show that it is always optimal to push the initial pyramid to the left as far as possible, probably removing some pillars on positions less than $k$. That way the leftmost pillar will have height $h_{1} = min(k, H)$. The total number of sand packs required to build it is $k^{2}-{\frac{h_{1}\cdot(h_{1}-1)}{2}}$. This pattern will also include all the integers from $1$ to $k$ and will have the minimal width you can achieve. Monotonicity of this function can be proven in the similar manner. Finally, the answer can be calculated using the following algorithm: Find the maximum $k$ such that $k^{2}-{\frac{h_{1}\cdot(h_{1}-1)}{2}}\leq n$, where $h_{1} = min(k, H)$. Solve the equation or just do the binary search; Output the width of resulting truncated pyramid plus the minimal number of additional pillars it will take to distribute leftover sand packs. You should also take into consideration the upper bound on $k$ to avoid multiplying huge numbers. It's about $\sqrt{2n}$, so $64$-bit integer type will be enough for all the calculations. Overall complexity: $O(1)$ or $O(\log n)$.
[ "binary search", "constructive algorithms", "math" ]
2,100
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) typedef long long li; using namespace std; const int INF = 2e9; li n, h; bool check(li maxh){ li k = min(h, maxh); li cnt = maxh * maxh - k * (k - 1) / 2; return (cnt <= n); } li get(li maxh){ li k = min(h, maxh); li cnt = maxh * maxh - k * (k - 1) / 2; li len = (2 * maxh - 1) - (k - 1); n -= cnt; return len + (n + maxh - 1) / maxh; } int main() { scanf("%lld%lld", &n, &h); li l = 1, r = INF; while (l < r - 1){ li m = (l + r) / 2; if (check(m)) l = m; else r = m; } printf("%lld\n", check(r) ? get(r) : get(l)); return 0; }
985
E
Pencils and Boxes
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence $a_{1}, a_{2}, ..., a_{n}$ of $n$ integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that: - Each pencil belongs to \textbf{exactly} one box; - Each non-empty box has at least $k$ pencils in it; - If pencils $i$ and $j$ belong to the same box, then $|a_{i} - a_{j}| ≤ d$, where $|x|$ means absolute value of $x$. Note that the opposite is optional, there can be pencils $i$ and $j$ such that $|a_{i} - a_{j}| ≤ d$ and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".
At first you need to sort the sequence. Then if there exists some answer, there also exists an answer such that every box in it contains some segment of pencils. Now it's pretty standard dp approach. Let $dp_{i}$ be $1$ if it's possible to distribute the first $i$ pencils into boxes correctly, $0$ otherwise, $dp_{0} = 1$ initially. Now you can come up with straightforward $O(n^{2})$ implementation. Let's iterate over every $j\in[0..i]$ and set $dp_{i + 1}$ to $1$ if for some $j$ $dp_{j} = 1$, $i - j + 1 \ge k$ and $a_{i} - a_{j} \le d$. Now we should optimize it a bit. Notice that the second and the third conditions actually form some segment of indices. You need to check if there is at least one $1$ value on this segment. This can be maintained with two pointers, set, BIT, segment tree. Anything you can code to get update in point and sum/max on segment queries. Overall complexity: $O(n\log n)$.
[ "binary search", "data structures", "dp", "greedy", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int N = 500 * 1000 + 13; int f[N]; void upd(int x){ for (int i = x; i < N; i |= i + 1) ++f[i]; } int sum(int x){ int res = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) res += f[i]; return res; } int get(int l, int r){ if (l > r) return 0; return sum(r) - sum(l - 1); } int main(){ int n, k, dif; scanf("%d%d%d", &n, &k, &dif); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); sort(a.begin(), a.end()); vector<int> dp(n + 1, 0); dp[0] = 1; upd(0); int l = 0; forn(i, n){ while (l < i && a[i] - a[l] > dif) ++l; dp[i + 1] = (get(l, i - k + 1) >= 1); if (dp[i + 1]) upd(i + 1); } puts(dp[n] ? "YES" : "NO"); }
985
F
Isomorphic Strings
You are given a string $s$ of length $n$ consisting of lowercase English letters. For two given strings $s$ and $t$, say $S$ is the set of distinct characters of $s$ and $T$ is the set of distinct characters of $t$. The strings $s$ and $t$ are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) $f$ between $S$ and $T$ for which $f(s_{i}) = t_{i}$. Formally: - $f(s_{i}) = t_{i}$ for any index $i$, - for any character $x\in S$ there is exactly one character $y\in T$ that $f(x) = y$, - for any character $y\in T$ there is exactly one character $x\in S$ that $f(x) = y$. For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best". You have to handle $m$ queries characterized by three integers $x, y, len$ ($1 ≤ x, y ≤ n - len + 1$). For each query check if two substrings $s[x... x + len - 1]$ and $s[y... y + len - 1]$ are isomorphic.
Yes, authors also implemented hashes. Note that if substrings $s$ and $t$ are isomophic, then position $pos$ of first encounter of some character $s_{i}$ in $s$ must be position of first encounter of some character $t_{j}$ in $t$. More over, if we sort all positions $pos_{i}^{s}$ for all distict characters in $s$ and sort all positions $pos_{j}^{t}$ for $t$, then $pos_{i}^{s}$ must be equal $pos_{i}^{t}$ for any $i$. This observation gives us fact, that $f(s[pos_{i}^{s}]) = t[pos_{i}^{t}]$. So, to check isomorphism of $s$ and $t$ we need check for each $i$, that positions of all encounters of character $s[pos_{i}^{s}]$ equal to posistions of all encounters of character $t[pos_{i}^{t}]$. To do that we can generate for each character boolean array with checked positions of its encounter and calculate prefix hashes on this arrays. Also we need precalculate order of first encounters $ord_{k}$ for each suffix of string $s$. To do it fast note that in transition from $ord_{k + 1}$ to $ord_{k}$ only $s_{k}$ can change its relative order. Result complexity is $O(n \cdot A)$ with quite big constant from hashing.
[ "hashing", "strings" ]
2,300
#include <bits/stdc++.h> #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 using namespace std; const int B = 2; typedef array<int, B> ht; ht MOD, BASE; inline int norm(int a, const int &MOD) { while(a >= MOD) a -= MOD; while(a < 0) a += MOD; return a; } inline int mul(int a, int b, const int &MOD) { return int(a * 1ll * b % MOD); } inline ht operator +(const ht &a, const ht &b) { ht ans; fore(i, 0, sz(ans)) ans[i] = norm(a[i] + b[i], MOD[i]); return ans; } inline ht operator -(const ht &a, const ht &b) { ht ans; fore(i, 0, sz(ans)) ans[i] = norm(a[i] - b[i], MOD[i]); return ans; } inline ht operator *(const ht &a, const ht &b) { ht ans; fore(i, 0, sz(ans)) ans[i] = mul(a[i], b[i], MOD[i]); return ans; } int CMODS[] = {int(1e9) + 7, int(1e9) + 9, int(1e9) + 21, int(1e9) + 33, int(1e9) + 87, int(1e9) + 93, int(1e9) + 97, int(1e9) + 103}; int CBASE[] = {1009, 1013, 1019, 1021}; const int N = 200 * 1000 + 555; int n, m; char s[N]; int x[N], y[N], len[N]; inline bool read() { if(!(cin >> n >> m)) return false; assert(scanf("%s", s) == 1); fore(i, 0, m) { assert(scanf("%d%d%d", &x[i], &y[i], &len[i]) == 3); x[i]--, y[i]--; } return true; } void setMods() { mt19937 rnd; unsigned int seed = n; fore(i, 0, n) seed = (seed * 3) + s[i]; fore(i, 0, m) { seed = (seed * 3) + x[i]; seed = (seed * 3) + y[i]; seed = (seed * 3) + len[i]; } rnd.seed(seed); set<int> mids; while(sz(mids) < sz(MOD)) mids.insert(rnd() % 8); vector<int> vmids(mids.begin(), mids.end()); fore(i, 0, sz(MOD)) { MOD[i] = CMODS[vmids[i]]; BASE[i] = CBASE[i]; } } ht pBase[N]; ht ph[27][N]; vector<int> ord[N]; ht getHash(int id, int l, int r) { return ph[id][r] - ph[id][l] * pBase[r - l]; } inline void solve() { setMods(); pBase[0] = {1, 1}; fore(i, 1, N) pBase[i] = pBase[i - 1] * BASE; fore(c, 0, 26) { ph[c][0] = {0, 0}; fore(i, 0, n) { int val = (s[i] == c + 'a'); ph[c][i + 1] = ph[c][i] * BASE + ht{val, val}; } } vector<int> curOrd(26, 0); iota(curOrd.begin(), curOrd.end(), 0); for(int i = n - 1; i >= 0; i--) { ord[i] = curOrd; auto it = find(ord[i].begin(), ord[i].end(), int(s[i] - 'a')); ord[i].erase(it); ord[i].insert(ord[i].begin(), int(s[i] - 'a')); curOrd = ord[i]; } fore(q, 0, m) { int s1 = x[q], s2 = y[q]; bool ok = true; fore(i, 0, 26) { if(getHash(ord[s1][i], s1, s1 + len[q]) != getHash(ord[s2][i], s2, s2 + len[q])) { ok = false; break; } } puts(ok ? "YES" : "NO"); } } int main(){ #ifdef _DEBUG freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif if(read()) { solve(); } return 0; }
985
G
Team Players
There are $n$ players numbered from $0$ to $n-1$ with ranks. The $i$-th player has rank $i$. Players can form teams: the team should consist of three players and \textbf{no pair} of players in the team should have a conflict. The rank of the team is calculated using the following algorithm: let $i$, $j$, $k$ be the ranks of players in the team and $i < j < k$, then the rank of the team is equal to $A \cdot i + B \cdot j + C \cdot k$. You are given information about the pairs of players who \textbf{have} a conflict. Calculate the total sum of ranks over all possible valid teams modulo $2^{64}$.
Let's solve this task in several steps. At first, let's calculate $all$ - sum of all triples. For each player $i$ consider three cases: $j<k<i$ - there are exactly ${i}\choose{2}$ ways to choose triple; $j<i<k$ - there are $i \cdot (n-i-1)$ ways; $i<j<k$ - there are ${n-i-1}\choose{2}$ ways. At second, let's calculate $sub_1$ - sum over all triples $j<k<i$ such that exists pair $(j,i)$ or $(k,i)$. To calculate it we need for each $i$ iterate over all neighbors $x<i$ of $i$. Again some cases: if $x=j<k<i$ then there are exactly $(i-j-1)$ ways to choose $k$; if $j<x=k<i$, there are $x$ ways to choose $j$. At third, let's calculate $sub_2$ - sum over all triple $j<k<i$ where exists pair $(j,k)$, but pairs $(j,i)$ and $(k,i)$ are not. $sub_2 = sub_2^0 - sub_2^1 - sub_2^2 + sub_2^{12}$. $sub_2^0$ is a sum of all triples $j<k<i$ where pair $(j,k)$ exists. It can be calculated while iterating $i$ in increasing order. $sub_2^1$ is a sum of all triples $j<k<i$ where pairs $(j,k)$ and $(j,i)$ exists. It can be calculated while iterating $(j,i)$ and asking sum on segment of adjacency list of $j$ ($O(1)$ with prefix sums for each vertex $j$). $sub_2^2$ is a sum of all triples $j<k<i$ where pairs $(j,k)$ and $(k,i)$ exists. It can be calculated while iterating $(k,i)$ and asking sum on prefix of adjacency list of $k$ (same $O(1)$). $sub_2^{12}$ is a sum of all triples $j<k<i$ where all pairs $(j,k)$, $(j,i)$ and $(k,i)$ exists. It is modification of calculating number of triangles in graph. It can be done in $O(M\sqrt{M})$ and will be explained below. Then result $res = all - sub_1 - sub_2$. The algorithm of finding all triangles in the given graph $G$ is following: Let's call vertex heavy if $|G(v)| \ge \sqrt{M}$ and light otherwise. For each heavy vertex $v$ precalculate $has_v[i]$ - boolean array of adjacency of vertex $v$. It's cost $O(N \sqrt{M})$ of memory and time but memory can be reduced by using bitsets. To calculate number of triangles $j<k<i$ let's iterate over $i$. There are two cases: if $i$ is heavy, then just iterate over all edges $(j,k)$ and check $has_i[j]$ and $has_i[k]$. This part works with $O(M\sqrt{M})$ time since there are $O(\sqrt{M})$ heavy vertices. if $i$ is light, then iterate over all pair $(j,k)$, where $j,k \in G(i)$ (at first fix $k$, then iterate $j<k$). To check existence of edge $(j,k)$ consider two more cases: if $k$ is heavy, just check $has_k[j]$. It works in $O(1)$. if $k$ is light, just check in some global array $curHas$ all neighbors of $k$, check all $j$ with $curHas[j]$ and uncheck neighbors of $k$. Checking in array $curHas$ require $O(|G(k)|)$ time and will be done $O(|G(k)|)$ times. So it will be $O(\sum{|G(v)|^2})=O(\sqrt{M}\sum{|G(v)|})=O(M\sqrt{M})$ in total. Similarly, iterating pairs $j,k\in G(i)$ works with $O(\sum{|G(i)|^2})=O(M\sqrt{M})$ in total. if $k$ is heavy, just check $has_k[j]$. It works in $O(1)$. if $k$ is light, just check in some global array $curHas$ all neighbors of $k$, check all $j$ with $curHas[j]$ and uncheck neighbors of $k$. Checking in array $curHas$ require $O(|G(k)|)$ time and will be done $O(|G(k)|)$ times. So it will be $O(\sum{|G(v)|^2})=O(\sqrt{M}\sum{|G(v)|})=O(M\sqrt{M})$ in total. So comlexity of algorithm and all task is $O(M\sqrt{M})$.
[ "combinatorics" ]
2,700
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int(a.size()) using namespace std; typedef unsigned long long uli; const int N = 200 * 1000 + 555; int n, m; uli a, b, c; vector<int> g[N]; inline bool read() { if(!(cin >> n >> m)) return false; assert(cin >> a >> b >> c); fore(i, 0, m) { int u, v; assert(scanf("%d%d", &u, &v) == 2); g[u].push_back(v); g[v].push_back(u); } return true; } vector<uli> ps[N]; inline uli getSum(int v, int l, int r) { return ps[v][r] - ps[v][l]; } const int MX = 700; int id[N]; const int B = 1111; bitset<N> has[B]; int szh = 0; inline void solve() { memset(id, -1, sizeof id); szh = 0; fore(v, 0, n) { sort(g[v].begin(), g[v].end()); ps[v].assign(sz(g[v]) + 1, 0); fore(i, 0, sz(g[v])) ps[v][i + 1] = ps[v][i] + g[v][i]; if(sz(g[v]) >= MX) { assert(szh < B); id[v] = szh++; for(int to : g[v]) has[id[v]][to] = 1; } } uli all = 0; fore(v, 0, n) { uli lw = v, gr = n - v - 1; all += a * v * (gr * (gr - 1) / 2); all += b * v * (lw * gr); all += c * v * (lw * (lw - 1) / 2); } uli sub1 = 0; fore(v, 0, n) { for(int to : g[v]) { if(to > v) break; uli cnt = to; uli sum = cnt * (cnt - 1) / 2; sub1 += a * sum + cnt * (b * to + c * v); cnt = v - to - 1; sum = (2 * to + cnt + 1) * cnt / 2; sub1 += b * sum + cnt * (a * to + c * v); } uli sum = 0; fore(i, 0, sz(g[v])) { if(g[v][i] > v) break; uli cnt = i; sub1 -= a * sum + cnt * (b * g[v][i] + c * v); sum += g[v][i]; } } all -= sub1; uli sub2 = 0; uli cntE = 0, sumE = 0; fore(v, 0, n) { sub2 += sumE + cntE * c * v; for(int to : g[v]) { if(to > v) break; cntE++; sumE += a * to + b * v; } } fore(v, 0, n) { for(int to : g[v]) { if(to > v) break; int pos = int(lower_bound(g[to].begin(), g[to].end(), to) - g[to].begin()); sub2 -= a * getSum(to, 0, pos) + pos * (b * to + c * v); int pos2 = int(lower_bound(g[to].begin(), g[to].end(), v) - g[to].begin()); sub2 -= b * getSum(to, pos, pos2) + (pos2 - pos) * (a * to + c * v); } } vector<char> curh(n + 5, 0); fore(v, 0, n) { if(id[v] == -1) { fore(i2, 0, sz(g[v])) { int u2 = g[v][i2]; if(u2 > v) break; if(id[u2] != -1) { fore(i1, 0, i2) { int u1 = g[v][i1]; if(has[id[u2]][u1]) sub2 += a * u1 + b * u2 + c * v; } } else { for(int to : g[u2]) { if(to > u2) break; curh[to] = 1; } fore(i1, 0, i2) { int u1 = g[v][i1]; if(curh[u1]) sub2 += a * u1 + b * u2 + c * v; } for(int to : g[u2]) { if(to > u2) break; curh[to] = 0; } } } } else { fore(u2, 0, v) { if(!has[id[v]][u2]) continue; for(int u1 : g[u2]) { if(u1 > u2) break; if(has[id[v]][u1]) sub2 += a * u1 + b * u2 + c * v; } } } } all -= sub2; cout << all << endl; } int main(){ #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif cout << fixed << setprecision(10); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; #endif } return 0; }
986
A
Fair
Some company is going to hold a fair in Byteland. There are $n$ towns in Byteland and $m$ two-way roads between towns. Of course, you can reach any town from any other town using roads. There are $k$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $s$ different types of goods. It costs $d(u,v)$ coins to bring goods from town $u$ to town $v$ where $d(u,v)$ is the length of the shortest path from $u$ to $v$. Length of a path is the number of roads in this path. The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of $n$ towns.
Let's find a cost to bring a good $t$ in each town. To do this we will run BFS from all towns producing good $t$ at once. Just add all that towns in queue and run usual BFS. Complexity of BFS is $O(n+m)$, so total complexity of $k$ BFSs will be $O(k(n+m))$. Now for each town we should choose $s$ cheapest goods. We can sort them in $O(k \log k)$, but we can use nth_element instead. It will put the $s$-th element in sorted order on place $s$, and all elements smaller will be to the left. Since we are interested only in their sum, we can just sum up first $s$ elements after calling nth_element. Another way to achieve $O(k(m+n))$ complexity is to run all $k$ BFSs simultaneously, then for each town first $s$ goods to reach it are the cheapest. Bonus: solve the problem in $O(s(m+n))$ time.
[ "graphs", "greedy", "number theory", "shortest paths" ]
1,600
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; #define mp make_pair const int INF = (int)1e7; const int N = 100010; const int K = 302; vector<int> g[N]; vector<int> forCol[K]; int q[N]; int topQ; int dist[N]; int ans[N][K]; int n, m, k, s; int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); scanf("%d%d%d%d", &n, &m, &k, &s); for (int i = 0; i < n; i++) { int x; scanf("%d", &x); x--; forCol[x].push_back(i); } while(m--) { int v, u; scanf("%d%d", &v, &u); v--;u--; g[v].push_back(u); g[u].push_back(v); } for (int c = 0; c < k; c++) { for (int i = 0; i < n; i++) dist[i] = INF; topQ = 0; for (int x : forCol[c]) { dist[x] = 0; q[topQ++] = x; } for (int i = 0; i < topQ; i++) { int v = q[i]; for (int u : g[v]) { if (dist[u] <= dist[v] + 1) continue; dist[u] = dist[v] + 1; q[topQ++] = u; } } for (int i = 0; i < n; i++) ans[i][c] = dist[i]; } for (int i = 0; i < n; i++) { nth_element(ans[i], ans[i] + s, ans[i] + k); int res = 0; for (int j = 0; j < s; j++) res += ans[i][j]; printf("%d ", res); } printf("\n"); return 0; }
986
B
Petr and Permutations
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?! You somehow get a test from one of these problems and now you want to know from which one.
Each swap change the parity of permutation. $3n$ and $7n+1$ always have different parities, so the solution is just to calculate the parity of the given permutation and check if it is equal to parity of $3n$ or to parity of $7n+1$. To calculate the parity you can just calculate the number of inversions with your favorite method (Fenwick tree, Segment tree, mergesort or whatever) in $O(n \log n)$ time. But it is easier to calculate the number of cycles in permutation in $O(n)$ time.
[ "combinatorics", "math" ]
1,800
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; #define mp make_pair const int N = (int)1e6 + 7; int n; int a[N]; int ans; int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); a[i]--; } ans = 0; for (int i = 0; i < n; i++) { if (a[i] == -1) continue; ans ^= 1; int x = i; while(x != -1) { int y = a[x]; a[x] = -1; x = y; } } if (ans) printf("Um_nik\n"); else printf("Petr\n"); return 0; }
986
C
AND Graph
You are given a set of size $m$ with integer elements between $0$ and $2^{n}-1$ inclusive. Let's build an undirected graph on these integers in the following way: connect two integers $x$ and $y$ with an edge if and only if $x \& y = 0$. Here $\&$ is the bitwise AND operation. Count the number of connected components in that graph.
Let's build directed graph on $m+2^n$ vertices. There will be two types of vertices: $(x, 1)$ is a vertex for $x$ from input and $(x, 2)$ is a vertex for all $x$ between $0$ and $2^{n}-1$. There will be edges of three classes: $(x, 1) \rightarrow (x, 2)$ for all $x$ from input $(x, 2) \rightarrow (x | (1 \ll k), 2)$ for all $x$ and $k$ such that $k$-th bit of $x$ is $0$ $(\sim x, 2) \rightarrow (x, 1)$ for all $x$ from input. Here $\sim x = ((2^n-1) - x)$ - the complement of $x$ Let's look at some path of form $(a, 1) \rightarrow (x_1, 2) \rightarrow (x_2, 2) \rightarrow \ldots \rightarrow (x_k, 2) \rightarrow (b, 1)$. The transition from $x_1$ to $x_k$ just change some $0$ bits to $1$. So, $x_1$ is a submask of $x_k$. $a$ is $x_1$ and $b$ is the complement of $x_k$. Now it is clear that $a \& b = 0$. The opposite is also true: whenever $a \& b = 0$, there is a path from $(a, 1)$ to $(b, 1)$. The solution is simple now: iterate over all $x$ from input, and if the vertex $(x, 1)$ is not visited yet, run a DFS from it and increase the answer by $1$. It is clear that we will run DFS exactly once for each connected component of original graph. Complexity - $O(n2^n)$
[ "bitmasks", "dfs and similar", "dsu", "graphs" ]
2,500
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; #define mp make_pair const int N = (1 << 22) + 5; int n, m; bool used[N]; int cnt[N]; void add(int x, int d) { int Z = x & ((1 << m) - 1); int y = x - Z; Z ^= (1 << m) - 1; for(int z = Z; z > 0; z = (z - 1) & Z) cnt[y + (1 << m) - 1 - z] += d; cnt[y + (1 << m) - 1] += d; } void dfs(int x) { // cerr << "dfs " << x << endl; used[x] = 1; add(x, -1); x ^= (1 << n) - 1; int Z = x & ((1 << m) - 1); int Y = x - Z; for(int y = Y;; y = (y - 1) & Y) { while (cnt[y + Z] > 0) { int z = Z; for (int i = 0; i < m; i++) { if (((z >> i) & 1) && cnt[y + z ^ (1 << i)] > 0) z ^= 1 << i; } if (used[y + z]) throw; dfs(y + z); } if (y == 0) break; } } int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); scanf("%d%d", &n, &m); for (int i = 0; i < (1 << n); i++) used[i] = 1; while(m--) { int x; scanf("%d", &x); used[x] = 0; } m = n / 2; for (int x = 0; x < (1 << n); x++) { if (used[x]) continue; add(x, 1); } int ans = 0; for (int x = 0; x < (1 << n); x++) { if (!used[x]) { dfs(x); ans++; } } printf("%d\n", ans); return 0; }
986
D
Perfect Encoding
You are working as an analyst in a company working on a new system for big data storage. This system will store $n$ different objects. Each object should have a unique ID. To create the system, you choose the parameters of the system — integers $m \ge 1$ and $b_{1}, b_{2}, \ldots, b_{m}$. With these parameters an ID of some object in the system is an array of integers $[a_{1}, a_{2}, \ldots, a_{m}]$ where $1 \le a_{i} \le b_{i}$ holds for every $1 \le i \le m$. Developers say that production costs are proportional to $\sum_{i=1}^{m} b_{i}$. You are asked to choose parameters $m$ and $b_{i}$ so that the system will be able to assign unique IDs to $n$ different objects and production costs are minimized. Note that you don't have to use all available IDs.
The problem asks to find integers $b_i$ such that $\prod b_i \ge n$ and $\sum b_i$ is minimized. Let's suppose that in optimal solution there is $x \ge 4$ among $b_i$. It is better to split it to $2$ and $(x-2)$: the sum remains the same and the product is increased (or stays the same). So we will use only $2$ and $3$ as our $b_i$. If there are at least three $2$ among $b_i$, we can replace them with two $3$: the sum remains the same, the product is increased. So, optimal solution looks like this: zero, one or two $2$s and some $3$s. For now let's say that we try all three possibilities for the number of $2$s. The problem now looks like "find $\left\lceil \log_{3} n \right\rceil$". The trick here is that we can estimate the answer very accurately. Let's say that the length of decimal form of $n$ is $L$. Then $\log_{3} n$ is very close to $L \frac{\log 10}{\log 3}$, the difference is not greater than $3$. So it is easy to calculate the number $p$ such that $3^p < n / 4 < n < 3^{p+6}$. If we will calculate $3^p$, then we should adjust this a little bit by multiplying by $3$ a few number of times. Multiplying by $3$ can be done in linear time, comparing two numbers also in linear time. Let's now remember that we have tried all the possibilities for the number of $2$s. We will do it not beforehand, but only now, because now each option can be checked in linear time. To calculate $3^p$ we will use binary exponentiation with FFT. If the length of the result is $L$, then the running time will be $O(L \log L + \frac{L}{2} \log L + \frac{L}{4} \log L + \ldots) = O(L \log L)$. To reduce the running time you should store the numbers in base $1000$, not in base $10$. This will reduce the length of the number $3$ times, and the numbers we are getting in FFT will be at most $5 \cdot 10^{11}$ which is good enough to avoid precision issues. In the end, running time is roughly equivalent to 4 FFT calls of size $2^{19}$ which is not that big. Total complexity - $O(L \log L)$.
[ "fft", "math" ]
3,100
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; #define mp make_pair typedef complex<double> cd; const double PI = 4 * atan(1); const ll B = (ll)1000; const int LOG = 19; const int N = (1 << LOG); const int NN = N + 5; cd w[NN]; int rev[NN]; void printVec(vector<ll> a) { for (ll x : a) eprintf("%lld ", x); eprintf("\n"); } void initFFT() { for (int i = 0; i < N; i++) w[i] = cd(cos(2 * PI * i / N), sin(2 * PI * i / N)); rev[0] = 0; for (int mask = 1; mask < N; mask++) { int k = 0; while(((mask >> k) & 1) == 0) k++; rev[mask] = rev[mask ^ (1 << k)] ^ (1 << (LOG - 1 - k)); } } cd F[2][NN]; void FFT(cd* A, int k) { int L = 1 << k; for (int i = 0; i < L; i++) F[0][rev[i] >> (LOG - k)] = A[i]; int t = 0, nt = 1; for (int lvl = 0; lvl < k; lvl++) { int len = 1 << lvl; for (int st = 0; st < L; st += (len << 1)) for (int i = 0; i < len; i++) { cd ad = F[t][st + len + i] * w[i << (LOG - 1 - lvl)]; F[nt][st + i] = F[t][st + i] + ad; F[nt][st + len + i] = F[t][st + i] - ad; } swap(t, nt); } for (int i = 0; i < L; i++) A[i] = F[t][i]; } cd A[NN]; bool ls(vector<ll> a, vector<ll> b) { if ((int)a.size() != (int)b.size()) return (int)a.size() < (int)b.size(); for (int i = (int)a.size() - 1; i >= 0; i--) { if (a[i] == b[i]) continue; return a[i] < b[i]; } return false; } vector<ll> sqr(vector<ll> a) { int L = (int)a.size(); int k = 0; while(L > (1 << k)) k++; k++; L = 1 << k; for (int i = 0; i < L; i++) A[i] = 0; for (int i = 0; i < (int)a.size(); i++) A[i] = a[i]; FFT(A, k); for (int i = 0; i < L; i++) A[i] *= A[i]; FFT(A, k); vector<ll> res; res.resize(L); for (int i = 0; i < L; i++) res[i] = (ll)(A[i].real() / L + 0.5); reverse(res.begin() + 1, res.end()); ll d = 0; for (int i = 0; i < L; i++) { d += res[i]; res[i] = d % B; d /= B; } while((int)res.size() > 1 && res.back() == 0) res.pop_back(); return res; } vector<ll> multBy(vector<ll> a, ll x) { ll d = 0; for (int i = 0; i < (int)a.size() || d; i++) { if (i >= (int)a.size()) a.push_back(0LL); d += a[i] * x; a[i] = d % B; d /= B; } return a; } vector<ll> pow3(int pw) { vector<ll> res; res.push_back(1LL); int k = 0; while(pw >= (1 << k)) k++; for (int i = k - 1; i >= 0; i--) { res = sqr(res); if ((pw >> i) & 1) res = multBy(res, 3); } return res; } char s[3 * NN]; vector<ll> c; int ANS = (int)1e9; int read() { scanf("%s", s); int L = strlen(s); for (int pos = L; pos > 0; pos -= 3) { ll x = 0; for (int i = pos - 3; i < pos; i++) { if (i < 0) continue; x = x * 10 + (ll)(s[i] - '0'); } c.push_back(x); } return L; } int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); initFFT(); /* vector<ll> a = pow3(59); printVec(a); return 0; */ int pw = (int)(read() * log(10) / log(3)) - 6; pw = max(pw, 0); vector<ll> st = pow3(pw); // printVec(st); for (int k = 0; k < 3; k++) { int curAns = pw * 3 + k * 2; vector<ll> cur = multBy(st, 1LL << k); while(ls(cur, c)) { curAns += 3; cur = multBy(cur, 3LL); } ANS = min(ANS, curAns); } ANS = max(ANS, 1); printf("%d\n", ANS); return 0; }
986
E
Prince's Problem
Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem. You are given a tree with $n$ vertices. In each vertex $v$ there is positive integer $a_{v}$. You have to answer $q$ queries. Each query has a from $u$ $v$ $x$. You have to calculate $\prod_{w \in P} gcd(x, a_{w}) \mod (10^{9} + 7)$, where $P$ is a set of vertices on path from $u$ to $v$. In other words, you are to calculate the product of $gcd(x, a_{w})$ for all vertices $w$ on the path from $u$ to $v$. As it might be large, compute it modulo $10^9+7$. Here $gcd(s, t)$ denotes the greatest common divisor of $s$ and $t$. Note that the numbers in vertices \textbf{do not} change after queries. I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them.
Let's solve the problem offline and independently for all primes, then multiply the answers. The sum of powers of all primes is $O((n+q) \log C)$. To factorize numbers we will precalculate smallest prime divisor for all numbers using sieve. For fixed prime $p$ let's write its power $b_v$ in every vertex. Then if $p$ is in $x$ from query in power $z$, then the query become "calculate $\sum_{v} min(b_v, z)$". Let's do the following. We will start with $c_v = 0$ in all vertices. Then we will iterate over $w$ - the power of $p$ - from $1$ to maximal power in queries. If $b_v \ge w$, then increase $c_v$ by $1$. Now in all vertices $c_v = min(b_v, w)$ so to answer all queries with $z=w$ we should just take sum on path. This can be done if we will maintain $c_v$ in Fenwick tree over Euler tour of our tree (this allows to calculate sum on path to root in $O(\log n)$ time, to get sum on arbitrary path we also need to compute LCA). The number of queries to Fenwick tree is $O((n+q) \log C)$, so total complexity is $O((n+q) \log C \log n)$.
[ "brute force", "data structures", "math", "number theory", "trees" ]
2,800
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; #define mp make_pair const ll MOD = (ll)1e9 + 7; ll mult(ll x, ll y) { return (x * y) % MOD; } const int N = 100100; const int LOG = 17; const int C = (int)1e7 + 10; const int M = (int)1e6 + 3; int d[C]; int pr[M]; int prSz; vector<pii> nodesForPrime[M]; vector<pii> queryForPrime[M]; vector<ll> primePowers[M]; vector<int> g[N]; int n; int par[N][LOG]; int h[N]; int T1, T2; int t[N][3]; void dfs(int v) { t[v][0] = T1++; for (int u : g[v]) { if (h[u] != -1) continue; h[u] = h[v] + 1; par[u][0] = v; for (int k = 0; k < LOG - 1; k++) { int w = par[u][k]; if (w != -1) par[u][k + 1] = par[w][k]; } dfs(u); } t[v][1] = T1; t[v][2] = T2++; } int up(int v, int dh) { for (int k = LOG - 1; k >= 0; k--) { if (dh < (1 << k)) continue; dh -= 1 << k; v = par[v][k]; } return v; } int LCA(int v, int u) { if (h[v] > h[u]) swap(v, u); u = up(u, h[u] - h[v]); if (v == u) return v; for (int k = LOG - 1; k >= 0; k--) { if (par[v][k] != par[u][k]) { v = par[v][k]; u = par[u][k]; } } return par[v][0]; } int fenv[2][N]; void fenvAdd(int k, int r, int dx) { for(; r < n; r |= r + 1) fenv[k][r] += dx; } int fenvGet(int k, int r) { int res = 0; for (; r >= 0; r = (r & (r + 1)) - 1) res += fenv[k][r]; return res; } int m; int qu[N][4]; ll ANS[N]; void precalc() { for (int i = 1; i < C; i++) d[i] = -1; for (int x = 2; x < C; x++) { if (d[x] != -1) continue; pr[prSz] = x; for (int y = x; y < C; y += x) if (d[y] == -1) d[y] = prSz; primePowers[prSz].push_back(1); prSz++; } } void addPrimeNode(int p, int id, int pw) { // eprintf("add prime node %d %d %d\n", pr[p], id, pw); nodesForPrime[p].push_back(mp(pw, id)); for (int i = 1; i <= pw; i++) { primePowers[p].push_back(mult(primePowers[p].back(), pr[p])); } } void addPrimeQuery(int p, int id, int pw) { // eprintf("add prime query %d %d %d\n", pr[p], id, pw); queryForPrime[p].push_back(mp(pw, id)); } void read() { scanf("%d", &n); for (int i = 1; i < n; i++) { int v, u; scanf("%d%d", &v, &u); v--;u--; g[v].push_back(u); g[u].push_back(v); } for (int v = 0; v < n; v++) { h[v] = -1; for (int i = 0; i < LOG; i++) par[v][i] = -1; } h[0] = 0; dfs(0); // eprintf("times:\n"); // for (int v = 0; v < n; v++) // eprintf("%d %d %d\n", t[v][0], t[v][1], t[v][2]); for (int i = 0; i < n; i++) { int x; scanf("%d", &x); while(x > 1) { int p = d[x]; int pw = 0; while(d[x] == p) { pw++; x /= pr[p]; } addPrimeNode(p, i, pw); } } scanf("%d", &m); for (int i = 0; i < m; i++) { ANS[i] = 1; int v, u, x; scanf("%d%d%d", &v, &u, &x); v--;u--; qu[i][0] = v; qu[i][1] = u; qu[i][2] = LCA(v, u); qu[i][3] = par[qu[i][2]][0]; // eprintf("%d %d %d %d\n", qu[i][0], qu[i][1], qu[i][2], qu[i][3]); while(x > 1) { int p = d[x]; int pw = 0; while(d[x] == p) { pw++; x /= pr[p]; } addPrimeQuery(p, i, pw); } } for (int i = 0; i < prSz; i++) { sort(nodesForPrime[i].begin(), nodesForPrime[i].end()); reverse(nodesForPrime[i].begin(), nodesForPrime[i].end()); sort(queryForPrime[i].begin(), queryForPrime[i].end()); } } void addInV(int v, int dx) { fenvAdd(0, t[v][0], dx); fenvAdd(1, t[v][2], dx); } int getSumV(int v) { if (v == -1) return 0; return fenvGet(0, t[v][1] - 1) - fenvGet(1, t[v][2] - 1); } int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); precalc(); read(); for (int id = 0; id < m; id++) { int it = 0; int k = 0; while(it < (int)queryForPrime[id].size()) { k++; for (int i = 0; i < (int)nodesForPrime[id].size() && nodesForPrime[id][i].first >= k; i++) { addInV(nodesForPrime[id][i].second, 1); } while(it < (int)queryForPrime[id].size() && queryForPrime[id][it].first == k) { int s = queryForPrime[id][it].second; it++; int pw = 0; pw += getSumV(qu[s][0]); pw += getSumV(qu[s][1]); pw -= getSumV(qu[s][2]); pw -= getSumV(qu[s][3]); ANS[s] = mult(ANS[s], primePowers[id][pw]); } } while(k > 0) { for (int i = 0; i < (int)nodesForPrime[id].size() && nodesForPrime[id][i].first >= k; i++) { addInV(nodesForPrime[id][i].second, -1); } k--; } } for (int i = 0; i < m; i++) printf("%lld\n", ANS[i]); return 0; }
986
F
Oppa Funcan Style Remastered
Surely you have seen insane videos by South Korean rapper PSY, such as "Gangnam Style", "Gentleman" and "Daddy". You might also hear that PSY has been recording video "Oppa Funcan Style" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find original description here): On the ground there are $n$ platforms, which are numbered with integers from $1$ to $n$, on $i$-th platform there is a dancer with number $i$. Further, every second all the dancers standing on the platform with number $i$ jump to the platform with the number $f(i)$. The moving rule $f$ is selected in advance and is not changed throughout the clip. The duration of the clip was $k$ seconds and the rule $f$ was chosen in such a way that after $k$ seconds all dancers were in their initial positions (i.e. the $i$-th dancer stood on the platform with the number $i$). That allowed to loop the clip and collect even more likes. PSY knows that enhanced versions of old artworks become more and more popular every day. So he decided to release a remastered-version of his video. In his case "enhanced version" means even more insanity, so the number of platforms can be up to $10^{18}$! But the video director said that if some dancer stays on the same platform all the time, then the viewer will get bored and will turn off the video immediately. Therefore, for all $x$ from $1$ to $n$ $f(x) \neq x$ must hold. Big part of classic video's success was in that looping, so in the remastered version all dancers should return to their initial positions in the end of the clip as well. PSY hasn't decided on the exact number of platforms and video duration yet, so he asks you to check if there is a good rule $f$ for different options.
Let's understand the problem first. The rule $f(x)$ must be bijective, because otherwise some platforms will be empty in $k$ seconds. So we are looking for permutations $p$ of size $n$. Let's say that cycles of the permutation have lengths $c_1, c_2, \ldots, c_m$. $p^k$ is an identity permutation if and only if $c_i$ divides $k$ for all $i$. Also $c_i \ne 1$. So, we need to check if there are such numbers $c_i$ for which all these holds: $n = \sum c_i$ $c_i \ne 1$ $c_i$ is a divisor of $k$ It is not profitable to use composite divisors of $k$ because we can substitute each of them with any its prime divisor repeated necessary number of times. Let's say that $p_1 < p_2 < \ldots < p_m$ - the list of all distinct prime divisors of $k$. Then the problem is essentially: Check if there are nonnegative coefficients $b_i$ such that $n = \sum b_i \cdot p_i$. If $m=0$ ($k=1$) answer is NO. If $m=1$, then the answer is YES if and only if $n$ is divisible by $p_1$. If $m=2$, then you have to say if there is a nonnegative solution to Diophantine equation. It can be done using extended Euclid algorithm. And if $m \ge 3$, then $p_1 \le k^{1/m} \le k^{1/3} \le 10^5$. Let's find $d(r)$ - the minimal number equal to $r$ modulo $p_1$ that can be written in form $\sum b_i \cdot p_i$. If we do this, the answer is obvious: YES if and only if $n \ge d(n \mod p_1)$. To find all the $d$ we'll build a directed graph. It's vertices are the remainders modulo $p_1$, and there is a directed edge from $x$ to $(x + p_i) \mod p_1$ with weight $p_i$ for all $x$ and $i$. Let's see that the path from $0$ in this graph is a set of $p_i$, its weight is the sum of $p_i$ and it leads to a remainder of this sum modulo $p_1$. Therefore, $d(r)$ is shortest path from $0$ to $r$ in this graph. There are $p_1$ vertices and $p_1 \cdot m$ edges in this graph, so dijkstra's running time is $O(mp_1 \log p_1) = O(m k^{1/m} \log (k^{1/m})) = O(k^{1/m} \log k) = O(k^{1/3} \log k)$. We also need to factorize $k$. Let's build sieve once and find all the primes up to $\sqrt{K}$ ($K=10^{15}$). Then we can factorize numbers up to $K$ in $O(\frac{\sqrt{K}}{\log K})$ just like in trivial $O(\sqrt{K})$ algorithm but trying only prime divisors. Let's calculate complexity now. Let's say that number of all tests is $t \le 10^4$ and number of different $k$ is $q \le 50$. Solutions for $m=1$ and $m=2$ works in $O(1)$ and $O(\log n)$ time, so total time is $O(t \log n)$. Solution for $m \ge 3$ works in $O(k^{1/3} \log k)$, but this dijkstra should be done once for each $k$, for different $n$ we should only check one condition using calculated distances. Therefore, total time for these solutions is $O(q k^{1/3} \log k + t)$. Also there is sieve in $O(\sqrt{K} \log \log K)$ and factorization in $O(\frac{\sqrt{k}}{\log k})$ $q$ times. Total complexity - $O(\sqrt{K} \log \log K + q (\frac{\sqrt{k}}{\log k} + k^{1/3} \log k) + t \log n)$.
[ "graphs", "math", "number theory", "shortest paths" ]
3,300
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, int> pli; #define mp make_pair map<ll, vector<pli>> mapchik; const ll INF = (ll)2e18; const int M = (int)35e6; const int PSZ = (int)3e6; bool p[M]; int pr[PSZ]; int prSz; const int N = (int)1e5 + 10; bool ANS[N]; ll dist[N]; ll euclid(ll x, ll y, ll &k, ll &l) { if (y == 0) { k = 1; l = 0; return x; } ll g = euclid(y, x % y, l, k); l -= k * (x / y); return g; } vector<ll> factorize(ll x) { vector<ll> res; for (int i = 0; i < prSz; i++) { if (x % pr[i]) continue; res.push_back(pr[i]); while(x % pr[i] == 0) x /= pr[i]; } if (x > 1) res.push_back(x); return res; } void solve(ll k, vector<pli> queries) { vector<ll> a = factorize(k); int n = (int)a.size(); if (n == 0) { return; } else if (n == 1) { for (pli q : queries) { ANS[q.second] = q.first % a[0] == 0; } return; } else if (n == 2) { ll r = 0, s = 0; if (euclid(a[0], a[1], r, s) != 1) throw; s %= a[0]; if (s < 0) s += a[0]; for (pli q : queries) { ll z = ((s * (q.first % a[0])) % a[0]) * a[1]; ANS[q.second] = z <= q.first; } return; } int m = a[0]; for (int i = 0; i < m; i++) dist[i] = INF; dist[0] = 0; set<pli> setik; for (int i = 0; i < m; i++) setik.insert(mp(dist[i], i)); while(!setik.empty()) { int v = setik.begin()->second; setik.erase(setik.begin()); for (int i = 1; i < n; i++) { int u = (v + a[i]) % m; ll w = dist[v] + a[i]; if (w >= dist[u]) continue; setik.erase(mp(dist[u], u)); dist[u] = w; setik.insert(mp(dist[u], u)); } } for (pli q : queries) { ANS[q.second] = dist[q.first % m] <= q.first; } } int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); for (int i = 2; i < M; i++) p[i] = 1; for (int x = 2; x < M; x++) { if (!p[x]) continue; pr[prSz++] = x; for (int y = 2 * x; y < M; y += x) p[y] = 0; } int t; scanf("%d", &t); for (int i = 0; i < t; i++) { ll n, k; scanf("%lld%lld", &n, &k); mapchik[k].push_back(mp(n, i)); } for (auto it : mapchik) { solve(it.first, it.second); } for (int i = 0; i < t; i++) if (ANS[i]) printf("YES\n"); else printf("NO\n"); return 0; }
987
A
Infinity Gauntlet
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: - the Power Gem of purple color, - the Time Gem of green color, - the Space Gem of blue color, - the Soul Gem of orange color, - the Reality Gem of red color, - the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of \textbf{absent} Gems.
Just do what is written in the statement. Convenient way is to use map in C++ or dict in Python.
[ "implementation" ]
800
d = {"purple":"Power", "green":"Time", "blue":"Space", "orange":"Soul", "red":"Reality", "yellow":"Mind"} s = set() n = int(input()) for _ in range(n): w = input() s.add(w) print(6 - n) for (key, value) in d.items(): if key not in s: print(value)
987
B
High School: Become Human
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.
We need to compare $x^y$ with $y^x$. Let's take logarithms of both sides. Now we need to compare $y \ln x$ with $x \ln y$. If you will compare this numbers with appropriate epsilon, it will get AC, but let's analyze a bit more and get solution in integers. Let's divide both sides by $xy$, now we need to compare $\frac{\ln x}{x}$ with $\frac{\ln y}{y}$. That's the values of some function $f(x)=\frac{\ln x}{x}$ taken in two points. Let's take a closer look on this function. You can take derivative or just look at the plot at WolframAlpha. It's clear that this function have maximum at point $e$, and it is increasing on $[1,e]$ and decreasing on $[e, +\infty)$. Considering only integer points, $f(1)=0$, $f(3)$ is maximal, $f(2)=f(4)$ (because $2^4=4^2=16$), and values in points greater than $4$ are decreasing but always positive. So, the order of $x$ from larger $f(x)$ to smaller $f(x)$ is $3, 2=4, 5, 6, \ldots, +\infty, 1$.
[ "math" ]
1,100
def main(): x, y = map(int, input().split()) if x == y: print('=') return if x == 1: print('<') return if y == 1: print('>') return if x + y == 6: print('=') return if x == 3: print('>') return if y == 3: print('<') return if x < y: print('>') else: print('<') main()
987
C
Three displays
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent such three displays with indices $i < j < k$ that the font size increases if you move along the road in a particular direction. Namely, the condition $s_i < s_j < s_k$ should be held. The rent cost is for the $i$-th display is $c_i$. Please determine the smallest cost Maria Stepanovna should pay.
Let's fix $j$. Now we can see that $i$ and $k$ are independent, so we can find best $i$ by iterating over all $i < j$, checking if $s_i < s_j$ holds and choosing the one with smallest $c_i$. Then do the same for $k$. There are $O(n)$ options for $j$, for each of them we will do $O(n)$ operations. Total complexity is $O(n^2)$
[ "brute force", "dp", "implementation" ]
1,400
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif typedef long long ll; typedef pair<int, int> pii; #define mp make_pair const int INF = (int)1e9; const int N = 3222; int n; int ans = INF; int a[N][2]; int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); scanf("%d", &n); for (int k = 0; k < 2; k++) for (int i = 0; i < n; i++) scanf("%d", &a[i][k]); for (int i = 0; i < n; i++) { int b = -1; int cost = a[i][1]; for (int j = 0; j < i; j++) { if (a[j][0] >= a[i][0]) continue; if (b == -1 || a[b][1] > a[j][1]) b = j; } if (b == -1) continue; cost += a[b][1]; b = -1; for (int j = i + 1; j < n; j++) { if (a[j][0] <= a[i][0]) continue; if (b == -1 || a[b][1] > a[j][1]) b = j; } if (b == -1) continue; cost += a[b][1]; ans = min(ans, cost); } if (ans == INF) printf("-1\n"); else printf("%d\n", ans); return 0; }
988
A
Diverse Team
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members \textbf{are distinct}. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.
Let's write our "unique" function. Keep the array of the taken elements $used$. Iterate over all elements in the array $a$ and if the current element is not used ($used[a_i] = false$) then add its index $i$ to the answer and set $used[a_i] := true$. When finished, check the number of distinct values (that is the size of answer array). If it is less than $k$, print "NO". Otherwise print "YES" and output the first $k$ elements of the answer.
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; set<int> el; vector<int> ans; for (int i = 0; i < n; ++i) { int x; cin >> x; if (!el.count(x)) { ans.push_back(i); el.insert(x); } } if (int(ans.size()) < k) { cout << "NO\n"; } else { cout << "YES\n"; for (int i = 0; i < k; ++i) cout << ans[i] + 1 << " "; cout << endl; } return 0; }
988
B
Substrings Sort
You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in such a way that they form $a$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".
Firstly, sort all the strings by their lengths (if there are several strings of the same length, their order does not matter because if the answer is "YES" then all the strings of the same length should be equal). Then for each $i \in [1..n - 1]$ check that $s_i$ is a substring of $s_{i + 1}$. If it doesn't hold for some $i$ then the answer is "NO". Otherwise the answer is "YES" and the sorted array is the correct order of strings.
[ "sortings", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<string> s(n); for (int i = 0; i < n; ++i) cin >> s[i]; sort(s.begin(), s.end(), [&] (const string &s, const string &t) { return s.size() < t.size(); }); for (int i = 0; i < n - 1; ++i) { if (s[i + 1].find(s[i]) == string::npos) { cout << "NO\n"; return 0; } } cout << "YES\n"; for (auto it : s) cout << it << endl; return 0; }
988
C
Equal Sums
You are given $k$ sequences of integers. The length of the $i$-th sequence equals to $n_i$. You have to choose exactly two sequences $i$ and $j$ ($i \ne j$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $i$ (its length will be equal to $n_i - 1$) equals to the sum of the changed sequence $j$ (its length will be equal to $n_j - 1$). Note that it's \textbf{required} to remove exactly one element in each of the two chosen sequences. Assume that the sum of the empty (of the length equals $0$) sequence is $0$.
Let's calculate the array of triples $t$. Triple $t_i = (sum_i, seq_i, el_i)$ means that the sum of the sequence $seq_i$ without the element at position $el_i$ will be equal to $sum_i$. Triples can be easily calculated in a following manner: for each sequence find its sum, then iterate over all its elements and subtract each of them one after another. Now sort array $t$ with the standard compare function. Finally the answer is "YES" if and only if there exist two adjacent elements with equal sums and different sequences (it is very easy to see). So if we find such a pair, then the answer will be "YES", otherwise the answer will be "NO". Time complexity of the solution is $O(\sum\limits_{i = 0}^{k - 1}n_i \cdot \log\sum\limits_{i = 0}^{k - 1}n_i$).
[ "implementation", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int k; cin >> k; vector<pair<int, pair<int, int>>> a; for (int i = 0; i < k; ++i) { int n; cin >> n; vector<int> x(n); for (int j = 0; j < n; ++j) cin >> x[j]; int sum = accumulate(x.begin(), x.end(), 0); for (int j = 0; j < n; ++j) a.push_back(make_pair(sum - x[j], make_pair(i, j))); } stable_sort(a.begin(), a.end()); for (int i = 0; i < int(a.size()) - 1; ++i) { if (a[i].first == a[i + 1].first && (a[i].second.first != a[i + 1].second.first)) { cout << "YES" << endl; cout << a[i + 1].second.first + 1 << " " << a[i + 1].second.second + 1 << endl; cout << a[i].second.first + 1 << " " << a[i].second.second + 1 << endl; return 0; } } cout << "NO\n"; return 0; }
988
D
Points and Powers of Two
There are $n$ distinct points on a coordinate line, the coordinate of $i$-th point equals to $x_i$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size. In other words, you have to choose the maximum possible number of points $x_{i_1}, x_{i_2}, \dots, x_{i_m}$ such that for each pair $x_{i_j}$, $x_{i_k}$ it is true that $|x_{i_j} - x_{i_k}| = 2^d$ where $d$ is some non-negative integer number (not necessarily the same for each pair of points).
Firstly, let's prove that the size of the answer is not greater than $3$. Suppose that the answer equals to $4$. Let $a, b, c, d$ be coordinates of the points in the answer (and $a < b < c < d$). Let $dist(a, b) = 2^k$ and $dist(b, c) = 2^l$. Then $dist(a, c) = dist(a, b) + dist(b, c) = 2^k + 2^l = 2^m$ (because of the condition). It means that $k = l$. Conditions must hold for a triple $b, c, d$ too. Now it is easy to see that if $dist(a, b) = dist(b, c) = dist(c, d) = 2^k$ then $dist(a, d) = dist(a, b) * 3$ that is not a power of two. So the size of the answer is not greater than $3$. Firstly, let's check if the answer is $3$. Iterate over all middle elements of the answer and over all powers of two from $0$ to $30$ inclusively. Let $x_i$ be the middle element of the answer and $j$ - the current power of two. Then if there are elements $x_i - 2^j$ and $x_i + 2^j$ in the array then the answer is $3$. Now check if the answer is $2$. Do the same as in the previous solution, but now we have left point $x_i$ and right point $x_i + 2^j$. If we did not find answer of lengths $3$ or $2$ then print any element of the array. The solution above have time complexity $O(n \cdot \log n \cdot \log 10^9)$ (because of we can check if the element is in the array with some data structure in $O(\log n)$).
[ "brute force", "math" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> x(n); for (int i = 0; i < n; ++i) { cin >> x[i]; } sort(x.begin(), x.end()); vector<int> res = { x[0] }; for (int i = 0; i < n; ++i) { for (int j = 0; j < 31; ++j) { int lx = x[i] - (1 << j); int rx = x[i] + (1 << j); bool isl = binary_search(x.begin(), x.end(), lx); bool isr = binary_search(x.begin(), x.end(), rx); if (isl && isr && int(res.size()) < 3) { res = { lx, x[i], rx }; } if (isl && int(res.size()) < 2) { res = { lx, x[i] }; } if (isr && int(res.size()) < 2) { res = { x[i], rx }; } } } cout << int(res.size()) << endl; for (auto it : res) cout << it << " "; cout << endl; return 0; }
988
E
Divisibility by 25
You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes. In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, \textbf{after each move} the number you have cannot contain any leading zeroes. What is the minimum number of moves you have to make to obtain a number that is divisible by $25$? Print -1 if it is impossible to obtain a number that is divisible by $25$.
Let's iterate over all pairs of digits in the number. Let the first digit in the pair be at position $i$ and the second at position $j$. Let's place these digits to the last two positions in the number. The first greedily goes to the last position and then the second goes to the position next to that. Now the number can contain a leading zero. Find the leftmost non-zero digit and move it to the first position. Then if the current number is divisible by $25$ try to update the answer with the number of swaps. It is easy to show that the number of swaps is minimal in this algorithm. The only difference we can introduce is the number of times digit $i$, digit $j$ and the leftmost non-zero digit swap among themselves. And that is minimized. You can also notice that the order of swaps doesn't matter and you can rearrange them in such a way that no leading zero appears on any step. This solution has time complexity $O(\log^3 n)$. You can also solve this problem with $O(\log n)$ complexity because you have to check only four options of the two last digits ($25$, $50$, $75$, $00$). It is always optimal to choose both rightmost occurrences of the corresponding digits. You can show that even if you are required to swap the chosen ones, there will be no other pair with smaller total amount of moves.
[ "brute force", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; const int INF = 1000 * 1000 * 1000; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif long long n; cin >> n; string s = to_string(n); int ans = INF; int len = s.size(); for (int i = 0; i < len; ++i) { for (int j = 0; j < len; ++j) { if (i == j) continue; string t = s; int cur = 0; for (int k = i; k < len - 1; ++k) { swap(t[k], t[k + 1]); ++cur; } for (int k = j - (j > i); k < len - 2; ++k) { swap(t[k], t[k + 1]); ++cur; } int pos = -1; for (int k = 0; k < len; ++k) { if (t[k] != '0') { pos = k; break; } } for (int k = pos; k > 0; --k) { swap(t[k], t[k - 1]); ++cur; } long long nn = atoll(t.c_str()); if (nn % 25 == 0) ans = min(ans, cur); } } if (ans == INF) ans = -1; cout << ans << endl; return 0; }
988
F
Rain and Umbrellas
Polycarp lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments, the $i$-th segment which is in the rain is represented as $[l_i, r_i]$ ($0 \le l_i < r_i \le a$). There are $m$ umbrellas lying on the line, the $i$-th umbrella is located at point $x_i$ ($0 \le x_i \le a$) and has weight $p_i$. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from $x = 0$ to $x = a$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $x$ to $x + 1$ if a segment $[x, x + 1]$ is in the rain (i.e. if there exists some $i$ such that $l_i \le x$ and $x + 1 \le r_i$). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point $x = 0$ to point $x = a$? If yes, find the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
Any experienced contestant can easily guess that the problem can be solved with dynamic programming. Coordinates are not really large so you can precalculate the array $rain_0, rain_1, \dots, rain_{a -1 }$, where $rain_i$ is a boolean value - $True$ if there exists some segment of rain to cover the segment between positions $i$ and $i + 1$ and $False$ otherwise. This can be done in $O(n \cdot a)$ with the most straightforward algorithm. You can also precalculate another array $umb_0, umb_1, \dots, umb_a$, where $umb_i$ is the index of the umbrella of minimal weight at position $i$ or $-1$ if there is no such umbrella. Now let $dp[i][j]$ be the minimal total fatigue you can take if you are holding umbrella number $j$ on the end of the walk up to position $i$. If $j = 0$ then you hold no umbrella. Initially all the values are $\infty$ and $dp[0][0]$ is $0$. You can either hold your umbrella, drop it or pick up the best one lying there (and drop the current one if any) when going from some position $i$ to $i + 1$. So here are the transitions for these cases: $dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + weight_j)$ if $j > 0$; $dp[i + 1][0] = min(dp[i + 1][0], dp[i][j])$ if $rain[i] = False$; $dp[i + 1][umb_i] = min(dp[i + 1][umb_i], dp[i][j] + weight[umb_i])$ if $umb_i \neq -1$. The answer is equal to $\min\limits_{i = 0}^{m} dp[a][i]$. If it is $\infty$ then there is no answer. So you have $a \cdot m$ states and all the transitions are $O(1)$. Overall complexity: $O(a \cdot (n + m))$. There is also a solution in $O(a \log^2 a)$ with Convex Hull Trick using Li Chao tree. You can probably even achieve $(n + m) \log^2 (n + m)$ with some coordinate compression. Obviously this wasn't required for the problem as the constraints are small enough.
[ "dp" ]
2,100
//#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") //#pragma GCC optimize("unroll-loops") #include <stdio.h> #include <bits/stdc++.h> #define uint unsigned int #define ll long long #define ull unsigned long long #define ld long double #define rep(i, l, r) for (int i = l; i < r; i++) #define repb(i, r, l) for (int i = r; i > l; i--) #define sz(a) (int)a.size() #define fi first #define se second #define mp(a, b) make_pair(a, b) using namespace std; inline void setmin(int &x, int y) { if (y < x) x = y; } inline void setmax(int &x, int y) { if (y > x) x = y; } inline void setmin(ll &x, ll y) { if (y < x) x = y; } inline void setmax(ll &x, ll y) { if (y > x) x = y; } const int N = 2001; const int inf = (int)1e9 + 1; const ll big = (ll)1e18 + 1; const int P = 239; const int MOD = (int)1e9 + 7; const int MOD1 = (int)1e9 + 9; const double eps = 1e-9; const double pi = atan2(0, -1); const int ABC = 26; struct Line { ll k, b; Line() {} Line(ll k, ll b) : k(k), b(b) {} ll val(ll x) { return k * x + b; } }; int cnt_v; Line tree[N * 4]; void build(int n) { cnt_v = 1; while (cnt_v < n) cnt_v <<= 1; rep(i, 0, cnt_v * 2 - 1) tree[i] = Line(0, inf); } void upd(int x, int lx, int rx, int l, int r, Line line) { if (lx >= r || l >= rx) return; else if (lx >= l && rx <= r) { int m = (lx + rx) / 2; if (line.val(m) < tree[x].val(m)) swap(tree[x], line); if (rx - lx == 1) return; if (line.val(lx) < tree[x].val(lx)) upd(x * 2 + 1, lx, (lx + rx) / 2, l, r, line); else upd(x * 2 + 2, (lx + rx) / 2, rx, l, r, line); } else { upd(x * 2 + 1, lx, (lx + rx) / 2, l, r, line); upd(x * 2 + 2, (lx + rx) / 2, rx, l, r, line); } } ll get(ll p) { int x = p + cnt_v - 1; ll res = tree[x].val(p); while (x > 0) { x = (x - 1) / 2; setmin(res, tree[x].val(p)); } return res; } int add[N]; int best[N]; ll dp[N]; int main() { //freopen("a.in", "r", stdin); //freopen("a.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.precision(20); cout << fixed; //ll TL = 0.95 * CLOCKS_PER_SEC; //clock_t time = clock(); int L, n, m; cin >> L >> n >> m; rep(i, 0, n) { int l, r; cin >> l >> r; add[l]++; add[r]--; } rep(i, 1, L + 1) add[i] += add[i - 1]; fill(best, best + L + 1, inf); rep(i, 0, m) { int x, p; cin >> x >> p; setmin(best[x], p); } // dp[i] + best[i] * (j - i) = best[i] * j + (dp[i] - best[i] * i) build(L + 1); fill(dp, dp + L + 1, inf); dp[0] = 0; upd(0, 0, cnt_v, 0 + 1, cnt_v, Line(best[0], dp[0] - best[0] * 0)); rep(i, 1, L + 1) { dp[i] = get(i); if (add[i - 1] == 0) setmin(dp[i], dp[i - 1]); upd(0, 0, cnt_v, i + 1, cnt_v, Line(best[i], dp[i] - best[i] * i)); } cout << (dp[L] != inf ? dp[L] : -1) << "\n"; return 0; }
989
A
A Blend of Springtime
\begin{quote} When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead."What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic. \end{quote} The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty. When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible. You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.
A cell can get its colours from at most three cells: itself and its two neighbouring cells (if they exist). In order to collect all three colours, all these three cells should contain a blossom, and their colours must be pairwise different. Therefore, the answer is "Yes" if and only if there are three consecutive cells containing all three letters. Implement it in any way you like.
[ "implementation", "strings" ]
900
puts gets.codepoints.each_cons(3).any?{|x,y,z|x*y*z==287430}?'Yes':'No'
989
B
A Tide of Riverscape
\begin{quote} Walking along a riverside, Mino silently takes a note of something."Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think I've figured out this one," says Mino with confidence. Doubtfully, Kanno peeks at Mino's records. \end{quote} The records are expressed as a string $s$ of characters '0', '1' and '.', where '0' denotes a low tide, '1' denotes a high tide, and '.' denotes an unknown one (either high or low). You are to help Mino determine whether it's possible that after replacing each '.' independently with '0' or '1', a given integer $p$ is \textbf{not} a period of the resulting string. In case the answer is yes, please also show such a replacement to Mino. In this problem, a positive integer $p$ is considered a period of string $s$, if for all $1 \leq i \leq \lvert s \rvert - p$, the $i$-th and $(i + p)$-th characters of $s$ are the same. Here $\lvert s \rvert$ is the length of $s$.
Our very first observation is that when $p \leq \frac n 2$, the answer can never be "No". Under this case, find any dot $s_i = \texttt{"."}$. At least one of $s_{i-p}$ and $s_{i+p}$ exists because $p \leq \frac n 2$ and $1 \leq i \leq n$. We want to make $s_i$ different from this character. In case this character is $\texttt{"0"}$ or $\texttt{"1"}$, replace the dot the other way round. In case it's a dot, replace the two dots differently with $\texttt{"0"}$ and $\texttt{"1"}$. After that, fill the remaining dots arbitrarily, and we obtain a valid answer. If $p \gt \frac n 2$, we'd like to find a dot with a similiar property. That is, $s_i = \texttt{"."}$, and $s_{i-p}$ or $s_{i+p}$ exists. Go over all dots, try find one, and carry out the same operation as above. If no such dot exists, the answer is "No".
[ "constructive algorithms", "strings" ]
1,200
#include <algorithm> #include <cstdio> static const int MAXN = 2005; static int n, p; static char s[MAXN]; static int dots_ct = 0, dots[MAXN]; int main() { scanf("%d%d%s", &n, &p, s); for (int i = 0; i < n; ++i) if (s[i] == '.') { dots[dots_ct++] = i; s[i] = '0'; } for (int i = 1; i <= (1 << std::min(dots_ct, 19)); ++i) { bool is_period = true; for (int j = 0; j < n - p; ++j) if (s[j] != s[j + p]) { is_period = false; break; } if (!is_period) { puts(s); return 0; } for (int j = 0; j <= __builtin_ctz(i); ++j) s[dots[j]] ^= 1; } puts("No"); return 0; }
989
C
A Mist of Florescence
\begin{quote} As the boat drifts down the river, a wood full of blossoms shows up on the riverfront."I've been here once," Mino exclaims with delight, "it's breathtakingly amazing." "What is it like?" "Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" \end{quote} There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses. The wood can be represented by a rectangular grid of $n$ rows and $m$ columns. In each cell of the grid, there is exactly one type of flowers. According to Mino, the numbers of connected components formed by each kind of flowers are $a$, $b$, $c$ and $d$ respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers. You are to help Kanno depict such a grid of flowers, with $n$ and $m$ arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem. Note that you can choose arbitrary $n$ and $m$ under the constraints below, they are not given in the input.
A picture is worth a thousand words. There are enormous ways to solve this problem. What's yours? Fine-tune your input and parameters, depict your woods here and share with us in the comments! (Remember to clip and scale the image, though. You can surround the image with a spoiler tag to avoid taking up too much space.) Note: in case jscolor doesn't load properly (a pop-up should appear when the colour inputs are clicked on), try refreshing once. Shoutouts to Alexander Golovanov (Golovanov399) for his grid-drawing tool, on which our utility is based!
[ "constructive algorithms", "graphs" ]
1,800
#include <cstdio> #include <cstdlib> #include <algorithm> #include <string> #include <utility> #include <vector> static const int MAXM = 50; int main() { srand(1); int a[4]; scanf("%d%d%d%d", &a[0], &a[1], &a[2], &a[3]); int M = std::max(2, std::min(MAXM, *std::max_element(a, a + 4))); std::vector<std::string> g; for (int k = 0; k < 4; ++k) { int islands = a[(k + 1) % 4] - 1; std::string s(M, 'A' + k); std::vector<std::pair<int, int>> pos; g.push_back(s); for (int x = 0; x < (islands + (M - 2)) / (M - 1); ++x) { for (int i = 0; i < 3; ++i) g.push_back(s); for (int i = (x & 1); i < M - !(x & 1); ++i) pos.push_back({(int)g.size() - 2 - ((i ^ x) & 1), i}); } std::random_shuffle(pos.begin(), pos.end()); for (int i = 0; i < islands; ++i) g[pos[i].first][pos[i].second] = 'A' + (k + 1) % 4; } if (g.size() <= M) { printf("%lu %d\n", g.size(), M); for (int i = 0; i < g.size(); ++i) puts(g[i].c_str()); } else { printf("%d %lu\n", M, g.size()); for (int i = 0; i < M; ++i) { for (int j = 0; j < g.size(); ++j) putchar(g[j][i]); putchar('\n'); } } return 0; }
989
D
A Shade of Moonlight
\begin{quote} Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river."To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can't be better," Mino turns to Kanno. \end{quote} The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$. There are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (\textbf{endpoints excluded}). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$. Furthermore, no pair of clouds intersect initially, that is, for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. With a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction. You are to help Mino count the number of pairs $(i, j)$ ($i < j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs.
There are some ways to play around with formulae of kinematics, but here's an intuitive way. With the concept of relative motion, let's not change the velocities of clouds, but the velocity of the moon instead. Namely, under a wind speed of $w$, consider the moon to be moving at a velocity of $-w$ (seriously). This doesn't affect the relative positions of all objects. Our next insight is to represent the passage of time with a vertical $y$ axis. In this way, a cloud becomes a stripe of width $\frac l {\sqrt 2}$ tilted at $45^\circ$, and the moon becomes a ray passing through the origin arbitrarily chosen above the curve $y = \frac {\lvert x \rvert} {w_\mathrm{max}}$. The diagram for the first sample, where $l = 1$ and $w_\mathrm{max} = 2$. Square-shaped intersections of sky blue stripes denote the intersections of clouds at different moments. The moon's track can be chosen in the range painted light yellow. Now we'd like to count how many squares above the $x$ axis (because of the "future moment" constraint) have positive-area intersections with the yellow range. Since $w_\mathrm{max} \geq 1$, the tilt angle of the curve does not exceed $45^\circ$ in either half-plane. Thus, a square has positive intersection with the range, if and only if its top corner lies strictly inside the range. For a pair of rightwards-moving cloud $u$ and leftwards-moving cloud $v$, their intersection in the diagram has a top corner of $(\frac 1 2 (x_u + x_v + l), \frac 1 2 (x_v - x_u + l))$. One additional constraint is $x_u < x_v$, which is a requirement for the square to be above the $x$ axis. For this point to be inside the allowed range, we need $x_v - x_u + l > \frac {\lvert x_u + x_v + l \rvert} {w_\mathrm{max}}$. Going into two cases where $x_u + x_v + l \geq 0$ and $x_u + x_v + l < 0$ and solving linear inequalities, we get the following necessary and sufficient condition of valid pairs: According to these formulae, go over each leftwards-moving cloud $v$, and find the number of $u$'s with binary search. The overall time complexity is $O(n \log n)$. It's recommended to calculate the fractions with integer floor-division, but... Lucky you.
[ "binary search", "geometry", "math", "sortings", "two pointers" ]
2,500
#include <cstdio> #include <algorithm> #include <vector> static const int MAXN = 1e5 + 3; static const int INF32 = 0x7fffffff; typedef long long int64; static int n, l, w; static int x[MAXN], v[MAXN]; static std::vector<int> pos, neg; inline int div_floor(int64 a, int b) { if (b == 0) return (a > 0 ? +INF32 : -INF32); if (a % b < 0) a -= (b + a % b); return a / b; } int main() { scanf("%d%d%d", &n, &l, &w); for (int i = 0; i < n; ++i) { scanf("%d%d", &x[i], &v[i]); (v[i] == +1 ? pos : neg).push_back(x[i]); } std::sort(pos.begin(), pos.end()); std::sort(neg.begin(), neg.end()); int64 ans = 0; for (int v : neg) { auto barrier = std::lower_bound(pos.begin(), pos.end(), -v - l); int u_max_0 = div_floor((int64)(v + l) * (w + 1) - 1, w - 1), u_max_1 = div_floor((int64)(v + l) * (w - 1) - 1, w + 1); ans += (std::upper_bound(pos.begin(), barrier, u_max_0) - pos.begin()) + (std::upper_bound(barrier, pos.end(), std::min(v, u_max_1)) - barrier); } printf("%lld\n", ans); return 0; }
989
E
A Trance of Nightfall
\begin{quote} The cool breeze blows gently, the flowing water ripples steadily."Flowing and passing like this, the water isn't gone ultimately; Waxing and waning like that, the moon doesn't shrink or grow eventually." "Everything is transient in a way and perennial in another." Kanno doesn't seem to make much sense out of Mino's isolated words, but maybe it's time that they enjoy the gentle breeze and the night sky — the inexhaustible gifts from nature. Gazing into the sky of stars, Kanno indulges in a night's tranquil dreams. \end{quote} There is a set $S$ of $n$ points on a coordinate plane. Kanno starts from a point $P$ that can be chosen on the plane. $P$ is not added to $S$ if it doesn't belong to $S$. Then the following sequence of operations (altogether called a move) is repeated several times, in the given order: - Choose a line $l$ such that it passes through at least two elements in $S$ and passes through Kanno's current position. If there are multiple such lines, one is chosen equiprobably. - Move to one of the points that belong to $S$ and lie on $l$. The destination is chosen equiprobably among all possible ones, including Kanno's current position (if it does belong to $S$). There are $q$ queries each consisting of two integers $(t_i, m_i)$. For each query, you're to help Kanno maximize the probability of the stopping position being the $t_i$-th element in $S$ after $m_i$ moves with a proper selection of $P$, and output this maximum probability. Note that according to rule 1, $P$ should belong to at least one line that passes through at least two points from $S$.
Is this a graph theory problem? Yes. Let's consider a graph $G = (V, E)$, where there is a vertex for each point in $S$ (the terms "vertices" and "points" are used interchangeably hereafter), and an edge $(u, v)$ of weight $w$ whenever $v$ can be reached from $u$ in one move with a probability of $w$. Finding out all the lines, removing duplicates, and building the graph can be done straightforwardly in $O(n^3)$ time. Represent the graph as an adjacency matrix $A$. Now, given a fixed target vertex $t$, we'd like to calculate for each vertex $u$ the probability of reaching $t$ from $u$ after $m$ moves. Let ${f^{(m)}}_u$ be this probability. We can represent $f^{(m)}$ as an $n \times 1$ vector. Obviously $f^{(0)} = (0, \ldots, 0, 1, 0, \ldots, 0)^\mathrm{T}$, where only the $t$-th element is $1$. Here $v^\mathrm{T}$ denotes transpose of $v$. It's not hard to see that ${f^{(m)}}_u = \sum_{(u, v) \in E} A_{u, v} \cdot {f^{(m-1)}}_v$. Thus we can deduce that $f^{(m)} = A \cdot f^{(m-1)}$. By induction, $f^{(m)} = A^m \cdot f^{(0)}$. In this way, for each query $(t, m)$, we can calculate $f^{(m-1)}$ in order to get for each $u$ the probability of reaching $t$ in $m - 1$ steps. You may ask, why $m - 1$? It's because after the first move, the whole process can be determined by Kanno's position; but the first step is up to us to decide. To be more precise, the process, therefore the desired probability, is determined after the $l$ in the first move has been chosen. We should observe that if we select a point from which there are multiple candidates of $l$, we can always select a point on one of the candidates, making it the only candidate without decreasing the whole probability. It's because the average of a set of numbers never exceeds the largest among them. Hence, we've proved that we only need to consider cases where there is only one candidate for $l$, and such cases are always valid. For each $l$, we should calculate the average of ${f^{(m-1)}}_u$ such that the $u$-th point lies on $l$. With $f^{(m-1)}$ calculated, this should take no more than $O(n^2)$ time. Now, one last thing remains: how to calculate $f^{(m-1)}$ quickly? We utilize a trick that a multiplication of an $n \times n$ matrix and an $n \times 1$ vector takes $O(n^2)$ time. With $A^{2^i}$ preprocessed for all non-negative integers $i \leq \log_2 m$ in $O(n^3 \log m)$ time, we can perform $O(\log m)$ matrix-vector multiplications in order to calculate $f^{(m-1)}$ in $O(n^2 \log m)$ time. Overall, the time complexity for the problem is $O((n + q) \cdot n^2 \cdot \log m)$. If anybody is ever too lazy (:P) to do the fast-exponentiation step, setting $m' = \min\{m, 100\}$ and applying $O(m)$ matrix-vector multiplications also work well with the error toleration.
[ "dp", "geometry", "matrices", "probabilities" ]
2,700
#include <cassert> #include <cstdio> #include <algorithm> #include <utility> #include <vector> static const int MAXN = 202; static const int LOGM = 15; static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } struct point { int x, y; point(int x = 0, int y = 0) : x(x), y(y) { } }; struct line { // ax + by + c = 0 int a, b, c; line() : a(0), b(0), c(0) { } line(const point &p, const point &q) : a(p.y - q.y) , b(q.x - p.x) , c(q.y * p.x - q.x * p.y) { int g = gcd(gcd(a, b), c); if (g != 1) { a /= g; b /= g; c /= g; } if (a < 0) { a = -a; b = -b; c = -c; } } inline bool contains(const point &p) { return a * p.x + b * p.y + c == 0; } // For sorting & duplicate removing inline bool operator < (const line &other) const { return a != other.a ? a < other.a : b != other.b ? b < other.b : c < other.c; } inline bool operator == (const line &other) const { return a == other.a && b == other.b && c == other.c; } }; struct mat { static const int N = ::MAXN; int sz; double a[N][N]; mat(int sz = N, int id = 0) : sz(sz) { for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) a[i][j] = (i == j ? id : 0); } inline mat operator * (const mat &other) { assert(other.sz == this->sz); mat ret(sz, 0); for (int i = 0; i < sz; ++i) for (int k = 0; k < sz; ++k) for (int j = 0; j < sz; ++j) ret.a[i][j] += this->a[i][k] * other.a[k][j]; return ret; } inline std::vector<double> operator * (const std::vector<double> &u) { assert(u.size() == this->sz); std::vector<double> v(sz); for (int i = 0; i < sz; ++i) for (int j = 0; j < sz; ++j) v[i] += a[i][j] * u[j]; return v; } }; static int n, q; static point p[MAXN]; static line l[MAXN * MAXN / 2]; // Lists of lines that pass through points static std::vector<int> pl[MAXN]; // Lists of points that lie on lines static std::vector<int> lp[MAXN * MAXN / 2]; static mat A, Ap[LOGM]; int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d%d", &p[i].x, &p[i].y); int l_num = 0; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) l[l_num++] = line(p[i], p[j]); std::sort(l, l + l_num); l_num = std::unique(l, l + l_num) - &l[0]; for (int i = 0; i < n; ++i) for (int j = 0; j < l_num; ++j) if (l[j].contains(p[i])) { pl[i].push_back(j); lp[j].push_back(i); } A = mat(n, 0); for (int i = 0; i < n; ++i) { for (int j : pl[i]) for (int k : lp[j]) A.a[i][k] += 1.0L / (pl[i].size() * lp[j].size()); } Ap[0] = A; for (int i = 1; i < LOGM; ++i) Ap[i] = Ap[i - 1] * Ap[i - 1]; scanf("%d", &q); std::vector<double> u(n); for (int i = 0, t, m; i < q; ++i) { scanf("%d%d", &t, &m); --t; std::fill(u.begin(), u.end(), 0); u[t] = 1.0; for (int j = 0; j < LOGM; ++j) if ((m - 1) & (1 << j)) u = Ap[j] * u; double max = -1.0; for (int j = 0; j < l_num; ++j) { double cur = 0.0; for (int k : lp[j]) cur += u[k]; cur /= lp[j].size(); max = std::max(max, cur); } printf("%.12lf\n", (double)max); } return 0; }
990
A
Commentary Boxes
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation. If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment. Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes. What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?
Notice that you need to check just two numbers: the closest one less or equal to $n$ and the closest one greater than $n$. Distances to them are $(n \mod m)$ and $(m - (n \mod m))$ respectively. Now you should multiply the first result by $b$, the second result by $a$ and compare the products. Overall complexity: $O(1)$.
[ "implementation", "math" ]
1,000
#include <bits/stdc++.h> #define forn(i, n) for(int i = 0; i < int(n); i++) using namespace std; int main() { long long n, m; int a, b; cin >> n >> m >> a >> b; cout << min(n % m * b, (m - n % m) * a) << endl; return 0; }
990
B
Micro-World
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$. The $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \le a_j + K$. The swallow operations go one after another. For example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \underline{101}, 55, 54]$ $\to$ $[101, \underline{53}, 42, 102, 55, 54]$ $\to$ $[\underline{101}, 42, 102, 55, 54]$ $\to$ $[42, 102, 55, \underline{54}]$ $\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish. Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.
It can be proved that the optimal answer equals to a number of bacteria which can't be eaten by any other bacteria. So for each bacteria $i$ you need to check existence of any bacteria $j$ satisfying condition $a_i < a_j \le a_i + K$. There plenty of ways to check this condition. One of them is to sort array $a$ and for each $i$ find minimal $a_j > a_i$ with upper_bound or with two-pointers technique. Or you can use the fact that $a_i \le 10^6$ and build solution around it. Result complexity is $O(n \log{n})$.
[ "greedy", "sortings" ]
1,200
#include<bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 555; int n, k, a[N]; inline bool read() { if(!(cin >> n >> k)) return false; for(int i = 0; i < n; i++) assert(scanf("%d", &a[i]) == 1); return true; } inline void solve() { sort(a, a + n); a[n++] = int(2e9); int ans = 0, u = 0; for(int i = 0; i < n - 1; i++) { while(u < n && a[i] == a[u]) u++; if(a[u] - a[i] > k) ans++; } cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; #endif } return 0; }
990
C
Bracket Sequences Concatenation Problem
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not. You are given $n$ bracket sequences $s_1, s_2, \dots , s_n$. Calculate the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. Operation $+$ means concatenation i.e. "()(" + ")()" = "()()()". If $s_i + s_j$ and $s_j + s_i$ are regular bracket sequences and $i \ne j$, then both pairs $(i, j)$ and $(j, i)$ must be counted in the answer. Also, if $s_i + s_i$ is a regular bracket sequence, the pair $(i, i)$ must be counted in the answer.
Let $f(s)$ be the mirror reflection of the string $s$. For example: $f$("((") = "))", $f$("))(") = ")((", $f$("()") = "()". Let string be good if it does not have a prefix, which have more closing brackets than opening ones. For example, "((", "(())(", "()()" are good, and "())", ")((", "()())" are not. The balance $bal(s)$ of the string $s$ is the difference between number of opening and closing brackets in $s$. For example, $bal$("(()") = 1, $bal$("()") = 0. Let $cnt[x]$ be the number of good strings with a balance $x$. The answer to the problem is $\sum\limits_{s,\ where\ f(s)\ is\ good} cnt [bal(f(s))]$.
[ "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 7; int n; string s[N]; char buf[N]; int cnt[N]; int getBalance(string &s){ int bal = 0; for(int i = 0; i < s.size(); ++i){ if(s[i] == '(') ++bal; else --bal; if(bal < 0) return -1; } return bal; } string rev(string &s){ string revs = s; reverse(revs.begin(), revs.end()); for(int i = 0; i < revs.size(); ++i) if(revs[i] == '(') revs[i] = ')'; else revs[i] = '('; return revs; } int main(){ scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%s", buf); s[i] = buf; } for(int i = 0; i < n; ++i){ int bal = getBalance(s[i]); if(bal != -1) ++cnt[bal]; } long long res = 0; for(int i = 0; i < n; ++i){ s[i] = rev(s[i]); int bal = getBalance(s[i]); if(bal != -1) res += cnt[bal]; } printf("%I64d\n", res); return 0; }
990
D
Graph And Its Complement
Given three numbers $n, a, b$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $a$, and the number of components in its complement is $b$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes. In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices. The adjacency matrix of an undirected graph is a square matrix of size $n$ consisting only of "0" and "1", where $n$ is the number of vertices of the graph and the $i$-th row and the $i$-th column correspond to the $i$-th vertex of the graph. The cell $(i,j)$ of the adjacency matrix contains $1$ if and only if the $i$-th and $j$-th vertices in the graph are connected by an edge. A connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to $X$ violates this rule. The complement or inverse of a graph $G$ is a graph $H$ on the same vertices such that two distinct vertices of $H$ are adjacent if and only if they are not adjacent in $G$.
Let's prove that if $a > 1$, then $b = 1$. Let $G$ be the original graph, and $H$ - the complement of the graph $G$. Let's look at each pair of vertices $(u, v)$. If $u$ and $v$ belong to different components of the graph $G$, then there is an edge between them in the graph $H$. Otherwise, $u$ and $v$ belong to the same component of the graph $G$, but since $G$ has more than one component, there is vertex $x$ in other component of $G$, and there are edges $\{u,x\}$ and $\{v, x\}$ in $H$. That's why, there is a connected path for any pair of vertices $(u, v)$, and the graph $H$ is connected. Similarly, the case $b > 1$ is proved. So, if $min(a, b) > 1$, then the answer is "NO". Otherwise, $min(a, b) = 1$. Consider the case where $b = 1$ (if $b > a$, we can swap $a$ and $b$, and output complement of the constructed graph). To have $a$ components in the graph $G$, it is enough to connect the vertex $1$ with the vertex $2$, the vertex $2$ with the vertex $3$, $\cdots$, the vertex $n - a$ with the vertex $n - a + 1$. A particular cases are the tests $n = 2, a = 1, b = 1$ and $n = 3, a = 1, b = 1$. There is no suitable graph for them.
[ "constructive algorithms", "graphs", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = int(1e3) + 7; int n, a, b; bool mat[N][N]; int main(){ scanf("%d %d %d", &n, &a, &b); if(min(a, b) > 1){ puts("NO"); return 0; } if(a == 1 && b == 1){ if(n == 2 || n == 3){ puts("NO"); return 0; } puts("YES"); for(int i = 1; i < n; ++i) mat[i][i - 1] = mat[i - 1][i] = true; for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j) printf("%c", '0' + mat[i][j]); puts(""); } return 0; } bool x = false; if(a == 1){ swap(a, b); x = true; } for(int i = n - a; i > 0; --i) mat[i][i - 1] = mat[i - 1][i] = true; puts("YES"); for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j) printf("%c", '0' + ((x ^ mat[i][j]) && (i != j))); puts(""); } return 0; }
990
E
Post Lamps
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has $n$ positions to install lamps, they correspond to the integer numbers from $0$ to $n - 1$ on the OX axis. However, some positions are blocked and no post lamp can be placed there. There are post lamps of different types which differ only by their power. When placed in position $x$, post lamp of power $l$ illuminates the segment $[x; x + l]$. The power of each post lamp is always a positive integer number. The post lamp shop provides an infinite amount of lamps of each type from power $1$ to power $k$. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power $l$ cost $a_l$ each. What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power $3$ in position $n - 1$ (even though its illumination zone doesn't completely belong to segment $[0; n]$).
Let's start with learning how to place lamps of fixed power to cover the segment with the minimal number of them. The following greedy strategy works: find the rightmost non-blocked position that is covered by lamps and place lamp there until either everything is covered or rightmost free position is to the left of the last placed lamp. Initially you only consider $0$ to be covered. Function $f(i)$ - the minimal number of post lamps to cover segment $[0; i]$ is clearly monotonous, thus you want to update states as early as possible. Okay, now you iterate over all $l \in [1; k]$ and update the answer with the results multiplied by cost. Now, why will this work fast? You obviously precalculate the rightmost free position for each prefix segment. If there are any free positions to the right of last placed lamp then the rightmost of them will always be the rightmost for the entire prefix segment. Finally, any two consecutive iterations of the algorithm will either move you by $k + 1$ positions or return -1. This can be easily proven by contradiction. Overall complexity: $O(n \cdot \log n)$, as you do about $\frac n l$ steps for each $l$ and that is a common series sum.
[ "brute force", "greedy" ]
2,100
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; const long long INF64 = 1e18; const int N = 1000 * 1000 + 13; int n, m, k; bool pos[N]; int lst[N], s[N], a[N]; int get(int l){ int r = 0, i = -1, res = 0; while (r < n){ if (lst[r] <= i) return INF; i = lst[r]; r = lst[r] + l; ++res; } return res; } int main() { scanf("%d%d%d", &n, &m, &k); forn(i, m) scanf("%d", &s[i]); forn(i, k) scanf("%d", &a[i]); forn(i, n) pos[i] = true; forn(i, m) pos[s[i]] = false; forn(i, n){ if (pos[i]) lst[i] = i; else if (i) lst[i] = lst[i - 1]; else lst[i] = -1; } long long ans = INF64; forn(i, k){ long long t = get(i + 1); if (t != INF) ans = min(ans, a[i] * t); } printf("%lld\n", ans == INF64 ? -1 : ans); return 0; }
990
F
Flow Control
You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$. The only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe will distribute $f_i$ units of water per second from junction $x_i$ to junction $y_i$ (if $f_i$ is negative, then the pipe will distribute $|f_i|$ units of water per second from junction $y_i$ to junction $x_i$). It is allowed to set $f_i$ to any integer from $-2 \cdot 10^9$ to $2 \cdot 10^9$. In order for the system to work properly, there are some constraints: for every $i \in [1, n]$, $i$-th junction has a number $s_i$ associated with it meaning that the difference between incoming and outcoming flow for $i$-th junction must be \textbf{exactly} $s_i$ (if $s_i$ is not negative, then $i$-th junction must receive $s_i$ units of water per second; if it is negative, then $i$-th junction must transfer $|s_i|$ units of water per second to other junctions). Can you choose the integers $f_1$, $f_2$, ..., $f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied?
The answer is "Impossible" if and only if the sum of values is not equal to $0$. Writing some number on edge does not change the total sum and the goal of the problem is to make $0$ in each vertex, thus getting $0$ in total. The algorithm is simple: you get an arbitrary spanning tree (with dfs or dsu), output the difference between sums of values of subtrees (can be calculated with dfs) for edges in this tree and $0$ for the rest of edges. Let's take an arbitrary correct answer. If is has some cycle in graph of edges with non-zero numbers on them, then you can remove it. For example, select any edge on it and subtract the number on it from all the edges of the cycle. This doesn't break the correctness of the answer, as you change both in and out flows for each vertex by the same value. Now that edge has $0$. This way, any answer can be transformed to tree. And for any edge on tree we want to tranfer excess water units from the larger subtree to the smaller. Overall complexity: $O(n + m)$.
[ "dfs and similar", "dp", "greedy", "trees" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; mt19937 rnd(time(NULL)); const int N = 1'000'013; int n, m; pair<int, int> e[N]; int a[N], rk[N]; long long sum[N], ans[N]; int p[N]; int getP(int a){ return (a == p[a] ? a : p[a] = getP(p[a])); } bool merge(int a, int b){ a = getP(a); b = getP(b); if (a == b) return false; if (rk[a] > rk[b]) swap(a, b); p[a] = b; rk[b] += rk[a]; return true; } bool used[N]; vector<int> g[N]; int h[N]; void dfs(int v, int p){ sum[v] = a[v]; for (auto u : g[v]){ if (u != p){ h[u] = h[v] + 1; dfs(u, v); sum[v] += sum[u]; } } } int main() { scanf("%d", &n); forn(i, n) scanf("%d", &a[i]); forn(i, n) p[i] = i, rk[i] = 1; scanf("%d", &m); forn(i, m){ int &v = e[i].first; int &u = e[i].second; scanf("%d%d", &v, &u); --v, --u; if (merge(v, u)){ g[v].push_back(u); g[u].push_back(v); used[i] = true; } } long long tot = 0; forn(i, n) tot += a[i]; if (tot != 0){ puts("Impossible"); return 0; } dfs(0, -1); puts("Possible"); forn(i, m){ if (used[i]){ int v = e[i].first, u = e[i].second; if (h[v] < h[u]) ans[i] = sum[u]; else ans[i] = -sum[v]; } printf("%lld\n", ans[i]); } return 0; }
990
G
GCD Counting
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$. Let's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vertices). For every integer from $1$ to $2 \cdot 10^5$ you have to count the number of pairs $(x, y)$ $(1 \le x \le y \le n)$ such that $g(x, y)$ is equal to this number.
Firstly, for every $i \in [1, 2 \cdot 10^5]$ we can calculate the number of paths such that $g(x, y)$ is divisible by $i$. We can do it as follows: generate all divisors of numbers $a_i$ (numbers not exceeding $2 \cdot 10^5$ have at most $160$ divisors, so this will be fast enough), and then for every $i \in [1, 2 \cdot 10^5]$ analyze the graph containing the vertices that have $i$ as its divisor. Each component of this graph gives us $\frac{k(k + 1)}{2}$ paths (if its size is $k$), and this is the only formula we need to calculate the number of paths where $g(x, y)$ is divisible by $i$ (let this be $h(i)$). How can we get the answer if we know the values of $h(i)$? We can use inclusion-exclusion with Mobius function, for example, to prove that $ans(1) = \sum \limits_{i = 1}^{2 \cdot 10^5} \mu(i) h(i)$; and then if we want to apply the same technique for finding $ans(x)$ with any possible $x$, we could divide all numbers $a_i$ by $x$ and do the same thing. But it might be too slow, so it's better to rewrite this formula as $ans(x) = \sum \limits_{i = 1}^{\lfloor \frac{2 \cdot 10^5}{x} \rfloor} \mu(i) h(xi)$, because we will do exactly the same when dividing all numbers by $x$. In fact, most contestants have written a much easier version of this solution, so this might be a bit too complicated. This problem can also be solved with centroid decomposition.
[ "divide and conquer", "dp", "dsu", "number theory", "trees" ]
2,400
#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; 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 << "["; for(auto &e : v) out << e << ", "; return out << "]"; } const int N = 1000 * 1000 + 555; const int LOGN = 21; int mind[N]; int pw[LOGN][N]; int n, a[N]; vector<int> g[N]; li res[N]; bool gen() { mt19937 rnd(42); n = 200 * 1000; fore(i, 0, n) a[i] = 831600; fore(i, 1, n) { int u = rnd() % i, v = i; g[u].push_back(v); g[v].push_back(u); } return true; } inline bool read() { // return gen(); if(!(cin >> n)) return false; fore(i, 0, n) assert(scanf("%d", &a[i]) == 1); fore(i, 0, n - 1) { int u, v; assert(scanf("%d%d", &u, &v) == 2); u--, v--; g[u].push_back(v); g[v].push_back(u); } return true; } vector<pt> dv[N]; inline int gcd(int a, int b) { int ans = 1; unsigned int u = 0, v = 0; while(u < dv[a].size() && v < dv[b].size()) { if(dv[a][u].x < dv[b][v].x) u++; else if(dv[a][u].x > dv[b][v].x) v++; else { ans *= pw[min(dv[a][u].y, dv[b][v].y)][dv[a][u].x]; u++, v++; } } return ans; } bool used[N]; int sz[N]; void calcSz(int v, int p) { sz[v] = 1; for(int to : g[v]) { if(to == p || used[to]) continue; calcSz(to, v); sz[v] += sz[to]; } } int findC(int v, int p, int all) { for(int to : g[v]) { if(to == p || used[to]) continue; if(sz[to] > all / 2) return findC(to, v, all); } return v; } int u[N], T = 0; int cntD[N]; inline void addDiv(int d, int cnt) { if(u[d] != T) u[d] = T, cntD[d] = 0; cntD[d] += cnt; } int cds[N], szcds; void calcDs(int v, int p, int gc) { gc = gcd(a[v], gc); cds[szcds++] = gc; for(int to : g[v]) { if(to == p || used[to]) continue; calcDs(to, v, gc); } } vector<int> cps, cmx, vmx; void check(int curd, int curg, int pos, int add) { if(pos >= (int)cps.size()) { if(u[curd] == T) res[curg] += cntD[curd] * 1ll * add; return; } fore(st, 0, cmx[pos] + 1) { check(curd, curg, pos + 1, add); curd *= cps[pos]; if(st < vmx[pos]) curg *= cps[pos]; } } pt ops[N]; int szops; int cntDiff[N]; void calc(int v) { calcSz(v, -1); int c = findC(v, -1, sz[v]); used[c] = 1; // cerr << "C = "<< c << endl; cps.resize(dv[a[c]].size()); cmx.resize(cps.size()); vmx.resize(cmx.size()); fore(i, 0, cps.size()) { cps[i] = dv[a[c]][i].x; cmx[i] = dv[a[c]][i].y; } T++; addDiv(a[c], 1); for(int to : g[c]) { if(used[to]) continue; szcds = 0; calcDs(to, c, a[c]); fore(i, 0, szcds) cntDiff[cds[i]]++; szops = 0; fore(j, 0, szcds) { if(cntDiff[cds[j]] == 0) continue; int p = 0, val = cds[j]; fore(i, 0, vmx.size()) { if(p >= (int)dv[val].size() || dv[val][p].x > cps[i]) vmx[i] = 0; else vmx[i] = dv[val][p].y, p++; } check(1, 1, 0, cntDiff[cds[j]]); ops[szops++] = {cds[j], cntDiff[cds[j]]}; cntDiff[cds[j]] = 0; } fore(j, 0, szops) addDiv(ops[j].x, ops[j].y); } for(int to : g[c]) { if(used[to]) continue; calc(to); } } inline void solve() { iota(mind, mind + N, 0); fore(i, 2, N) { if(mind[i] != i) continue; pw[0][i] = 1; fore(st, 1, LOGN) pw[st][i] = pw[st - 1][i] * i; for(li j = i * 1ll * i; j < N; j += i) mind[j] = min(mind[j], i); } fore(i, 2, N) { int val = i; while(mind[val] > 1) { if(dv[i].empty() || dv[i].back().x != mind[val]) dv[i].emplace_back(mind[val], 0); dv[i].back().y++; val /= mind[val]; } } memset(res, 0, sizeof res); T = 0; calc(0); fore(i, 0, n) res[a[i]]++; fore(i, 1, 1000'000 + 1) { if(res[i]) printf("%d %lld\n", i, res[i]); } } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; #endif } return 0; }
991
A
If at first you don't succeed...
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKing — by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group. Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time?
There are 4 groups of students - those who visited only the first restaurant, who visited only the second, who visited both places and who stayed at home. One of the easiest ways to detect all the incorrect situations is to calculate number of students in each group. For the first group it is $A - C$, for the second: $B - C$, for the third: $C$ and for the fourth: $N - A - B + C$. Now we must just to check that there are non-negative numbers in the first three groups and the positive number for the last group. If such conditions are met the answer is the number of students in the fourth group. In general you are recommended to view inclusion-exclusion principle. Moreover the limitations allow to go over all possible numbers of students for each group (except for the third) in $O(N^{3})$ and to check whether such numbers produce a correct solution. If no correct numbers found, just print $- 1$:
[ "implementation" ]
1,000
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint a, b, c, n;\n\tcin >> a >> b >> c >> n;\n\n\tint n1 = a - c;\n\tint n2 = b - c;\n\tint n3 = c;\n\tint n4 = n - n1 - n2 - n3;\n\n\tif (n1 >= 0 && n2 >= 0 && n3 >= 0 && n4 > 0)\n\t\tcout << n4;\n\telse\n\t\tcout << -1;\n}"
991
B
Getting an A
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically  — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — $4.5$ would be rounded up to $5$ (as in example 3), but $4.4$ would be rounded down to $4$. This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than $5$ (maybe even the dreaded $2$). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get $5$ for the course. Of course, Vasya will get $5$ for the lab works he chooses to redo. Help Vasya — calculate the minimum amount of lab works Vasya has to redo.
It is necessary to use the greedy approach: of course Vasya should redo the lowest grades firstly. So we have to sort the values in the ascending order and begin to replace the values by 5 until we get the desired result. In order to check whether the current state is suitable we may calculate the mean value after each iteration ($O(N^{2})$ complexity in total), or just update sum of the grades and calculate the arithmetic mean in $O(1)$ with $O(N)$ total complexity (excluding sorting). For example: Of course, both approaches easily fit TL. Finally, it is recommended to avoid floating-point operations while calculating the mean value.
[ "greedy", "sortings" ]
900
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool check(int sum, int n) {\n\t// integer representation of sum / n >= 4.5\n\treturn sum * 10 >= n * 45;\n}\n\nint main() {\n\tvector<int> v;\n\tint sum = 0;\n\n\tint n;\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\tv.push_back(x);\n\t\tsum += x;\n\t}\n\n\tsort(v.begin(), v.end());\n\tint ans = 0;\n\twhile (!check(sum, n)) {\n\t\tsum += 5 - v[ans];\n\t\tans++;\n\t}\n\n\tcout << ans;\n}"
991
C
Candies
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself. This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies \textbf{remaining} in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\%$ of the candies left in a box, and so on. If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all. Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.
It is easy to check that if for some value $k$ the necessary condition is met (Vasya eats at least half of the candies), then it is met for each integer greater $k$. Let's consider the number of candies remaining at the evening of each day for some selected $k_{1}$ - let $a_{i}$ candies remain at day $i$. If Vasya will use another number $k_{2}$ > $k_{1}$ we will have less candies in the first day: $b_{1}$ < $a_{1}$. So Petya will eat no more candies than in the first case (for $k_{1}$), but in the next day the number of candies will be not greater than in the first case (if $n_{1}$ > $n_{2}$ then $n_{1} - n_{1} / 10 \ge n_{2} - n_{2} / 10$). The same way, including that $k_{2}$ > $k_{1}$ at the evening of the second day we get $b_{2}$ < $a_{2}$ and so on. In general, for each $i$ we have $b_{i}$ < $a_{i}$, so Petya will eat not more candies than in the first case in total. It means that Vasya will eat not less candies than in the first case. So this problem can be solved using the binary search (answer) approach. In order to check whether selected $k$ is applicable it necessary just to implement the process described in the problem statement. Since Petya eats $10%$ of candies, its amount decreases exponentially, so there will be only few days before all the candies will be eaten. In the worst case it is necessary 378 days. Formally the complexity of the solution is $O(log(n)^{2})$. Like in the previous problem it is recommended to avoid floating operations and to use only integer types.
[ "binary search", "implementation" ]
1,500
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool check(long long k, long long n) {\n\tlong long sum = 0;\n\tlong long cur = n;\n\twhile (cur > 0) {\n\t\tlong long o = min(cur, k);\n\t\tsum += o;\n\t\tcur -= o;\n\t\tcur -= cur / 10;\n\t}\n\treturn sum * 2 >= n;\n}\n\nint main() {\n\tlong long n;\n\tcin >> n;\n\n\tlong long l = 1, r = n;\n\tlong long ans = r;\n\twhile (l <= r) {\n\t\tlong long k = (l + r) / 2;\n\t\tif (check(k, n)) {\n\t\t\tans = k;\n\t\t\tr = k - 1;\n\t\t}\n\t\telse\n\t\t\tl = k + 1;\n\t}\n\n\tcout << ans << endl;\n}"
991
D
Bishwock
Bishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states: \begin{center} \begin{verbatim} XX XX .X X. X. .X XX XX \end{verbatim} \end{center} Bishwocks don't attack any squares and can even occupy on the adjacent squares as long as they don't occupy the same square. Vasya has a board with $2\times n$ squares onto which he wants to put some bishwocks. To his dismay, several squares on this board are already occupied by pawns and Vasya can't put bishwocks there. However, pawns also don't attack bishwocks and they can occupy adjacent squares peacefully. Knowing the positions of pawns on the board, help Vasya to determine the maximum amount of bishwocks he can put onto the board so that they wouldn't occupy the same squares and wouldn't occupy squares with pawns.
In this problem we may use the greedy approach. Let's go through columns from left to right. If we are currently considering column $i$ and we may place a figure occupying only cells at columns $i$ and $i + 1$, we have to place this figure. Really if the optimal solution doesn't contain a bishwock at column $i$ then column $i + 1$ may be occupied by at most one bishwock. So we can remove this figure and place it at columns $i$ and $i + 1$, the result will be at least the same. A bit harder question is - how exactly we should place the figure if all 4 cells of columns $i$ and $i + 1$ are empty (in other cases there will be only one way to place a bishwock)? Of course, we should occupy both cells of column $i$. Moreover it does not matter which cell we will occupy at column $i + 1$ in this case. The cells of $i + 1$ may be used only for placing a bishwock in columns $i + 1$,$i + 2$. If column $i + 2$ has at most one empty cell we are unable to place such figure and the remaining empty cells of column $i + 1$ are useless at all. If both cells of column $i + 2$ are empty we may place a bishwock regardless of the position of the remaining empty cell at column $i + 1$. It means that we don't have to place the figures actually - we have to calculate and update number of empty cells in columns. According to the described algorithm we may write such code: Moreover this implementation can be simplified to just two cases: Formally such algorithm may be considered as the dynamic programming. Of course it is not necessary to have a deep understanding of DP to write such implementation and solve the problem. This problem also can be solved by more ''obvious'' DP approach (for example we may consider index of current column and state of the cells of the previous column as a state of DP). In this case the implementation will be a bit more complicated but it won't be necessary to prove described solution.
[ "dp", "greedy" ]
1,500
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tstring s[2];\n\n\tint n = 2;\n\tint m;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s[i];\n\t\tm = s[i].length();\n\t}\n\n\tint ans = 0;\n\tint previous = 0;\n\tfor (int i = 0; i < m; i++) {\n\t\tint current = (s[0][i] == '0') + (s[1][i] == '0');\n\n\t\tif (current == 0)\n\t\t\tprevious = 0;\n\n\t\tif (current == 1) {\n\t\t\tif (previous == 2) {\n\t\t\t\tans++;\n\t\t\t\tprevious = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\tprevious = 1;\n\t\t}\n\n\t\tif (current == 2) {\n\t\t\tif (previous > 0) {\n\t\t\t\tans++;\n\t\t\t\tif (previous == 2)\n\t\t\t\t\tprevious = 1;\n\t\t\t\telse\n\t\t\t\t\tprevious = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\tprevious = 2;\n\t\t}\n\t}\n\n\tcout << ans;\n}"
991
E
Bus Number
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all. In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number $n$. In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too. Given $n$, determine the total number of possible bus number variants.
According to the statement, digits of original bus number form a subset of digits of the number seen by Vasya. It is possible to iterate through all the subsets in $2^{k}$ operations (where $k$ is length of $n$). For each subset we need to check whether it is correct (contains all necessary digits) and transform it to ''normal'' state (sort the digits for example), in order to avoid conflicts with another subsets which differ only at the digits order. We have to keep only unique subsets. Now for each subset of digits we have to calculate amount of corresponding correct bus numbers. It can be calculated in $O(k)$ operations using permutations of multisets formula (see ''Permutations of multisets'' at the article about permutations and multinomial coefficients) $C = k! / (c_{0}! * c_{1}! * ... * c_{9}!)$, where $k$ - total number of digits in the subset and $c_{i}$ - number of digits $i$: Now, we have to subtract amount of bus numbers with leading zeroes from the result for this subset if it contains digit $0$. This can be done in the very same way: if we place digit $0$ at the first position of the number, we have to decrease $k$ by $1$ and decrease $c_{0}$ by 1; the formula described above will calculate amount of ways to place remaining digits of the subset and this number should be subtract from the answer: In total, even with such rough evaluation of complexity and naive implementation we get $O(2^{k} * k)$ operations, where $k \le 19$ - amount of digits in $n$. It is easy to check that the answer doesn't exceed $10^{18}$ so the standard 64-bit integer type will be enough.
[ "brute force", "combinatorics", "math" ]
1,800
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long fact[20];\n\nset<string> was;\nint c0[10];\nint c[10];\n\nvoid split(string s, int *c) {\n\tfor (int i = 0; i < 10; i++)\n\t\tc[i] = 0;\n\tfor (char ch : s)\n\t\tc[ch - 48]++;\n}\n\nlong long getCount() {\n\tlong long ans = fact[accumulate(c, c + 10, 0)];\n\tfor (int i = 0; i < 10; i++)\n\t\tans /= fact[c[i]];\n\treturn ans;\n}\n\nlong long getans(string s) {\n\tsplit(s, c);\n\n\t// check whether the string contains all digits\n\tfor (int i = 0; i < 10; i++)\n\t\tif (c0[i] && !c[i])\n\t\t\treturn 0;\n\n\t// check whether we already processed such string\n\tsort(s.begin(), s.end());\n\tif (was.count(s))\n\t\treturn 0;\n\twas.insert(s);\n\n\tlong long ans = getCount();\n\tif (c[0] > 0) {\n\t\tc[0]--;\n\t\tans -= getCount();\n\t}\n\n\treturn ans;\n}\n\nint main() {\n\tfact[0] = 1;\n\tfor (int i = 1; i < 20; i++)\n\t\tfact[i] = i * fact[i - 1];\n\n\tstring n;\n\tcin >> n;\n\n\tint k = n.length();\n\tsplit(n, c0);\n\n\tlong long ans = 0;\n\tfor (int i = 1; i <= (1 << k); i++) {\n\t\tstring c;\n\t\tfor (int j = 0; j < k; j++)\n\t\t\tif (i & (1 << j))\n\t\t\t\tc += n[j];\n\t\tans += getans(c);\n\t}\n\n\tcout << ans;\n}"
991
F
Concise and clear
Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the number at the first glance. Could it be shortened? For example, instead of 1000000 you could write $10^{6}$, instead of 1000000000  —$10^{9}$, instead of 1000000007 — $10^{9}+7$. Vasya decided that, to be concise, the notation should follow several rules: - the notation should only consist of numbers, operations of addition ("+"), multiplication ("*") and exponentiation ("^"), in particular, the use of braces is forbidden; - the use of several exponentiation operations in a row is forbidden, for example, writing "2^3^4" is unacceptable; - the value of the resulting expression equals to the initial number; - the notation should consist of the minimal amount of symbols. Given $n$, find the equivalent concise notation for it.
All the problem numbers (except for $10^{10}$, which is given in the samples) contain at most 10 digits. It means that we have to use at most 9 digits if we want to find a shorter representation. Notice that the length of sum of two integers is not greater than sum of the lengths of these integers, so in the optimal representation at most one term is a number while other terms are expressions containing * and/or ^. Each expression (not a number) contains at least 3 symbols, so the optimal representation can contain at most 3 terms. The maximal integer that can be represented in such manner is 9^9+9^9+9, but it contains only 9 digits while expressions with 3 terms always contain at least 9 symbols. So we proved that there always exists an optimal representation which is a sum of at most two terms. So there exist only 3 types of representation of the original number: n = a^b n = x+y n = x*y where $x$ and $y$ - some expressions (in the first case $a$ and $b$ are numbers), which doesn't contain +. Moreover in all the cases such expressions should contain at most 7 digits. Let's find for each $x \le n$ a shortest valid representation $m[x]$, containing at most 7 symbols (if it exists and contains less digits than simple number $x$), and for each length $d$ - set of integers $s[d]$ which can be represented by an expression of length $d$. The standard containers (std::map and std::set in C++) are suitable for that: Firstly let's add all expressions a^b, there are about sqrt(n) such expressions. Now lets consider the expressions containing several multipliers. The same way (as for addition) in such representation at most one multiplier is a number. Including that the expression can contain at most 7 digits we have only 2 possible ways: x = a^b*c^d x = a^b*c where $a$, $b$, $c$ and $d$ are some numbers. Lets iterate through $i$ - the length of the representation of the first multiplier and go over all values stored in $s[i]$. The second multiplier can have length at most $d = 7 - i - 1$ and the total number of ways to choose two multipliers will be small enough. The second multiplier should be selected from containers $s[j]$ for length at most $d$ (in the first case), or we should iterate from $1$ to $10^{d}$ (in the second case). After that we will have about $k = 150000$ numbers in $m$ in total: Now lets go back to the representation of the original number. For the first case - a^b - we have already stored such values in $m$. For the cases x+y and x*y we may assume that the length of expression of $x$ is not greater than 4. Now lets iterate through $x$ among found representations of length up to 4, and among integers from 1 to $10^{4}$. For each such $x$ and for each of 2 cases we determine value of $y$ uniquely, and the optimal representation of $y$ is already stored in $m$ or it is just a number. So, for each such $x$ we can find optimal answer for $n$ by at most two addressing to $m$ i.e. in $log(k)$ operations. Finally, the total algorithm complexity is $O((sqrt(n) + k + 10^{4}) * log(k))$.
[ "brute force", "greedy", "implementation", "math" ]
2,700
"#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long n;\nlong long p10[10];\nmap<long long, string> m;\nset<long long> s[10];\n\ntemplate<class T> string toString(T x) {\n\tostringstream sout;\n\tsout << x;\n\treturn sout.str();\n}\n\nint getlen(long long x) {\n\tint ans = 0;\n\twhile (x) {\n\t\tx /= 10;\n\t\tans++;\n\t}\n\treturn max(ans, 1);\n}\n\nstring get(long long x) {\n\tif (m.count(x))\n\t\treturn m[x];\n\treturn toString(x);\n}\n\nvoid relax(long long x, string str) {\n\t// obviously not optimal\n\tif (x > n || str.length() >= getlen(x))\n\t\treturn;\n\n\t// already have better\n\tif (m.count(x) && m[x].length() <= str.length())\n\t\treturn;\n\n\ts[m[x].length()].erase(x);\n\tm[x] = str;\n\ts[str.length()].insert(x);\n}\n\nvoid generatePowers() {\n\tfor (long long x = 2; x * x <= n; x++) {\n\t\tlong long c = x * x;\n\t\tint p = 2;\n\t\twhile (c <= n) {\n\t\t\tstring tmp = toString(x) + \"^\" + toString(p);\n\t\t\trelax(c, tmp);\n\t\t\tc *= x;\n\t\t\tp++;\n\t\t}\n\t}\n}\n\nvoid generatePowerAndPower(int maxlen) {\n\tfor (int i = 1; i <= maxlen; i++)\n\t\tfor (int j = i; i + j + 1 <= maxlen; j++)\n\t\t\tfor (auto x : s[i])\n\t\t\t\tfor (auto y : s[j])\n\t\t\t\t\trelax(x * y, get(x) + \"*\" + get(y));\n}\n\nvoid generateSimpleAndPower(int maxlen) {\n\tfor (int i = 1; i + 2 <= maxlen; i++)\n\t\tfor (long long x = 1; x < p10[maxlen - 1 - i]; x++)\n\t\t\tfor (long long y : s[i])\n\t\t\t\trelax(x * y, toString(x) + \"*\" + get(y));\n}\n\nvoid precalc() {\n\tgeneratePowers();\n\tgeneratePowerAndPower(7);\n\tgenerateSimpleAndPower(7);\n}\n\nstring ans;\nvoid relaxAns(string s) {\n\tif (ans.length() > s.length())\n\t\tans = s;\n}\n\nvoid check2() {\n\tfor (int i = 1; i * 2 + 1 < ans.length(); i++) {\n\t\tfor (long long x = 1; x <= p10[i]; x++) {\n\t\t\trelaxAns(get(n - x) + \"+\" + get(x));\n\t\t\tif (n % x == 0)\n\t\t\t\trelaxAns(get(n / x) + \"*\" + get(x));\n\t\t}\n\t\tfor (auto x : s[i]) {\n\t\t\trelaxAns(get(n - x) + \"+\" + get(x));\n\t\t\tif (n % x == 0)\n\t\t\t\trelaxAns(get(n / x) + \"*\" + get(x));\n\t\t}\n\t}\n}\n\nint main() {\n\tp10[0] = 1;\n\tfor (int i = 1; i < 10; i++)\n\t\tp10[i] = 10 * p10[i - 1];\n\n\tcin >> n;\n\n\tprecalc();\n\tans = get(n);\n\tcheck2();\n\tcout << ans;\n}"
992
A
Nastya and an Array
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: - In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. - When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
Let's notice that after one second we aren't able to decrease the number of distinct non-zero elements in the array more than by 1. It means that we can't make all elements equal to zero faster than after $X$ seconds, where $X$ is the number of distinct elements in the array initially. And let's notice that we are able to make it surely after $X$ second, if we will subtract every second some number which is in the array, so all elements equal this number in the array will have become zero, and the number of distinct non-zero elements will be decreased. So the answer is the number of distinct non-zero elements initially. Complexity is $O(n\cdot l o g(n))$
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; set <int> ms; for (int i = 0; i < n; ++i) { int x; cin >> x; if (x) ms.insert(x); } cout << ms.size() << '\n'; return 0; }
992
B
Nastya Studies Informatics
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well. We define a pair of integers $(a, b)$ good, if $GCD(a, b) = x$ and $LCM(a, b) = y$, where $GCD(a, b)$ denotes the greatest common divisor of $a$ and $b$, and $LCM(a, b)$ denotes the least common multiple of $a$ and $b$. You are given two integers $x$ and $y$. You are to find the number of good pairs of integers $(a, b)$ such that $l ≤ a, b ≤ r$. Note that pairs $(a, b)$ and $(b, a)$ are considered different if $a ≠ b$.
Let's consider some suitable pair $(a,b)$. As $G C D(a,b)=x$, we can present number ${\boldsymbol{Q}}$ as $c\cdot x$, and number ${\boldsymbol{b}}$ as $d\cdot x$, where we know that $c,d\geq1$ and $G C D(c,d)=1$. Let's consider too that from the restriction from the problem $l\leq a,b\leq r$ we surely know the restriction for ${\mathit{\mathbb{C}}}_{-}^{*}$ and $d$, that is $\frac{\iota}{x}\leq c,d\leq\frac{\L_{\L}}{x}$. Let's remember we know that $x\cdot y=a\cdot b$ (because $\textstyle{\bar{\mathbf{Z}}}$ is $G C D(a,b)$, $\mathbf{\mathbf{y}}$ is $L C M(a,b)$). Then we can get $x\cdot y=c\cdot x\cdot d\cdot x$. Dividing by $\textstyle{\bar{\mathbf{Z}}}$: $y=c\cdot d\cdot x$. $\textstyle{\frac{\nu}{x}}=c\cdot d\,$. Now if $y\forall_{c x}\neq0$, answer equals 0. Else as $\frac{y}{x}$ is surely less than $10^{9}$, we can just sort out all possible pairs $(c,d)$ of divisors $\frac{y}{x}$, such that $c\cdot d={\frac{\nu}{x}}$ , and then to check that $G C D(c,d)=1$ and $c.d$ are in the getting above restrictions. Complexity of this solution is $O({\sqrt{y}})$.
[ "math", "number theory" ]
1,600
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int l, r, x, y; cin >> l >> r >> x >> y; if (y % x != 0){ cout << 0 << '\n'; return 0; } int ans = 0; int n = y / x; for (int d = 1; d * d <= n; ++d) { if (n % d == 0) { int c = n / d; if (l <= c * x && c * x <= r && l <= d * x && d * x <= r && gcd(c, d) == 1) { if (d * d == n) ++ans; else ans += 2; } } } cout << ans << '\n'; return 0; }
992
C
Nastya and a Wardrobe
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month). Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the $50%$ probability. It happens every month except the last one in the year. Nastya owns $x$ dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for $k + 1$ months. Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo $10^{9} + 7$, because it is easy to see that it is always integer.
Let's present we have initially $X=Y+{\frac{1}{2}}$ dresses. What does occur in the first month? Initially the number of dresses is multiplied by 2, that is becomes $2\cdot Y+1$. Then with probability $\mathbf{z}=\mathbf{z}(\mathbf{z})^{(y)}{\mathcal{V}}$ the wardrobe eats a dress, that is expected value of the number of dresses becomes $2\cdot Y+{\frac{1}{2}}$. The same way after the second month expected value becomes $\textstyle1\cdot Y+{\frac{1}{2}}$. It's easy to notice that after $D\!\!\!\!/$-th month(if $p\leq k$) expected value equals $2^{p}\cdot Y+{\frac{1}{2}}$. Eventually it will be only doubled(as the wardrobe doesn't eat a dress in the last month), that is will be equal $2^{k+1}\cdot Y+1$. Thus, answer of the problem is $2^{k+1}\cdot Y+1$. Expressing it with $X$, we get: $\boldsymbol{M}$ = $2^{k+1}\cdot(X-{\frac{1}{2}})+1$. $\boldsymbol{M}$ = $2^{k+1}\cdot X-2^{k}+1$. Thus, we need to calculate degree of 2 right up to $10^{18}$. Complexity of the soltion is $O(l o g(k))$. Let's notice that the case $x=0$ we need to calculate separately, because wardrobe can't eat a dress when it doesn't exist. If $x>0$ it's easy to proof that the number of dresses is never negative, that is the formula works.
[ "math" ]
1,600
#include <bits/stdc++.h> using namespace std; #define int long long const int MOD = 1000 * 1000 * 1000 + 7; int mod(int n) { return (n % MOD + MOD) % MOD; } int fp(int a, int b) { if (b == 0) return 1; int t = fp(a, b / 2); if (b % 2 == 0) return mod(t * t); else return mod(mod(t * t) * a); } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int x, k; cin >> x >> k; if (x == 0) { cout << "0\n"; return 0; } if (k == 0) cout << mod(2 * x) << '\n'; else { int a = mod(2 * x - 1); cout << mod(2 * a * fp(2, k - 1) + 1) << '\n'; } return 0; }
992
D
Nastya and a Game
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that $\overset{p}{s}=k$, where $p$ is the product of all integers on the given array, $s$ is their sum, and $k$ is a given constant for all subsegments. Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Let's call numbers which are more than 1 as good. Notice the following fact: If a subsegment is suitable, it contains not more than 60 good numbers. Indeed, let's assume that a subsegment contains more than 60 good numbers. In this subsegment $p\geq2^{61}>2\cdot10^{18}$. At the same time, as $k\leq10^{5}$, and $s\leq n\cdot10^{8}=2\cdot10^{15}$, there is $s\cdot k\leq2\cdot10^{18}$. Therefore, this subsegment can't be suitable due to $s\cdot k<p$. Let's keep all positions of good numbers in a sorted array. We sort out possible left border of a subsegment and then with binary search we find the next good number to the right of this left border. Then let's iterate from this found number to the right by the good numbers(that is we sort out the rightmost good number in a subsegment), until product of all numbers in the subsegment becomes more than $2\cdot10^{18}$ (it's flag which shows us, that product is too big for a suitable subsgment and we need to finish to iterate). We have shown above the number of iterations isn't more than 60. Now for sorted out the left border and the rightmost good number we only need to know the number of 1's which needs to be added to the right of the rightmost good number, as we can easily maintain sum and product in the subsegment during iterating. Then we need to check whether found number of 1's exists to the right of the rightmost good number. It can be checked if we look at the next good number's position. Complexity is $O(n\cdot l o g(10^{18}))$. In order to check that $a\cdot b$ is more than $2\cdot10^{18}$, you shouldn't calculate ${\boldsymbol{Q}}$ multiply by ${\boldsymbol{b}}$, due to overflow. You must only check that ${\frac{210^{18}}{a}}\geq b$. (Idea of the problem - DmitryGrigorev)
[ "brute force", "implementation", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; #define int long long const int MAXN = 2e5 + 7; const int INF = 1e18 + 2007; int a[MAXN]; int go[MAXN]; signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; for (int i = 0; i < n; ++i) cin >> a[i]; go[n - 1] = n; for (int i = n - 2; i >= 0; --i) { if (a[i + 1] != 1) go[i] = i + 1; else go[i] = go[i + 1]; } int ans = 0; for (int l = 0; l < n; ++l) { int r = l; ans += (k == 1); int f = a[l]; int s = a[l]; while (go[r] != n && a[go[r]] <= (INF / f)) { f *= a[go[r]]; s += go[r] - r - 1 + a[go[r]]; r = go[r]; int want = -1; if (f % k == 0) want = f / k; int have = go[r] - r - 1; ans += (s <= want && want <= s + have); } } cout << ans << '\n'; return 0; }
992
E
Nastya and King-Shamans
Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were $n$ shamans in total enumerated with integers from $1$ to $n$ in the order they lived. Also, each shaman had a magic power which can now be expressed as an integer. The chronicle includes a list of powers of the $n$ shamans. Also, some shamans can be king-shamans, if they gathered all the power of their predecessors, i.e. their power is exactly the sum of powers of all previous shamans. Nastya is interested in whether there was at least one king-shaman in Byteland. Unfortunately many of the powers are unreadable in the list, so Nastya is doing the following: - Initially she supposes some power for each shaman. - After that she changes the power of some shaman $q$ times (the shamans can differ) and after that wants to check if there is at least one king-shaman in the list. If yes, she wants to know the index of any king-shaman. Unfortunately the list is too large and Nastya wants you to help her.
This problem was inspired by idea which was offered by my unbelievable girlfriend :) Solution I In this problem we maintain two segment trees - with maximum and with sum. After every query we recalculate these trees in $O(l o g N)$ for a query. Now we only have to understand, how to answer for a query? Let's call a prefix of the array as good in the case if we surely know that it doesn't contain a king-shaman. So either the first shaman is king and we are able to answer for the query, or we call the prefix with length 1 as good. Then let's repeat the following operation: We call $p_{i}$ as sum in the good prefix now. We find it using the segment tree with sums. We find the leftmost element which may be king-shaman yet. We can realise that it's the leftmost element, which doesn't lie in the good prefix (as there isn't king-shaman according the definition), which have a value at least $p_{i}$. It can be done using segment tree with maximums, with descent. We check if this found shaman is king. If isn't, we can say that the good prefix finishes in this shaman now, because it was the leftmost shaman who might be king. Every operation works in $O(l o g N)$. Let's notice, that one operation increases sum in the good prefix at least by two times. So, after $O(l o g M a x(A_{i}))$ operations sum in the good prefix will become more than a maximal possible number in the array, so that we will be able to finish, because we will be sure that answer will be -1. Complexity of the solution is $O(N\cdot l o g N\times l o g M a x(a_{i}))$. Solution II Let $p_{i}$ be the prefix sums of $a$. We're gonna introduce $f_{i} = p_{i} - 2 \cdot a_{i}$ and reformulate the queries using these new terms. Imagine we wanna change the value at $j$ to $val$. Let $ \delta = val - a_{j}$. Then $f_{j}$ will decrease by $ \delta $ whereas $f_{i > j}$ will increase by $ \delta $. Imagine we wanna find the answer. Then it's sufficient to find any $i$ satisfying $f_{i} = 0$. Split $f$ into blocks of size $M$. Each block will be comprised of pairs $(f_{i}, i)$ sorted by $f$. At the same time we will maintain $overhead$ array responsible for lazy additions to blocks. How does this help? Let $b = j / M$. The goal is to find the position of $j$, decrease its value and increase values for all $i > j$ within this block. It can be done in a smart way in $O(M)$ (actually, this can be represented as merging sorted vectors). You should also take care of the tail, i.e add $ \delta $ to $overhead_{j > b}$ in $O(n / M)$ time. We're asked to find such $i$ that $f_{i} + overhead_{j / M} = 0$. All blocks are sorted, thus we can simply apply binary search in $O((n/M)\cdot\log M)$ overall. The optimal assignment is $M={\sqrt{n\log n}}$ which results into $O(q{\sqrt{n\log n}})$ total runtime. The huge advantage of this approach is its independency from constraints on $a$ (i.e non-negativity). Although we didn't succeed in squeezing this into TL :) Solution III Group the numbers according to their highest bits (with groups of the form $[2^{k}... 2^{k + 1}]$ and separately for zeros). Inside each groups (no more than $\log10^{9}$ of them) we maintain elements in increasing order of indexes. It's easy to see that each group contains no more than two candidates for answer (since their sum is guaranteed to be greater than any of the remaining ones). This observation leads to an easy solution in $O(q\log n\log10^{9})$ - we iterate over groups and check prefix sums for these candidates. There's actually further space for optimizations. Let's maintain prefix sums for our candidates - this allows us to get rid of the extra log when quering the tree. Almost everything we need at this step is to somehow process additions and deletions - change the order inside two blocks and probably recalculate prefix sums. The only thing left is to stay aware of prefix sum changes for the remaining blocks. Luckily, they can be fixed in $O(1)$ per block (if $i > j$ then the sum increases by $val - a_{j}$ and stays the same otherwise). The resulting comlexity is $O(q\cdot(\log10^{9}+\log n))$.
[ "binary search", "data structures" ]
2,500
#include <iostream> #include <cstdio> #include <vector> #include <set> template <class T> class FenwickTree { public: void init(int n) { this->n = n; bit.assign(n + 1, 0); } void init(const std::vector<T> &a) { n = a.size(); bit.assign(n + 1, 0); for(int i = 1; i <= n; i++) { bit[i] += a[i - 1]; if(i + (i & -i) <= n) { bit[i + (i & -i)] += bit[i]; } } } T qry(int x) { x = std::min(x, (int)bit.size() - 1); T ans = 0; for(; x > 0; x -= x & -x) { ans += bit[x]; } return ans; } void upd(int x, T v) { if(x <= 0) return; for(; x <= n; x += x & -x) { bit[x] += v; } } private: int n; std::vector<T> bit; }; int getGroup(int x) { return x == 0 ? 0 : 1 + getGroup(x / 2); } int main() { //std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); int n, q; std::cin >> n >> q; std::vector<long long> base(n); const int me = 33; std::set<int> groups[me]; int cands[me][2]; long long sum[me][2]; for(int i = 0; i < n; i++) { //std::cin >> base[i]; scanf("%lld", &base[i]); groups[getGroup(base[i])].insert(i); } FenwickTree<long long> tree; auto reconstruct = [&](int idx) { int i = 0; for(auto it = groups[idx].begin(); i < std::min(2, (int)groups[idx].size()); i++, it++) { cands[idx][i] = *it; sum[idx][i] = tree.qry(*it); } }; auto getAnswer = [&](int idx) { for(int i = 0; i < std::min(2, (int)groups[idx].size()); i++) { if(base[cands[idx][i]] == sum[idx][i]) { return cands[idx][i] + 1; } } return -1; }; tree.init(base); for(int i = 0; i < me; i++) { reconstruct(i); } while(q--) { int pos, v; //std::cin >> pos >> v; scanf("%d %d", &pos, &v); pos--; int diff = v - base[pos]; int a = getGroup(base[pos]); int b = getGroup(v); groups[a].erase(pos); base[pos] = v; groups[b].insert(pos); for(int i = 0; i < me; i++) { for(int j = 0; j < std::min(2, (int)groups[i].size()); j++) { if(pos < cands[i][j]) { sum[i][j] += diff; } } } tree.upd(pos + 1, diff); reconstruct(a); reconstruct(b); int ans = -1; for(int i = 0; i < me && ans == -1; i++) { ans = getAnswer(i); } printf("%d\n", ans); } }
993
A
Two Squares
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
It can be shown that if two squares intersect, then at least for one of the squares it is true that either one of its corners lies within the other square, or its center lies within the other square. It is very easy to check if any corner or the center of the square rotated by 45 degrees lies within the square with sides parallel to the axes. To check in the opposite directions in a similarly simple fashion, it is enough to rotate both squares by 45 degrees. To turn both squares by 45 degrees (with some scaling, which is OK) it is sufficient to replace each $x$ coordinate with $x + y$ and each $y$ coordinate with $x - y$.
[ "geometry", "implementation" ]
1,600
null
993
B
Open Communication
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers. Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.
One way to approach this problem is to 1. Iterate over each pair $p1$ communicated by the first participant, and do the following: Iterate over all pairs $p2$ of the second participant that are not equal to $p1$ and count whether the first number of $p1$ appears in any of them and whether the second number of $p1$ appears in any of them. If only one of them appears, that number is a candidate to be the matching number. If after iterating over all pairs communicated by the first participant only one candidate number was observed, then we know with certainty that that number is the one, and can immediately return it. 2. Do (1) but iterating over the numbers communicated by the second participant in the outer loop. 3. If at this point no number was returned, the answer is either -1 or 0. It is -1 iff for some pair $(a,b)$ communicated by one of the participants, there are both pairs $(a, c)$ and $(b, d)$ among pairs communicated by the other participants, such that $c \ne b$ and $d \ne a$ (but possibly $c = d$), since in that case if the first participant indeed has the pair $(a, b)$, they can't tell whether the actual number is $a$ or $b$. Otherwise the answer is 0.
[ "bitmasks", "brute force" ]
1,900
null
993
C
Careful Maneuvering
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $-100$, while the second group is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $100$. Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $x=0$ (with not necessarily integer $y$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
One way to solve the problem is to fix one spaceship in the left half and one spaceship in the right half, and assume that they shoot each other by the means of shooting towards one of the small spaceships. This gives us a coordinate of one small spaceship. Once we have it, iterate over all the large spaceships, mark those that are already shot. Now all that is left is to find the best place to position the second spaceship. To do that, create a map from a coordinate to number of unmarked spaceships that would be destroyed if the second small spaceship is at that coordinate. Iterate over each unique spaceship coordinate on the left and each unique spaceship coordinate on the right, and increment the value in the map that corresponds to the position of the second small spaceship that would result in those two large spaceships shooting each other down by the number of large unmarked spaceships at the fixed coordinates. Then update the final answer with the largest value in the map plus the number of marked spaceships and move to the next pair of spaceships in the outer loop. This is a $O((n \times m) ^ 2)$ solution.
[ "bitmasks", "brute force", "geometry" ]
2,100
null
993
D
Compute Power
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned. If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible. Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.
First observe that if for some threshold there's a way to assign tasks in a way that they will finish computation, it is also possible for all higher thresholds. Because of that, we can use binary search to find the threshold. Now the problem is reduced to figuring out if for a given threshold the tasks can be assigned in a way that the system doesn't blow up too early. For that, observe that if the average power per processor exceeds a given threshold, it also means that the average power exceeds the threshold multiplied by the number of processors, which in turn means that the average power minus threshold multiplied by the number of processors exceeds 0. By regrouping summands, we can associate the value $(power - threshold * num_of_processors)$ to each task, and reduce the problem to finding the mapping of tasks to computers that minimizes the sum of values of all the tasks assigned as the first task, and compare it to zero. To do that, we can use sort the tasks by the power value in decreasing order and use dynamic programming. The dimensions are: $i$: The current task considered $j$: How many tasks that use strictly more power than the $i - 1$st task are assigned as the first task to some computer that doesn't have a second task yet. $k$: How many tasks that use exactly as much power as the $i - 1$st task are assigned as the first task to some computer that doesn't have a second task yet. Transitions involve either assigning the task as a first task to some computer that has no tasks yet (increasing $k$, increasing the value by the value of the $i$-th task) or assigning the task to some computer that has a first task (decreasing $j$, not changing the value). Whenever $i$-th task's power differs from $i - 1$st task, $j$ increases by $k$, and $k$ becomes equal to zero. The minimal sum of task values is then equal to the minimum of $dp[n][j][k]$ over all $j, k$. Update the state of the binary search depending on whether the minimal sum is greater than zero or not. Note that this is $O(n^{3}) \times log(precision)$. As an exercise, find a solution that is $O(n^{2}) \times log(precision)$
[ "binary search", "dp", "greedy" ]
2,500
null
993
E
Nikita and Order Statistics
Nikita likes tasks on order statistics, for example, he can easily find the $k$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $x$ is the $k$-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly $k$ numbers of this segment which are less than $x$. Nikita wants to get answer for this question for each $k$ from $0$ to $n$, where $n$ is the size of the array.
First, we can find amount of numbers that less than $x$ for each prefix of $a$ (including empty prefix). We get array $s$ of this values. You can see that for each $i,j, i < j$ the truth that $s[i] \leq s[j]$ and if $s[i]<s[j]$ then $i<j$. Let's count array $r$ such that $r[i]$ is number of occurences $i$ in $s$. Then answer for each $d$ from $1$ to $k$ answer $ans[d]$ is $\sum_{i,j,i-j=d} r[i] \cdot r[j]$. Let's create array $v$, $v[i]=r[n-i]$. If $p = r \times v$ then $p[n+d]=\sum_{i,h,i+h=n+d} r[i] \cdot v[h] =\sum_{i,j,i+n-j=n+d} r[i] \cdot r[j] = \sum_{i,j,i-j=d} r[i] \cdot r[j]= ans[d]$. Multiplication $r$ and $v$ can be done by FFT. You should write it accuracy or use extended floating point types because values in $p$ can reach $10^{10}$. Also you can use NTT by two modules and Chinese Remainder Theorem. Case $k=0$ should be processed separately because of if $s[i] \leq s[j]$ it's not true that $i<j$. We can get answer easily by using set or array of labels. Time complexity is $O(n \cdot \log (n))$.
[ "chinese remainder theorem", "fft", "math" ]
2,300
null
993
F
The Moral Dilemma
Hibiki and Dita are in love with each other, but belong to communities that are in a long lasting conflict. Hibiki is deeply concerned with the state of affairs, and wants to figure out if his relationship with Dita is an act of love or an act of treason. Hibiki prepared several binary features his decision will depend on, and built a three layer logical circuit on top of them, each layer consisting of one or more logic gates. Each gate in the circuit is either "or", "and", "nor" (not or) or "nand" (not and). Each gate in the first layer is connected to exactly two features. Each gate in the second layer is connected to exactly two gates in the first layer. The third layer has only one "or" gate, which is connected to all the gates in the second layer (in other words, the entire circuit produces 1 if and only if at least one gate in the second layer produces 1). The problem is, Hibiki knows very well that when the person is in love, his ability to think logically degrades drastically. In particular, it is well known that when a person in love evaluates a logical circuit in his mind, every gate evaluates to a value that is the opposite of what it was supposed to evaluate to. For example, "or" gates return 1 if and only if both inputs are zero, "t{nand}" gates produce 1 if and only if both inputs are one etc. In particular, the "or" gate in the last layer also produces opposite results, and as such if Hibiki is in love, the entire circuit produces 1 if and only if all the gates on the second layer produced 0. Hibiki can’t allow love to affect his decision. He wants to know what is the smallest number of gates that needs to be removed from the second layer so that the output of the circuit for all possible inputs doesn't depend on whether Hibiki is in love or not.
First lets observe that for the original and the inverted circuit to return the same value for each input, for each possible input one of the two conditions must be met: either in the original circuit all the gates in the second layer return 0, or in the inverted circuit all the gates in the second layer return 0. This in turn means, that for each input *each* gate in the second layer must return zero in either original or inverted circuit. Since its output only depends on at most two gates in the first layer, and at most four inputs, we can iterate over all possible configurations of gates in the first layer, gate in the second layer, and connections to the inputs to find all configurations that meet this criteria. All these configurations will share an important property: for a gate to return zero for each input in either the original or inverted circuit, it must either return zero in the original circuit for all inputs, or return zero in the inverted circuit for all inputs. Some of these configurations (e.g. $and(nand(a,b),and(a,b))$) always return 0 in one circuit, and 1 in the opposite circuit. Other configurations (e.g. $and(and(a,b), nor(a,c))$) return 0 in one circuit, and something depending on the input in another, but critically 0 for the case of all inputs equal to 1. For a circuit to meet the condition in the problem, it needs to have gates such that all of them return zero in either original or inverted circuit, and at least one of them to return one in the other circuit. WLOG let's consider the case of all gates returning zero in the original configuration, and at least one returning zero in the inverted configuration. Such circuit has two properties: 1. The circuit only contains the following gates in the second layer: $and(nand(a,b), and(a,b))$, $and(or(a,b), nor(a,b))$, $nor(nand(a,b), and(a,b))$, $nor(or(a,b), nor(a,b))$, $and(and(a,b), nor(a,c))$, $nor(nand(a,b), or(a,b))$. The first four of them in the inverted graph will always return 1, and the last two will return something depending on the input. 2. The circuit contains at least one of the first four gate kinds, and having at least one such gate is sufficient for the circuit to meet the condition from the problem. The latter is easy to show: since each of the first four gate kinds always returns 1 in the inverted mode, having it is sufficient to have at least one gate return 1 in the second layer. To show the former, remember that the last two gates return zero in the inverted mode when all three inputs are ones. It means that no matter how many of last two kinds of gates we have, and no matter how they are wired with the inputs, if all the inputs are equal to 1, all such gates will return 0, and at least one gate of the first four kinds will be necessary to have at least one gate to return 1. From here the solution is trivial: to find the largest subset of the gates in the second layer that would all return 0 in the original circuit, and at least one return 1 in the inverted, we choose the largest set of gates that belong to the abovementioned set, for as long as at least one of them belongs to the first four kinds. If no gate in the second layer belongs to the first four kinds, the desired subset doesn't exist. Solution for the case when the inverted circuit has all gates in the second layer always return zero and original has at least one that returns one is solved similarly.
[]
3,200
null
994
A
Fingerprints
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits. Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.
The problem can be solved by iterating over every number of the sequence, then iterating over the sequence of fingerprints to check if the number corresponds to a key with a fingerprint, resulting in an $O(n \times m)$ solution.
[ "implementation" ]
800
null
994
B
Knights of a Polygonal Table
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins. Now each knight ponders: how many coins he can have if only he kills other knights? You should answer this question for each knight.
Sort the knights by increasing the power. Now we can iterate over an array and greedy store set of $k$ prevous knights with maximum if coins. After handling knight, if set contains less than $k$ elements, we add current knight in set. Else if number of coins from current knight greater than from knight with minimum coins in set, we can replace this knight with current knight. You can store the set in vector, multiset or priority_queue. Be careful with overflowing and corner case $k=0$. Time complexity is $O(n \cdot k)$ or $O(n \cdot \log(k))$.
[ "greedy", "implementation", "sortings" ]
1,400
null
995
A
Tesla
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $4$ rows and $n$ ($n \le 50$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $k$ ($k \le 2n$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. \begin{center} {\small Illustration to the first example.} \end{center} However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $20000$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
First, whenever any cars are directly to their parking spot, we should move them into the correct parking spot. Now, we can view rows $2$ and $3$ as a cycle. In at most $k$ moves, we can spin the entire cycle of cars counterclockwise. By repeating this $2n$ times, each car will have been adjacent to each parking space, and will have had some chance to park. The exception to this rule is when there are no empty spaces in rows $2$ and $3$. In this case, no cars can even make a valid move, so the answer is $-1$. (This requires $k = 2n$ and no cars are initially adjacent to their parking space) This process will can be implemented in $O(nk)$ or $O(n^2)$ time, with at most $2nk + k \le 10100$, which fits below the $20000$ move limit.
[ "constructive algorithms", "implementation" ]
2,100
null
995
B
Suit and Tie
Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic. Help Allen find the minimum number of swaps of \textbf{adjacent} positions he must perform to make it so that each couple occupies adjacent positions in the line.
We describe a greedy algorithm that achieves the minimum number of swaps. If the leftmost person is in pair $a$, swap the other person in pair $a$ left, to the second position. Now the first two people are both in pair $a$, and we repeat the process on the remaining $n-1$ pairs of people recursively. We now prove that this number of swaps is optimal, and we accomplish this by showing that every swap we made is 'necessary'. For two pairs numbered $a$ and $b$, we can consider the number of times people of pair $a$ and $b$ are swapped by our process. There are $3$ possible relative orderings: $a a b b$, $a b a b$, and $a b b a$. In the case $a a b b$, our algorithm will never swap $a$ and $b$. In the case $a b a b$, any correct swap sequence must swap $a$ and $b$ at least once, and our algorithm will swap the second $a$ left of the first $b$ when $a$ is the leftmost person. In the case $a b b a$, any correct swap sequence must swap $a$ and $b$ at least twice, and our algorithm will swap the second $a$ left of both $b$ when $a$ is the leftmost person. Therefore every swap in our greedy algorithm is necessary, so it is optimal. We can directly simulate this algorithm in $O(n^2)$ time. We can also use data structures such as a binary indexed tree, or balanced binary search tree to compute the answer in $O(n \log n)$. (Maybe it can be even done in $O(n)$, anyone?).
[ "greedy", "implementation", "math" ]
1,400
null
995
C
Leaving the Bar
For a vector $\vec{v} = (x, y)$, define $|v| = \sqrt{x^2 + y^2}$. Allen had a bit too much to drink at the bar, which is at the origin. There are $n$ vectors $\vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}$. Allen will make $n$ moves. As Allen's sense of direction is impaired, during the $i$-th move he will either move in the direction $\vec{v_i}$ or $-\vec{v_i}$. In other words, if his position is currently $p = (x, y)$, he will either move to $p + \vec{v_i}$ or $p - \vec{v_i}$. Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $p$ satisfies $|p| \le 1.5 \cdot 10^6$ so that he can stay safe.
We first prove a claim which will help us significantly. The claim is that among any three vectors $\vec{v_1}, \vec{v_2}, \vec{v_3}$ of lengths at most $r$, then some sum $\vec{v_i} + \vec{v_j}$ or difference $\vec{v_i} - \vec{v_j}$ has at length at most $r$. Draw a circle with radius $r$ centered at the origin. If we plot the vectors $\vec{v_1}, \vec{v_2}, \vec{v_3}, -\vec{v_1}, -\vec{v_2},-\vec{v_3}$ from the origin, two of these will lie in the same $60^{\circ}$ sector. Any two points in this sector will have distance at most $r$. Therefore, as long as there are at least $3$ vectors, two of them can be combined and the input constraints will still be satisfied. In the final step, we can combine two vectors of length at most $r$ into one of length at most $\sqrt{2} r$. Implementation can be done in a number of ways: for example, constructing a binary tree with the input vectors as leaves, or maintaining sets of signed vectors and merging small sets to large sets. These approaches can take $O(n)$ or $O(n \log n)$.
[ "brute force", "data structures", "geometry", "greedy", "math", "sortings" ]
2,300
null
995
D
Game
Allen and Bessie are playing a simple number game. They both know a function $f: \{0, 1\}^n \to \mathbb{R}$, i. e. the function takes $n$ binary arguments and returns a real value. At the start of the game, the variables $x_1, x_2, \dots, x_n$ are all set to $-1$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $i$ such that $x_i = -1$ and either setting $x_i \to 0$ or $x_i \to 1$. After $n$ rounds all variables are set, and the game value resolves to $f(x_1, x_2, \dots, x_n)$. Allen wants to maximize the game value, and Bessie wants to minimize it. Your goal is to help Allen and Bessie find the expected game value! They will play $r+1$ times though, so between each game, exactly one value of $f$ changes. In other words, between rounds $i$ and $i+1$ for $1 \le i \le r$, $f(z_1, \dots, z_n) \to g_i$ for some $(z_1, \dots, z_n) \in \{0, 1\}^n$. You are to find the expected game value in the beginning and after each change.
One can show by induction that the expected value of the game is $\mathbb{E}[f] = 2^{-n} \sum_{x \in \{0, 1\}^n} f(x)$. Consider the first turn. For notation, let $v_{i, 0}$ be the expected value of the game when $x_i$ is set to $0$, and let $v_{i, 1}$ be the expected value of the game when $x_i$ is set to $1$. By induction, it is easy to see that $\frac{v_{i, 0} + v_{i, 1}}{2} = \mathbb{E}[f].$ Consider Allen's strategy. If it is Allen's turn, he will set $x_s = t$, where $0 \le s < n, 0 \le t \le 1$ are such that $v_{s, t}$ is maximal. As $\frac{v_{i, 0} + v_{i, 1}}{2} = \mathbb{E}[f]$ for all $i$, it is clear that $v_{s, 1-t}$ is actually minimal among all the $v_{i, j}$. This means that Bessie would have chosen to set $x_s = 1-t$ if it were her turn. Therefore, the expected game value is $\frac{v_{s, t} + v_{s, 1-t}}{2} = \mathbb{E}[f].$
[ "math" ]
2,500
null
995
E
Number Clicker
Allen is playing Number Clicker on his phone. He starts with an integer $u$ on the screen. Every second, he can press one of 3 buttons. - Turn $u \to u+1 \pmod{p}$. - Turn $u \to u+p-1 \pmod{p}$. - Turn $u \to u^{p-2} \pmod{p}$. Allen wants to press at most 200 buttons and end up with $v$ on the screen. Help him!
Our first observation is that the game can be modeled the following way. Construct an undirected graph on $\{0, 1, \dots, p-1\}$ such that $i$ is connected to $i-1, i+1,$ and $i^{p-2} \pmod{p}.$ We want to find a path of length at most 200 between $u$ and $v$ in this graph. Running a BFS will take too long, so we need different techniques. We present two solutions, which both essentially use the fact that the graph is almost "random". This follows from some known number theoretic results on expander graphs (keyword is "Margulis expanders"). Solution 1: Generate $\sqrt{p}$ random paths of length $100$ from vertex $u$. Now, generate random paths from $v$ of length $100$ until some pair of endpoints coincide. By the birthday paradox, assuming that the graph is approximately random, the runtime will be $O(\sqrt{p} \log p).$ Solution 2: We can try running a simultaneous BFS from both directions (starting at $u$ and $v$). When they meet, make that path. If you are careful, it should be possible to cover $\le 10^7$ vertices, which should then run in time. Additionally, our tester found a different solution. It suffices to find a path from $u \to 1$ of length $100.$ The way we do this is: pick a random $x \pmod{p}.$ Now run the Euclidean algorithm on $(ux \pmod{p}, x)$, using operation $2$ for a normal subtraction step, and a $3$ for the flipping the two entries step. It happens to take a few steps in most cases, but we have no proof.
[ "divide and conquer", "graphs", "meet-in-the-middle", "number theory" ]
2,700
null
995
F
Cowmpany Cowmpensation
Allen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires $n-1$ other employees, each of which is assigned a direct superior. If $u$ is a superior of $v$ and $v$ is a superior of $w$ then also $u$ is a superior of $w$. Additionally, there are no $u$ and $v$ such that $u$ is the superior of $v$ and $v$ is the superior of $u$. Allen himself has no superior. Allen is employee number $1$, and the others are employee numbers $2$ through $n$. Finally, Allen must assign salaries to each employee in the company including himself. Due to budget constraints, each employee's salary is an integer between $1$ and $D$. Additionally, no employee can make strictly more than his superior. Help Allen find the number of ways to assign salaries. As this number may be large, output it modulo $10^9 + 7$.
A immediate simple observation is that we can compute the answer in $O(nD)$ with a simple dynamic program. How to speed it up though? To speed it up, we need the following lemma. Lemma 1: For a tree with $n$ vertices, the answer is a polynomial in $D$ of degree at most $n$. We can prove this via induction, and the fact that for any polynomial $p(x)$ of degree $d$, the sum $p(0) + p(1) + \dots + p(n)$ is a polynomial in $n$ of degree $d+1.$ Now the solution is easy: compute the answer for $0 \le D \le n$ and use interpolation to compute the answer for $D > n.$ The complexity is $O(n^2)$ for the initial dp and $O(n)$ for the interpolation step.
[ "combinatorics", "dp", "math", "trees" ]
2,700
null
996
A
Hit the Lottery
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
The problem is to minimize $x_1 + x_2 + x_3 + x_4 + x_5$ given that $x_1 + 5x_2 + 10x_3 + 20x_4 + 100x_5 = n.$ It is pretty simple to see that we can operate greedily: take as many $100$ as we can, then $20$, then $10$, etc. The solutions works because each number in the sequence $1, 5, 10, 20, 100$ is a divisor of the number after it.
[ "dp", "greedy" ]
800
null
996
B
World Cup
Allen wants to enter a fan zone that occupies a round square and has $n$ entrances. There already is a queue of $a_i$ people in front of the $i$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute. Allen uses the following strategy to enter the fan zone: - Initially he stands in the end of the queue in front of the first entrance. - Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.
For gate $k$ (where $1 \le k \le n$) we visit the gate at times $k, k+n, k+2n, \cdots$ Therefore, the earliest Allen could enter from gate $k$ is the time $k + tn$ such that $k + tn \ge a_k.$ Now, for each $k$, compute the minimal integer $b_k = k+tn$ such that $k+tn \ge a_k$. Now, find the integer $k$ with minimum $b_k$ and output $k$.
[ "binary search", "math" ]
1,300
null
997
A
Convert to Ones
You've got a string $a_1, a_2, \dots, a_n$, consisting of zeros and ones. Let's call a sequence of consecutive elements $a_i, a_{i + 1}, \ldots, a_j$ ($1\leq i\leq j\leq n$) a substring of string $a$. You can apply the following operations any number of times: - Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «{01\underline{011}01}» $\to$ «{01\underline{110}01}»); - Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «{01\underline{011}01}» $\to$ «{01\underline{100}01}»). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring. What is the minimum number of coins you need to spend to get a string consisting only of ones?
Let's partite consecutive elements of the same color into groups. For example, we will split <<00011001110>> into <<000>> + <<11>> + <<00>> + <<111>> + <<0>>. Then it is obvious that it is useless to make moves within one group, and then (if we have at least two groups of color $0$) for one move we can reduce by one (and can't reduce by two) the number of segments of color $0$, paying for it either $x$ or $y$ (whatever). Let's consider, for example, if we have a string <<11001100>>, we can flip the segment $[5 \dots 8]$, and turn it into a string <<11000011>>, or, for example, invert the segment $[3 \dots 4]$, turning the string into <<111111111100> (Then the number of color groups $0$ decreased from two to one). But in the end you still need to do at least one inverting of the segment (which will be one at the end). Then let $p$ - number of groups of color $0$. If $p = 0$, the answer is $0$. Otherwise, the answer is $(p-1) \cdot \min(x, y) + y$
[ "brute force", "greedy", "implementation", "math" ]
1,500
null
997
B
Roman Digits
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it. For example, the number XXXV evaluates to $35$ and the number IXI — to $12$. Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $11$, not $9$. One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by \textbf{exactly} $n$ roman digits I, V, X, L.
TL; DR - among all the sequences, select the one, which contains the maximum number of $50$, in case of tie, select one with largest number of $9$. Bruteforce all configurations in such way, that each number is counted only in it's "maximum" configuration. Since the length of sequence is fixed, we can solve problem not for digits $\{1, 5, 10, 50\}$, but for digits $\{0, 4, 9, 49\}$. Let's solve the problem for digits $\{0, 4, 9\}$ first. We have a problem that some numbers have many representations. But this, in fact, is easy to deal with - if we have at least nine digits "4" than we can convert them no some number of "9" digits, and fill the rest with zeroes. In this case, the solution is to bruteforce the number of "4" from $0$ to $min(8, n)$, and then from the remaining digits select any arbitrary number of "9", each such choice leads to an unique number. Let's return to the original problem with $\{0, 4, 9, 49\}$. In this case we can also face the situation, when the number of $49$ can be increased. We need to identify all pairs $(x, y)$ where $x, y \le 50$, such that they can be transformed to other pair $(x', y')$ with detachment of few $49$. We can bruteforce all $x$, $y$, $x'$, $y'$ with four nested for-loops and check, that the sum of first differs from sum of latter by few number of $49$ removed, in such case we mark the pair $(x, y)$ as broken. We can also note, that if some pair is marked as broken, than all "dominating" pairs also marked as broken. When we discovered which pairs are good we can simply: --- Another solution: if you examine the solution above precisely, you will notice that starting some reasonable $n$ (you can easy proof a lowerbound like $50$ or $100$, but it is, in fact, $12$), the function grows linearly. So if $n \le 12$, you count the answer in any stupid way, and otherwise, simply approximate it linearly using $answer(12)$ and $answer(13)$.
[ "brute force", "combinatorics", "dp", "greedy", "math" ]
2,000
null
997
C
Sky Full of Stars
On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game. It is well known that one month on this planet consists of $n^2$ days, so calendars, represented as square matrix $n$ by $n$ are extremely popular. Weather conditions are even more unusual. Due to the unique composition of the atmosphere, when interacting with sunlight, every day sky takes one of three colors: blue, green or red. To play the bingo, you need to observe the sky for one month — after each day, its cell is painted with the color of the sky in that day, that is, blue, green or red. At the end of the month, students examine the calendar. If at least one row or column contains only cells of one color, that month is called lucky. Let's call two colorings of calendar different, if at least one cell has different colors in them. It is easy to see that there are $3^{n \cdot n}$ different colorings. How much of them are lucky? Since this number can be quite large, print it modulo $998244353$.
Let $A_i$ be the set of all colorings, where $i$-th line contains only one color, and $B_i$ be the set of colorings, where $i$-th column contains only one color. This way, you need to calculate $|A_1 \cup A_2 \ldots A_n \cup B_1 \cup B_2 \ldots B_n|$. As usual, we can use inclusion-exclusion formula to reduce the calculation of multiplications to calculation all possible intersections of sets above. More over, due to the obvious symmetry, to calculate the size of intersection of some set of $A_i$ and $B_i$ it is not important to know exact indices - only number of taken $A$-s and number of $B$-s. This way $ans = \sum_{i=0 \ldots n, j=0 \ldots n, i + j > 0} C_n^i C_n^j (-1)^{i + j + 1} f(i, j)$ Where $f(i, j)$ - is the number of colorings, where first $i$ rows and first $j$ columns are onecolored. It turns out, that formula for $f$ differs significantly depending on presence of zero in it's arguments. Let's examine the case where zero is present, the $f(0, k) = 3^k \cdot 3^{n (n - k)}$. Indeed, you should choose one color in each of the first $k$ columns, and the rest should be painted in any way. -- If both arguments are $> 0$, that is, there is at least one one-colored column and at least one-colored row, than we can notice, that all one-colored rows and columns are in fact of one color. This way, $f(i, j) = 3 \cdot 3^{(n - i)(n - j)}$ Since we should first select the globally common color, and then paint all the rest in any way. Summation of all $f$-s gives solution with $\mathcal{O}(n^2)$ or $\mathcal{O}(n^2 \log)$ complexity, depending on implementation. But we need to go faster. -- Let's sum all summands with $i = 0$ or $j = 0$ in a stupid way, in $\mathcal{O}(n)$. Then examine all other summands. We have a formula: $ans = \sum_{i=1}^{n} \sum_{j=1}^{n} C_n^i C_n^j (-1)^{i + j + 1} 3 \cdot 3^{(n - i)(n - j)}$ Let's replace our variables: $i \to n - i$, $j \to n - j$. $ans = 3 \sum_{i=0}^{n - 1} \sum_{j = 0}^{n - 1} C_n^{n - i} C_n^{n - j} (-1)^{n - i + n - j + 1} \cdot 3^{ij}$ Since $C_n^{n - i} = C_n^i$, $(-1)^{2n} = 1$, $(-1)^{-i} = (-1)^{i}$ we have $ans = 3 \sum_{i=0}^{n - 1} \sum_{j = 0}^{n - 1} C_n^i C_n^j (-1)^{i + j + 1} \cdot 3^{ij}$ Note, that $(a + b)^n = \sum_{i = 0}^{n} C_n^i a^i b^{n - i}$. Using this, we can collect all summands for fixed $i$, however with fixed $i$ we have not $n$ summands, but $n - 1$. We can workaround it by adding and removing the missing summand. -- Let's go: $ans = 3 \sum_{i=0}^{n - 1} \sum_{j = 0}^{n - 1} C_n^i C_n^j (-1)^{i + j + 1} \cdot 3^{ij}$ $ans = 3 \sum_{i=0}^{n - 1} C_n^i (-1)^{i+1} \sum_{j = 0}^{n - 1} C_n^j (-1)^{j} \cdot (3^i)^j$ $ans = 3 \sum_{i=0}^{n - 1} C_n^i (-1)^{i+1} \sum_{j = 0}^{n - 1} C_n^j (- 3^i)^j$ $ans = 3 \sum_{i=0}^{n - 1} C_n^i (-1)^{i+1} [(1 + (-3^i))^n - (-3^i)^n]$ -- This formula has only $\mathcal{O}(n)$ summands, and hence can be evaluated fast enough. To calculate powers of number fast, we can use binary pow method.
[ "combinatorics", "math" ]
2,500
null
997
D
Cycles in product
Consider a tree (that is, an undirected connected graph without loops) $T_1$ and a tree $T_2$. Let's define their cartesian product $T_1 \times T_2$ in a following way. Let $V$ be the set of vertices in $T_1$ and $U$ be the set of vertices in $T_2$. Then the set of vertices of graph $T_1 \times T_2$ is $V \times U$, that is, a set of ordered pairs of vertices, where the first vertex in pair is from $V$ and the second — from $U$. Let's draw the following edges: - Between $(v, u_1)$ and $(v, u_2)$ there is an undirected edge, if $u_1$ and $u_2$ are adjacent in $U$. - Similarly, between $(v_1, u)$ and $(v_2, u)$ there is an undirected edge, if $v_1$ and $v_2$ are adjacent in $V$. Please see the notes section for the pictures of products of trees in the sample tests. Let's examine the graph $T_1 \times T_2$. How much cycles (not necessarily simple) of length $k$ it contains? Since this number can be very large, print it modulo $998244353$. The sequence of vertices $w_1$, $w_2$, ..., $w_k$, where $w_i \in V \times U$ called cycle, if any neighboring vertices are adjacent and $w_1$ is adjacent to $w_k$. Cycles that differ only by the cyclic shift or direction of traversal are still considered \textbf{different}.
Consider an arbitrary cycle in a graph product. Due to the definition of the product, the adjacent vertices in the cycle correspond to the transition by the edge either in the first tree or in the second tree. This way, if you write the edges corresponding to one tree in a separate list, you will get a cycle in this tree. Also, if we have a cycle in one tree of length $a$ and a cycle of length $b$ in the second tree, we can make $C_{a+b}^a$ cycles in the product. Thus, the problem is reduced to calculating for each length up to $k$ the number of cycles in each tree separately, and then mixing them into cycles in the product. -- Let's select the centroid $c$ of the tree and count all cycles, which go through it, delete centroid and then recursively count in remaining components. How looks cycle which goes through $c$? We need to start in some vertex $v$, then go to $c$ (not going through $c$ in between), and then go back to $v$, possibly going through $c$. Let's define two dp's: $f[v][k]$ - number of ways to go from $c$ to $v$ by exactly $k$ steps not going through $c$ in between, $g[v][k]$ - number of ways to go from $c$ to $v$, but without previous limitation. This way the answer for $v$ through centroid $c$ in convolution of $f[v]$ and $g[v]$: $ans[i+j] += f[v][i] * g[v][j]$. Case where $v = c$ should be processed separately, in this case we can simply $ans[i] += g[c][i]$. How much time it takes to compute dp? In fact, it is $\mathcal{O}(nk)$, $g[v][i]$ is equal to sum of $g[u][i - 1]$ where $u$ is neighbor of $v$. Since the graph is tree, there are $\mathcal{O}(n)$ neighbors in total and $\mathcal{O}(nk)$ transitions. $f[v]$ is counted the same way, but with removed transitions through $c$. -- The final complextiy is: $\mathcal{O}(n k^2 log(n))$. $\O(\log(n))$ is for centroid decomposition. On one level we need to compute dp $\mathcal{O}(nk)$ and then compute convolution $\mathcal{O}(nk^2)$, so it is $\mathcal{O}(n k^2 log(n))$. Solution can be optimized with fast polynomial multiplication, leading to complexity $\mathcal{O}(n k \log(k) log(n))$, but it wasn't required.
[ "combinatorics", "divide and conquer", "trees" ]
2,900
null
997
E
Good Subsegments
A permutation $p$ of length $n$ is a sequence $p_1, p_2, \ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \leq p_i \leq n$) . Let's call the subsegment $[l,r]$ of the permutation \textbf{good} if all numbers from the minimum on it to the maximum on this subsegment occur among the numbers $p_l, p_{l+1}, \dots, p_r$. For example, good segments of permutation $[1, 3, 2, 5, 4]$ are: - $[1, 1]$, - $[1, 3]$, - $[1, 5]$, - $[2, 2]$, - $[2, 3]$, - $[2, 5]$, - $[3, 3]$, - $[4, 4]$, - $[4, 5]$, - $[5, 5]$. You are given a permutation $p_1, p_2, \ldots, p_n$. You need to answer $q$ queries of the form: find the number of good subsegments of the given segment of permutation. In other words, to answer one query, you need to calculate the number of good subsegments $[x \dots y]$ for some given segment $[l \dots r]$, such that $l \leq x \leq y \leq r$.
Let's look at two solutions for all array, and each of them can be upgraded to subquadratic time for queries on subsegments. First solution is Divide&Conquer. Let's take a middle of the array and find number of segments, that contain it. If minimum and maximum are at one side of middle, then by the end on the half where they are, you can restore the entire segment and check that it is correct (and remember it somewhere). Else let them be on different sides. Then let maximum will be at the right (other case are symmetric and you can solve them similarly), so we need $r - l = \max - \min$, but we already know $r$ and $\max$ , so we can get $r - \max = l - \min$. Then let's partite the elements into equivalence classes, where we broke into classes by $r - \max$ if element on the left and $l - \min$ if element on the right (where the $\max$ and $\min$ is the minimum and maximum on the segment to the middle $m$), then the segment $l \leq m < r$ (where the maximum on the left) is good if and only if when in the interval $[l \dots m]$ there are no numbers less than minimum on the interval $(m, \dots r]$ and the interval $(m, \dots r]$ has no numbers larger than maximum on the interval $[l \dots m]$, and $l$ and $r$ are in the same class. Then, for one segment end, some interval of elements from its class is suitable (these intervals can be selected, for example, by stack or a binary search). Also you need (don't forget it!) to go recursively to the left half and to the right half :) And then you can apply the Mo's algorithm! Let's move the left and right ends, run through the classes where this end lies, and add/subtract from the answer the size of the intersection of the interval of this class that fits this end and the interval of this class that current segment now contains, so this part works for $O(n \sqrt{n} \log {n})$ (but operations are not so heavy, so it is working fast). Also you need to not forget about the segments where the minimum and maximum contained at one side of the middle, they can be processed, for example, by passing with a sweep line with a fenwick tree, this part works in $O(n \log {n})$. So we can upgrade D&C idea to $O(n \sqrt{n} \log {n})$. But let's look at the geometric interpretation of the problem. Let good segments be points $(l, r)$ on the plane! Then the query is just the sum on the rectangle $[1 \dots l] [r \dots n]$. To solve the problem on the whole array, let's move the right end of the query, and for each left we will store $r - l - (\max - \min)$, this can be stored in the segment tree (and you can recalculate it with stacks), and then you can note that values always are $\leq 0$, so you can simply store in the segment tree the maximum and number of maximums, and at each time add this value to the answer. In order to generalize this idea for a complete solution, let's split the field $N \times N$ into squares $K \times K$ (Colors are not important, they are just for convenience). Then let's go with the same sweep line from left to right, but we will store everything not in the segment tree, but in the sqrt decomposition. And we will store for a piece of size $K$ by $y$-coordinate the number of (good segments) points that we have already met in it. So we can cut off from the original query The lower part, leaving a horizontal strip of size $\leq K$. We made it in $O(n \cdot k + n \cdot \frac{n}{k})$. With similar sweep line from top to bottom, and not from left to right, we can cut off the left part, leaving as a query a rectangle with sides $< K$. Then you can create $< K$ events of the form: "Add the sum on the vertical segment to the answer to $i$-th query", and these events can be processed by a sweep line from left to right with the segment tree , so you can solve this part in $O(n \cdot k \cdot \log{n})$. So we can get a solution in $O(n \cdot \frac{n}{k} + n \cdot k \cdot \log{n})$, and choosing $k = \sqrt{\frac{n}{\log{n}}}$ allows to solve the task in $O(n \cdot \sqrt{n \cdot \log{n}})$.
[ "data structures" ]
3,000
null
998
A
Balloons
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons inside. They want to divide the balloons among themselves. In addition, there are several conditions to hold: - Do not rip the packets (both Grigory and Andrew should get unbroken packets); - Distribute all packets (every packet should be given to someone); - Give both Grigory and Andrew at least one packet; - To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.
It is easy to show, that if at least one solution exists, than it is possible to use the answer, which contains only one, minimal, element. Suppose, that this set is not valid. Then one of the following holds: Either $n = 1$, and then there is no solution Or $n = 2$, and other element is equal to minimum, in this case it is ease to see that there are not solution too. Also, the limits were set in such way, that solution which bruteforces all $2^n$ subsets and checks them also passes.
[ "constructive algorithms", "implementation" ]
1,000
null
998
B
Cutting
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers. There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers. Cuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, $[4, 1, 2, 3, 4, 5, 4, 4, 5, 5]$ $\to$ two cuts $\to$ $[4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]$. On each segment the number of even elements should be equal to the number of odd elements. The cost of the cut between $x$ and $y$ numbers is $|x - y|$ bitcoins. Find the maximum possible number of cuts that can be made while spending no more than $B$ bitcoins.
It is possible to proof, that cut after $i$-th number can be done if and only if the prefix of length $i$ contains equal number of odd and even numbers. This way each cut can be done or not done independently of all other cuts (except the budget issue). Why it is true? Let's proof that criterion is sufficient. If you make some set of cuts, where each cut is valid according to criterion above, than the result would be correct - each part of result lies between to cuts, and if prefixes which correspond to cuts have same number of odds-evens, than the part between also will have these numbers equal. Let's show that the condition is required - if there is some set of cuts, which produces correct parts, than each part has same number of odds-evens, and than all prefixes, which correspond to cuts also have the same number of odds-evens. This way each cut can be done independently, so you can identify all valid cuts, order them by cut-price, and take greedy from the beginning of the list while the budget allows.
[ "dp", "greedy", "sortings" ]
1,200
null
999
A
Mishka and Contest
Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list. Mishka cannot solve a problem with difficulty greater than $k$. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by $1$. Mishka stops when he is unable to solve any problem from any end of the list. How many problems can Mishka solve?
You can iterate over all the elements of the array from left to right. Count the number of problems Mishka will solve from the left end of the list and break if he cannot solve the next one. Let's denote the number of problems Mishka will solve from the left end of the list by $\mathit{lf}$. Do the same thing independently from right to left. Denote the number of problems Mishka will solve from the right end of the list by $\mathit{rg}$. Then the answer is $\min(n, \mathit{lf} + \mathit{rg})$. Time complexity - $O(n)$.
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; int ans = 0; while (!a.empty() && a.back() <= k) { ++ans; a.pop_back(); } reverse(a.begin(), a.end()); while (!a.empty() && a.back() <= k) { ++ans; a.pop_back(); } cout << ans << endl; return 0; }
999
B
Reversing Encryption
A string $s$ of length $n$ can be encrypted by the following algorithm: - iterate over all divisors of $n$ in decreasing order (i.e. from $n$ to $1$), - for each divisor $d$, reverse the substring $s[1 \dots d]$ (i.e. the substring which starts at position $1$ and ends at position $d$). For example, the above algorithm applied to the string $s$="codeforces" leads to the following changes: "codeforces" $\to$ "secrofedoc" $\to$ "orcesfedoc" $\to$ "rocesfedoc" $\to$ "rocesfedoc" (obviously, the last reverse operation doesn't change the string because $d=1$). You are given the encrypted string $t$. Your task is to decrypt this string, i.e., to find a string $s$ such that the above algorithm results in string $t$. It can be proven that this string $s$ always exists and is unique.
To solve the problem, we can implement the encryption algorithm with a single change: we have to iterate over all divisors of $n$ in increasing order. Time complexity - $O(n~ \cdot d(n))$, where $d(n)$ is a divisor count function for $n$. For example, $\max\limits_{i = 1}^{10^6}d(i) = 240$.
[ "implementation" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; for (int i = 1; i <= n; ++i) { if (n % i == 0) { reverse(s.begin(), s.begin() + i); } } cout << s << endl; return 0; }
999
C
Alphabetic Removals
You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \le n$) from the string $s$. Polycarp uses the following algorithm $k$ times: - if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; - if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; - ... - remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $k$ times, thus removing exactly $k$ characters. Help Polycarp find the resulting string.
Let the lowercase Latin letters be indexed from $0$ to $25$. There are exists at least two different solutions: If $k = n$ exit the program. Otherwise, count the number of occurrences of each letter $i$ from $0$ to $25$. Let it be $\mathit{cnt}$. Now, find the (alphabetically) smallest letter that will be in the resulting string. It can be done as follows: iterate over all $i$ from $0$ to $25$, and if $\mathit{cnt}_i \le k$ then subtract it from $k$, otherwise, $i$ will be the smallest letter that will be in the resulting string. But we (possibly) need to remove some number of its leftmost occurrences. It is obvious that letters smaller than $i$ will not appear in the resulting string. Also, the $k$ leftmost occurrences of letter $i$ will be removed. Now, let's iterate over all letters in string $s$ from left to right and construct the resulting string $\mathit{res}$. If the current character of $s$ (let it be $s_j$) is smaller than $i$, then do nothing. If $s_j$ is greater than $i$, then add it to $\mathit{res}$. Otherwise $s_j = i$. If $k > 0$, then decrease $k$ by one, otherwise, add $s_j$ to $\mathit{res}$. The time complexity is $O(n)$. Another solution is the following. Let's carry the vector of pairs $(s_i, i)$ where $s_i$ is the $i$-th character of $s$ and $i$ is its position. If we sort this vector with the standard compare function, it is easy to see that the first $k$ elements of this vector will be removed from the input string. Then if we will sort the last $n - k$ elements of this vector by its positions in the input string in increasing order, we will obtain the answer. The time complexity is $O(n \log n)$.
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; string s; cin >> s; vector<pair<char, int>> c(n); for (int i = 0; i < n; ++i) c[i] = make_pair(s[i], i); sort(c.begin(), c.end()); sort(c.begin() + k, c.end(), [&] (const pair<char, int> &a, const pair<char, int> &b) { return a.second < b.second; }); for (int i = k; i < n; ++i) cout << c[i].first; cout << endl; return 0; }
999
D
Equalize the Remainders
You are given an array consisting of $n$ integers $a_1, a_2, \dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$. In a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$. Let's calculate $c_r$ ($0 \le r \le m-1)$ — the number of elements having remainder $r$ when divided by $m$. In other words, for each remainder, let's find the number of corresponding elements in $a$ with that remainder. Your task is to change the array in such a way that $c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}$. Find the minimum number of moves to satisfy the above requirement.
For each $i$ from $0$ to $m - 1$, find all elements of the array that are congruent to $i$ modulo $m$, and store their indices in a list. Also, create a vector called $\mathit{free}$, and let $k$ be $\frac{n}{m}$. We have to cycle from $0$ to $m - 1$ twice. For each $i$ from $0$ to $m - 1$, if there are in list too many (i.e., $> k$) elements congruent to $i$ modulo $m$, remove the extra elements from this list and add them to $\mathit{free}$. If instead there are too few (i.e., $< k$) elements congruent to $i$ modulo $m$, remove the last few elements from the vector $\mathit{free}$. For every removed index $\mathit{idx}$, increase $a_\mathit{idx}$ by $(i - a_\mathit{idx}) \bmod m$. After doing so (after two passes), we print the total increase and the updated array. It is obvious that after the first $m$ iterations, every list will have size at most $k$, and after $m$ more iterations, all lists will have the same sizes. It can be easily proved that this algorithm produces an optimal answer. The time complexity is $O(n + m)$.
[ "data structures", "greedy", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; int k = n / m; vector<int> a(n); vector<vector<int>> val(m); for (int i = 0; i < n; ++i) { cin >> a[i]; val[a[i] % m].push_back(i); } long long ans = 0; vector<pair<int, int>> fre; for (int i = 0; i < 2 * m; ++i) { int cur = i % m; while (int(val[cur].size()) > k) { int elem = val[cur].back(); val[cur].pop_back(); fre.push_back(make_pair(elem, i)); } while (int(val[cur].size()) < k && !fre.empty()) { int elem = fre.back().first; int mmod = fre.back().second; fre.pop_back(); val[cur].push_back(elem); a[elem] += i - mmod; ans += i - mmod; } } cout << ans << endl; for (int i = 0; i < n; ++i) cout << a[i] << " "; cout << endl; return 0; }
999
E
Reachability from the Capital
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way. What is the minimum number of new roads that need to be built to make all the cities reachable from the capital? New roads will also be one-way.
This problem is (almost) equivalent to the following: count the number of sources (the vertices with indegree equal to $0$) in the given graph's condensation. Thus, there exist solutions with complexity $O(n + m)$. However, the constraints in the problem are small, so solutions with complexity $O(n \cdot m)$ also pass. One of these solutions is the following: first, let's mark all the vertices reachable from $s$ as good, using a simple DFS. Then, for each bad vertex $v$, count the number of bad vertices reachable from $v$ (it also can be done by simple DFS). Let this number be $\mathit{cnt}_v$. Now, iterate over all bad vertices in non-increasing order of $\mathit{cnt}_v$. For the current bad vertex $v$, if it is still not marked as good, run a DFS from it, marking all the reachable vertices as good, and increase the answer by $1$ (in fact, we are implicitly adding the edge $(s, v)$). It can be proved that this solution gives an optimal answer.
[ "dfs and similar", "graphs", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 5010; int n, m, s; vector<int> g[N]; vector<int> tg[N]; vector<int> cg[N]; vector<int> ord; int indeg[N]; bool ucomp[N]; bool used[N]; int comp[N]; int cnt; void dfs1(int v) { used[v] = true; for (auto to : g[v]) if (!used[to]) dfs1(to); ord.push_back(v); } void dfs2(int v) { comp[v] = cnt; for (auto to : tg[v]) if (comp[to] == -1) dfs2(to); } void dfs3(int v) { ucomp[v] = true; for (auto to : cg[v]) if (!ucomp[to]) dfs3(to); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n >> m >> s; --s; for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; --x, --y; g[x].push_back(y); tg[y].push_back(x); } for (int i = 0; i < n; ++i) { if (!used[i]) { dfs1(i); } } reverse(ord.begin(), ord.end()); memset(comp, -1, sizeof(comp)); for (int i = 0; i < n; ++i) { if (comp[ord[i]] == -1) { dfs2(ord[i]); ++cnt; } } for (int v = 0; v < n; ++v) { for (auto to : g[v]) { if (comp[v] != comp[to]) { cg[comp[v]].push_back(comp[to]); ++indeg[comp[to]]; } } } dfs3(comp[s]); int ans = 0; for (int i = 0; i < cnt; ++i) if (!ucomp[i] && indeg[i] == 0) ++ans; cout << ans << endl; return 0; }
999
F
Cards and Joy
There are $n$ players sitting at the card table. Each player has a favorite number. The favorite number of the $j$-th player is $f_j$. There are $k \cdot n$ cards on the table. Each card contains a single integer: the $i$-th card contains number $c_i$. Also, you are given a sequence $h_1, h_2, \dots, h_k$. Its meaning will be explained below. The players have to distribute all the cards in such a way that each of them will hold exactly $k$ cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals $h_t$ if the player holds $t$ cards containing his favorite number. If a player gets no cards with his favorite number (i.e., $t=0$), his joy level is $0$. Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence $h_1, \dots, h_k$ is the same for all the players.
It is obvious that we can solve the problem separately for each favorite number because each player has only one favorite number, and if the player gets a card not having his favorite number, his joy will not change. Let $\mathit{dp}[x][y]$ be the maximum possible total joy of $x$ players with the same favorite number (it doesn't matter which one) and $y$ cards (containing their favorite number) if the cards are distributed among the players optimally. Note that $x \in [0, n]$ and $y \in [0, k \cdot n]$. At the beginning, all entries of the $\mathit{dp}$ table are zeroes. The transition in this dynamic programming depends on how many cards the $x$-th player will receive (which is between $0$ and $k$). In other words, the dynamic programming transition will look like: where $h[i]$ is the joy of the player if he receives exactly $i$ cards containing his favorite number. Note that $h[0] = 0$. After filling the $\mathit{dp}$ table, the answer can be calculated very easily: $\mathit{ans} = \sum\limits_{i = 1}^{10^5}\mathit{dp}[f_i][c_i]$, where $f_i$ is the number of players with favorite number $i$ and $c_i$ is the number of cards containing the number $i$. Time complexity is $O(n^2 \cdot k^2)$.
[ "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 520; const int K = 12; const int C = 100 * 1000 + 11; int n, k; int c[C]; int f[C]; vector<int> h; int dp[N][K * N]; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n >> k; h = vector<int>(k + 1); for (int i = 0; i < n * k; ++i) { int x; cin >> x; ++c[x]; } for (int i = 0; i < n; ++i) { int x; cin >> x; ++f[x]; } for (int i = 1; i <= k; ++i) cin >> h[i]; for (int i = 0; i < n; ++i) { for (int j = 0; j <= n * k; ++j) { for (int cur = 0; cur <= k; ++cur) { dp[i + 1][j + cur] = max(dp[i + 1][j + cur], dp[i][j] + h[cur]); } } } int ans = 0; for (int i = 0; i < C; ++i) { if (f[i] != 0) ans += dp[f[i]][c[i]]; } cout << ans << endl; return 0; }
1000
A
Codehorses T-shirts
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from $0$ to $3$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. There are $n$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words. What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one? The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
At first, let's remove all coinciding entries of both lists. The most convinient way is to use map/hashmap but it's not the only option. Now divide entries into categories by their length. You can notice that it takes exactly one second to remove an entry in each category (to make it equal to an entry of the opposing list). Thus the answer is $n - (number~of~coinciding~entries)$. Overall complexity: $O(n \log n)$ or $O(n)$.
[ "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n; cin >> n; vector<string> a(n), b(n); forn(i, n) cin >> a[i]; forn(i, n) cin >> b[i]; map<string, int> cnta, cntb; forn(i, n) ++cnta[a[i]]; forn(i, n) ++cntb[b[i]]; int ans = n; for (auto it : cnta) ans -= min(it.second, cntb[it.first]); cout << ans << endl; return 0; }
1000
B
Light It Up
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp. The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program. The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state. Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can \textbf{insert at most one} element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$. Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.
At first, let's insert $0$ and $M$ in array $a$, so all possible positions for inserting will always belong to $(a_i, a_{i + 1})$. At second, let $x$ be value to insert and $a_i < x < a_{i + 1}$. It can be proven, that it's always optimal to move $x$ to $a_i$ or to $a_{i + 1}$. So, for each $(a_i, a_{i + 1})$ we need to check only $x = a_i + 1$ and $x = a_{i + 1} - 1$. To check it fast enough, we need to know total time of lamp is lit for each prefix and precalculate for each $i$, total time of lamp is lit if starting from $a_i$ light is on / lights is off. Result complexity is $O(n)$.
[ "greedy" ]
1,500
#include<bits/stdc++.h> using namespace std; int n, M; vector<int> a; inline bool read() { if(!(cin >> n >> M)) return false; a.assign(n, 0); for(int i = 0; i < n; i++) scanf("%d", &a[i]); return true; } vector<int> f[2]; inline void solve() { a.insert(a.begin(), 0); a.push_back(M); f[0].assign(a.size(), 0); f[1].assign(a.size(), 0); for(int i = int(a.size()) - 2; i >= 0; i--) { f[0][i] = f[1][i + 1]; f[1][i] = (a[i + 1] - a[i]) + f[0][i + 1]; } int ans = f[1][0]; for(int i = 0; i + 1 < int(a.size()); i++) { if(a[i + 1] - a[i] < 2) continue; int tp = (i & 1) ^ 1; int pSum = f[1][0] - f[tp][i]; ans = max(ans, pSum + (a[i + 1] - a[i] - 1) + f[tp][i + 1]); } cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif if(read()) solve(); return 0; }
1000
C
Covered Points Count
You are given $n$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every $k \in [1..n]$, calculate the number of points with integer coordinates such that the number of segments that cover these points equals $k$. A segment with endpoints $l_i$ and $r_i$ covers point $x$ if and only if $l_i \le x \le r_i$.
This problem with small coordinates can be solved using partial sums and some easy counting. Let's carry an array $cnt$, where $cnt_i$ will be equal to the number of segments that cover the point with coordinate $i$. How to calculate $cnt$ in $O(n + maxX)$? For each segment ($l_i, r_i$) let's add $+1$ to $cnt_{l_i}$ and $-1$ to $cnt_{r_i + 1}$. Now build on this array prefix sums and notice that $cnt_i$ equals the number of segments that cover the point with coordinate $i$. Then $ans_i$ will be equal to $\sum\limits_{j = 0}^{maxX} cnt_j = i$. All the answers can be calculated in $O(maxX)$ in total. So the total complexity of this solution is $O(n + maxX)$. But in our problem it is too slow to build an entire array $cnt$. So what should we do? It is obvious that if any coordinate $j$ is not equals some $l_i$ or some $r_i + 1$ then $cnt_i = cnt_{i - 1}$. So we do not need carry all the positions explicitly. Let's carry all $l_i$ and $r_i + 1$ in some logarithmic data structure or let's use the coordinate compression method. The coordinate compression method allows us to transform the set of big sparse objects to the set of small compressed objects maintaining the relative order. In our problems let's make the following things: push all $l_i$ and $r_i + 1$ in vector $cval$, sort this vector, keep only unique values and then use the position of elements in vector $cval$ instead of original value (any position can be found in $O(\log n)$ by binary search or standard methods as lower_bound in C++). So the first part of the solution works in $O(n \log n)$. Answer can be calculated using almost the same approach as in solution to this problem with small coordinates. But now we know that between two adjacent elements $cval_i$ and $cval_{i + 1}$ there is exactly $cval_{i + 1} - cval_{i}$ points with answer equals to $cnt_i$. So if we will iterate over all pairs of the adjacent elements $cval_i$ and $cval_{i + 1}$ and add $cval_{i + 1} - cval_i$ to the $ans_{cnt_i}$, we will calculate all the answers in $O(n)$. So the total complexity of the solution is $O(n \log n)$.
[ "data structures", "implementation", "sortings" ]
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<pair<long long, long long>> a(n); vector<long long> cval; for (auto &i : a) { scanf("%lld %lld", &i.first, &i.second); cval.push_back(i.first); cval.push_back(i.second + 1); } sort(cval.begin(), cval.end()); cval.resize(unique(cval.begin(), cval.end()) - cval.begin()); vector<int> cnt(2 * n); for (auto &i : a) { int posl = lower_bound(cval.begin(), cval.end(), i.first) - cval.begin(); int posr = lower_bound(cval.begin(), cval.end(), i.second + 1) - cval.begin(); ++cnt[posl]; --cnt[posr]; } for (int i = 1; i < 2 * n; ++i) cnt[i] += cnt[i - 1]; vector<long long> ans(n + 1); for (int i = 1; i < 2 * n; ++i) ans[cnt[i - 1]] += cval[i] - cval[i - 1]; for (int i = 1; i <= n; ++i) printf("%lld ", ans[i]); puts(""); return 0; }
1000
D
Yet Another Problem On a Subsequence
The sequence of integers $a_1, a_2, \dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 > 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ — are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $[2, -3, 0, 1, 4]$, $[1, 2, 3, -3, -9, 4]$ are good, and the sequences $[2, -3, 0, 1]$, $[1, 2, 3, -3 -9, 4, 1]$ — are not. For a given sequence of numbers, count the number of its \textbf{subsequences} that are good sequences, and print the number of such subsequences modulo \textbf{998244353}.
The problem is solved by the dynamic programming. Let $dp_i$ be the answer for the prefix of the array starting at $i$ (it contains the indices $i, i + 1, \dots, n$). If $a_i \le 0$, then $dp_i = 0$. Otherwise, let's go over the position $j$, with which the next good array begins. Then we need to select $a_i$ positions among $j-i-1$ positions, which will be elements of the array. The number of ways to choose an unordered set of $k$ items from $n$ of different objects is calculated using the formula $C_n^k = \frac{n!}{K!(N -k)!}$. Thus, the dynamics is as follows: $dp_i = \sum\limits_{j = i + a_i + 1}^{n + 1} {C_{j - i - 1}^{a_i} \cdot dp_j}$. The basis of dynamics is the value $dp_{n + 1} = 1$.
[ "combinatorics", "dp" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 1009; const int MOD = 998244353; int n; int a[N]; int dp[N]; int C[N][N]; int main() { for(int i = 0; i < N; ++i){ C[i][0] = C[i][i] = 1; for(int j = 1; j < i; ++j) C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; } cin >> n; for(int i = 0; i < n; ++i) cin >> a[i]; dp[n] = 1; for(int i = n - 1; i >= 0; --i){ if(a[i] <= 0) continue; for(int j = i + a[i] + 1; j <= n; ++j){ dp[i] += (dp[j] * 1LL * C[j - i - 1][a[i]]) % MOD; dp[i] %= MOD; } } int sum = 0; for(int i = 0; i < n; ++i){ sum += dp[i]; sum %= MOD; } cout << sum << endl; return 0; }
1000
E
We Need More Bosses
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $n$ locations connected by $m$ \textbf{two-way} passages. The passages are designed in such a way that it should be possible to get from any location to any other location. Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called \textbf{bosses}). And your friend wants you to help him place these bosses. The game will start in location $s$ and end in location $t$, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from $s$ to $t$ without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as $s$ or as $t$.
It's quite obvious that we can place bosses only on the bridges of the given graph - if an edge is not a bridge, then removing it doesn't make the graph disconnected, so there still exists a path between any pair of vertices. And if we fix two vertices $s$ and $t$, and then find some simple path between them, then we will place the bosses on all bridges belonging to this path (since the set of bridges would stay the same no matter which simple path between $s$ and $t$ we choose). If we find bridges in the given graph and compress all 2-edge-connected components (two vertices belong to the same 2-edge-connected component iff there exists a path between these vertices such that there are no bridges on this path) into single vertices, we will obtain a special tree called bridge tree. Every edge of a bridge tree corresponds to a bridge in the original graph (and vice versa). Since we want to find the path with maximum possible number of bridges, we only need to find the diameter of the bridge tree, and this will be the answer to the problem.
[ "dfs and similar", "graphs", "trees" ]
2,100
#include<bits/stdc++.h> using namespace std; const int N = 500043; vector<int> g[N]; vector<int> t[N]; int tin[N], tout[N], fup[N]; int p[N]; int T = 1; int rnk[N]; vector<pair<int, int> > bridges; int st; int d[N]; int n, m; int get(int x) { return (p[x] == x ? x : p[x] = get(p[x])); } void link(int x, int y) { x = get(x); y = get(y); if(x == y) return; if(rnk[x] > rnk[y]) swap(x, y); p[x] = y; rnk[y] += rnk[x]; } int dfs(int x, int par = -1) { tin[x] = T++; fup[x] = tin[x]; for(auto y : g[x]) { if(tin[y] > 0) { if(par != y) fup[x] = min(fup[x], tin[y]); } else { int f = dfs(y, x); fup[x] = min(fup[x], f); if(f > tin[x]) bridges.push_back(make_pair(x, y)); else link(x, y); } } tout[x] = T++; return fup[x]; } void build() { for(auto z : bridges) { int x = get(z.first); int y = get(z.second); st = x; t[x].push_back(y); t[y].push_back(x); } } pair<int, int> bfs(int x) { for(int i = 0; i < n; i++) d[i] = n + 1; d[x] = 0; queue<int> q; q.push(x); int last = 0; while(!q.empty()) { last = q.front(); q.pop(); for(auto y : t[last]) if(d[y] > d[last] + 1) { d[y] = d[last] + 1; q.push(y); } } return make_pair(last, d[last]); } int main() { scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) rnk[i] = 1, p[i] = i; for(int i = 0; i < m; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; g[x].push_back(y); g[y].push_back(x); } dfs(0); build(); pair<int, int> p1 = bfs(st); pair<int, int> p2 = bfs(p1.first); printf("%d\n", p2.second); }
1000
F
One Occurrence
You are given an array $a$ consisting of $n$ integers, and $q$ queries to it. $i$-th query is denoted by two integers $l_i$ and $r_i$. For each query, you have to find \textbf{any} integer that occurs \textbf{exactly once} in the subarray of $a$ from index $l_i$ to index $r_i$ (a subarray is a contiguous subsegment of an array). For example, if $a = [1, 1, 2, 3, 2, 4]$, then for query $(l_i = 2, r_i = 6)$ the subarray we are interested in is $[1, 2, 3, 2, 4]$, and possible answers are $1$, $3$ and $4$; for query $(l_i = 1, r_i = 2)$ the subarray we are interested in is $[1, 1]$, and there is no such element that occurs exactly once. Can you answer all of the queries?
Suppose all queries have the same right border $r$. Then the answer for the query can be some integer $i$ such that the last occurence of $i$ on the prefix $[1, r]$ of the array is inside the segment, but the second to last occurence is outside the segment (or even does not exist). More formally, let $f(i)$ be the maximum index $j$ such that $j < i$ and $a_j = a_i$ (or $-1$ if there is no such $j$); the answer to the query is some number $a_k$ such that $l \le k \le r$ and $f(k) < l$ (and $k$ is the rightmost occurence of $a_k$ in the segment $[1, r]$). For a fixed right border $r$, we can build a segment tree which for every index $x$ such that $x$ is the rightmost occurence of $a_x$ on $[1, r]$ stores the value of $f(x)$; and if we query minimum on the segment $[l, r]$ in such tree, we can try to find the answer. Let the position of minimum be $m$. If $f(m) < l$, then $a_m$ can be the answer; otherwise there is no answer. But this is too slow since we can't afford to build a segment tree for every possible value of $r$. There are two methods how to deal with this problem: you may sort all queries by their right borders and maintain the segment tree while shifting the right border (when going from $r$ to $r + 1$, we have to update the values in the positions $f(r + 1)$ and $r + 1$), or we may use a persistent segment tree and get an online solution. We tried to eliminate solutions using Mo's algorithm, but in fact it's possible to squeeze some implementations of it into TL. There are two optimizations that might help there. When dividing the elements into blocks, we may sort the first block in the ascending order of right borders, the second - in descending, the third - in ascending order again, and so on. And also it's possible to obtain a Mo-based solution with worst case complexity of $O((n + q) \sqrt{n})$ if we maintain the set of possible answers using sqrt decomposition on it.
[ "data structures", "divide and conquer" ]
2,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) #define x first #define y second const int N = 500 * 1000 + 13; const int P = 800; const int INF = 1e9; bool comp(const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b){ int num = a.x.x / P; if (num != b.x.x / P) return a.x.x < b.x.x; if (num & 1) return a.x.y < b.x.y; return a.x.y > b.x.y; } int val[N]; int cnt[N]; int bl[P]; int tot; inline void add(int x){ ++cnt[x]; if (cnt[x] == 1){ ++val[x]; ++bl[x / P]; ++tot; } else if (cnt[x] == 2){ --val[x]; --bl[x / P]; --tot; } } inline void sub(int x){ --cnt[x]; if (cnt[x] == 1){ ++val[x]; ++bl[x / P]; ++tot; } else if (cnt[x] == 0){ --val[x]; --bl[x / P]; --tot; } } int get(){ if (tot == 0) return 0; forn(i, P){ if (bl[i] > 0){ for (int j = i * P;; ++j){ if (val[j]){ return j; } } } } assert(false); } int n, m; int a[N], ans[N]; pair<pair<int, int>, int> q[N]; int main() { scanf("%d", &n); forn(i, n) scanf("%d", &a[i]); scanf("%d", &m); forn(i, m){ scanf("%d%d", &q[i].x.x, &q[i].x.y); --q[i].x.x, --q[i].x.y; q[i].y = i; } sort(q, q + m, comp); int l = 0, r = -1; forn(i, m){ int L = q[i].x.x; int R = q[i].x.y; while (r < R){ ++r; add(a[r]); } while (r > R){ sub(a[r]); --r; } while (l > L){ --l; add(a[l]); } while (l < L){ sub(a[l]); ++l; } ans[q[i].y] = get(); } forn(i, m) printf("%d\n", ans[i]); return 0; }
1000
G
Two-Paths
You are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with $n$ vertices. The edge $\{u_j, v_j\}$ has weight $w_j$. Also each vertex $i$ has its own value $a_i$ assigned to it. Let's call a path starting in vertex $u$ and ending in vertex $v$, where each edge can appear no more than twice (regardless of direction), a 2-path. Vertices can appear in the 2-path multiple times (even start and end vertices). For some 2-path $p$ profit $\text{Pr}(p) = \sum\limits_{v \in \text{distinct vertices in } p}{a_v} - \sum\limits_{e \in \text{distinct edges in } p}{k_e \cdot w_e}$, where $k_e$ is the number of times edge $e$ appears in $p$. That is, vertices are counted once, but edges are counted the number of times they appear in $p$. You are about to answer $m$ queries. Each query is a pair of vertices $(qu, qv)$. For each query find 2-path $p$ from $qu$ to $qv$ with maximal profit $\text{Pr}(p)$.
Let's solve this task in several steps. Step 1. Calculate $dp_i$ for each vertex. Let $dp_i$ be maximal profit of some 2-path starting at $i$ and finishing at $i$. If vertex $i$ is a root of the tree, then $dp_i$ equivalent to $d'_i$, where $d'_i$ - maximal profit of 2-path $(i, i)$, when we can go only in subtree of $i$. The $d'_i$ can be calculated with next approach: $d'_v = a_v + \sum\limits_{to \in \text{Children}(v)}{\max(0, d'_{to} - 2 \cdot w(v, to))}$. To calculate $dp_i$ we can use next technique. Let's manage next invariant: when processing vertex $v$ all its neighbours (even parent) will hold $d'_i$ as if $v$ its parent. Then $dp_v = a_v + \sum\limits_{to \in \text{Neighbours}(v)}{\max(0, d'_{to} - 2 \cdot w(v, to))}$. After that, we can proceed with each child $to$ of $v$, but before moving to it we must change value $d'_v$ since we must keep invariant true. To keep it true, it's enough to set $d'_v = dp_v - \max(0, d'_{to} - 2 \cdot w(v, to))$. Also let's memorize value $\max(0, d'_{to} - 2 \cdot w(v, to))$ as $dto(v, to)$. Step 2. Processing queries. Let simple path $(qu, qv)$ be $qu \rightarrow p_1 \rightarrow p_2 \rightarrow \dots \rightarrow p_k \rightarrow qv$. If $qu = qv$ then answer is $dp_{qu}$. Otherwise, each edge on this simple path must be used exactly once. But, while travelling from $qu$ to $qv$ using this simple path, at each vertex $v$ we can go somewhere and return to $v$ - the only condition is not use edges from simple path. And we can do it using precalculated values $dp_i$ and $dto(v, to)$. So, if we want to find max profit of 2-path $(v, v)$ with prohibited edges $(v, to_1)$, $(v, to_2)$, so we can use value $dp_v - dto(v, to_1) - dto(v, to_2)$. Finally, to process queries, let's find $l = lca(qu, qv)$, divide it on two queries $(qu, l)$, $(qv, l)$. Now we can handle all queries offline, travelling on tree in dfs order. Let's manage some data structure on current path from current vertex to the root (this DS can be based on array of depths). Then, when we come to vertex $v$, just add value $dp_v - dto(v, \text{parent}(v))$ to DS in position $\text{depth}(v)$ (and erase it before exit). Each query $(v, l)$ becomes a query of sum to some subsegment in DS (don't forget carefully handle value in lca). And, before moving from $v$ to $to$, you need subtract $dto(v, to)$ from current value of $v$ (here you can at once subtract weight of edge $(v, to)$). Don't forget to return each change in DS, when it needed. As we can see, DS is just a BIT with sum on segment and change in position. Result complexity is $O((n + m) \log{n})$. Fast IO are welcome.
[ "data structures", "dp", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y << ")"; } template<class A> ostream& operator <<(ostream& out, const vector<A> &v) { out << "["; fore(i, 0, sz(v)) { if(i) out << ", "; out << v[i]; } return out << "]"; } const int M = 400 * 1000 + 555; const int N = 300 * 1000 + 555; const int LOGN = 19; int n, m, a[N]; vector<pt> g[N]; inline bool read() { if(!(cin >> n >> m)) return false; fore(i, 0, n) assert(scanf("%d", &a[i]) == 1); fore(i, 0, n - 1) { int u, v, w; assert(scanf("%d%d%d", &u, &v, &w) == 3); u--, v--; g[u].emplace_back(v, w); g[v].emplace_back(u, w); } fore(i, 0, n) sort(all(g[i])); return true; } int tin[N], tout[N], T = 0; int p[N][LOGN]; int h[N]; li d1[N]; void calc1(int v, int pr) { tin[v] = T++; p[v][0] = pr; fore(st, 1, LOGN) p[v][st] = p[p[v][st - 1]][st - 1]; d1[v] = a[v]; fore(i, 0, sz(g[v])) { int to = g[v][i].x; int w = g[v][i].y; if(to == pr) continue; h[to] = h[v] + 1; calc1(to, v); d1[v] += max(0ll, d1[to] - 2ll * w); } tout[v] = T++; } li dp[N]; vector<li> dto[N]; void calcRRT(int v) { dp[v] = a[v]; dto[v].assign(sz(g[v]), 0ll); fore(i, 0, sz(g[v])) { int to = g[v][i].x; int w = g[v][i].y; li curVal = max(0ll, d1[to] - 2ll * w); dp[v] += curVal; dto[v][i] = curVal; } fore(i, 0, sz(g[v])) { int to = g[v][i].x; if(h[to] < h[v]) continue; li tmp = d1[v]; d1[v] = dp[v] - dto[v][i]; calcRRT(to); d1[v] = tmp; } } inline bool isP(int l, int v) { return tin[l] <= tin[v] && tout[v] <= tout[l]; } int lca(int u, int v) { if(isP(u, v)) return u; if(isP(v, u)) return v; for(int st = LOGN - 1; st >= 0; st--) if(!isP(p[v][st], u)) v = p[v][st]; return p[v][0]; } li getDto(int v, int to) { int pos = int(lower_bound(all(g[v]), pt(to, -1)) - g[v].begin()); if(pos >= sz(g[v]) || g[v][pos].x != to) return 0; return dto[v][pos]; } li f[N]; inline void inc(int pos, li val) { for(; pos < N; pos |= pos + 1) f[pos] += val; } inline li sum(int pos) { li ans = 0; for(; pos >= 0; pos = (pos & (pos + 1)) - 1) ans += f[pos]; return ans; } inline li getSum(int l, int r) { return sum(r) - sum(l); } li ans[M]; vector<pt> qs[N]; void calcAns(int v) { li vAdd = dp[v] - getDto(v, p[v][0]); inc(h[v], vAdd); for(pt &q : qs[v]) { int up = q.x, id = q.y; ans[id] += getSum(h[up] - 1, h[v]) + getDto(up, p[up][0]); } fore(i, 0, sz(g[v])) { int to = g[v][i].x; int w = g[v][i].y; if(h[to] < h[v]) continue; li curSub = dto[v][i] + w; inc(h[v], -curSub); calcAns(to); inc(h[v], +curSub); } inc(h[v], -vAdd); } inline void solve() { T = 0; h[0] = 0; calc1(0, 0); calcRRT(0); fore(i, 0, m) { int u, v; assert(scanf("%d%d", &u, &v) == 2); u--, v--; int l = lca(u, v); ans[i] = -dp[l]; qs[u].emplace_back(l, i); qs[v].emplace_back(l, i); } calcAns(0); fore(i, 0, m) printf("%lld\n", ans[i]); } 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; }
1003
A
Polycarp's Pockets
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$. Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.
We have to find the maximum number of elements with the same value (it can be done by counting). This number will be the answer because if there are no more than $k$ elements with the same value in the array it is obvious that we cannot use less than $k$ pockets, but we also doesn't need to use more than $k$ pockets because of the other values can be also distributed using $k$ pockets. Overall complexity is $O(n + maxAi)$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> cnt(101); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[x]; } cout << *max_element(cnt.begin(), cnt.end()) << endl; return 0; }
1003
B
Binary String Constructing
You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \le i < n$) such that $s_i \ne s_{i + 1}$. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices $i$ such that $1 \le i < n$ and $s_i \ne s_{i + 1}$ ($i = 1, 2, 3, 4$). For the string "111001" there are two such indices $i$ ($i = 3, 5$). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1.
This problem has several general cases: $x$ is even and $a > b$, then the answer is 01 repeated $\frac{x}{2}$ times, then $b - \frac{x}{2}$ ones and $a - \frac{x}{2}$ zeroes; $x$ is even and $a \le b$, then the answer is 10 repeated $\frac{x}{2}$ times, then $a - \frac{x}{2}$ zeroes and $b - \frac{x}{2}$ ones; $x$ is odd and $a > b$, then the answer is 01 repeated $\lfloor\frac{x}{2}\rfloor$ times, then $a - \lfloor\frac{x}{2}\rfloor$ zeroes and $b - \lfloor\frac{x}{2}\rfloor$ ones; $x$ is odd and $a \le b$, then the answer is 10 repeated $\lfloor\frac{x}{2}\rfloor$ times, then $b - \lfloor\frac{x}{2}\rfloor$ ones and $a - \lfloor\frac{x}{2}\rfloor$ zeroes. I am sure that there are other more beautiful solution, but for me the easiest way to solve this problem is to extract general cases and handle it. Overall complexity is $O(a + b)$.
[ "constructive algorithms" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int a, b, x; cin >> a >> b >> x; if (x % 2 == 0) { if (a > b) { for (int i = 0; i < x / 2; ++i) cout << "01"; cout << string(b - x / 2, '1'); cout << string(a - x / 2, '0'); } else { for (int i = 0; i < x / 2; ++i) cout << "10"; cout << string(a - x / 2, '0'); cout << string(b - x / 2, '1'); } } else if (a > b) { for (int i = 0; i < x / 2; ++i) cout << "01"; cout << string(a - x / 2, '0'); cout << string(b - x / 2, '1'); } else { for (int i = 0; i < x / 2; ++i) cout << "10"; cout << string(b - x / 2, '1'); cout << string(a - x / 2, '0'); } cout << endl; return 0; }
1003
C
Intense Heat
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are. Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows: Suppose we want to analyze the segment of $n$ consecutive days. We have measured the temperatures during these $n$ days; the temperature during $i$-th day equals $a_i$. We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $x$ to day $y$, we calculate it as $\frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1}$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $k$ consecutive days. For example, if analyzing the measures $[3, 4, 1, 2]$ and $k = 3$, we are interested in segments $[3, 4, 1]$, $[4, 1, 2]$ and $[3, 4, 1, 2]$ (we want to find the maximum value of average temperature over these segments). You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?
This task is very straight-forward implementation problem. So we can iterate over all segments of the given array, calculate their sum, and if the length of the current segment is not less than $k$, try to update the answer with the mean of this segment. Overall complexity is $O(n^2)$.
[ "brute force", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sqr(a) ((a) * (a)) #define sz(a) int(a.size()) #define all(a) a.begin(), a.end() #define forn(i, n) for(int i = 0; i < int(n); i++) #define fore(i, l, r) for(int i = int(l); i < int(r); i++) typedef long long li; typedef long double ld; typedef pair<int, int> pt; template <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) { return out << "(" << a.x << ", " << a.y << ")"; } template <class A> ostream& operator << (ostream& out, const vector<A> &v) { out << "["; forn(i, sz(v)) { if(i) out << ", "; out << v[i]; } return out << "]"; } mt19937 rnd(time(NULL)); const int INF = int(2e9); const li INF64 = li(1e18); const int MOD = INF + 7; const ld EPS = 1e-9; const ld PI = acos(-1.0); const int N = 10000 + 7; int n, k; int a[N]; bool read () { if (scanf("%d%d", &n, &k) != 2) return false; forn(i, n) scanf("%d", &a[i]); return true; } int pr[N]; void solve() { pr[0] = 0; forn(i, n) pr[i + 1] = pr[i] + a[i]; ld ans = 0; forn(r, n) forn(l, r + 1){ if (r - l + 1 >= k){ ans = max(ans, (pr[r + 1] - pr[l]) / ld(r - l + 1)); } } printf("%.15f\n", double(ans)); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int tt = clock(); #endif cerr.precision(15); cout.precision(15); cerr << fixed; cout << fixed; while(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } }
1003
D
Coins and Queries
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. It is guaranteed that all the values are integer powers of $2$ (i.e. $a_i = 2^d$ for some \textbf{non-negative} integer number $d$). Polycarp wants to know answers on $q$ queries. The $j$-th query is described as integer number $b_j$. The answer to the query is the minimum number of coins that is necessary to obtain the value $b_j$ using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value $b_j$, the answer to the $j$-th query is -1. The queries are independent (the answer on the query doesn't affect Polycarp's coins).
We can solve the problem by the following way: firstly, for each power of $2$ let's calculate the number of coins with the value equals this degree. Let's call it $cnt$. It is obvious that we can obtain the value $b_j$ greedily (because all less values of coins are divisors of all greater values of coins). Now let's iterate over all powers of $2$ from $30$ to $0$. Let's $deg$ be the current degree. We can take $min(\lfloor\frac{b_j}{2^{deg}}\rfloor, cnt_{deg})$ coins with the value equals $2^{deg}$. Let it be $cur$. Add $cur$ to the answer and subtract $2^{deg} \cdot cur$ from $b_j$. If after iterating over all powers $b_j$ still be non-zero, print -1. Otherwise print the answer. Overall complexity: $O((n + q) \log maxAi)$.
[ "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, q; cin >> n >> q; vector<int> cnt(31); for (int i = 0; i < n; ++i) { int x; cin >> x; ++cnt[__builtin_ctz(x)]; } while (q--) { int x; cin >> x; int ans = 0; for (int i = 30; i >= 0 && x > 0; --i) { int need = min(x >> i, cnt[i]); ans += need; x -= (1 << i) * need; } if (x > 0) ans = -1; cout << ans << endl; } return 0; }
1003
E
Tree Constructing
You are given three integers $n$, $d$ and $k$. Your task is to construct an undirected tree on $n$ vertices with diameter $d$ and degree of each vertex at most $k$, or say that it is impossible. An undirected tree is a connected undirected graph with $n - 1$ edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex $u$ it is the number of edges $(u, v)$ that belong to the tree, where $v$ is any other vertex of a tree).
Let's construct a tree by the following algorithm: if $d \ge n$, let's print "NO" and terminate the program. Otherwise let's keep the array $deg$ of the length $n$ which will represent degrees of vertices. The first step is to construct the diameter of the tree. Let first $d + 1$ vertices form it. Let's add $d$ edges to the answer, increase degrees of vertices corresponding to this edges, and if some vertex has degree greater than $k$, print "NO" and terminate the program. The second (and the last) step is to attach the remaining $n - d - 1$ vertices to the tree. Let's call the vertex free if its degree is less than $k$. Also let's keep all free vertices forming the diameter in some data structure which allows us to take the vertex with the minimum maximal distance to any other vertex and remove such vertices. It can be done by, for example, set of pairs ($dist_v, v$), where $dist_v$ is a maximum distance from the vertex $v$ to any other vertex. Now let's add all vertices from starting from the vertex $d + 1$ (0-indexed) to the vertex $n - 1$, let the current vertex be $u$. We get the vertex with the minimum maximal distance to any other vertex, let it be $v$. Now we increase the degree of vertices $u$ and $v$, add the edge between they, and if $v$ still be free, return it to the data structure, otherwise remove it. The same with the vertex $u$ (it is obvious that its maximal distance to any other vertex will be equals $dist_v + 1$). If at any step our data structure will be empty or the minimum maximal distance will be equals $d$, the answer is "NO". Otherwise we can print the answer. See my solution to better understanding. Overall complexity: $O(n \log n)$ or $O(n)$ (depends on implementation).
[ "constructive algorithms", "graphs" ]
2,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, d, k; cin >> n >> d >> k; if (d >= n) { cout << "NO" << endl; return 0; } vector<int> deg(n); vector<pair<int, int>> ans; set<pair<int, int>> q; for (int i = 0; i < d; ++i) { ++deg[i]; ++deg[i + 1]; if (deg[i] > k || deg[i + 1] > k) { cout << "NO" << endl; return 0; } ans.push_back(make_pair(i, i + 1)); } for (int i = 1; i < d; ++i) q.insert(make_pair(max(i, d - i), i)); for (int i = d + 1; i < n; ++i) { while (!q.empty() && deg[q.begin()->second] == k) q.erase(q.begin()); if (q.empty() || q.begin()->first == d) { cout << "NO" << endl; return 0; } ++deg[i]; ++deg[q.begin()->second]; ans.push_back(make_pair(i, q.begin()->second)); q.insert(make_pair(q.begin()->first + 1, i)); } assert(int(ans.size()) == n - 1); cout << "YES" << endl; vector<int> p(n); for (int i = 0; i < n; i++) p[i] = i; random_shuffle(p.begin(), p.end()); for (int i = 0; i < n - 1; ++i) if (rand() % 2) cout << p[ans[i].first] + 1 << " " << p[ans[i].second] + 1 << endl; else cout << p[ans[i].second] + 1 << " " << p[ans[i].first] + 1 << endl; return 0; }
1003
F
Abbreviation
You are given a text consisting of $n$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $w_i$ is the $i$-th word of text. All words consist only of lowercase Latin letters. Let's denote a segment of words $w[i..j]$ as a sequence of words $w_i, w_{i + 1}, \dots, w_j$. Two segments of words $w[i_1 .. j_1]$ and $w[i_2 .. j_2]$ are considered \textbf{equal} if $j_1 - i_1 = j_2 - i_2$, $j_1 \ge i_1$, $j_2 \ge i_2$, and for every $t \in [0, j_1 - i_1]$ $w_{i_1 + t} = w_{i_2 + t}$. For example, for the text "to be or not to be" the segments $w[1..2]$ and $w[5..6]$ are equal, they correspond to the words "to be". An abbreviation is a replacement of some segments of words with their first \textbf{uppercase} letters. In order to perform an abbreviation, you have to choose \textbf{at least two} non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words $w[2..4]$ and $w[6..8]$ with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words $w[2..5]$ and $w[6..9]$ with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c". What is the minimum length of the text after at most one abbreviation?
Let $eq_{i, j}$ equals true if words $s_i$ and $s_j$ are equal, otherwise it will be equals false. We can iterate over all pairs of words and compare they just using standard string comparator (constraints are really small so we can do it naively). The next step is to calculate dynamic programming $dp_{i, j}$, which will be equal to the maximum length of coinciding segments of words which starts in positions $i$ and $j$, respectively. In other words, if $dp_{i, j}$ equals $k$, then $s[i..i+k-1] = s[j..j+k-1]$, word by word. We can calculate this dynamic programming in reverse order ($i := n - 1 .. 0, j := n - 1 .. 0$) and $dp_{i, j} := 0$ if $s_i \ne s_j$, else if $i < n - 1$ and $j < n - 1$, then $dp_{i, j} := dp_{i + 1, j + 1} + 1$, otherwise $dp_{i, j} := 1$. Let's keep the length of the text in the variable $allsum$. Then iterate over all starting positions of the possible abbreviation and all its possible lengths. Let the current starting position will be equals $i$ (0-indexed) and its length will be equal $j$. Then we need to calculate the number of possible replacements by its abbreviation. Let it be $cnt$ and now it equals $1$. Let's iterate over all positions $pos$, at the beginning $pos = i + j$ (0-indexed). If $dp_{i, pos} \ge j$ then we can replace the segment of words which starts at the position $pos$ with its abbreviation, so $cnt := cnt + 1$ and $pos := pos + j$ (because we cannot replace intersecting segments), otherwise $pos := pos + 1$. After this we need to update the answer. The length of the segment of words $s[i..j]$ can be calculated easily, let it be $seglen$. Also let $segcnt$ be the number of words in the current segment of words. Then we can update the answer with the value $allsum - seglen * cnt + cnt * segcnt$. Overall complexity is $O(n^3 + n \cdot \sum\limits_{i = 0}^{n - 1}|s_i|)$, where $|s_i|$ is the length of the $i$-th word.
[ "dp", "hashing", "strings" ]
2,200
#include <bits/stdc++.h> using namespace std; const int N = 303; int n; bool eq[N][N]; int dp[N][N]; string s[N]; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif cin >> n; int allsum = n - 1; for (int i = 0; i < n; ++i) { cin >> s[i]; allsum += s[i].size(); } for (int i = 0; i < n; ++i) { eq[i][i] = true; for (int j = 0; j < i; ++j) { eq[i][j] = eq[j][i] = s[i] == s[j]; } } for (int i = n - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { if (eq[i][j]) { if (i + 1 < n && j + 1 < n) dp[i][j] = dp[i + 1][j + 1] + 1; else dp[i][j] = 1; } } } int ans = allsum; for (int i = 0; i < n; ++i) { int sum = 0; for (int j = 0; i + j < n; ++j) { sum += s[i + j].size(); int cnt = 1; for (int pos = i + j + 1; pos < n; ++pos) { if (dp[i][pos] > j) { ++cnt; pos += j; } } int cur = allsum - sum * cnt + (j + 1) * cnt - j * cnt; if (cnt > 1 && ans > cur) { ans = cur; } } } cout << ans << endl; return 0; }
1004
A
Sonya and Hotels
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city. Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.
One hotel always can be built to the left of the first hotel. One more can be built to the right of the last hotel. Let's look at each pair of the adjacent hotels. If the distance between these two hotels is greater than $2\cdot d$, we can build one hotel at a distance of $d$ to the right from the left hotel and one more at a distance of $d$ to the left from the right hotel. If the distance between these two hotels is equal to $2\cdot d$, we can build only one hotel in the middle of them. Otherwise, we can not build a hotel between them.
[ "implementation" ]
900
null
1004
B
Sonya and Exhibition
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily. She knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies. Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.
Note, that it is always optimal to use roses in even positions and lilies in odd positions. That is, the string $01010101010\ldots$ is always optimal.
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,300
null
1004
C
Sonya and Robots
Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers. Sonya has drawn $n$ numbers in a row, $a_i$ is located in the $i$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position. Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one. For example, if the numbers $[1, 5, 4, 1, 3]$ are written, and Sonya gives the number $1$ to the first robot and the number $4$ to the second one, the first robot will stop in the $1$-st position while the second one in the $3$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $4$ to the first robot and the number $5$ to the second one, they will meet since the first robot will stop in the $3$-rd position while the second one is in the $2$-nd position. Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot. Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($p$, $q$), where she will give $p$ to the first robot and $q$ to the second one. Pairs ($p_i$, $q_i$) and ($p_j$, $q_j$) are different if $p_i\neq p_j$ or $q_i\neq q_j$. Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.
Let's assume that our left robot is located in the $p$ position. The robot could be there only if the value that is written there did not occur earlier. The number of possible locations of the second robot is equal to the number of distinct numbers on the segment $[(p+1)\ldots n]$. Let $dp_i$ be the number of different numbers on $[(p+1)\ldots n]$. Let's find these number from right to left. If $a_i$ occurs the first time $dp_i=dp_{i+1} + 1$, otherwise, $dp_i=dp_{i+1}$.
[ "constructive algorithms", "implementation" ]
1,400
null
1004
D
Sonya and Matrix
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit. Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so. The Manhattan distance between two cells ($x_1$, $y_1$) and ($x_2$, $y_2$) is defined as $|x_1 - x_2| + |y_1 - y_2|$. For example, the Manhattan distance between the cells $(5, 2)$ and $(7, 1)$ equals to $|5-7|+|2-1|=3$. \begin{center} {\small Example of a rhombic matrix.} \end{center} Note that rhombic matrices are uniquely defined by $n$, $m$, and the coordinates of the cell containing the zero. She drew a $n\times m$ rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of $n\cdot m$ numbers). Note that Sonya will not give you $n$ and $m$, so only the sequence of numbers in this matrix will be at your disposal. Write a program that finds such an $n\times m$ rhombic matrix whose elements are the same as the elements in the sequence in some order.
Suppose that a matrix has sizes $n\times m$, zero is located at $(x,y)$. Let $a$ be the distance to the cell $(1,1)$, and let $b$ the distance to the cell $(n,m)$. Obvious that the farthest distance from the zero cell will be to a corner cell. The maximum number in the list is equal to the maximum distance to a corner cell (let's assume that it is $b$). We know that $n\cdot m = t$; $a=x-1+y-1$; $b=n-x+m-y$; $n+m=a+b+2$. And $a=n+m-b-2$; $x-1+y-1=n+m-b-2$; $y=n+m-b-x$. Let's find the minimum $i$ $(i>0$) such that the number of occurrences of $i$ in the list is not equal to $4\cdot i$. We can notice that $x=i$. Let's look at each pair $(n, m)$ ($n\cdot m=t$). If we know $n, m, x$, and $b$, we can find $y$ and restore the matrix. If it could be done, we already found the answer.
[ "brute force", "constructive algorithms", "implementation" ]
2,300
null
1004
E
Sonya and Ice Cream
Sonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops. Sonya lives in a city with $n$ junctions and $n-1$ streets between them. All streets are two-way and connect two junctions. It is possible to travel from any junction to any other using one or more streets. City Hall allows opening shops only on junctions. The girl cannot open shops in the middle of streets. Sonya has exactly $k$ friends whom she can trust. If she opens a shop, one of her friends has to work there and not to allow anybody to eat an ice cream not paying for it. Since Sonya does not want to skip an important competition, she will not work in shops personally. Sonya wants all her ice cream shops to form a simple path of the length $r$ ($1 \le r \le k$), i.e. to be located in different junctions $f_1, f_2, \dots, f_r$ and there is street between $f_i$ and $f_{i+1}$ for each $i$ from $1$ to $r-1$. The girl takes care of potential buyers, so she also wants to minimize the maximum distance between the junctions to the nearest ice cream shop. The distance between two junctions $a$ and $b$ is equal to the sum of all the street lengths that you need to pass to get from the junction $a$ to the junction $b$. So Sonya wants to minimize $$\max_{a} \min_{1 \le i \le r} d_{a,f_i}$$ where $a$ takes a value of all possible $n$ junctions, $f_i$ — the junction where the $i$-th Sonya's shop is located, and $d_{x,y}$ — the distance between the junctions $x$ and $y$. Sonya is not sure that she can find the optimal shops locations, that is why she is asking you to help her to open not more than $k$ shops that will form a simple path and the maximum distance between any junction and the nearest shop would be minimal.
The editorial for the main solution with centroid decomposition will be published later. Another Solution (without really formal proof) It is possible to show, that if we have all weights equal to $1$, then optimal answer is always a middle part of diameter of right length. However, weights are arbitrary. Then we need to select a "weighted" middle part. We can do it in a following way: set two pointers - one to the diameter beginning, and one to the end. And while the number of vertices is greater $k$ we move the pointer, which has moved less from it's end. However, in fact, sometimes we need to look at the neighboring $\pm 1$ possible subpaths -- for example if the last step was the same distance, then the optimal move depends on where the edge was longer. This way we need to count answer for $\le 3$ paths. To count the answer for path we can run few dfs's, each of them will cover only part of graph, which hangs on related vertex of the path. Complexity is $\mathcal{O}(n)$. The sketch of the proof is something like this: Examine the diameter. Notice, that the answer should contain it's middle point (vertex, which is most close to $1/2$) because the answer would be greater than the largest half of this diameter otherwise. From this we already bounded our answer, but we need more. Then we want to start to grow the way to the ends of the diameter, so that at least from the end of the diameter of the distance was small. Not the fact that this will be enough (for example, if there are several diameters), but it is necessary. Two pointers are needed because growing in two directions may be necessary unevenly.
[ "binary search", "data structures", "dp", "greedy", "shortest paths", "trees" ]
2,400
null
1005
A
Tanya and Stairways
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $1$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $3$ steps, and the second contains $4$ steps, she will pronounce the numbers $1, 2, 3, 1, 2, 3, 4$. You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.
The answer contains such elements $a_i$ that $a_{i+1}=1$. Also add to the answer the last element $a_n$.
[ "implementation" ]
800
int n; cin >> n; vector<int> a; int p = -1; forn(i, n) { int x; cin >> x; if (x == 1 && p != -1) a.push_back(p); p = x; } a.push_back(p); cout << a.size() << endl; for (int i: a) cout << i << " ";
1005
B
Delete from the Left
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty. For example: - by applying a move to the string "where", the result is the string "here", - by applying a move to the string "a", the result is an empty string "". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings. Write a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.
Let's find the value $w$ - the length of the longest common suffix of $s$ and $t$. You can easily find it in one linear loop: just compare the last letters of $s$ and $t$. If they are equal then compare before the last letters of $s$ and $t$. And so on. The last $w$ letters of $s$ and $t$ are two equal strings which will be the result of after optimal moves. So the answer is $|s|+|t|-2 \cdot w$.
[ "brute force", "implementation", "strings" ]
900
string s, t; cin >> s >> t; int w = 0; while (true) { int i = s.length() - w - 1; int j = t.length() - w - 1; if (i >= 0 && j >= 0 && s[i] == t[j]) w++; else break; } cout << s.length() + t.length() - 2 * w << endl;
1005
C
Summarize to the Power of Two
A sequence $a_1, a_2, \dots, a_n$ is called good if, for each element $a_i$, there exists an element $a_j$ ($i \ne j$) such that $a_i+a_j$ is a power of two (that is, $2^d$ for some non-negative integer $d$). For example, the following sequences are good: - $[5, 3, 11]$ (for example, for $a_1=5$ we can choose $a_2=3$. Note that their sum is a power of two. Similarly, such an element can be found for $a_2$ and $a_3$), - $[1, 1, 1, 1023]$, - $[7, 39, 89, 25, 89]$, - $[]$. Note that, by definition, an empty sequence (with a length of $0$) is good. For example, the following sequences are not good: - $[16]$ (for $a_1=16$, it is impossible to find another element $a_j$ such that their sum is a power of two), - $[4, 16]$ (for $a_1=4$, it is impossible to find another element $a_j$ such that their sum is a power of two), - $[1, 3, 2, 8, 8, 8]$ (for $a_3=2$, it is impossible to find another element $a_j$ such that their sum is a power of two). You are given a sequence $a_1, a_2, \dots, a_n$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.
You should delete only such $a_i$ for which there is no such $a_j$ ($i \ne j$) that $a_i+a_j$ is a power of $2$. For each value let's find the number of its occurrences. You can use simple $map$ standard data-structure. Do $c[a[i]] := c[a[i]]+1$ for each element $a[i]$. Now you can easily check that $a_i$ doesn't have a pair $a_j$. Let's iterate over all possible sums $s=2^0, 2^1, \dots, 2^{30}$ and for each $s$ find calculate $s-a[i]$. If for some $s$: $c[s-a[i]] \ge 2$ or $c[s-a[i]] = 1$ && $s-a[i] \ne a[i]$ then a pair $a_j$ exists. Note that in C++ solutions, it's better to first check that $s-a[i]$ is a key in $c$, and only after it calculate $c[s - a[i]]$. This needs to be done, since in C++ when you access a key using the "square brackets" operator, a default mapping key-value is created on the absence of the key. This increases both the running time and the memory consumption.
[ "brute force", "greedy", "implementation" ]
1,300
int n; cin >> n; vector<int> a(n); map<int,int> c; forn(i, n) { cin >> a[i]; c[a[i]]++; } int ans = 0; forn(i, n) { bool ok = false; forn(j, 31) { int x = (1 << j) - a[i]; if (c.count(x) && (c[x] > 1 || (c[x] == 1 && x != a[i]))) ok = true; } if (!ok) ans++; } cout << ans << endl;
1005
D
Polycarp and Div 3
Polycarp likes numbers that are divisible by 3. He has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $3$. For example, if the original number is $s=3121$, then Polycarp can cut it into three parts with two cuts: $3|1|21$. As a result, he will get two numbers that are divisible by $3$. Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid. What is the maximum number of numbers divisible by $3$ that Polycarp can obtain?
There are multiple approaches to solve this problem. We will use dynamic programming approach. Let's calculate values of the array $z[0 \dots n]$, where $z[i]$ is the answer for prefix of the length $i$. Obviously, $z[0] := 0$, since for the empty string (the prefix of the length $0$) the answer is $0$. For $i>0$ you can find $z[i]$ in the following way. Let's look in the last digit of the prefix of length $i$. It has index $i-1$. Either it doesn't belong to segment divisible by $3$, or it belongs. If it doesn't belongs, it means we can't use the last digit, so $z[i] = z[i-1]$. If it belongs we need to find shortest $s[j \dots i-1]$ that is divisible by $3$ and try to update $z[i]$ with the value $z[j]+1$. It means that we "bite off" the shortest divisible by $3$ suffix and reduce the problem to a previous. A number is divisible by $3$ if and only if sum of its digits is divisible by $3$. So the task is to find the shortest suffix of $s[0 \dots i-1]$ with sum of digits divisible by $3$. If such suffix is $s[j \dots i-1]$ then $s[0 \dots j-1]$ and $s[0 \dots i-1]$ have the same remainder of sum of digits modulo $3$. Let's maintain $fin[0 \dots 2]$ - array of the length $3$, where $fin[r]$ is the length of the longest processed prefix with sum of digits equal to $r$ modulo $3$. Use $fin[r]=-1$ if there is no such prefix. It is easy to see that $j=fin[r]$ where $r$ is the sum of digits on the $i$-th prefix modulo $3$. So to find the maximal $j \le i-1$ that substring $s[j \dots i-1]$ is divisible by $3$, just check that $fin[r] \ne -1$ and use $j=fin[r]$, where $r$ is the sum of digits on the $i$-th prefix modulo $3$. It means that to handle case that the last digit belongs to divisible by $3$ segment, you should try to update $z[i]$ with value $z[fin[r]] + 1$. In other words, just do if (fin[r] != -1) z[i] = max(z[i], z[fin[r]] + 1). Sequentially calculating the values of $z [0 \dots n]$, we obtain a linear $O(n)$ solution.
[ "dp", "greedy", "number theory" ]
1,500
string s; cin >> s; int n = s.length(); int r = 0; vector<int> fin(3, -1); fin[0] = 0; vector<int> z(n + 1); for (int i = 1; i <= n; i++) { r = (r + s[i - 1] - '0') % 3; z[i] = z[i - 1]; if (fin[r] != -1) z[i] = max(z[i], z[fin[r]] + 1); fin[r] = i; } cout << z[n] << endl;
1005
E1
Median on Segments (Permutations Edition)
You are given a permutation $p_1, p_2, \dots, p_n$. A permutation of length $n$ is a sequence such that each integer between $1$ and $n$ occurs exactly once in the sequence. Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly the given number $m$. The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used. For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence. Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly the given number $m$.
The segment $p[l \dots r]$ has median equals $m$ if and only if $m$ belongs to it and $less=greater$ or $less=greater-1$, where $less$ is number of elements in $p[l \dots r]$ that strictly less than $m$ and $greater$ is number of elements in $p[l \dots r]$ that strictly greater than $m$. Here we've used a fact that $p$ is a permutation (on $p[l \dots r]$ there is exactly one occurrence of $m$). In other words, $m$ belongs $p[l \dots r]$ and the value $greater-less$ equals $0$ or $1$. Calculate prefix sums $sum[0 \dots n]$, where $sum[i]$ the value $greater-less$ on the prefix of the length $i$ (i.e. on the subarray $p[0 \dots i-1]$). For fixed value $r$ it is easy to calculate number of such $l$ that $p[l \dots r]$ is suitable. At first, check that $m$ met on $[0 \dots r]$. Valid values $l$ are such indices that: no $m$ on $[0 \dots l-1]$ and $sum[l]=sum[r]$ or $sum[r]=sum[l]+1$. Let's maintain number of prefix sums $sum[i]$ to the left of $m$ for each value. We can use just a map $c$, where $c[s]$ is number of such indices $l$ that $sum[l]=s$ and $l$ is to the left of $m$. So for each $r$ that $p[0 \dots r]$ contains $m$ do ans += c[sum] + c[sum - 1], where $sum$ is the current value $greater-less$. Time complexity is $O(n \log n)$ if a standard map is used or $O(n)$ if classical array for $c$ is used (remember about possible negative indices, just use an offset).
[ "sortings" ]
1,800
int n, m; cin >> n >> m; vector<int> p(n); forn(i, n) cin >> p[i]; map<int,int> c; c[0] = 1; bool has = false; int sum = 0; long long ans = 0; for (int r = 0; r < n; r++) { if (p[r] < m) sum--; else if (p[r] > m) sum++; if (p[r] == m) has = true; if (has) ans += c[sum] + c[sum - 1]; else c[sum]++; } cout << ans << endl;
1005
E2
Median on Segments (General Case Edition)
You are given an integer sequence $a_1, a_2, \dots, a_n$. Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$. The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used. For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence. Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$.
Let's define a function greaterCount($m$) - number of subarrays with median greater or equal than $m$. In this case, the answer on the problem is greaterCount($m$) $-$ greaterCount($m + 1$). The subarray $a[l \dots r]$ has median greater or equal than $m$, if and only if $notLess>less$, where $notLess$ is the number equal or greater than $m$ elements, and $less$ is the number of less than $m$ elements. In other words, instead of processing $a[l \dots r]$ you can use the sequence $x[l \dots r]$ containing $-1$ or/and $+1$. An element $x[i]=-1$, if $a[i]<m$. An element $x[i]=+1$, if $a[i] \ge m$. Now, the median of $a[l \dots r]$ is greater or equal than $m$ if and only if $x[l] + x[l+1] + \dots + x[r] > 0$. Let's iterate over $a$ from left to right. Maintain the current partial sum $sum=x[0]+x[1]+\dots+x[i]$. Additionally, in the array $s$ let's maintain the number of partial sum for each its value. It means that before increase of $i$ you should do s[sum]++. So if $i$ is the index of the right endpoint of a subarray (i.e. $r=i$), then number of suitable indices $l$ is number of such $j$ that $x[0]+x[1]+\dots+x[j]<sum$. In other words, find sum of all $s[w]$, where $w<sum$ - it is exactly number of indices with partial sum less than $sum$. Each time partial sum changes on $-1$ or $+1$. So the value "sum of all $s[w]$, where $w<sum$" is easy to recalculate on each change. If you decrease $sum$, just subtract the value $s[sum]$. If you increase $sum$, before increasing just add $s[sum]$. Since indices in $s$ can be from $-n$ to $n$, you can use 0-based indices using an array $s[0 \dots 2 \cdot n]$. In this case, initialize $sum$ as $n$ but not as $0$ (it makes $sum$ to be non-negative on each step). This solution works in $O(n)$.
[ "sortings" ]
2,400
long long greaterCount(int m) { vector<int> s(2 * n + 1); int sum = n; long long result = 0; s[sum] = 1; long long add = 0; forn(i, n) { if (a[i] < m) sum--, add -= s[sum]; else add += s[sum], sum++; result += add; s[sum]++; } return result; } cin >> n >> m; a = vector<int>(n); forn(i, n) cin >> a[i]; cout << greaterCount(m) - greaterCount(m + 1) << endl;
1005
F
Berland and the Shortest Paths
There are $n$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $1$ to $n$. It is known that, from the capital (the city with the number $1$), you can reach any other city by moving along the roads. The President of Berland plans to improve the country's road network. The budget is enough to repair exactly $n-1$ roads. The President plans to choose a set of $n-1$ roads such that: - it is possible to travel from the capital to any other city along the $n-1$ chosen roads, - if $d_i$ is the number of roads needed to travel from the capital to city $i$, moving only along the $n-1$ chosen roads, then $d_1 + d_2 + \dots + d_n$ is minimized (i.e. as minimal as possible). In other words, the set of $n-1$ roads should preserve the connectivity of the country, and the sum of distances from city $1$ to all cities should be minimized (where you can only use the $n-1$ chosen roads). The president instructed the ministry to prepare $k$ possible options to choose $n-1$ roads so that both conditions above are met. Write a program that will find $k$ possible ways to choose roads for repair. If there are fewer than $k$ ways, then the program should output all possible valid ways to choose roads.
Use BFS to precalculate an array $d$ - the array of the shortest path lengths from the Capital. The condition to minimize sum of distances in each tree is equal to the fact that each tree is a shortest path tree. Let's think about them as about oriented outgoing from the Capital trees. Moving along edges of such trees, you always move by shortest paths. An edge $(u,v)$ can be included into such a tree if and only if $d[u]+1=d[v]$ (since original edges are bidirectional, you should consider each of them twice: as $(u,v)$ and as $(v,u)$). Let's focus only on edges for which $d[u]+1=d[v]$. Call them "red" edges. To build a tree for each city (except the Capital) you should choose exactly one red edge finishing in this city. That's why the number of suitable trees is a product of numbers of incoming edges over all vertices (cities). But we need to find only $k$ of such trees. Let's start from some such tree and rebuild it on each step. As initial tree you can choose the first incoming red edge into each vertex (except the City). Actually, we will do exactly increment operation for number in a mixed radix notation. To rebuild a tree iterate over vertices and if the current used red edge is not the last for the vertex, use the next and stop algorithm. Otherwise (the last red edge is used), use the first red edge for this vertex (and go to the next vertex) and continue with the next vertex. Compare this algorithm with simple increment operation for long number.
[ "brute force", "dfs and similar", "graphs", "shortest paths" ]
2,100
int n, m, k; cin >> n >> m >> k; vector<vector<int>> g(n); vector<int> a(m), b(m); forn(i, m) { cin >> a[i] >> b[i]; a[i]--, b[i]--; g[a[i]].push_back(b[i]); g[b[i]].push_back(a[i]); } queue<int> q; q.push(0); vector<int> d(n, INT_MAX); d[0] = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (int v: g[u]) if (d[v] == INT_MAX) { d[v] = d[u] + 1; q.push(v); } } vector<vector<int>> inc(n); forn(i, m) { if (d[a[i]] + 1 == d[b[i]]) inc[b[i]].push_back(i); if (d[b[i]] + 1 == d[a[i]]) inc[a[i]].push_back(i); } vector<int> f(n); vector<string> result; forn(i, k) { string s(m, '0'); for (int j = 1; j < n; j++) s[inc[j][f[j]]] = '1'; result.push_back(s); bool ok = false; for (int j = 1; j < n; j++) if (f[j] + 1 < inc[j].size()) { ok = true; f[j]++; break; } else f[j] = 0; if (!ok) break; } cout << result.size() << endl; forn(i, result.size()) cout << result[i] << endl;
1006
A
Adjacent Replacements
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: - Replace each occurrence of $1$ in the array $a$ with $2$; - Replace each occurrence of $2$ in the array $a$ with $1$; - Replace each occurrence of $3$ in the array $a$ with $4$; - Replace each occurrence of $4$ in the array $a$ with $3$; - Replace each occurrence of $5$ in the array $a$ with $6$; - Replace each occurrence of $6$ in the array $a$ with $5$; - $\dots$ - Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; - Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above. For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm: $[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array. Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.
It is easy to see that for the odd elements there is no changes after applying the algorithm described in the problem statement, and for the even elements there is only one change: each of the even elements will be decreased by $1$. So we can iterate over all the elements of the array and print $a_i - (a_i \% 2)$, where $x \% y$ is taking $x$ modulo $y$. Overall complexity is $O(n)$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; for (int i = 0; i < n; ++i) { int x; cin >> x; cout << x - !(x & 1) << " "; } return 0; }