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
1195
E
OpenStreetMap
Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size $n \times m$ cells on a map (rows of grid are numbered from $1$ to $n$ from north to south, and columns are numbered from $1$ to $m$ from west to east). After that he measured the average height of each cell above Rybinsk sea level and obtained a matrix of heights of size $n \times m$. The cell $(i, j)$ lies on the intersection of the $i$-th row and the $j$-th column and has height $h_{i, j}$. Seryozha is going to look at the result of his work in the browser. The screen of Seryozha's laptop can fit a subrectangle of size $a \times b$ of matrix of heights ($1 \le a \le n$, $1 \le b \le m$). Seryozha tries to decide how the weather can affect the recreation center — for example, if it rains, where all the rainwater will gather. To do so, he is going to find the cell having minimum height among all cells that are shown on the screen of his laptop. Help Seryozha to calculate the sum of heights of such cells for all possible subrectangles he can see on his screen. In other words, you have to calculate the sum of minimum heights in submatrices of size $a \times b$ with top left corners in $(i, j)$ over all $1 \le i \le n - a + 1$ and $1 \le j \le m - b + 1$. Consider the sequence $g_i = (g_{i - 1} \cdot x + y) \bmod z$. You are given integers $g_0$, $x$, $y$ and $z$. By miraculous coincidence, $h_{i, j} = g_{(i - 1) \cdot m + j - 1}$ ($(i - 1) \cdot m + j - 1$ is the index).
There is almost nothing to say about this problem. It is pretty standard data structure problem. Let $mn_{i, j}$ be the minimum value over all values $h_{i, j}, h_{i - 1, j}, \dots, h_{i - a + 1}{j}$. If $i$ is less than $a$ then its value does not matter for us because the corresponding submatrix is not counted in the answer. These values can be calculated using std::deque or minimum queue. You can read more about it here: https://cp-algorithms.com/data_structures/stack_queue_modification.html. After building such matrix $mn$ we can actually calculate the answer. Let's iterate over all rows of the matrix (starting from row $a$) $i$ and carry the floating window of width $b$ of values $mn_{i, j}$. And when the size of the queue with minimums reaches $b$ we know the minimum on the corresponding submatrix that ends in the current element and we can add it to the answer. Time complexity: $O(nm)$.
[ "data structures", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; long long n, m, a, b, g, x, y, z; vector<deque<long long> > deq; vector<vector<long long> > mi; vector<int> power; const long long MAX_V = 1000000000000000ll; void ins(deque<long long>& de, long long val) { while(!de.empty() && de.back() > val) { de.pop_back(); } de.push_back(val); } void del(deque<long long>& de, long long val) { if (!de.empty() && de.front() == val) { de.pop_front(); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; cin >> a >> b; cin >> g >> x >> y >> z; mi.resize(n); deq.resize(m); for (int i = 0; i < n; i++) { mi[i].resize(m); for (int j = 0; j < m; j++) { mi[i][j] = g; g = (g * x + y) % z; } } for (int i = 0; i < m; i++) { for (int j = 0; j < a; j++) { ins(deq[i], mi[j][i]); } } deque<long long> real_deq; for (int i = 0; i < b; i++) { ins(real_deq, deq[i].front()); } long long ans = 0; ans += real_deq.front(); for (int i = b; i < m; i++) { del(real_deq, deq[i - b].front()); ins(real_deq, deq[i].front()); ans += real_deq.front(); } for (int i = a; i < n; i++) { for (int j = 0 ; j < m; j++) { ins(deq[j], mi[i][j]); del(deq[j], mi[i - a][j]); } deque<long long> real_d; for (int j = 0; j < b; j++) { ins(real_d, deq[j].front()); } ans += real_d.front(); for (int j = b; j < m; j++) { del(real_d, deq[j - b].front()); ins(real_d, deq[j].front()); ans += real_d.front(); } } cout << ans << "\n"; }
1195
F
Geometers Anonymous Club
Denis holds a Geometers Anonymous Club meeting in SIS. He has prepared $n$ convex polygons numbered from $1$ to $n$ for the club. He plans to offer members of the club to calculate Minkowski sums of these polygons. More precisely, he plans to give $q$ tasks, the $i$-th of them asks to calculate the sum of Minkowski of polygons with indices from $l_i$ to $r_i$ inclusive. The sum of Minkowski of two sets $A$ and $B$ is the set $C = \{a + b : a \in A, b \in B\}$. It can be proven that if $A$ and $B$ are convex polygons then $C$ will also be a convex polygon. \begin{center} Sum of two convex polygons \end{center} To calculate the sum of Minkowski of $p$ polygons ($p > 2$), you need to calculate the sum of Minkowski of the first $p - 1$ polygons, and then calculate the sum of Minkowski of the resulting polygon and the $p$-th polygon. For the convenience of checking answers, Denis has decided to prepare and calculate the number of vertices in the sum of Minkowski for each task he prepared. Help him to do it.
Suppose we want to compute the Minkowski sum of two polygons $a$ and $b$. Let's denote two sequences of free vectors: $u_1$, $u_2$, ..., $u_{k_a}$ such that free vector $u_i$ is congruent to the bound vector starting in $i$-th vertex of the first polygon and ending in the $(i + 1)$-th vertex of this polygon (if $i = k_a$, then we use the $1$st point as the $(i + 1)$-th one); $v_1$, $v_2$, ..., $v_{k_b}$ such that free vector $v_i$ is congruent to the bound vector starting in $i$-th vertex of the second polygon and ending in the $(i + 1)$-th vertex of this polygon (if $i = k_b$, then we again use the $1$st point as the $(i + 1)$-th one). It's impossible to choose a pair of vectors from the same sequence in such a way that they are parallel, since there are no three points lying on the same line in the same polygon (but it may be possible to find a pair of antiparallel vectors belonging to the same sequence). Let's try to analyze how we can construct such sequence for the resulting polygon. For example, let's pick some side of the first polygon (let vector $u_i$ denote this side of the polygon) and analyze how this side can affect the resulting polygon. There are two cases: there is a vector $v_j$ such that it is parallel (not antiparallel) to $u_i$. Then this vector represents a side of the second polygon. If we construct the Minkowski sum of these two sides (the side represented by $u_i$ in the first polygon and the side represented by $v_j$ in the second polygon), then we will get a segment having length equal to $|u_i| + |v_j|$. The line coming through this segment divides the plane into two halfplanes, and all points belonging to the Minkowski sum of these polygons will be contained in the same halfplane. That's because all points of the first polygon belong to the same halfplane (if we divide the plane by the line coming through the side represented by $u_i$), and all points of the second polygon belong to the same halfplane (if we divide the plane by the line coming through the side represented by $v_j$) - moreover, both these halfplanes are either upper halfplanes (and then the whole resulting polygon belongs to the upper halfplane) or lower halfplanes (then result belongs to the lower halfplane). So, the resulting polygon will have a side represented by the free vector equal to $u_i + v_j$ (obviously, there can be only one such side); there is no such vector in the second sequence such that it is parallel to $u_i$. Then there exists exactly one vertex of the second polygon such that if we draw a line parallel to $u_i$ through this vertex, the whole second polygon will be contained in the upper halfplane or the lower halfplane (depending on whether the first polygon belongs to the upper halfplane or the lower halfplane in respect to the side parallel to $u_i$). Actually, this case can be analyzed as the case where $v_j$ exists, but has zero length: the resulting polygon will have a side represented by the vector $u_i$. So, for every vector in the sequences constructed by the given polygons, there will be a vector parallel to it in the resulting sequence of vectors. It is quite obvious that every vector in the resulting sequence is also parallel to some vector from the first two sequences. It means that the number of sides in the Minkowski sum is equal to the number of vectors in these two sequences, but all parallel vectors count as one. This fact can be extended to computing the Minkowski sum of multiple polygons: the resulting polygon will have the number of sides equal to the number of vectors in all sequences for given polygons, if we count all parallel vectors as one. Now we can solve the problem in such a way: construct the sequences of vectors for the given polygons and divide these vectors into equivalence classes in such a way that vectors belong to the same class if and only if they are parallel. The answer to each query is equal to the number of equivalence classes such that at least one vector belonging to this class is contained in at least one sequence on the segment of polygons; this can be modeled as the query "count the number of distinct values on the given segment of the given array". This problem can be solved with Mo's algorithm, mergesort tree or persistent segment tree.
[ "data structures", "geometry", "math", "sortings" ]
2,500
// Created by Nikolay Budin #ifdef LOCAL # define _GLIBCXX_DEBUG #else # define cerr __get_ce #endif #include <bits/stdc++.h> #define ff first #define ss second #define szof(x) ((int)x.size()) using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef unsigned long long ull; int const INF = (int)1e9 + 1e3; ll const INFL = (ll)1e18 + 1e6; #ifdef LOCAL mt19937 tw(9450189); #else mt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count()); #endif uniform_int_distribution<ll> ll_distr; ll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; } struct point { int x, y; point(int _x, int _y) : x(_x), y(_y) {} point operator-(point const& other) const { return point(x - other.x, y - other.y); } point& operator/=(int num) { x /= num; y /= num; return *this; } bool operator<(point const& other) const { return x < other.x || (x == other.x && y < other.y); } }; void solve() { int n; cin >> n; vector<vector<point>> polys; vector<point> vecs; vector<int> borders; borders.push_back(0); for (int i = 0; i < n; ++i) { int k; cin >> k; borders.push_back(borders.back() + k); polys.push_back({}); for (int j = 0; j < k; ++j) { int x, y; cin >> x >> y; polys.back().push_back(point(x, y)); } for (int j = 0; j < k; ++j) { int next = (j + 1) % k; point v = polys[i][next] - polys[i][j]; int tmp = __gcd(abs(v.x), abs(v.y)); v /= tmp; vecs.push_back(v); } } vector<int> arr; map<point, int> inds; for (auto v : vecs) { if (!inds.count(v)) { int tmp = szof(inds); inds[v] = tmp; } arr.push_back(inds[v]); } vector<int> next(szof(vecs)); vector<int> last(szof(inds), INF); for (int i = szof(vecs) - 1; i >= 0; --i) { next[i] = last[arr[i]]; last[arr[i]] = i; } vector<vector<pii>> here(szof(vecs)); int q; cin >> q; vector<int> ans(q); for (int i = 0; i < q; ++i) { int l, r; cin >> l >> r; --l; l = borders[l]; r = borders[r]; here[l].push_back({r, i}); } int bpv = 1; while (bpv < szof(vecs)) { bpv *= 2; } vector<int> segtree(bpv * 2); function<void(int, int)> segtree_set = [&](int pos, int val) { pos += bpv; segtree[pos] = val; pos /= 2; while (pos) { segtree[pos] = segtree[pos * 2] + segtree[pos * 2 + 1]; pos /= 2; } }; function<int(int, int, int, int, int)> segtree_get = [&](int v, int vl, int vr, int l, int r) { if (vr <= l || r <= vl) { return 0; } if (l <= vl && vr <= r) { return segtree[v]; } int vm = (vl + vr) / 2; return segtree_get(v * 2, vl, vm, l, r) + segtree_get(v * 2 + 1, vm, vr, l, r); }; for (int i = 0; i < szof(inds); ++i) { segtree_set(last[i], 1); } for (int i = 0; i < szof(vecs); ++i) { for (auto p : here[i]) { ans[p.ss] = segtree_get(1, 0, bpv, i, p.ff); } segtree_set(i, 0); if (next[i] != INF) { segtree_set(next[i], 1); } } for (int num : ans) { cout << num << "\n"; } } int main() { #ifdef LOCAL auto start_time = clock(); cerr << setprecision(3) << fixed; #endif cout << setprecision(15) << fixed; ios::sync_with_stdio(false); cin.tie(nullptr); int test_count = 1; // cin >> test_count; for (int test = 1; test <= test_count; ++test) { solve(); } #ifdef LOCAL auto end_time = clock(); cerr << "Execution time: " << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << " ms\n"; #endif }
1196
A
Three Piles of Candies
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it. After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies. Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies). You have to answer $q$ independent queries. Let's see the following example: $[1, 3, 4]$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $4$ candies, and Bob has $4$ candies. Another example is $[1, 10, 100]$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $54$ candies, and Alice takes $46$ candies. Now Bob has $55$ candies, and Alice has $56$ candies, so she has to discard one candy — and after that, she has $55$ candies too.
The answer is always $\lfloor\frac{a + b + c}{2}\rfloor$. Let's understand why it is so. Let $a \le b \le c$. Then let Bob take the pile with $a$ candies and Alice take the pile with $b$ candies. Then because of $b \le a + c$ we can see that Bob's pile always can reach size of Alice's pile (and remaining candies can be divided between them fairly except one candy if $a + b + c$ is odd).
[ "brute force", "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { long long a, b, c; cin >> a >> b >> c; cout << (a + b + c) / 2 << endl; } return 0; }
1196
B
Odd Sum Segments
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. You want to split it into exactly $k$ \textbf{non-empty non-intersecting subsegments} such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $n$ elements of the array $a$ must belong to exactly one of the $k$ subsegments. Let's see some examples of dividing the array of length $5$ into $3$ subsegments (not necessarily with odd sums): $[1, 2, 3, 4, 5]$ is the initial array, then all possible ways to divide it into $3$ non-empty non-intersecting subsegments are described below: - $[1], [2], [3, 4, 5]$; - $[1], [2, 3], [4, 5]$; - $[1], [2, 3, 4], [5]$; - $[1, 2], [3], [4, 5]$; - $[1, 2], [3, 4], [5]$; - $[1, 2, 3], [4], [5]$. Of course, it can be impossible to divide the initial array into exactly $k$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and \textbf{any} possible division of the array. See the output format for the detailed explanation. You have to answer $q$ independent queries.
Firstly, let $cnt$ be the number of odd elements in the array. Note that even elements are don't matter at all because they cannot change the parity of the sum. If $cnt < k$ then it is obviously impossible to split the given array into $k$ subsegments with odd sum. And if $cnt \% 2 \ne k \% 2$ then it is impossible to split the array into $k$ subsegments with odd sum also because at least one of $k$ segments will have even number of odd elements (so will have odd sum). In other cases the answer is always "YES" and you can print $k-1$ leftmost positions of odd elements and $n$ as right borders of segments (it means that when you find one odd element, you end one segment). Because $cnt \% 2 = k \% 2$ now, the last segment will have odd number of odd elements so it will have odd sum also.
[ "constructive algorithms", "math" ]
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 q; cin >> q; for (int i = 0; i < q; ++i) { int n, k; cin >> n >> k; vector<int> a(n); int cntodd = 0; for (int j = 0; j < n; ++j) { cin >> a[j]; cntodd += a[j] % 2; } if (cntodd < k || cntodd % 2 != k % 2) { cout << "NO" << endl; continue; } cout << "YES" << endl; for (int j = 0; j < n; ++j) { if (k == 1) break; if (a[j] % 2 == 1) { cout << j + 1 << " "; --k; } } cout << n << endl; } return 0; }
1196
C
Robot Breakout
$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $i$-th robot is currently located at the point having coordinates ($x_i$, $y_i$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $X$ and $Y$, and when each robot receives this command, it starts moving towards the point having coordinates ($X$, $Y$). The robot stops its movement in two cases: - either it reaches ($X$, $Y$); - or it cannot get any closer to ($X$, $Y$). Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($x_c$, $y_c$). Then the movement system allows it to move to any of the four adjacent points: - the first action allows it to move from ($x_c$, $y_c$) to ($x_c - 1$, $y_c$); - the second action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c + 1$); - the third action allows it to move from ($x_c$, $y_c$) to ($x_c + 1$, $y_c$); - the fourth action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c - 1$). Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform. You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $X$ and $Y$ so that each robot can reach the point ($X$, $Y$). Is it possible to find such a point?
In fact, we have some restrictions on $OX$ axis and $OY$ axis (for example, if some robot stays at the position $x$ and cannot move to the left, then the answer point should have $X \ge x$). So we can take the minimum among all $y$-coordinates of robots that cannot go up and save it into $maxy$, maximum among all $y$-coordinates of robots that cannot go down and save it into $miny$, minimum among all $x$-coordinates of robots that cannot go right and save it into $maxx$ and maximum among all $x$-coordinates of robots that cannot go right and save it into $minx$. Initially $minx = miny = -\infty, maxx = maxy = +\infty$. So these restrictions are describe some rectangle (possibly incorrect, with $minx > maxx$ or $miny > maxy$). Let $(minx, miny)$ be the bottom-left point of this rectangle and $(maxx, maxy)$ be the top-right point of this rectangle. In case if this rectangle have $minx > maxx$ or $miny > maxy$, the answer is "NO". Otherwise this rectangle describes all integer points which can be reachable all robots and you can print any of them.
[ "implementation" ]
1,500
#include <algorithm> #include <iostream> using namespace std; const int MAXC = 1e5; int main() { int q; cin >> q; while (q--) { int n; cin >> n; int mnx = -MAXC, mxx = MAXC; int mny = -MAXC, mxy = MAXC; while (n--) { int x, y, f1, f2, f3, f4; cin >> x >> y >> f1 >> f2 >> f3 >> f4; if (!f1) mnx = max(mnx, x); if (!f2) mxy = min(mxy, y); if (!f3) mxx = min(mxx, x); if (!f4) mny = max(mny, y); } if (mnx <= mxx && mny <= mxy) cout << "1 " << mnx << " " << mny << "\n"; else cout << "0\n"; } return 0; }
1196
D1
RGB Substring (easy version)
\textbf{The only difference between easy and hard versions is the size of the input}. You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'. You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there will be a string of length $k$ that is a substring of $s$, and is also a substring of the infinite string "RGBRGBRGB ...". A string $a$ is a substring of string $b$ if there exists a positive integer $i$ such that $a_1 = b_i$, $a_2 = b_{i + 1}$, $a_3 = b_{i + 2}$, ..., $a_{|a|} = b_{i + |a| - 1}$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not. You have to answer $q$ independent queries.
You can just implement what is written in the problem statement and solve this problem this way. Let's iterate over all starting positions of the substring $i$ from $0$ to $n-k+1$ and over all possible offsets of the string $t$ = "RGB" $offset$ from $0$ to $2$ inclusive. Then let's iterate over all position of the current substring $pos$ from $0$ to $k-1$ and carry the variable $cur$ which denotes the answer for the current starting position and the current offset. And if $s_{i + pos} \ne t_{(offset + pos) \% 3}$ then let's increase $cur$ by $1$. After iterating over all positions $pos$ let's update the answer with the value of $cur$.
[ "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif const string t = "RGB"; int q; cin >> q; for (int i = 0; i < q; ++i) { int n, k; string s; cin >> n >> k >> s; int ans = 1e9; for (int j = 0; j < n - k + 1; ++j) { for (int offset = 0; offset < 3; ++offset) { int cur = 0; for (int pos = 0; pos < k; ++pos) { if (s[j + pos] != t[(pos + offset) % 3]) { ++cur; } } ans = min(ans, cur); } } cout << ans << endl; } return 0; }
1196
D2
RGB Substring (hard version)
\textbf{The only difference between easy and hard versions is the size of the input}. You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'. You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there will be a string of length $k$ that is a substring of $s$, and is also a substring of the infinite string "RGBRGBRGB ...". A string $a$ is a substring of string $b$ if there exists a positive integer $i$ such that $a_1 = b_i$, $a_2 = b_{i + 1}$, $a_3 = b_{i + 2}$, ..., $a_{|a|} = b_{i + |a| - 1}$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not. You have to answer $q$ independent queries.
In this problem you should make the same as in the previous one but faster. Let's consider three offsets of string "RGB": "RGB", "GBR" and "BRG". Let's copy the current offset of the string so that it will has the length $n$ (possibly, without some trailing characters) and save it in the string $t$. Then let's compare the string $s$ with this offset of length $n$ and build an array $diff$ of length $n$ where $diff_i = 1$ if $s_i \ne t_i$. Then let's iterate over all possible continuous subsegments of this array $diff$ and maintain the variable $cur$ denoting the current answer. Firstly, for the current position $i$ let's add $diff_i$ to $cur$. Then if the current position $i$ is greater than or equal to $k-1$ ($0$-indexed) let's decrease $cur$ by $diff_{i-k}$. So now we have the continuous subsegment of the array $diff$ of length no more than $k$. Then if the current position $i$ is greater than or equal to $k$ ($0$-indexed again) (the current subsegment has the length $k$) then let's update the answer with $cur$. Then let's do the same with two remaining offsets.
[ "data structures", "dp", "implementation", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif const string t = "RGB"; int q; cin >> q; for (int i = 0; i < q; ++i) { int n, k; string s; cin >> n >> k >> s; int ans = 1e9; for (int offset = 0; offset < 3; ++offset) { vector<int> res(n); int cur = 0; for (int j = 0; j < n; ++j) { res[j] = (s[j] != t[(j + offset) % 3]); cur += res[j]; if (j >= k) cur -= res[j - k]; if (j >= k - 1) ans = min(ans, cur); } } cout << ans << endl; } return 0; }
1196
E
Connected Component on a Chessboard
You are given two integers $b$ and $w$. You have a chessboard of size $10^9 \times 10^9$ with the top left cell at $(1; 1)$, the cell $(1; 1)$ is painted \textbf{white}. Your task is to find a connected component on this chessboard that contains exactly $b$ black cells and exactly $w$ white cells. Two cells are called connected if they share a side (i.e. for the cell $(x, y)$ there are at most four connected cells: $(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)$). A set of cells is called a connected component if for every pair of cells $C_1$ and $C_2$ from this set, there exists a sequence of cells $c_1$, $c_2$, ..., $c_k$ such that $c_1 = C_1$, $c_k = C_2$, all $c_i$ from $1$ to $k$ are belong to this set of cells and for every $i \in [1, k - 1]$, cells $c_i$ and $c_{i + 1}$ are connected. Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and \textbf{any} suitable connected component. You have to answer $q$ independent queries.
I'll consider the case when $b \ge w$, the other case is symmetric and the answer I construct is the same but shifted by $1$ to the right. Consider the given field as a matrix where $x$ is the number of row and $y$ is the number of column. Firstly, let's build the line of length $2w-1$ from the cell $(2, 2)$ to the cell $(2, 2w)$. Then $b$ will decrease by $w-1$ and $w$ will (formally) become $0$. Then we have two black cells to the left and to the right ($(2, 1)$ and $(2, 2w+1)$) and $w-1$ black cells to the up (all cells ($1, 2w+2*i$) for all $i$ from $0$ to $w-1$) and $w-1$ black cells to the down (all cells ($3, 2w+2*i$) for all $i$ from $0$ to $w-1$). Let's add the required number of cells to the answer. If even after adding all these cells $b$ still be greater than $0$ then the answer is "NO" (maybe there will be a proof why it is so but you can read it already from other participants). Otherwise the answer is "YES" and we constructed the required component.
[ "constructive algorithms", "implementation" ]
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 q; cin >> q; for (int i = 0; i < q; ++i) { int b, w; cin >> b >> w; vector<pair<int, int>> res; bool need = b < w; if (need) swap(w, b); int x = 2, y = 2; while (w > 0) { if ((x + y) % 2 == 1) { res.push_back({x, y}); --b; } else { res.push_back({x, y}); --w; } ++y; } int cx = 1, cy = 2; while (b > 0 && cy <= y) { res.push_back({cx, cy}); --b; cy += 2; } cx = 3, cy = 2; while (b > 0 && cy <= y) { res.push_back({cx, cy}); --b; cy += 2; } if (b > 0) { res.push_back({2, 1}); --b; } if (b > 0) { res.push_back({2, y}); --b; } if (b > 0) { cout << "NO" << endl; } else { assert(w == 0); cout << "YES" << endl; for (auto it : res) cout << it.first << " " << it.second + need << endl; } } return 0; }
1196
F
K-th Path
You are given a connected undirected weighted graph consisting of $n$ vertices and $m$ edges. You need to print the $k$-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one). More formally, if $d$ is the matrix of shortest paths, where $d_{i, j}$ is the length of the shortest path between vertices $i$ and $j$ ($1 \le i < j \le n$), then you need to print the $k$-th element in the sorted array consisting of all $d_{i, j}$, where $1 \le i < j \le n$.
The main observation is that you don't need more than $min(k, m)$ smallest by weight edges (among all edges with the maximum weights you can choose any). Maybe there will be a proof later, but now I ask other participant to write it. So you sort the initial edges and after that you can construct a graph consisting of no more than $2min(k, m)$ vertices and no more than $min(m, k)$ edges. You just can build the new graph consisting only on these vertices and edges and run Floyd-Warshall algorithm to find the matrix of shortest paths. Then sort all shorted distances and print the $k$-th element of this sorted array. Time complexity: $O(m \log m + k^3)$. I know that there are other approaches that can solve this problem with greater $k$, but to make this problem easily this solution is enough.
[ "brute force", "constructive algorithms", "shortest paths", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; const long long INF64 = 1e18; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, k; scanf("%d %d %d", &n, &m, &k); vector<pair<int, pair<int, int>>> e; for (int i = 0; i < m; ++i) { int x, y, w; scanf("%d %d %d", &x, &y, &w); --x, --y; e.push_back(make_pair(w, make_pair(x, y))); } sort(e.begin(), e.end()); vector<int> vert; for (int i = 0; i < min(m, k); ++i) { vert.push_back(e[i].second.first); vert.push_back(e[i].second.second); } sort(vert.begin(), vert.end()); vert.resize(unique(vert.begin(), vert.end()) - vert.begin()); int cntv = vert.size(); vector<vector<long long>> dist(cntv, vector<long long>(cntv, INF64)); for (int i = 0; i < cntv; ++i) dist[i][i] = 0; for (int i = 0; i < min(m, k); ++i) { int x = lower_bound(vert.begin(), vert.end(), e[i].second.first) - vert.begin(); int y = lower_bound(vert.begin(), vert.end(), e[i].second.second) - vert.begin(); dist[x][y] = dist[y][x] = min(dist[x][y], (long long)e[i].first); } for (int z = 0; z < cntv; ++z) { for (int x = 0; x < cntv; ++x) { for (int y = 0; y < cntv; ++y) { dist[x][y] = min(dist[x][y], dist[x][z] + dist[z][y]); } } } vector<long long> res; for (int i = 0; i < cntv; ++i) { for (int j = 0; j < i; ++j) { res.push_back(dist[i][j]); } } sort(res.begin(), res.end()); cout << res[k - 1] << endl; return 0; }
1197
A
DIY Wooden Ladder
Let's denote a $k$-step ladder as the following structure: exactly $k + 2$ wooden planks, of which - two planks of length \textbf{at least} $k+1$ — the base of the ladder; - $k$ planks of length \textbf{at least} $1$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example, ladders $1$ and $3$ are correct $2$-step ladders and ladder $2$ is a correct $1$-step ladder. On the first picture the lengths of planks are $[3, 3]$ for the base and $[1]$ for the step. On the second picture lengths are $[3, 3]$ for the base and $[2]$ for the step. On the third picture lengths are $[3, 4]$ for the base and $[2, 3]$ for the steps. You have $n$ planks. The length of the $i$-th planks is $a_i$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks. The question is: what is the maximum number $k$ such that you can choose some subset of the given planks and assemble a $k$-step ladder using them?
Since all planks have length at least $1$ so we can take any $n - 2$ planks as steps. So, all we need is to maximize the length of base planks. We can take the first and second maximum as base, then the answer is minimum among second maximum - 1 and $n - 2$.
[ "greedy", "math", "sortings" ]
900
fun main(args: Array<String>) { val T = readLine()!!.toInt() for (tc in 1..T) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() }.sortedDescending() println(minOf(a[1] - 1, n - 2)) } }
1197
B
Pillars
There are $n$ pillars aligned in a row and numbered from $1$ to $n$. Initially each pillar contains exactly one disk. The $i$-th pillar contains a disk having radius $a_i$. You can move these disks from one pillar to another. You can take a disk from pillar $i$ and place it on top of pillar $j$ if all these conditions are met: - there is no other pillar between pillars $i$ and $j$. Formally, it means that $|i - j| = 1$; - pillar $i$ contains \textbf{exactly} one disk; - either pillar $j$ contains no disks, or the topmost disk on pillar $j$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar. You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $n$ disks on the same pillar simultaneously?
Suppose we have a disk that is smaller than both of its neighbours. Then it's impossible to collect all the disks on the same pillar: eventually we will put this disk on the same pillar with one of its neighbours, and then we can't put the other neighbouring disk on the same pillar since it is greater than the middle disk. Okay, and what if there is no disk that is strictly smaller than both of its neighbours? Let $k$ be the index of the largest disk. $a_{k - 1} < a_k$, that implies $a_{k - 2} < a_{k - 1}$, and so on. $a_{k + 1} < a_k$, $a_{k + 2} < a_{k + 1}$, and so on. It means that the array $a$ is sorted in ascending until the index $k$, and after that it is sorted in descending order. If this condition is met, then we can collect all the disks on the pillar $k$ one by one, starting with the disk having radius $n - 1$ and ending with the disk having radius $1$. So the only thing that we need to check is the following condition: array $a$ is sorted in ascending order until $a_k = n$, and then it is sorted in descending order.
[ "greedy", "implementation" ]
1,000
#include<bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); int pos = max_element(a.begin(), a.end()) - a.begin(); bool res = true; for(int i = 0; i < pos; i++) res &= (a[i] < a[i + 1]); for(int i = pos; i < n - 1; i++) res &= (a[i] > a[i + 1]); if(res) puts("YES"); else puts("NO"); }
1197
C
Array Splitting
You are given a \textbf{sorted} array $a_1, a_2, \dots, a_n$ (for each index $i > 1$ condition $a_i \ge a_{i-1}$ holds) and an integer $k$. You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $max(i)$ be equal to the maximum in the $i$-th subarray, and $min(i)$ be equal to the minimum in the $i$-th subarray. The cost of division is equal to $\sum\limits_{i=1}^{k} (max(i) - min(i))$. For example, if $a = [2, 4, 5, 5, 8, 11, 19]$ and we divide it into $3$ subarrays in the following way: $[2, 4], [5, 5], [8, 11, 19]$, then the cost of division is equal to $(4 - 2) + (5 - 5) + (19 - 8) = 13$. Calculate the minimum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays.
Let's carefully look at the coefficients with which the elements of the array will be included in the answer. If pair of adjacent elements $a_i$ and $a_{i+1}$ belong to different subarrays then element $a_i$ will be included in the answer with coefficient $1$, and element $a_{i+1}$ with coefficient $-1$. So they add value $a_{i} - a_{i+1}$ to the answer. If element belongs to subarray with length $1$ then it will be included in the sum with coefficient $0$ (because it will be included with coefficient $1$ and $-1$ simultaneously). Elements at positions $1$ and $n$ will be included with coefficients $-1$ and $1$ respectively. So initially our answer is $a_n - a_1$. All we have to do is consider $n-1$ values $a_1 - a_2, a_2 - a_3, \dots , a_{n-1} - a_n$ and add up the $k-1$ minimal ones to the answer.
[ "greedy", "sortings" ]
1,400
#include<bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int n, k; int a[N]; int main(){ cin >> n >> k; for(int i = 0; i < n; ++i) cin >> a[i]; vector <int> v; for(int i = 1; i < n; ++i) v.push_back(a[i - 1] - a[i]); sort(v.begin(), v.end()); int res = a[n - 1] - a[0]; for(int i = 0; i < k - 1; ++i) res += v[i]; cout << res << endl; return 0; }
1197
D
Yet Another Subarray Problem
You are given an array $a_1, a_2, \dots , a_n$ and two integers $m$ and $k$. You can choose some subarray $a_l, a_{l+1}, \dots, a_{r-1}, a_r$. The cost of subarray $a_l, a_{l+1}, \dots, a_{r-1}, a_r$ is equal to $\sum\limits_{i=l}^{r} a_i - k \lceil \frac{r - l + 1}{m} \rceil$, where $\lceil x \rceil$ is the least integer greater than or equal to $x$. \textbf{The cost of empty subarray is equal to zero.} For example, if $m = 3$, $k = 10$ and $a = [2, -4, 15, -3, 4, 8, 3]$, then the cost of some subarrays are: - $a_3 \dots a_3: 15 - k \lceil \frac{1}{3} \rceil = 15 - 10 = 5$; - $a_3 \dots a_4: (15 - 3) - k \lceil \frac{2}{3} \rceil = 12 - 10 = 2$; - $a_3 \dots a_5: (15 - 3 + 4) - k \lceil \frac{3}{3} \rceil = 16 - 10 = 6$; - $a_3 \dots a_6: (15 - 3 + 4 + 8) - k \lceil \frac{4}{3} \rceil = 24 - 20 = 4$; - $a_3 \dots a_7: (15 - 3 + 4 + 8 + 3) - k \lceil \frac{5}{3} \rceil = 27 - 20 = 7$. Your task is to find the maximum cost of some subarray (possibly empty) of array $a$.
At first let's solve this problem when $m = 1$ and $k = 0$ (it is the problem of finding subarray with maximum sum). For each position from $1$ to $n$ we want to know the value of $maxl_i = \max\limits_{1 \le j \le i + 1} sum(j, i)$, where $sum(l, r) = \sum\limits_{k = l}^{k \le r} a_k$, and $sum(x+1, x) = 0$. We will calculate it the following way. $maxl_i$ will be the maximum of two values: $0$ (because we can take segments of length $0$); $a_i + maxl_{i-1}$. The maximum sum of some subarray is equal to $\max\limits_{1\le i \le n} maxl_i$. So, now we can calculate the values of $best_i = \max\limits_{0 \le len, i - len \cdot m \ge 0} (sum(i-len \cdot m + 1, i) - len * k)$ the same way. $best_i$ is the maximum of two values: 0; $sum(i - m + 1, i) - k + best_{i-m}$. After calculating all values $best_i$ we can easily solve this problem. At first, let's iterate over the elements $best_i$. When we fix some element $best_i$, lets iterate over the value $len = 1, 2, \dots, m$ and update the answer with value $best_i + sum(i - len, i - 1) - k$.
[ "dp", "greedy", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; int n, m, k; int a[N]; long long bst[N]; long long psum[N]; long long sum(int l, int r){ l = max(l, 0); return psum[r] - (l == 0? 0 : psum[l - 1]); } int main() { cin >> n >> m >> k; for(int i = 0; i < n; ++i){ cin >> a[i]; psum[i] = a[i] + (i == 0? 0 : psum[i - 1]); } long long res = 0; for(int len = 1; len <= m && len <= n; ++len) res = max(res, sum(0, len - 1) - k); for(int i = 0; i < n; ++i){ if(i + 1 >= m){ long long nbst = sum(i - m + 1, i) - k; if(i - m >= 0) nbst += bst[i - m]; bst[i] = max(bst[i], + nbst); } for(int len = 0; len < m && i + len < n; ++len) res = max(res, bst[i] + sum(i + 1, i + len) - k * (len > 0)); } cout << res << endl; return 0; }
1197
E
Culture Code
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $n$ different matryoshkas. Any matryoshka is a figure of volume $out_i$ with an empty space inside of volume $in_i$ (of course, $out_i > in_i$). You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka $i$ can be nested inside matryoshka $j$ if $out_i \le in_j$. So only the last doll will take space inside your bag. Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$, where $i_1$, $i_2$, ..., $i_k$ are the indices of the chosen dolls in the order they are nested in each other. Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property. You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $i$ such that one of the subsets contains the $i$-th doll, and another subset doesn't. Since the answer can be large, print it modulo $10^9 + 7$.
Let's, at first, sort all matryoshkas by increasing its inner volume $in_i$. Then each nested subset will appear as subsequence in its "canonical" order. Now we'll write the DP with $d[i] = (x, y)$ - the minimum extra space $x$ and number of such subsequences $y$ among all nested subsets, where the $i$-th doll is minimal. Why minimal (not maximal, for example)? It's just easier transitions (and easier proof). There are two main cases. If there isn't $j$, such that $out_i \le in_j$ then we can't put the $i$-th doll inside any other. So, $d[i] = (in_i, 1)$. Otherwise, we must put the $i$-th doll inside other doll (otherwise, the subset won't be a big enough). If we put the $i$-th doll inside the $j$-th doll then we extra space of such subset is equal to $d[j].first - (out_i - in_i)$. Since we minimize the extra space, then $d[i].first = \min\limits_{out_i \le in_j}{(d[j].first - (out_i - in_i))} = \min\limits_{out_i \le in_j}{(d[j].first)} - (out_i - in_i).$ Since we sorted all matryoshkas, so there is a position $pos$ such that $\forall j \ge pos : out_i \le in_j$ and $d[i].first = \min\limits_{j = pos}^{n}{(d[j].first)} - (out_i - in_i)$. The $d[i].second$ is just a sum from all minimums. As you can see: we can store $d[i]$ in Segment Tree with minimum + number of minimums. Why in the second transition we will build only big enough subsets? It's because not big enough subsets are not optimal in terms of minimality of extra space. The result complexity is $O(n \log(n))$.
[ "binary search", "combinatorics", "data structures", "dp", "shortest paths", "sortings" ]
2,300
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9) + 555; const li INF64 = li(1e18); const ld EPS = 1e-9; const int MOD = int(1e9) + 7; int norm(int a) { if(a >= MOD) a -= MOD; if(a < 0) a += MOD; return a; } pt combine(const pt &a, const pt &b) { if(a.x < b.x) return a; if(a.x > b.x) return b; return {a.x, norm(a.y + b.y)}; } int n; vector<pt> p; inline bool read() { if(!(cin >> n)) return false; p.resize(n); fore(i, 0, n) cin >> p[i].x >> p[i].y; return true; } vector<pt> T; void setVal(int pos, const pt &val) { T[pos += n] = val; for(pos >>= 1; pos > 0; pos >>= 1) T[pos] = combine(T[2 * pos], T[2 * pos + 1]); } pt getMin(int l, int r) { pt ans = {INF, 0}; for(l += n, r += n; l < r; l >>= 1, r >>= 1) { if(l & 1) ans = combine(T[l++], ans); if(r & 1) ans = combine(T[--r], ans); } return ans; } inline void solve() { auto comp = [](const pt &a, const pt &b) { if(a.y != b.y) return a.y < b.y; return a.x < b.x; }; sort(p.begin(), p.end(), comp); T.assign(2 * n, {INF, 0}); for (int i = n - 1; i >= 0; i--) { int pos = int(lower_bound(p.begin(), p.end(), pt(0, p[i].x), comp) - p.begin()); if(pos >= n) { setVal(i, {p[i].y, 1}); continue; } pt bst = getMin(pos, n); setVal(i, {bst.x - (p[i].x - p[i].y), bst.y}); } cout << getMin(0, n).y << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1197
F
Coloring Game
Alice and Bob want to play a game. They have $n$ colored paper strips; the $i$-th strip is divided into $a_i$ cells numbered from $1$ to $a_i$. Each cell can have one of $3$ colors. In the beginning of the game, Alice and Bob put $n$ chips, the $i$-th chip is put in the $a_i$-th cell of the $i$-th strip. Then they take turns, Alice is first. Each player during their turn has to choose one chip and move it $1$, $2$ or $3$ cells backwards (i. e. if the current cell is $x$, then the chip can be moved to the cell $x - 1$, $x - 2$ or $x - 3$). There are two restrictions: the chip cannot leave the borders of the strip (for example, if the current cell is $3$, then you can't move the chip $3$ cells backwards); and some moves may be prohibited because of color of the current cell (a matrix $f$ with size $3 \times 3$ is given, where $f_{i, j} = 1$ if it is possible to move the chip $j$ cells backwards from the cell which has color $i$, or $f_{i, j} = 0$ if such move is prohibited). The player who cannot make a move loses the game. Initially some cells may be uncolored. Bob can color all uncolored cells as he wants (but he cannot leave any cell uncolored). Let's call a coloring good if Bob can win the game no matter how Alice acts, if the cells are colored according to this coloring. Two colorings are different if at least one cell is colored in different colors in these two colorings. Bob wants you to calculate the number of good colorings. Can you do it for him? Since the answer can be really large, you have to print it modulo $998244353$.
Suppose there is only one strip and we want to count the number of ways to paint it. We can do it with some dynamic programming: let $dp_{i, r_1, r_2, r_3}$ be the number of ways to paint first $i$ cells of the strip so that $r_1$ denotes the result of the game if it starts in the last cell ($r_1 = 0$ if the player that makes a turn from this state loses, or $r_1 = 1$ if he wins), $r_2$ - the result if the game starts in the second-to-last, and so on. Then, if we paint the next cell, we can easily determine the result of the game starting in it, using the values of $r_i$ and the set of possible moves: if there is a value $r_i = 0$ such that we can move the chip $i$ cells backwards from the cell we just painted, then that cell is a winning one (if the game starts in it, the first player wins), otherwise it is a losing one. This dynamic programming works too slow since the strip can be very long, but we can skip long uncolored segments converting the transitions of this dp into matrix-vector multiplication: each possible combination of values of ($r_1$, $r_2$, $r_3$) can be encoded as a number from $0$ to $7$, and we may construct a $8 \times 8$ transition matrix $T$: $T_{i, j}$ will be equal to the number of ways to color one cell so that the previous values of ($r_1$, $r_2$, $r_3$) have code $i$, and the next values have code $j$. To model painting $k$ consecutive uncolored segments, we may compute $T^k$ with fast exponentiation method. Now we can solve the problem for one strip. What changes if we try to apply the same method to solve the problem with many strips? Unfortunately, we can't analyze each cell as "winning" or "losing" now, we need more information. When solving a problem related to a combination of acyclic games, we may use Sprague-Grundy theory (you can read about it here: https://cp-algorithms.com/game_theory/sprague-grundy-nim.html). Instead of marking each cell as "winning" or "losing", we can analyze the Grundy value of each cell. When considering a strip, we should count the number of ways to color it so that its Grundy is exactly $x$ (we should do it for every possible value of $x$), which can help us to solve the initial problem with the following dynamic programming: $z_{i, j}$ is the number of ways to color $i$ first strips so that the Grundy value of their combination is exactly $j$. The only thing that's left to consider is how do we count the number of ways to color a single strip so that its Grundy value is fixed. We can to it by modifying the method described in the first paragraph: let $dp_{i, r_1, r_2, r_3}$ be the number of ways to paint $i$ first cells so that the Grundy value of the last cell is $r_1$, the value of the previous-to-last cell is $r_2$, and so on. Since we have only $3$ possible moves, the Grundy values are limited to $3$, and each possible combination of values of ($r_1$, $r_2$, $r_3$) can be encoded as a number from $0$ to $63$. The transition matrix $T$ that allows us to skip long uncolored segments will be a $64 \times 64$ one, so if we will just exponentiate it every time we want to skip a segment, we'll get TL - but we can optimize it by precalculating $T$, $T^2$, $T^4$, ..., $T^{2^{30}}$ and using matrix-vector multiplication instead of matrix-matrix multiplication every time we skip an uncolored segment.
[ "dp", "games", "matrices" ]
2,700
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { return (x + y) % MOD; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } typedef vector<int> vec; typedef vector<vec> mat; vec mul(const mat& a, const vec& b) { int n = a.size(); int m = b.size(); vector<int> c(m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) c[i] = add(c[i], mul(b[j], a[i][j])); return c; } mat add(const mat& a, const mat& b) { int n = a.size(); int m = a[0].size(); mat c(n, vec(m, 0)); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) c[i][j] = add(a[i][j], b[i][j]); return c; } mat mul(const mat& a, const mat& b) { int x = a.size(); int y = b.size(); int z = b[0].size(); mat c(x, vec(z, 0)); for(int i = 0; i < x; i++) for(int j = 0; j < y; j++) for(int k = 0; k < z; k++) c[i][k] = add(c[i][k], mul(a[i][j], b[j][k])); return c; } mat binpow(mat a, int d) { int n = a.size(); mat c = mat(n, vec(n, 0)); for(int i = 0; i < n; i++) c[i][i] = 1; while(d > 0) { if(d % 2 == 1) c = mul(c, a); a = mul(a, a); d /= 2; } return c; } int f[3][3]; int extend(int color, vector<int> last_numbers) { vector<int> used(4, 0); for(int i = 0; i < 3; i++) if(f[color][i]) used[last_numbers[i]] = 1; for(int i = 0; i <= 3; i++) if(used[i] == 0) return i; return 3; } vector<int> extend_state(int color, vector<int> last_numbers) { int z = extend(color, last_numbers); last_numbers.insert(last_numbers.begin(), z); last_numbers.pop_back(); return last_numbers; } vector<int> int2state(int x) { vector<int> res; for(int i = 0; i < 3; i++) { res.push_back(x % 4); x /= 4; } return res; } int state2int(const vector<int>& x) { int res = 0; int deg = 1; for(auto y : x) { res += deg * y; deg *= 4; } return res; } mat form_matrix(int color) { mat res(64, vec(64, 0)); for(int i = 0; i < 64; i++) { int j = state2int(extend_state(color, int2state(i))); res[j][i] = add(res[j][i], 1); } return res; } mat color_matrices[3]; mat full_matrix; vector<pair<int, int> > colored[1043]; int len[1043]; int dp[1043][4]; mat full_pows[31]; void precalc_pows() { full_pows[0] = full_matrix; for(int i = 0; i <= 30; i++) full_pows[i + 1] = mul(full_pows[i], full_pows[i]); } vec powmul(int d, vec b) { for(int i = 0; i <= 30; i++) { if(d % 2 == 1) b = mul(full_pows[i], b); d /= 2; } return b; } int main() { int n; cin >> n; for(int i = 0; i < n; i++) cin >> len[i]; int m; cin >> m; for(int i = 0; i < m; i++) { int x, y, c; cin >> x >> y >> c; --x; --y; --c; colored[x].push_back(make_pair(y, c)); } for(int i = 0; i < n; i++) sort(colored[i].begin(), colored[i].end()); for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) cin >> f[i][j]; for(int i = 0; i < 3; i++) color_matrices[i] = form_matrix(i); full_matrix = color_matrices[0]; for(int i = 1; i < 3; i++) full_matrix = add(full_matrix, color_matrices[i]); precalc_pows(); dp[0][0] = 1; for(int i = 0; i < n; i++) { vec cur(64); cur[state2int({3, 3, 3})] = 1; int last = 0; for(auto x : colored[i]) { cur = powmul(x.first - last, cur); cur = mul(color_matrices[x.second], cur); last = x.first + 1; } cur = powmul(len[i] - last, cur); for(int j = 0; j < 4; j++) for(int k = 0; k < 64; k++) { vector<int> s = int2state(k); dp[i + 1][j ^ s[0]] = add(dp[i + 1][j ^ s[0]], mul(dp[i][j], cur[k])); } } cout << dp[n][0] << endl; }
1198
A
MP3
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers. If there are exactly $K$ distinct values in the array, then we need $k = \lceil \log_{2} K \rceil$ bits to store each value. It then takes $nk$ bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $l \le r$, and after that all intensity values are changed in the following way: if the intensity value is within the range $[l;r]$, we don't change it. If it is less than $l$, we change it to $l$; if it is greater than $r$, we change it to $r$. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size $I$ bytes, and the number of changed elements in the array is minimal possible. We remind you that $1$ byte contains $8$ bits. $k = \lceil log_{2} K \rceil$ is the smallest integer such that $K \le 2^{k}$. In particular, if $K = 1$, then $k = 0$.
First let's calculate how many different values we can have. Maximal $k$ is $\frac{8I}{n}$, maximal $K$ is $2^{k}$. We have to be careful not to overflow, let's use $K=2^{\min(20, k)}$ ($2^{20}$ is bigger than any $n$). Let's sort the array and compress equal values. Now we have to choose no more than $K$ consecutive values in such a way that they cover as much elements as possible. If $K$ is bigger than number of different values, then answer is 0. Otherwise we can precalculate prefix sums and try all the variants to choose $K$ consecutive values. Complexity is $O(n \log n)$.
[ "sortings", "two pointers" ]
1,600
null
1198
B
Welfare State
There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt. You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.
For every citizen only the last query of type $1$ matters. Moreover, all queries before don't matter at all. So the answer for each citizen is maximum of $x$ for last query of type $1$ for this citizen and maximum of all $x$ for queries of type $2$ after that. We can calculate maximum $x$ for all suffices of queries of type $2$, and remember the last query of type $1$ for each citizen. It can be implemented in $O(n+q)$ time.
[ "binary search", "brute force", "data structures", "sortings" ]
1,600
null
1198
C
Matching vs Independent Set
You are given a graph with $3 \cdot n$ vertices and $m$ edges. You are to find a matching of $n$ edges, \textbf{or} an independent set of $n$ vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge.
Let's try to take edges to matching greedily in some order. If we can add an edge to the matching (both endpoints are not covered), then we take it. It is easy to see that all vertices not covered by the matching form an independent set - otherwise we would add an edge to the matching. Either matching or independent set has size at least $n$. Complexity - $O(n+m)$.
[ "constructive algorithms", "graphs", "greedy", "sortings" ]
2,000
null
1198
D
Rectangle Painting 1
There is a square grid of size $n \times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\max(h, w)$ to color a rectangle of size $h \times w$. You are to make all cells white for minimum total cost.
Let's solve the problem for rectangle $W \times H$ ($W \ge H$). Of course, we can cover all rectangle with itself for cost $W$. To get something smaller than $W$ we have to leave at least one column uncovered - otherwise we pay at least sum of $w$ over all rectangles which is at least $W$. This gives us an idea to use DP on rectangles to solve the problem: $dp[x_{1}][x_{2}][y_{1}][y_{2}]$ is minimal cost to cover the rectangle $[x_{1};x_{2})\times[y_{1};y_{2})$. It is initialized by $\max(x_{2}-x_{1}, y_{2}-y_{1})$, and we have to try not to cover every column/row. Of course, we have to check if it is all white from the beginning; to do that we will precalculate 2D prefix sums. Total complexity is $O(n^{5})$.
[ "dp" ]
2,300
null
1198
E
Rectangle Painting 2
There is a square grid of size $n \times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\min(h, w)$ to color a rectangle of size $h \times w$. You are to make all cells white for minimum total cost. The square is large, so we give it to you in a compressed way. The set of black cells is the union of $m$ rectangles.
If we use some rectangle $[x_{1};x_{2}) \times [y_{1};y_{2})$ ($x_{2}-x_{1} \le y_{2}-y_{1}$), then we can change it to $[x_{1};x_{2}) \times [0, n)$ without changing the cost. Also we can choose $w$ rectangles of width $1$ instead of one rectangle of width $w$, it will not change the cost. So, we have to choose minimal number of columns and rows such that all black cells are covered by at least one chosen column/row. If we will build a bipartite graph - left part is columns, right part is rows, there is an edge iff the cell in the intersection of given row and column is black - then the answer is minimal vertex cover in this graph. Minimal vertex cover is the same size as maximum matching, which can be found using flow. All that is left is to see that we can compress identical vertices, and we will have $O(m)$ vertices in both parts. With Dinic algorithm complexity is $O(m^{4})$.
[ "flows", "graph matchings", "graphs" ]
2,500
null
1198
F
GCD Groups 2
You are given an array of $n$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one. The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group. Both groups have to be non-empty.
All numbers have no more than $k=9$ different prime divisors. If there exist a solution, then for every number there exist a solution in which this number is in group of size not more than $(k+1)$, because all we have to do is to "kill" all prime numbers from this number, and to do it we only need one number for each prime. If $n \le 2(k+1)$, we can try all the splits in time $O(2^{n} (n + \log C))$. Let's take two numbers which will be in different groups. How to do it? - let's take random pair. For fixed first number probability of mistake is no more than $\frac{k}{n-1}$. Now in each group we have to kill no more than $k$ primes. Let's do subset DP - our state is what primes are still alive. This solution has complexity $O(n 2^{2k})$. But we actually don't need all $n$ numbers. For each prime we can look at no more than $2k$ candidates which can kill it, because to kill all other primes we need strictly less numbers, and we will have a spare one anyways. Thus the solution has complexity $O(2^{2k}k^{2} + nk)$. We don't need factorization for any numbers except two chosen, and we can factorize them in $O(\sqrt{C})$.
[ "greedy", "number theory", "probabilities" ]
2,900
null
1199
A
City Day
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $n$ days of summer. On the $i$-th day, $a_i$ millimeters of rain will fall. All values $a_i$ are distinct. The mayor knows that citizens will watch the weather $x$ days before the celebration and $y$ days after. Because of that, he says that a day $d$ is not-so-rainy if $a_d$ is smaller than rain amounts at each of $x$ days before day $d$ and and each of $y$ days after day $d$. In other words, $a_d < a_j$ should hold for all $d - x \le j < d$ and $d < j \le d + y$. Citizens only watch the weather during summer, so we only consider such $j$ that $1 \le j \le n$. Help mayor find the \textbf{earliest} not-so-rainy day of summer.
$x$ and $y$ are small, so we can explicitly check every day. Complexity $O(n(x+y))$.
[ "implementation" ]
1,000
null
1199
B
Water Lily
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $H$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $L$ centimeters. Exactly at this point the flower touched the water surface. Suppose that the lily grows at some point $A$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $A$. Also suppose that initially the flower was exactly above the point $A$, i.e. its stem was vertical. Can you determine the depth of the lake at point $A$?
We can use Pythagorean theorem and get the equation $x^{2} + L^{2} = (H+x)^{2}$. Its solution is $x=\frac{L^{2}-H^{2}}{2H}$.
[ "geometry", "math" ]
1,000
null
1200
A
Hotelier
Amugae has a hotel consisting of $10$ rooms. The rooms are numbered from $0$ to $9$ from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance. One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.
Make an array of size 10 filled with 0. Then for each character from the input: L : Find the first position containing 0, then change it to 1. R : Find the last position containing 0, then change it to 1. 0 9 : array[x] = 0. Time complexity: $O(n)$
[ "brute force", "data structures", "implementation" ]
800
null
1200
B
Block Adventure
Gildong is playing a video game called Block Adventure. In Block Adventure, there are $n$ columns of blocks in a row, and the columns are numbered from $1$ to $n$. All blocks have equal heights. The height of the $i$-th column is represented as $h_i$, which is the number of blocks stacked in the $i$-th column. Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $1$-st column. The goal of the game is to move the character to the top of the $n$-th column. The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $i$-th column, Gildong can take one of the following three actions as many times as he wants: - if there is at least one block on the column, remove one block from the top of the $i$-th column and put it in the bag; - if there is at least one block in the bag, take one block out of the bag and place it on the top of the $i$-th column; - if $i < n$ and $|h_i - h_{i+1}| \le k$, move the character to the top of the $i+1$-st column. $k$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the \textbf{next} column. In actions of the first two types the character remains in the $i$-th column, and the value $h_i$ changes. The character initially has $m$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.
We can easily see that it's always optimal to have as many blocks as possible in the bag before getting to the next column. Therefore, if the character is currently on the top of the $i$-th column, Gildong just needs to make $h_i$ become $max(0, h_{i+1} - k)$ by repeating the $1$-st or the $2$-nd action. In other words, we should add $h_i - max(0, h_{i+1} - k)$ blocks to the bag. Adding or subtracting one by one will lead to TLE. If there exists a situation where the bag will have negative number of blocks, the answer is NO. Otherwise the answer is YES. Time complexity: $O(n)$ for each test case.
[ "dp", "greedy" ]
1,200
null
1200
C
Round Corridor
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $n$ sectors, and the outer area is equally divided by $m$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position. The inner area's sectors are denoted as $(1,1), (1,2), \dots, (1,n)$ in clockwise direction. The outer area's sectors are denoted as $(2,1), (2,2), \dots, (2,m)$ in the same manner. For a clear understanding, see the example image above. Amugae wants to know if he can move from one sector to another sector. He has $q$ questions. For each question, check if he can move between two given sectors.
Denote the corridor's length as $1$. Then, there is a wall at $(1, \frac{1}{n}), (1, \frac{2}{n}), \cdots, (1, \frac{n}{n}), (2, \frac{1}{m}), (2, \frac{2}{m}), \cdots (2, \frac{m}{m})$. For some value $x$, If there are walls at $(1, x)$ and $(2, x)$ at the same time, we can't move from $y$ to $z$ for $y \lt x$ and $z \gt x$. Let's call them a "dual wall." Suppose $g = gcd(n, m)$. Then dual walls exist at $\frac{1}{g}, \frac{2}{g}, \cdots, \frac{g}{g}$. So we can make $g$ groups. We can move freely in the same group, and we can't move from one group to another group.For $x = 1$, $(1, 1), (1,2), \cdots, (1,\frac{n}{g})$ belong to group $1$, and $(1, \frac{n}{g} + 1), (1, \frac{n}{g} + 2), \cdots, (1, \frac{2n}{g})$ belong to group $2$, and so on. For $x = 2$, $(2, 1), (2, 2), \cdots, (2, \frac{m}{g})$ belong to group $1$, and $(2, \frac{m}{g} + 1), (2, \frac{m}{g} + 2), \cdots, (2, \frac{2m}{g})$ belong to group $2$, and so on. For each query, print YES if $(sx, sy)$ and $(ex, ey)$ belong to the same group. Otherwise, print NO. time complexity: $O(log(max(n,m)) + q)$
[ "math", "number theory" ]
1,400
null
1200
D
White Lines
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $n$ rows and $n$ columns of square cells. The rows are numbered from $1$ to $n$, from top to bottom, and the columns are numbered from $1$ to $n$, from left to right. The position of a cell at row $r$ and column $c$ is represented as $(r, c)$. There are only two colors for the cells in cfpaint — black and white. There is a tool named eraser in cfpaint. The eraser has an integer size $k$ ($1 \le k \le n$). To use the eraser, Gildong needs to click on a cell $(i, j)$ where $1 \le i, j \le n - k + 1$. When a cell $(i, j)$ is clicked, all of the cells $(i', j')$ where $i \le i' \le i + k - 1$ and $j \le j' \le j + k - 1$ become white. In other words, a square with side equal to $k$ cells and top left corner at $(i, j)$ is colored white. A white line is a row or a column without any black cells. Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser \textbf{exactly once}. Help Gildong find the answer to his question.
Let's consider a single row that contains at least one black cell. If the first appearance of a black cell is at the $l$-th column and the last appearance of a black cell is at the $r$-th column, we can determine whether it becomes a white line when a certain cell $(i, j)$ is clicked in $O(1)$, after some preprocessing. It becomes a white line if and only if a cell $(i,j)$ is clicked where the row is at $[i,i+k-1]$ and $j \le l \le r \le j+k-1$. We just need to compute $l$ and $r$ in advance. Now let's consider all $n$ rows (not columns). First, count all rows that are already white lines before clicking. Then we count the number of white rows when the cell $(1,1)$ is clicked, by applying the above method to all rows from $1$ to $k$. Ignore the already-white rows that we counted before. So far we obtained the number of white rows when the cell $(1,1)$ is clicked. From now, we slide the window. Add the $k+1$-st row and remove the $1$-st row by applying the same method to them, and we obtain the number of white rows when the cell $(2,1)$ is clicked. We can repeat this until we calculate all $n-k+1$ cases for clicking the cells at the $1$-st column. Then we repeat the whole process for all $n-k+1$ columns. The same process can be done for counting white columns, too. Now we know the number of white rows and white columns when each cell is clicked, so we can find the maximum value among their sums. Time complexity: $O(n^2)$
[ "brute force", "data structures", "dp", "implementation", "two pointers" ]
1,900
null
1200
E
Compress Words
Amugae has a sentence consisting of $n$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease". Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.
Denote the words from left to right as $W_1, W_2, W_3, \cdots, W_n$. If we define string $F(k)$ as the result of merging as described in the problem $k$ times, we can get $F(k+1)$ by the following process: If length of $F(k)$ > length of $W_{k+1}$ Assume the length of $F(K)$ is $x$, and the length of $W_{k+1}$ is $y$. Construct the string $c = W_{k+1} + F(k)[x-y...x]$ ( * $s[x..y]$ for string $s$ is the substring from index $x$ to $y$) Get the KMP failure function from string $c$. We can get maximum overlapped length of $W_{k+1}$'s prefix and $F(k)$'s suffix from this function. Suppose the last element of the failure function smaller than the length of $W_{k+1}$ is $z$. Then the longest overlapped length of $F(k)$'s suffix and $W_{k+1}$'s prefix is $min(z, y)$. Let $L = min(z, y)$. Then, $F(k+1) = F(k) + W_{k+1}[L+1...y]$ Otherwise Construct $c$ as $W_{k+1}[1...x] + F(k)$. We can get $F(k+1)$ from the same process described in 1. In this process, we can get $F(k+1)$ from $F(k)$ in time complexity $O(len(W_{k+1}))$. So, we can get $F(N)$ (the answer of this problem) in $O(len(W_1) + len(W_2) + \cdots + len(W_N))$.
[ "brute force", "hashing", "implementation", "string suffix structures", "strings" ]
2,000
null
1200
F
Graph Traveler
Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of $n$ vertices numbered from $1$ to $n$. The $i$-th vertex has $m_i$ outgoing edges that are labeled as $e_i[0]$, $e_i[1]$, $\ldots$, $e_i[m_i-1]$, each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The $i$-th vertex also has an integer $k_i$ written on itself. A travel on this graph works as follows. - Gildong chooses a vertex to start from, and an integer to start with. Set the variable $c$ to this integer. - After arriving at the vertex $i$, or when Gildong begins the travel at some vertex $i$, add $k_i$ to $c$. - The next vertex is $e_i[x]$ where $x$ is an integer $0 \le x \le m_i-1$ satisfying $x \equiv c \pmod {m_i}$. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex $1$ with $c = 5$, and $m_1 = 2$, $e_1[0] = 1$, $e_1[1] = 2$, $k_1 = -3$. Right after he starts at vertex $1$, $c$ becomes $2$. Since the only integer $x$ ($0 \le x \le 1$) where $x \equiv c \pmod {m_i}$ is $0$, Gildong goes to vertex $e_1[0] = 1$. After arriving at vertex $1$ again, $c$ becomes $-1$. The only integer $x$ satisfying the conditions is $1$, so he goes to vertex $e_1[1] = 2$, and so on. Since Gildong is quite inquisitive, he's going to ask you $q$ queries. He wants to know how many \textbf{distinct} vertices will be visited \textbf{infinitely many times}, if he starts the travel from a certain vertex with a certain value of $c$. Note that you should \textbf{not} count the vertices that will be visited only finite times.
Since a travel will never end, it is clear that every travel will eventually get into an infinite loop. But we should consider more than just the vertices, since $c$ could be different every time he visits the same vertex. Since the number of outgoing edges of each vertex is at most $10$, we can see a state can be reduced to $lcm(1..10) = 2520$ for each vertex. Therefore, we can think that the graph actually has $2520 \cdot n$ vertices, each with a single outgoing edge. To simulate the travels, we just need to follow the exact process written in the description, except that $c$ should be kept in modulo $2520$. The problem is when to stop, and how to count the number of distinct vertices that are in the loop. We can stop simulating until we find a state that we already have visited. There can be two cases when we find a visited state. The first case is when we have not visited this state in the previous travels, i.e. this is the first travel that visits this state. We need to check all of the states after the first visit of this state and count the number of distinct vertices. Duplicated vertices can be removed simply by using a set, or more efficiently, using timestamp. Then we can apply the answer to all of the states we visited in this travel. The second case is when the state was visited in one of the previous travels. We know that both the previous travel and the current travel will end in the same loop, so we can apply the same answer to all of the states we visited in this travel. On a side note, the simulation can be done with recursion, but this can lead to maximum of $2520000$ recursion depth. This causes stack overflow or recursion limit excess for some languages (including Java). Time complexity: $O(2520n + q)$
[ "brute force", "data structures", "dfs and similar", "dp", "graphs", "implementation", "math", "number theory" ]
2,300
null
1201
A
Important Exam
A class of students wrote a multiple-choice test. There are $n$ students in the class. The test had $m$ questions, each of them had $5$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $i$ worth $a_i$ points. Incorrect answers are graded with zero points. The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.
For each of the question let's count the number of answers of different type. Let $cnt[i][A]=$The number of A answers to the i-th question. The maximum score for that answer is $a[i]\cdot max(cnt[i][A], cnt[i][B], cnt[i][C], cnt[i][D], cnt[i][E])$. The answer is the sum of the maximum answer for the $m$ questions.
[ "implementation", "strings" ]
900
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, m; string s[1005]; ll a[1005]; ll ans; ll b[1005][5]; ll ma; int main() { ios_base::sync_with_stdio(false); cin>>n>>m; for (ll i=1; i<=n; i++) { cin>>s[i]; } for (ll i=0; i<m; i++) { cin>>a[i]; } for (ll i=0; i<m; i++) { ma=0; for (ll j=1; j<=n; j++) { b[i][s[j][i]-'A']++; } for (ll j=0; j<5; j++) { ma=max(ma, b[i][j]); } ans+=ma*a[i]; } cout<<ans; }
1201
B
Zero Array
You are given an array $a_1, a_2, \ldots, a_n$. In one operation you can choose two elements $a_i$ and $a_j$ ($i \ne j$) and decrease each of them by one. You need to check whether it is possible to make all the elements equal to zero or not.
There are 2 things needed to be possible to make all elements zero: 1: The sum of the elements must be even. 2: The biggest element have to be less or equal than the sum of all the other elements. If both are true, the answer is "YES", otherwise "NO".
[ "greedy", "math" ]
1,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, m, a, s; int main() { ios_base::sync_with_stdio(false); cin>>n; for (ll i=1; i<=n; i++) { cin>>a; s+=a; m=max(m, a); } if (s%2==1 || s<2*m) { cout<<"NO"; return 0; } cout<<"YES"; return 0; }
1201
C
Maximum Median
You are given an array $a$ of $n$ integers, where $n$ is odd. You can make the following operation with it: - Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$). You want to make the median of the array the largest possible using at most $k$ operations. The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $[1, 5, 2, 3, 5]$ is $3$.
Sort the array in non-decreasing order. In the new array $b_1, b_2, \ldots, b_n$ you can make binary search with the maximum median value. For a given median value ($x$), it is required to make $\sum_{i=(n+1)/2}^{n} max(0,x-b_i)$ operations. If this value is more than $k$, $x$ can't be median, otherwise it can. Time complexity: $O((n/2) \cdot log(10^9))$
[ "binary search", "greedy", "math", "sortings" ]
1,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, k; ll x; vector < ll > a; bool check(ll x) { ll moves=0; for (int i=n/2; i<n; i++) { if (x-a[i]>0) moves+=x-a[i]; if (moves>k) return false; } if (moves<=k) return true; else return false; } int main() { ios_base::sync_with_stdio(false); cin>>n>>k; for (int i=1; i<=n; i++) { cin>>x; a.push_back(x); } sort(a.begin(), a.end()); ll small=1; ll big=2000000000; while (small!=big) { ll mid=(small+big+1)/2; if (check(mid)) { small=mid; } else{ big=mid-1; } } cout<<small; }
1201
D
Treasure Hunting
You are on the island which can be represented as a $n \times m$ table. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are $k$ treasures on the island, the $i$-th of them is located at the position $(r_i, c_i)$. Initially you stand at the lower left corner of the island, at the position $(1, 1)$. If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from $(r, c)$ to $(r+1, c)$), left (from $(r, c)$ to $(r, c-1)$), or right (from position $(r, c)$ to $(r, c+1)$). Because of the traps, you can't move down. However, moving up is also risky. You can move up only if you are in a safe column. There are $q$ safe columns: $b_1, b_2, \ldots, b_q$. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.
Make two arrays: left and right. $left[i]$ is the treasure in the leftmost position in row i (0 if there are no treasures in row $i$). $right[i]$ is the treasure in the rightmost cell in row $i$ (0 if there are no treasures in row $i$). We can simply take out rows where there is no treasure (and add 1 to the result if there are treasure above that line, because we have to move up there). For every row, except the last, we have to leave that row at one of the safe columns. Let's notice that the last treasure we collect in the row will be either $left[i]$ or $right[i]$. Let's take a look at both possibilities: If we collect the $left[i]$ treasure last, we have to leave the row either going left or going right to the closest safe column, because going further wouldn't worth it (consider moving up earlier and keep doing the same thing at row $i+1$). The same is true for $right[i]$. For the first row, we start at the first column, we can calculate the moves required to go up the second row at the for cells. For all the other rows, we have 4 possibilities, and we have to calculate how many moves it takes to reach the row $i+1$ at the 4 possible columns. For the last row, we don't have to reach a safe column, we just have to collect all the treasures there. We can count the answer for the problem from the calculated results from the previous row. Time complexity: $O(16*n)$
[ "binary search", "dp", "greedy", "implementation" ]
2,100
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll n, m, k, q; ll tleft[300005]; ll tright[300005]; ll safeleft[300005]; ll saferight[300005]; ll a[300005][4]; ll b[4]; ll ans; vector < ll > safe; ll dis(ll pa, ll pb) { return abs(pa-pb); } ll solve(ll i, ll x, ll y) { ll ansa=dis(x, tright[i]); ansa+=dis(tright[i], tleft[i]); ansa+=dis(tleft[i], y); ll ansb=dis(x, tleft[i]); ansb+=dis(tright[i], tleft[i]); ansb+=dis(tright[i], y); return 1+min(ansa, ansb); } ll solvelast(ll x) { ll ansa=dis(x, tright[n]); ansa+=dis(tright[n], tleft[n]); ll ansb=dis(x, tleft[n]); ansb+=dis(tright[n], tleft[n]); return 1+min(ansa, ansb); } int main() { ios_base::sync_with_stdio(false); cin>>n>>m>>k>>q; ll x=0, y=0; for (ll i=1; i<=k; i++) { cin>>x>>y; if (tleft[x]==0) tleft[x]=y; tleft[x]=min(tleft[x], y); tright[x]=max(tright[x], y); } for (ll i=1; i<=q; i++) { cin>>x; safe.push_back(x); } sort(safe.begin(), safe.end()); for (ll j=1; j<=safe[0]; j++) { saferight[j]=safe[0]; } for (ll j=safe[0]; j<safe[1]; j++) { safeleft[j]=safe[0]; } for (ll i=1; i<safe.size()-1; i++) { for (ll j=safe[i-1]+1; j<=safe[i]; j++) { saferight[j]=safe[i]; } for (ll j=safe[i]; j<safe[i+1]; j++) { safeleft[j]=safe[i]; } } for (ll j=safe[safe.size()-2]+1; j<=safe[safe.size()-1]; j++) { saferight[j]=safe[safe.size()-1]; } for (ll j=safe[safe.size()-1]; j<=m; j++) { safeleft[j]=safe[safe.size()-1]; } while (tleft[n]==0) { n--; } if (n==1) { cout<<tright[1]-1; return 0; } if (tright[1]==0) { a[1][0]=saferight[1]-1; b[0]=saferight[1]; } else{ if (safeleft[tright[1]]!=0) { a[1][0]=tright[1]-1+dis(tright[1], safeleft[tright[1]]); b[0]=safeleft[tright[1]]; } if (saferight[tright[1]]!=0) { a[1][1]=tright[1]-1+dis(tright[1], saferight[tright[1]]); b[1]=saferight[tright[1]]; } } for (ll i=2; i<n; i++) { ll c[4]; if (tright[i]==0) { for (ll j=0; j<4; j++) { a[i][j]=a[i-1][j]+1; } continue; } c[0]=safeleft[tleft[i]]; c[1]=saferight[tleft[i]]; c[2]=safeleft[tright[i]]; c[3]=saferight[tright[i]]; for (ll p=0; p<4; p++) { a[i][p]=INT_MAX; a[i][p]*=a[i][p]; } for (ll j=0; j<4; j++) { if (b[j]!=0) { for (ll p=0; p<4; p++) { if (c[p]!=0) { a[i][p]=min(a[i][p], a[i-1][j]+solve(i, b[j], c[p])); } } } } for (ll j=0; j<4; j++) { b[j]=c[j]; } } ans=INT_MAX; ans*=ans; for (ll j=0; j<4; j++) { if (b[j]!=0) { ans=min(ans, a[n-1][j]+solvelast(b[j])); } } cout<<ans; }
1201
E2
Knightmare (hard)
This is an interactive problem. Alice and Bob are playing a game on the chessboard of size $n \times m$ where $n$ and $m$ are \textbf{even}. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are two knights on the chessboard. A white one initially is on the position $(x_1, y_1)$, while the black one is on the position $(x_2, y_2)$. Alice will choose one of the knights to play with, and Bob will use the other one. The Alice and Bob will play in turns and whoever controls \textbf{the white} knight starts the game. During a turn, the player must move their knight adhering the chess rules. That is, if the knight is currently on the position $(x, y)$, it can be moved to any of those positions (as long as they are inside the chessboard): \begin{center} $(x+1, y+2)$, $(x+1, y-2)$, $(x-1, y+2)$, $(x-1, y-2)$,$(x+2, y+1)$, $(x+2, y-1)$, $(x-2, y+1)$, $(x-2, y-1)$. \end{center} We all know that knights are strongest in the middle of the board. Both knight have a single position they want to reach: - the owner of the white knight wins if it captures the black knight or if the white knight is at $(n/2, m/2)$ and this position is not under attack of the black knight at this moment; - The owner of the black knight wins if it captures the white knight or if the black knight is at $(n/2+1, m/2)$ and this position is not under attack of the white knight at this moment. Formally, the player who captures the other knight wins. The player who is at its target square ($(n/2, m/2)$ for white, $(n/2+1, m/2)$ for black) and this position is not under opponent's attack, also wins. A position is under attack of a knight if it can move into this position. Capturing a knight means that a player moves their knight to the cell where the opponent's knight is. If Alice made $350$ moves and nobody won, the game is a draw. Alice is unsure in her chess skills, so she asks you for a help. Choose a knight and win the game for her. It can be shown, that Alice always has a winning strategy.
First calculate the number of moves needed to reach (without capturing) positions $(a_1;b_1)$ and $(a_2;b_2)$. If one of the knights can reach it's goal at least 2 moves faster than the other can and faster than the other can reach it's goal, than there is a winning strategy with it. Just go the shortest path. The other knight won't be able to capture your knight, because after you move you are $x$ moves away from it, than the other knight must be at least $x+2$ far, so it will be at least $x+1$ after it's move. If one of the knights can reach it's goal at exactly 1 move faster than the other can and faster than the other can reach it's goal, we have to count the moves needed to reach all the positions which is 1 move away from the goal. If there is a position from these which can be reached at least 2 moves faster, than that knight can win. Let's color the chessboard the regular way with white and black colors. If the 2 knights are in same color, than only the black knight can capture the white, otherwise only the white can capture the black (that is because knights always move to different color than they come from). In all the other situation there is at least drawing strategy with the knight that can capture the other: Move to the position that the other knight have to reach and stay there or 1 move away from it. The other knight won't be able to reach that position without getting captured. So we choose that knight and search for the winning strategy. You can win the game in 2 steps: First: Go to your opponent's target cell in the fastest way (if the opponent could go there faster, you can still outrun him, because there is no position which is 1 move away from the opponents goal and can be reached at least 2 moves faster (we already looked that situation), so you can take away the opponent's possibility to reach the target by threatening with capturing their knight). This is maximum of 333 moves. Second: Go from there to your target cell on the fastest way. It can be easily shown that it takes 3 moves to go there. When you are in the opponent's target position your opponent can be either exactly 1 move or at least 3 moves away from you (because the distance (in moves) between you and your opponent's knight after your opponent's turn is always odd). If it is 1 move away, you can capture his knight, if at least 3 or moves away from you (and therefore the target position), you can reach your target faster than your opponent. That's a total of 336 moves.
[ "graphs", "interactive", "shortest paths" ]
3,000
/** * This line was copied from template * This is nk_n4.cpp * * @author: Nikolay Kalinin * @date: Sun, 04 Aug 2019 03:59:47 +0300 */ #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; using pii = pair<int, int>; using pli = pair<ll, int>; using pll = pair<ll, ll>; #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 45; const int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2}; const int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1}; int n, m, xw, yw, xb, yb, mode; bool isterm[maxn][maxn][maxn][maxn][2]; bool wins[maxn][maxn][maxn][maxn][2]; int remmoves[maxn][maxn][maxn][maxn][2]; int dist[maxn][maxn][maxn][maxn][2]; vector<array<int, 6>> terms; int moves[maxn][maxn]; int cntpos = 0; void markterm(int x1, int y1, int x2, int y2, int turn, int res) { if (isterm[x1][y1][x2][y2][turn]) return; isterm[x1][y1][x2][y2][turn] = true; dist[x1][y1][x2][y2][turn] = 0; terms.pb({x1, y1, x2, y2, turn, res}); } void mark(int x1, int y1, int x2, int y2, int turn, int res) { cntpos++; wins[x1][y1][x2][y2][turn] = res; isterm[x1][y1][x2][y2][turn] = true; dist[x1][y1][x2][y2][turn]++; if (turn == 1) // now second moves, previous move made first { for (int d = 0; d < 8; d++) { int nx = x1 + dx[d]; int ny = y1 + dy[d]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m && !isterm[nx][ny][x2][y2][1 - turn]) { if (res == 0) { dist[nx][ny][x2][y2][1 - turn] = dist[x1][y1][x2][y2][turn]; mark(nx, ny, x2, y2, 1 - turn, true); } else { remmoves[nx][ny][x2][y2][1 - turn]--; dist[nx][ny][x2][y2][1 - turn] = max(dist[nx][ny][x2][y2][1 - turn], dist[x1][y1][x2][y2][turn]); if (remmoves[nx][ny][x2][y2][1 - turn] == 0) { mark(nx, ny, x2, y2, 1 - turn, false); } } } } } else { for (int d = 0; d < 8; d++) { int nx = x2 + dx[d]; int ny = y2 + dy[d]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m && !isterm[x1][y1][nx][ny][1 - turn]) { if (res == 0) { dist[x1][y1][nx][ny][1 - turn] = dist[x1][y1][x2][y2][turn]; mark(x1, y1, nx, ny, 1 - turn, true); } else { remmoves[x1][y1][nx][ny][1 - turn]--; dist[x1][y1][nx][ny][1 - turn] = max(dist[x1][y1][nx][ny][1 - turn], dist[x1][y1][x2][y2][turn]); if (remmoves[x1][y1][nx][ny][1 - turn] == 0) { mark(x1, y1, nx, ny, 1 - turn, false); } } } } } } inline bool canmove(int x1, int y1, int x2, int y2) { return minmax(abs(x1 - x2), abs(y1 - y2)) == minmax(1, 2); } bool won() { if (xw == xb && yw == yb) return true; if (mode == 0) { return xw == n / 2 && yw == m / 2 && !canmove(xw, yw, xb, yb); } else { return xb == n / 2 + 1 && yb == m / 2 && !canmove(xw, yw, xb, yb); } } int main() { scanf("%d%d", &n, &m); for (int x1 = 1; x1 <= n; x1++) { for (int y1 = 1; y1 <= m; y1++) { moves[x1][y1] = 0; for (int d = 0; d < 8; d++) { int nx = x1 + dx[d]; int ny = y1 + dy[d]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m) moves[x1][y1]++; } } } for (int x1 = 1; x1 <= n; x1++) { for (int y1 = 1; y1 <= m; y1++) { for (int x2 = 1; x2 <= n; x2++) { for (int y2 = 1; y2 <= m; y2++) { remmoves[x1][y1][x2][y2][0] = moves[x1][y1]; remmoves[x1][y1][x2][y2][1] = moves[x2][y2]; } } } } for (int x1 = 1; x1 <= n; x1++) { for (int y1 = 1; y1 <= m; y1++) { if (x1 != n / 2 || y1 != m / 2) { if (!canmove(x1, y1, n / 2, m / 2)) markterm(n / 2, m / 2, x1, y1, 1, false); markterm(n / 2, m / 2, x1, y1, 0, true); } if (x1 != n / 2 + 1 || y1 != m / 2) { if (!canmove(x1, y1, n / 2 + 1, m / 2)) markterm(x1, y1, n / 2 + 1, m / 2, 0, false); markterm(x1, y1, n / 2 + 1, m / 2, 1, true); } markterm(x1, y1, x1, y1, 0, false); markterm(x1, y1, x1, y1, 1, false); } } for (auto &t : terms) { mark(t[0], t[1], t[2], t[3], t[4], t[5]); } assert(cntpos == n * m * n * m * 2); scanf("%d%d", &xw, &yw); scanf("%d%d", &xb, &yb); if (wins[xw][yw][xb][yb][0]) mode = 0; else mode = 1; if (mode == 0) cout << "WHITE" << endl; else cout << "BLACK" << endl; for (int IT = 0; ; IT++) { if (IT % 2 == mode) { if (mode == 0) { for (int d = 0; d < 8; d++) { int nx = xw + dx[d]; int ny = yw + dy[d]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && !wins[nx][ny][xb][yb][1] && dist[nx][ny][xb][yb][1] < dist[xw][yw][xb][yb][0]) { cout << nx << ' ' << ny << endl; xw = nx; yw = ny; break; } } } else { for (int d = 0; d < 8; d++) { int nx = xb + dx[d]; int ny = yb + dy[d]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && !wins[xw][yw][nx][ny][0] && dist[xw][yw][nx][ny][0] < dist[xw][yw][xb][yb][1]) { cout << nx << ' ' << ny << endl; xb = nx; yb = ny; break; } } } } else { int xx, yy; cin >> xx >> yy; if (mode == 0) xb = xx, yb = yy; else xw = xx, yw = yy; } if (won()) break; } return 0; }
1202
A
You Are Given Two Binary Strings...
You are given two binary strings $x$ and $y$, which are binary representations of some two integers (let's denote these integers as $f(x)$ and $f(y)$). You can choose any integer $k \ge 0$, calculate the expression $s_k = f(x) + f(y) \cdot 2^k$ and write the binary representation of $s_k$ in \textbf{reverse order} (let's denote it as $rev_k$). For example, let $x = 1010$ and $y = 11$; you've chosen $k = 1$ and, since $2^1 = 10_2$, so $s_k = 1010_2 + 11_2 \cdot 10_2 = 10000_2$ and $rev_k = 00001$. For given $x$ and $y$, you need to choose such $k$ that $rev_k$ is \textbf{lexicographically minimal} (read notes if you don't know what does "lexicographically" means). It's guaranteed that, with given constraints, $k$ exists and is finite.
Multiplying by power of $2$ is "shift left" binary operation (you, probably, should know it). Reverse $x$ and $y$ for the simplicity and look at leftmost $1$ in $y$ (let's denote its position as $pos_y$). If you move it to $0$ in $x$ then you make the $rev_k$ lexicographically bigger than the reverse of $x$. So you should move it to $1$ in $x$ too. You can choose any $1$ with position $\ge pos_y$. Let $pos_x$ be the minimum position of $1$ in $x$, such that $pos_x \ge pos_y$. You must move $pos_y$ to $pos_x$, otherwise the $1$ in $pos_x$ still be present in $rev_k$ and it will be not optimal. So, the solution is next: reverse $x$ and $y$, find $pos_y$, find $pos_x \ge pos_y$, print $pos_x - pos_y$.
[ "bitmasks", "greedy" ]
1,100
fun main(args: Array<String>) { val T = readLine()!!.toInt() for (tc in 1..T) { val x = readLine()!!.reversed() val y = readLine()!!.reversed() val posY = y.indexOf('1') val posX = x.indexOf('1', posY) println(posX - posY) } }
1202
B
You Are Given a Decimal String...
Suppose you have a special $x$-$y$-counter. This counter can store some value as a decimal number; at first, the counter has value $0$. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $x$ or $y$ to its value. So all sequences this counter generates are starting from $0$. For example, a $4$-$2$-counter can act as follows: - it prints $0$, and adds $4$ to its value, so the current value is $4$, and the output is $0$; - it prints $4$, and adds $4$ to its value, so the current value is $8$, and the output is $04$; - it prints $8$, and adds $4$ to its value, so the current value is $12$, and the output is $048$; - it prints $2$, and adds $2$ to its value, so the current value is $14$, and the output is $0482$; - it prints $4$, and adds $4$ to its value, so the current value is $18$, and the output is $04824$. This is only one of the possible outputs; for example, the same counter could generate $0246802468024$ as the output, if we chose to add $2$ during each step. You wrote down a printed sequence from one of such $x$-$y$-counters. But the sequence was corrupted and several elements from the sequence could be erased. Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $s$ — the remaining data of the sequence. For all $0 \le x, y < 10$, calculate the minimum number of digits you have to insert in the string $s$ to make it a possible output of the $x$-$y$-counter. Note that you can't change the order of digits in string $s$ or erase any of them; only insertions are allowed.
All you need to know to solve this task is the minimal number of steps to move from any digit $a$ to any digit $b$ for fixed $x$ and $y$ (let's denote it as $ds[a][b]$). Shortest path? BFS? Floyd? Of course, you can use it, but you can think a little harder and save nerves and time. Since order of choosing operations $x$ and $y$ doesn't matter for transferring from $a$ to $b$, so only number of $x$-s and $y$-s are matter. Let's denote them as $cnt_x$ and $cnt_y$. Since adding any fixed value $10$ times are meaningless, so $cnt_x, cnt_y < 10$. Now you can, for each $x < 10$, for each $y < 10$, for each $a < 10$ iterate over all possible $cnt_x < 10$ and $cnt_y < 10$. Digit $b$ you'd move to is equal to $(a + cnt_x \cdot x + cnt_y \cdot y) \mod 10$. Just relax value of $ds[a][b]$ by $cnt_x + cnt_y$. Now you can, for each $x$ and $y$, calculate the answer by iterating over string $s$ by summing $ds[s[i]][s[i + 1]] - 1$ (number of inserted values is less by one than number of steps). But, it will work only in C++, since the language is fast and $2 \cdot 10^8$ basic operations are executed in less than 0.5 second. But the model solution is written in Kotlin. How is it? The string $s$ can be long, but there are only $10 \times 10$ different neighbouring digits, so you can just one time precalculate $cf[a][b]$ - the number of such $i$ that $s[i] = a$ and $s[i + 1] = b$. And calculate the answer not by iterating over $s$ but by multiplying $ds[a][b]$ by $cf[a][b]$. The result complexity is $O(|s| + A^5)$, where $A = 10$. But $O(A^2(n + A^3))$ will pass on fast languages like C++. P.S.: There are no real problem with I/O - both Python and Kotlin read one string up to $2 \cdot 10^6$ in less than 0.5 seconds.
[ "brute force", "dp", "shortest paths" ]
1,700
const val INF = 1e9.toInt() fun main(args: Array<String>) { val s = readLine()!!.map { it - '0' } val cf = Array(10) {Array(10) {0}} for (i in 1 until s.size) cf[s[i - 1]][s[i]]++ for (x in 0..9) { for (y in 0..9) { val ds = Array(10) {Array(10) {INF + 7}} for (v in 0..9) { for (cx in 0..9) { for (cy in 0..9) { if (cx + cy == 0) continue val to = (v + cx * x + cy * y) % 10 ds[v][to] = minOf(ds[v][to], cx + cy) } } } var res = 0 for (v in 0..9) { for (to in 0..9) { if (ds[v][to] > INF && cf[v][to] > 0) { res = -1 break } res += (ds[v][to] - 1) * cf[v][to] } if (res == -1) break } print("$res ") } println() } }
1202
C
You Are Given a WASD-string...
You have a string $s$ — a sequence of commands for your toy robot. The robot is placed in some cell of a \textbf{rectangular} grid. He can perform four commands: - 'W' — move one cell up; - 'S' — move one cell down; - 'A' — move one cell left; - 'D' — move one cell right. Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: - you can place the robot in the cell $(3, 2)$; - the robot performs the command 'D' and moves to $(3, 3)$; - the robot performs the command 'S' and moves to $(4, 3)$; - the robot performs the command 'A' and moves to $(4, 2)$; - the robot performs the command 'W' and moves to $(3, 2)$; - the robot performs the command 'W' and moves to $(2, 2)$; - the robot performs the command 'A' and moves to $(2, 1)$; - the robot performs the command 'W' and moves to $(1, 1)$. You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert \textbf{at most one of these letters} in any position of sequence $s$ to minimize the area of $Grid(s)$. What is the minimum area of $Grid(s)$ you can achieve?
The problem asks us to maintain the bounding box while inserting the character of one of $4$ types between every adjacent characters in $s$. Of course, we can do it, but do we really need to do it in such cumbersome way? Let's think a little. Inserting 'W' or 'S' doesn't affect the width of the bounding box, and 'A' or 'D' doesn't affect the height. So, they are absolutely independent! And we can divide our WASD-string on WS-string and AD-string. Moreover, inserting 'W' or 'S' in WS-string and 'A' or 'D' in AD-string is almost same thing, so we don't even need to write different code for different string! How to handle only WS-string? Let's replace 'W' as $+1$ and 'S' as $-1$ and suppose that we started in position $0$. Then the position, where we go after $i$ commands, is just prefix sum of first $i$ elements ($i \ge 0$). Then the length of the bounding box is (maximum position - minimum position + 1). The maximum (minimum) position is a maximum (minimum) element in array of prefix sums $pSum$. What the inserted value do? It add $\pm 1$ to suffix of $pSum$. Let's choose, for example, $+1$. The $+1$ can't decrease the maximum, but can increase the minimum, so we need to place it somewhere before all minimums in $pSum$ (or before the first minimum). But, if we place it before any of maximum elements then we will increase it and prevent decreasing the length of bounding box. So we need to place $+1$ somewhere after all maximums on $pSum$ (or after the last maximum). And here goes the solution: find position $firstMin$ of the first minimum in $pSum$ and position $lastMax$ of the last maximum. If $lastMax < firstMin$ then we can insert $+1$ and decrease the length of bounding box (but, since, we insert command that move robot, we can't achieve bounding box of length $< 2$). What to do with $-1$? Just multiply $pSum$ by $-1$ and now we can insert $+1$ instead of $-1$ in absolutely same manner. What to do with AD-string? Denote 'A' as $+1$ and 'D' as $-1$ and everything is absolutely the same.
[ "brute force", "data structures", "dp", "greedy", "implementation", "math", "strings" ]
2,100
const val INF = 1e9.toInt() fun main(args: Array<String>) { val T = readLine()!!.toInt() for (tc in 1..T) { val s = readLine()!! val alp = arrayOf("WS", "AD") val aDir = arrayOf( s.filter { alp[0].indexOf(it) != -1 }, s.filter { alp[1].indexOf(it) != -1 } ) val baseW = arrayOf(INF, INF) val bestW = arrayOf(INF, INF) for (k in 0..1) { val pSum = arrayListOf(0) for (c in aDir[k]) { val add = if (c == alp[k][0]) +1 else -1 pSum.add(pSum.last() + add) } for (tp in 0..1) { val firstMin = pSum.withIndex().minBy { it.value }!!.index val lastMax = pSum.withIndex().reversed().maxBy { it.value }!!.index val curBase = pSum[lastMax] - pSum[firstMin] + 1 var curBest = curBase if (curBase > 2 && lastMax < firstMin) --curBest baseW[k] = minOf(baseW[k], curBase) bestW[k] = minOf(bestW[k], curBest) for (i in pSum.indices) pSum[i] = -pSum[i] } } println("${minOf(baseW[0] * 1L * bestW[1], baseW[1] * 1L * bestW[0] )}") } }
1202
D
Print a 1337-string...
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given an integer $n$. You have to find a sequence $s$ consisting of digits $\{1, 3, 7\}$ such that it has exactly $n$ subsequences equal to $1337$. For example, sequence $337133377$ has $6$ subsequences equal to $1337$: - $337\underline{1}3\underline{3}\underline{3}7\underline{7}$ (you can remove the second and fifth characters); - $337\underline{1}\underline{3}3\underline{3}7\underline{7}$ (you can remove the third and fifth characters); - $337\underline{1}\underline{3}\underline{3}37\underline{7}$ (you can remove the fourth and fifth characters); - $337\underline{1}3\underline{3}\underline{3}\underline{7}7$ (you can remove the second and sixth characters); - $337\underline{1}\underline{3}3\underline{3}\underline{7}7$ (you can remove the third and sixth characters); - $337\underline{1}\underline{3}\underline{3}3\underline{7}7$ (you can remove the fourth and sixth characters). \textbf{Note that the length of the sequence $s$ must not exceed $10^5$.} You have to answer $t$ independent queries.
Let's consider the following string $1333 \dots 3337$. If digit $3$ occurs $x$ times in it, then string have $\frac{x (x-1)}{2}$ subsequences $1337$. Let's increase the number of digits $3$ in this string while condition $\frac{x (x-1)}{2} \le n$ holds ($x$ is the number of digits $3$ in this string). The length of this string will not exceed $45000$ because $\frac{45000 (45000-1)}{2} > 10^9$. The value $rem = n - \frac{x (x-1)}{2}$ will not exceed $45000$ as well. All we have to do is increase the number of subsequences $1337$ in the current string by $rem$. So if we add $rem$ digits $7$ after the first two digits $3$ we increase the number of subsequences $1337$ by $rem$. The string $s$ will look like this: $133{77 \dots 77}{33 \dots 33}7$, where sequence ${77\dots77}$ consists of exactly $rem$ digits $7$ and sequence ${33\dots33}$ consists of exactly $x-2$ digits $3$.
[ "combinatorics", "constructive algorithms", "math", "strings" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int tc = 0; tc < t; ++tc){ int n; cin >> n; int len = 2; while(len * (len + 1) / 2 <= n) ++len; n -= len * (len - 1) / 2; assert(n >= 0); assert(n <= 45000); string s = "133"; while(n > 0){ --n; s += "7"; } len -= 2; while(len > 0){ --len; s += "3"; } s += "7"; cout << s << endl; } return 0; }
1202
E
You Are Given Some Strings...
You are given a string $t$ and $n$ strings $s_1, s_2, \dots, s_n$. All strings consist of lowercase Latin letters. Let $f(t, s)$ be the number of occurences of string $s$ in string $t$. For example, $f('\text{aaabacaa}', '\text{aa}') = 3$, and $f('\text{ababa}', '\text{aba}') = 2$. Calculate the value of $\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$, where $s + t$ is the concatenation of strings $s$ and $t$. Note that if there are two pairs $i_1$, $j_1$ and $i_2$, $j_2$ such that $s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}$, you should include both $f(t, s_{i_1} + s_{j_1})$ and $f(t, s_{i_2} + s_{j_2})$ in answer.
Let's look at any occurrence of arbitrary pair $s_i + s_j$. There is exactly one special split position, where the $s_i$ ends and $s_j$ starts. So, instead of counting occurrences for each pair, we can iterate over the position of split and count the number of pairs. This transformation is convenient, since any $s_i$, which ends in split position can be paired with any $s_j$ which starts here. So, all we need is to calculate for each suffix the number of strings $s_i$, which starts here, and for each prefix - the number of strings $s_i$, which ends here. But calculating the prefixes can be transformed to calculating suffixes by reversing both $t$ and all $s_i$. Now we need, for each position $pos$, calculate the number of strings $s_i$ which occur from $pos$. It can be done by Aho-Corasick, Suffix Array, Suffix Automaton, Suffix Tree, but do we really need them since constrains are pretty low? The answer is NO. We can use sqrt-heuristic! Let's divide all $s_i$ in two groups: short and long. The $s_i$ is short if $|s_i| \le MAG$. There are no more than $\frac{\sum{|s_i|}}{MAG}$ long strings and, for each such string, we can find all its occurrences with z-function (or prefix-function). It will cost as $O(\frac{\sum{|s_i|}}{MAG} \cdot |t| + \sum{|s_i|})$. What to do with short strings? Let's add them to trie! The trie will have $O(\sum{|s_i|})$ vertices, but only $MAG$ depth. So we can, for each $pos$, move down through the trie, while counting the occurrences, using only $s[pos..(pos + MAG)]$ substring. It will cost us $O(|t| \cdot MAG)$. So, if we choose $MAG = \sqrt{\sum{|s_i|}}$ we can acquire $O(\sum{|s_i|} + |t| \sqrt{\sum{|s_i|}})$ complexity, using only basic string structures.
[ "brute force", "string suffix structures", "strings" ]
2,400
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9) + 7; const li INF64 = li(1e18) + 7; const int N = 500005; const int A = 27; const int MAG = 500; struct node { node *to[A]; int cnt; } nodes[N]; int szn = 0; typedef node* vt; vt getNode() { assert(szn < N); fore(i, 0, A) nodes[szn].to[i] = NULL; nodes[szn].cnt = 0; return &nodes[szn++]; } void addWord(vt v, const string &s) { fore(i, 0, sz(s)) { int c = s[i] - 'a'; if (!v->to[c]) v->to[c] = getNode(); v = v->to[c]; } v->cnt++; } int calcCnt(vt v, const string &s, int pos) { assert(v->cnt == 0); int ans = 0; while(pos < sz(s)) { int c = s[pos] - 'a'; if (!v->to[c]) break; v = v->to[c]; ans += v->cnt; pos++; } return ans; } vector<int> zf(string s) { vector<int> z(sz(s), 0); for (int i = 1, l = 0, r = 0; i < sz(s); ++i) { if(i < r) z[i] = min(r - i, z[i - l]); while (i + z[i] < sz(s) && s[i + z[i]] == s[z[i]]) z[i]++; if(i + z[i] > r) l = i, r = i + z[i]; } return z; } string t; int n; vector<string> s; inline bool read() { if(!(cin >> t)) return false; cin >> n; s.resize(n); fore(i, 0, n) cin >> s[i]; return true; } inline void solve() { vector<int> cnt[2]; fore(k, 0, 2) { cnt[k].assign(sz(t) + 1, 0); szn = 0; vt root = getNode(); forn(i, n) { if (sz(s[i]) > MAG) { auto z = zf(s[i] + t); fore(j, 0, sz(t)) cnt[k][j] += (z[sz(s[i]) + j] >= sz(s[i])); } else { addWord(root, s[i]); } } fore(i, 0, sz(t)) cnt[k][i] += calcCnt(root, t, i); reverse(all(t)); fore(i, 0, n) reverse(all(s[i])); } li ans = 0; fore(i, 0, sz(t) + 1) ans += cnt[0][i] * 1ll * cnt[1][sz(t) - i]; cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1202
F
You Are Given Some Letters...
You are given $a$ uppercase Latin letters 'A' and $b$ letters 'B'. The period of the string is the smallest such positive integer $k$ that $s_i = s_{i~mod~k}$ ($0$-indexed) for each $i$. Note that this implies that $k$ won't always divide $a+b = |s|$. For example, the period of string "ABAABAA" is $3$, the period of "AAAA" is $1$, and the period of "AABBB" is $5$. Find the number of different periods over all possible strings with $a$ letters 'A' and $b$ letters 'B'.
Let's introduce the slightly naive solution. Iterate over all values for periods and check the possibility of each one being correct. The conditions for some period $k$ can be formulated the following way. $g = n / k$ ($n = a + b$ is the total length of the string) is the number of full periods of length $k$. Let's find at least one such pair $cnt_a$ and $cnt_b$ such that $cnt_a + cnt_b = x$ and the remainder part of the string can be filled with $a - cnt_a \cdot g$ letters 'A' and $b - cnt_b \cdot g$ letters 'B'. By easy construction one can deduce that the conditions of $a - cnt_a \cdot g \le cnt_a$ and $b - cnt_b \cdot g \le cnt_b$ are enough. Thus $cnt_a$ should be greater or equal to $\frac{a}{g + 1}$ and $cnt_b \ge \frac{b}{g + 1}$. In order to move to the faster solution one should also remember that both remainder parts $a - cnt_a \cdot g$ and $b - cnt_b \cdot g$ should be non-negative. Let's learn how to solve the problem for the whole range of lengths which all have the number of full periods equal to the same value $g$. Let this range be $[l; r]$. From the aforementioned formulas one can notice that the restrictions on both $cnt_a$ and $cnt_b$ don't depend on the length itself but only on value of $g$. To be more specific: $\frac{a}{g + 1} \le cnt_a \le \frac{a}{g}$ $\frac{b}{g + 1} \le cnt_b \le \frac{b}{g}$ The lowest and the highest values for $cnt_a$ and $cnt_b$ will be the following: $a_{low} = \lceil \frac{a}{g + 1} \rceil$ $a_{high} = \lfloor \frac{a}{g} \rfloor$ $b_{low} = \lceil \frac{b}{g + 1} \rceil$ $b_{high} = \lfloor \frac{b}{g} \rfloor$ It is claimed that every value between $a_{low} + b_{low}$ and $a_{high} + b_{high}$ exists if the values are valid ($a_{low} \le a_{high}$ and $b_{low} \le b_{high}$). The full proof about the given conditions being sufficient and the existence of every value on that range is left to the reader. Some kind of a hint might be the suggestion to check how the inequalities change on the transition from some period $k$ to $k + 1$. Restrict the values by $l$ and $r$ to count each answer on exactly one range of lengths. Finally, the value of $min(r, a_{high} + b_{high}) - max(l, a_{low} + b_{low}) + 1$ is added to the answer. The number of ranges with the same $g$ is $O(\sqrt n)$. Overall complexity: $O(\sqrt n)$.
[ "binary search", "implementation", "math" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int a, b; scanf("%d%d", &a, &b); int n = a + b; int ans = 0; int l = 1; while (l <= n){ int g = n / l; if (a < g || b < g){ l = n / g + 1; continue; } int r = n / g; int a_low = (a + g) / (g + 1); int a_high = a / g; int b_low = (b + g) / (g + 1); int b_high = b / g; if (a_low <= a_high && b_low <= b_high) ans += max(0, min(r, a_high + b_high) - max(l, a_low + b_low) + 1); l = r + 1; } printf("%d\n", ans); }
1203
A
Circle of Students
There are $n$ students standing in a circle in some order. The index of the $i$-th student is $p_i$. It is guaranteed that all indices of students are distinct integers from $1$ to $n$ (i. e. they form a permutation). Students want to start a round dance. A \textbf{clockwise} round dance can be started if the student $2$ comes right after the student $1$ in clockwise order (there are no students between them), the student $3$ comes right after the student $2$ in clockwise order, and so on, and the student $n$ comes right after the student $n - 1$ in clockwise order. A \textbf{counterclockwise} round dance is almost the same thing — the only difference is that the student $i$ should be right after the student $i - 1$ in counterclockwise order (this condition should be met for every $i$ from $2$ to $n$). For example, if the indices of students listed in clockwise order are $[2, 3, 4, 5, 1]$, then they can start a clockwise round dance. If the students have indices $[3, 2, 1, 4]$ in clockwise order, then they can start a counterclockwise round dance. Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer $q$ independent queries.
We just need to find the position of the $1$ in the array and then check if the sequence $2, 3, \dots, n$ is going counterclockwise or clockwise from the position $pos-1$ or $pos+1$ correspondingly. We can do this by two cycles. Total complexity: $O(n)$.
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> a(n); int pos = -1; for (int j = 0; j < n; ++j) { cin >> a[j]; if (a[j] == 1) pos = j; } bool okl = true, okr = true; for (int j = 1; j < n; ++j) { okl &= (a[(pos - j + n) % n] == j + 1); okr &= (a[(pos + j + n) % n] == j + 1); } if (okl || okr) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1203
B
Equal Rectangles
You are given $4n$ sticks, the length of the $i$-th stick is $a_i$. You have to create $n$ rectangles, each rectangle will consist of exactly $4$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length. You want to all rectangles to have equal area. The area of the rectangle with sides $a$ and $b$ is $a \cdot b$. Your task is to say if it is possible to create exactly $n$ rectangles of equal area or not. You have to answer $q$ independent queries.
After sorting $a$ we can observe that if the answer is "YES" then the area of each rectangle is $area = a_{1} \cdot a_{4n}$. Then we just need to check for each $i$ from $1$ to $n$ that $a_{2i-1} = a_{2i}$ and $a_{4n-2i+1} = a_{4n-2i+2}$ and $a_{2i-1} \cdot a_{4n-2i+2} = area$. If all conditions are satisfied for all $i$ then the answer is "YES". Otherwise the answer is "NO".
[ "greedy", "math" ]
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 q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; vector<int> a(4 * n); for (int j = 0; j < 4 * n; ++j) { cin >> a[j]; } sort(a.begin(), a.end()); int area = a[0] * a.back(); bool ok = true; for (int i = 0; i < n; ++i) { int lf = i * 2, rg = 4 * n - (i * 2) - 1; if (a[lf] != a[lf + 1] || a[rg] != a[rg - 1] || a[lf] * 1ll * a[rg] != area) { ok = false; } } if (ok) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
1203
C
Common Divisors
You are given an array $a$ consisting of $n$ integers. Your task is to say the number of such positive integers $x$ such that $x$ divides \textbf{each} number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array $a$ will be $[2, 4, 6, 2, 10]$, then $1$ and $2$ divide each number from the array (so the answer for this test is $2$).
Let $g = gcd(a_1, a_2, \dots, a_n)$ is the greatest common divisor of all elements of the array. You can find it by Euclidean algorithm or some standard library functions. Then the answer is just the number of divisors of $g$. You can find this value in $\sqrt{g}$.
[ "implementation", "math" ]
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 n; cin >> n; long long g = 0; for (int i = 0; i < n; ++i) { long long x; cin >> x; g = __gcd(g, x); } int ans = 0; for (int i = 1; i * 1ll * i <= g; ++i) { if (g % i == 0) { ++ans; if (i != g / i) { ++ans; } } } cout << ans << endl; return 0; }
1203
D1
Remove the Substring (easy version)
\textbf{The only difference between easy and hard versions is the length of the string}. You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from $s$ of \textbf{maximum possible length} such that after removing this substring $t$ will remain a subsequence of $s$. If you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$). Your task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.
In this problem we can just iterate over all possible substrings and try to remove each of them. After removing the substring we can check if $t$ remains the subsequence of $s$ in linear time. Let we remove the substring $s[l; r]$. Let's maintain a pointer $pos$ (the initial value of the pointer is $1$) and iterate over all possible $i$ from $1$ to $|s|$. If $pos \le |t|$ and $s_i = t_{pos}$ let's increase $pos$ by one. If after all iterations $pos = |t| + 1$ then let's update the answer with the length of the current substring.
[ "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s, t; cin >> s >> t; int ans = 0; for (int i = 0; i < int(s.size()); ++i) { for (int j = i; j < int(s.size()); ++j) { int pos = 0; for (int p = 0; p < int(s.size()); ++p) { if (i <= p && p <= j) continue; if (pos < int(t.size()) && t[pos] == s[p]) ++pos; } if (pos == int(t.size())) ans = max(ans, j - i + 1); } } cout << ans << endl; return 0; }
1203
D2
Remove the Substring (hard version)
\textbf{The only difference between easy and hard versions is the length of the string}. You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from $s$ of \textbf{maximum possible length} such that after removing this substring $t$ will remain a subsequence of $s$. If you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$). Your task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.
Let $rg_i$ be such rightmost position $x$ in $s$ that the substring $t[i;|t|]$ is the subsequence of $s[x;|s|]$. We need values $rg_i$ for all $i$ from $1$ to $|t|$. We can calculate it just iterating from right to left over all characters of $s$ and maintaining the pointer to the string $t$ as in easy version. Then let's iterate over all positions $i$ from $1$ to $|s|$ and maintain the pointer $pos$ as in the easy version which tells us the maximum length of the prefix of $t$ we can obtain using only the substring $s[1;i)$ (exclusively!). Suppose we want to remove the substring of $s$ starting from $i$. Then if $pos \le |t|$ then let $rpos$ be $rg_{pos} - 1$, otherwise let $rpos$ be $|s|$. $rpos$ tells us the farthest rightmost character of the substring we can remove. So we can update the answer with the value $rpos - i + 1$ and go to the next position (and don't forget to increase $pos$ if needed).
[ "binary search", "greedy", "implementation", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif string s, t; cin >> s >> t; vector<int> rg(t.size()); for (int i = int(t.size()) - 1; i >= 0; --i) { int pos = int(s.size()) - 1; if (i + 1 < int(t.size())) pos = rg[i + 1] - 1; while (s[pos] != t[i]) --pos; rg[i] = pos; } int ans = 0; int pos = 0; for (int i = 0; i < int(s.size()); ++i) { int rpos = int(s.size()) - 1; if (pos < int(t.size())) rpos = rg[pos] - 1; ans = max(ans, rpos - i + 1); if (pos < int(t.size()) && t[pos] == s[i]) ++pos; } cout << ans << endl; return 0; }
1203
E
Boxers
There are $n$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique). Write a program that for given current values ​$a_i$ will find the maximum possible number of boxers in a team. It is possible that after some change the weight of some boxer is $150001$ (but no more).
Let $lst$ be the last weight of the boxer taken into the team. Initially $lst = \infty$. Let's sort all boxers in order of non-increasing their weights and iterate over all boxers in order from left to right. If the current boxer has the weight $w$ then let's try to take him with weight $w+1$ (we can do it if $w+1<lst$). If we cannot do it, let's try to take him with weight $w$. And in case of fault let's try to take him with weight $w-1$. If we cannot take him even with weight $w-1$ then let's skip him. And if we take him let's replace $lst$ with him weight. The answer is the number of boxers we took.
[ "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); int lst = a[0] + 2; int ans = 0; for (int i = 0; i < n; ++i) { int cur = -1; for (int dx = 1; dx >= -1; --dx) { if (a[i] + dx > 0 && a[i] + dx < lst) { cur = a[i] + dx; break; } } if (cur == -1) continue; ++ans; lst = cur; } cout << ans << endl; }
1203
F1
Complete the Projects (easy version)
\textbf{The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version}. Polycarp is a very famous freelancer. His current rating is $r$ units. Some very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Is it possible to complete all the projects? Formally, write a program to check if such an order of the projects exists, that Polycarp has enough rating before starting each project, and he has non-negative rating after completing each project. In other words, you have to check that there exists such an order of projects in which Polycarp will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.
Firstly, let's divide all projects into two sets: all projects giving us non-negative rating changes (let this set be $pos$) and all projects giving up negative rating changes (let this set be $neg$). Firstly let's take all projects from the set $pos$. How do we do that? Let's sort them by $a_i$ in non-decreasing order because each project we take cannot make our rating less and we need to consider them in order of their requirements. If we can take the current project $i$ ($r \ge a_i$), set $r := r + b_i$ and go further, otherwise print "NO" and terminate the program. Okay, what do we do with the projects that has negative $b_i$? Firstly, let's set $a_i := max(a_i, -b_i)$. This means the tighter requirement of this project, obviously. Then let's sort all projects in order of $a_i + b_i$ in non-increasing order and go from left to right and take all of them. If we cannot take at least one project, the answer is "NO". Otherwise the answer is "YES".
[ "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; bool comp(const pair<int, int>& a, const pair<int, int>& b) { return a.first + a.second > b.first + b.second; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, r; cin >> n >> r; vector<pair<int, int>> pos, neg; for (int i = 0; i < n; ++i) { pair<int, int> cur; cin >> cur.first >> cur.second; if (cur.second >= 0) pos.push_back(cur); else { cur.first = max(cur.first, abs(cur.second)); neg.push_back(cur); } } sort(pos.begin(), pos.end()); sort(neg.begin(), neg.end(), comp); int taken = 0; for (int i = 0; i < int(pos.size()); ++i) { if (r >= pos[i].first) { r += pos[i].second; ++taken; } } vector<vector<int>> dp(neg.size() + 1, vector<int>(r + 1, 0)); dp[0][r] = taken; for (int i = 0; i < int(neg.size()); ++i) { for (int cr = 0; cr <= r; ++cr) { if (cr >= neg[i].first && cr + neg[i].second >= 0) { dp[i + 1][cr + neg[i].second] = max(dp[i + 1][cr + neg[i].second], dp[i][cr] + 1); } dp[i + 1][cr] = max(dp[i + 1][cr], dp[i][cr]); } } int ans = 0; for (int cr = 0; cr <= r; ++cr) ans = max(ans, dp[int(neg.size())][cr]); cout << (ans == n ? "YES" : "NO") << endl; return 0; }
1203
F2
Complete the Projects (hard version)
\textbf{The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version}. Polycarp is a very famous freelancer. His current rating is $r$ units. Some very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects \textbf{having maximum possible size} and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects.
To view the main idea of the problem, read the editorial of easy version. The only difference is that for non-negative $b_i$ we don't need to print "NO" if we cannot take the project, we just need to skip it because we cannot take it at all. And for negative $b_i$ we need to write the knapsack dynamic programming to take the maximum possible number of projects (we need to consider them in order of their sorting). Dynamic programming is pretty easy: $dp_{i, j}$ means that we consider $i$ projects and our current rating is $j$ and the value of dp is the maximum number of negative projects we can take. If the current project is the $i$-th negative project in order of sorting, we can do two transitions: $dp_{i + 1, j} = max(dp_{i + 1, j}, dp_{i, j})$ and if $r + b_i \ge 0$ then we can make the transition $dp_{i + 1, j + b_i} = max(dp_{i + 1, j + b_i}, dp_{i, j} + 1)$. And then we just need to find the maximum value among all values of dp and add the number of positive projects we take to find the answer.
[ "dp", "greedy" ]
2,300
#include <bits/stdc++.h> using namespace std; bool comp(const pair<int, int>& a, const pair<int, int>& b) { return a.first + a.second > b.first + b.second; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, r; cin >> n >> r; vector<pair<int, int>> pos, neg; for (int i = 0; i < n; ++i) { pair<int, int> cur; cin >> cur.first >> cur.second; if (cur.second >= 0) pos.push_back(cur); else { cur.first = max(cur.first, abs(cur.second)); neg.push_back(cur); } } sort(pos.begin(), pos.end()); sort(neg.begin(), neg.end(), comp); int taken = 0; for (int i = 0; i < int(pos.size()); ++i) { if (r >= pos[i].first) { r += pos[i].second; ++taken; } } vector<vector<int>> dp(neg.size() + 1, vector<int>(r + 1, 0)); dp[0][r] = taken; for (int i = 0; i < int(neg.size()); ++i) { for (int cr = 0; cr <= r; ++cr) { if (cr >= neg[i].first && cr + neg[i].second >= 0) { dp[i + 1][cr + neg[i].second] = max(dp[i + 1][cr + neg[i].second], dp[i][cr] + 1); } dp[i + 1][cr] = max(dp[i + 1][cr], dp[i][cr]); } } int ans = 0; for (int cr = 0; cr <= r; ++cr) ans = max(ans, dp[int(neg.size())][cr]); cout << ans << endl; return 0; }
1204
A
BowWow and the Timetable
In the city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \geq 0$. Team BowWow has arrived at the station at the time $s$ and it is trying to count how many trains have they missed; in other words, the number of trains that have departed \textbf{strictly before} time $s$. For example if $s = 20$, then they missed trains which have departed at $1$, $4$ and $16$. As you are the only one who knows the time, help them! Note that the number $s$ will be given you in a binary representation without leading zeroes.
Basically, the problem asks you to count $\lceil \log_4 s \rceil$, which is equal to $\Bigl\lceil \dfrac{\log_2 s}{\log_2 4} \Bigr\rceil = \Bigl\lceil \dfrac{\log_2 s}{2} \Bigr\rceil$. If we denote $l$ as a length of the input number, then $\lceil \log_2 s \rceil$ is either equal to $l-1$ if $s$ is the power of two (it can be checked by checking that there is not more than one $1$ in the input string), or to $l-1$ otherwise, so the answer to the problem is either $\Bigl\lceil \dfrac{l-1}{2} \Bigr\rceil$ or $\Bigl\lceil \dfrac{l}{2} \Bigr\rceil$. Also for $s=0$ the answer is $0$.
[ "math" ]
1,000
null
1204
B
Mislove Has Lost an Array
Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it: - The number of different numbers in the array is not less than $l$ and is not greater than $r$; - For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there is a number $\dfrac{a_i}{2}$ in the array. For example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\frac{16}{2} = 8$. According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.
Any array that satisfies statements' conditions contains only powers of two from $2^0$ to $2^{k-1}$, where $l \leq k \leq r$, so the minimal sum is achieved when we take powers of two from $2^0$ to $2^{l-1}$ and set the other $n-l$ elements equal to $2^0$; the maximal sum is achieved when we take powers of two from $2^0$ to $2^{r-1}$ and set the other $n-r$ elements equal to $2^{r-1}$.
[ "greedy", "math" ]
900
null
1204
C
Anna, Svyatoslav and Maps
The main characters have been omitted to be short. You are given a directed unweighted graph without loops with $n$ vertexes and a path in it (that path is not necessary simple) given by a sequence $p_1, p_2, \ldots, p_m$ of $m$ vertexes; for each $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$. Define the sequence $v_1, v_2, \ldots, v_k$ of $k$ vertexes as good, if $v$ is a subsequence of $p$, $v_1 = p_1$, $v_k = p_m$, and $p$ is one of the shortest paths passing through the vertexes $v_1$, $\ldots$, $v_k$ in that order. A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $p$ is good but your task is to find the \textbf{shortest} good subsequence. If there are multiple shortest good subsequences, output any of them.
Firstly, find the matrix of the shortest paths using Floyd-Warshall algortihm or running dfs from all vertexes; then a greedy approach works here: add $p_1$ to the answer and then go along the path; if the distance from the last vertex in the answer to the current vertex $p_i$ is shorter than in given path, add the vertex $p_{i-1}$ to the answer and continue traversing the path. Don't forget to add $p_m$ in the end!
[ "dp", "graphs", "greedy", "shortest paths" ]
1,700
null
1204
D2
Kirk and a Binary String (hard version)
\textbf{The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.} Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions: - For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$; - The number of zeroes in $t$ is the maximum possible. A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$. If there are multiple substrings which satisfy the conditions, output any.
Solution 1: Let's call a string $p$ fixed if there isn't another string $t$ of the same length which satisfies the first condition of the statement (it was about the same lengths of the longest nondecreasing subsequences on substrings). The following statements are obivous: string $10$ is fixed; if strings $p$ and $q$ are fixed, then their concatenation $pq$ is fixed; if a string $p$ is fixed, then the string $1p0$ is fixed; each fixed string contains the same number of ones and zeroes; the length of the longest nondecreasing subsequence for any fixed string is equal to the half of its length, which can be obtained by taking all zeroes or all ones; So if we erase all fixed strings from the given string, the remaining parts consists of zeroes at prefix and ones at suffix; it is obvious that we can change all these ones to zeroes and the string still satisfies the condition. Solution 2: If we change any $1$ to $0$ and the longest nondecreasing sequence of the whole string remains the same, then we are able to change it to $0$. To count the longest nondecreasing sequence of a new string, store and maintain following arrays: $dp^p_i$ - the longest nondecreasing sequence of the substring $s_{1 \ldots i}$; $zero_i$ - number of zeroes in the substring $s_{1 \ldots i}$; $dp^s_i$ - the longest nondecreasing sequence of the substring $s_{i \ldots n}$ and $ones_i$ - number of ones in the substring $s_{i \ldots n}$; now, if we change $1$ to $0$ at a position $i$, then the length of the longest nondecreasing sequence of a new string is $\max(dp^p_{i-1}+ones_{i+1},zero_{i-1}+1+dp^s_{i+1})$.
[ "data structures", "greedy", "math", "strings" ]
2,100
null
1204
E
Natasha, Sasha and the Prefix Sums
Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ elements are equal to $-1$. For each such array they counted its maximal prefix sum, probably an empty one which is equal to $0$ (in another words, if every nonempty prefix sum is less to zero, then it is considered equal to zero). Formally, denote as $f(a)$ the maximal prefix sum of an array $a_{1, \ldots ,l}$ of length $l \geq 0$. Then: $$f(a) = \max (0, \smash{\displaystyle\max_{1 \leq i \leq l}} \sum_{j=1}^{i} a_j )$$ Now they want to count the sum of maximal prefix sums for each such an array and they are asking you to help. As this sum can be very large, output it modulo $998\: 244\: 853$.
Let's count a dp $k[x][y]$ - the number of arrays consisting of $x$ ones and $y$ minus ones such that their maximal prefix sum is equal to $0$: if $x=0$ then $k[x][y] = 1$, else if $x>y$ then $k[x][y] = 0$, else $k[x][y] = k[x-1][y] + k[x][y-1]$, because if we consider any array consisting of $x$ ones and $y-1$ minus ones which maximal prefix sum is $0$ then adding a minus one to the end leaves it equal to $0$; also if we consider any array consisting of $x-1$ ones and $y$ minus ones which maximal prefix sum is $0$ then adding a one to the end leaves it equal to $0$, because $x \leq y$. Now let's count a dp $d[x][y]$ - the answer to the problem for $n=x$ and $m=y$: if $x=0$ then $d[x][y]=0$, else if $y=0$ then $d[x][y]=x$, else $d[x][y] = (\binom{x+y-1}{y}+d[x-1][y]) + (d[x][y-1] - (\binom{x+y-1}{x}-k[x][y-1]))$. That is because if we consider any array of $x-1$ ones and $y$ minus ones (there are $\binom{x+y-1}{y}$ such arrays) then adding a one in its beginning increases its maximal prefix sum by $1$; also if we consider any array of $x$ ones and $y-1$ minus ones then adding a minus one in its beginning either decreases its maximal prefix sum by $1$ if it was greater than $0$ (there are $\binom{x+y-1}{x}-k[x][y-1]$ such arrays) or leaves it equal to $0$. So the answer to the problem is $d[n][m]$.
[ "combinatorics", "dp", "math", "number theory" ]
2,300
null
1205
A
Almost Equal
You are given integer $n$. You have to arrange numbers from $1$ to $2n$, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every $n$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $2n$ numbers differ not more than by $1$. For example, choose $n = 3$. On the left you can see an example of a valid arrangement: $1 + 4 + 5 = 10$, $4 + 5 + 2 = 11$, $5 + 2 + 3 = 10$, $2 + 3 + 6 = 11$, $3 + 6 + 1 = 10$, $6 + 1 + 4 = 11$, any two numbers differ by at most $1$. On the right you can see an invalid arrangement: for example, $5 + 1 + 6 = 12$, and $3 + 2 + 4 = 9$, $9$ and $12$ differ more than by $1$.
Consider a valid arrangement for some $n$. We denote $S_i = a_i + a_ {i + 1} + a_ {i + 2} + \dots + a_ {i + n-1}$ for each $i$ from $1$ to $2n$, where $a_ {t + 2n} = a_ {t}$. Then we have: $S_ {i + 1} -S_i = (a_ {i + 1} + a_ {i + 2} + a_ {i + 3} + \dots + a_ {i + n}) - (a_i + a_ {i + 1} + a_ {i + 2} + \dots + a_ {i + n-1}) = a_ {i + n} -a_i$. Hence $| a_ {i + n} -a_i | \le 1$. Since $a_ {i + n}$ and $a_i$ are different, $| a_ {i + n} - a_i | =$ 1. It is also clear from this that $a_ {i + n} - a_i$ and $a_ {i + n + 1} - a_ {i + 1}$ have opposite signs: if they were both equal to $1$, we would get $S_ {i + 2} - S_i = (S_ {i + 2} - S_ {i + 1}) + (S_ {i + 1} - S_i) = (a_ {i + n + 1} - a {i + 1 }) + (a_ {i + n} - a_i) =$ 2, similarly with $-1$. Thus, the values $a_ {i + n} -a_i$ for $i$ from $1$ to $2n$ shoul be $1$ and $-1$ alternating, and this is a sufficient condition. Now, if $n$ is even, we get a contradiction, since $a_ {i + n} - a_i = - (a _ {(i + n) + n} - a_ {i + n})$, but due to the alternating they must be equal. If $n$ is odd, then it's now easy to build an example: for $i$ from $1$ to $n$ $a_i = 2i-1$, $a_i = 2i$, if $i$ is even, and $a_i = 2i$ , $a_i = 2i-1$ if $i$ is odd. Asymptotics $O (n)$. Challenge: For which pairs of $(n, k)$ ($n> k \ge 1$) is there an arrangement of numbers from $1$ to $n$ on a circle such that the sums of each $k$ consecutive numbers differ by not more than $1$ ?
[ "constructive algorithms", "greedy", "math" ]
1,200
null
1205
B
Shortest Cycle
You are given $n$ integer numbers $a_1, a_2, \dots, a_n$. Consider graph on $n$ nodes, in which nodes $i$, $j$ ($i\neq j$) are connected if and only if, $a_i$ AND $a_j\neq 0$, where AND denotes the bitwise AND operation. Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
The most important thing in this task is to notice that if any bit is contained at least $3$ numbers, then they will form a cycle of length $3$, and the answer is $3$. Suppose now that each bit is in no more than two numbers. It follows that each bit can be shared by at most one pair of numbers. From here we get that in the graph there are no more than $60$ edges. Then in it you can find the shortest cycle in $O (m ^ 2)$: for each edge between the vertices $u$ and $v$ we will try to remove it and find the shortest distance between the vertices $u$, $v$ in the resulting graph. If each time $u$ and $v$ turned out to be in different components, then there is no cycle in the graph, otherwise its length is $1$ + the minimal of the distances found. Asymptotics $O (n \ log {10 ^ {18}} + 60 ^ 2)$.
[ "bitmasks", "brute force", "graphs", "shortest paths" ]
1,900
null
1205
C
Palindromic Paths
\textbf{This is an interactive problem} You are given a grid $n\times n$, where $n$ is \textbf{odd}. Rows are enumerated from $1$ to $n$ from up to down, columns are enumerated from $1$ to $n$ from left to right. Cell, standing on the intersection of row $x$ and column $y$, is denoted by $(x, y)$. Every cell contains $0$ or $1$. It is known that the top-left cell contains $1$, and the bottom-right cell contains $0$. We want to know numbers in all cells of the grid. To do so we can ask the following questions: "$?$ $x_1$ $y_1$ $x_2$ $y_2$", where $1 \le x_1 \le x_2 \le n$, $1 \le y_1 \le y_2 \le n$, and $x_1 + y_1 + 2 \le x_2 + y_2$. In other words, we output two different cells $(x_1, y_1)$, $(x_2, y_2)$ of the grid such that we can get from the first to the second by moving only to the right and down, and they aren't adjacent. As a response to such question you will be told if there exists a path between $(x_1, y_1)$ and $(x_2, y_2)$, going only to the right or down, numbers in cells of which form a palindrome. For example, paths, shown in green, are palindromic, so answer for "$?$ $1$ $1$ $2$ $3$" and "$?$ $1$ $2$ $3$ $3$" would be that there exists such path. However, there is no palindromic path between $(1, 1)$ and $(3, 1)$. Determine all cells of the grid by asking not more than $n^2$ questions. It can be shown that the answer always exists.
Denote $ask ((x_1, y_1), (x_2, y_2)) = 1$ if there is a palindromic path between them, and $0$ otherwise. We also denote by $grid [i] [j]$ the number written in the cell $(i, j)$. Firstly, make an observation: if the Manhattan distance is $| x_2-x_1 | + | y_2-y_1 | =$ 2, then $ask ((x_1, y_1), (x_2, y_2)) = 1 \iff board [x1] [y1] = board [x2] [y2]$. In fact, the path between the cells $(x_1, y_1)$ and $(x_2, y_2)$ has a length of $3$, and therefore it is palindromic if and only if $board [x1] [y1] = board [x2 ] [y2]$. Consider a chessboard coloring such that the upper left unit is painted white. Then, using the observation described above, we can restore the numbers in all white cells. In a similar way, if we fix a certain number in a black cell, then all other numbers in black cells will be restored uniquely. Thus, we only have two options for arranging numbers on the board, which differ in the fact that in the second option, the numbers in the black cells are opposite to those in the first option. In the figure below, green pairs of white cells are connected, about which we can ask questions to find out all the values in them, and red - pairs of black cells. Now there are two approaches. First: for each option, calculate $ask ((x_1, y_1), (x_2, y_2))$ for each pair of suitable cells, find where they differ, and ask a question about these two cells. This way we can uniquely identify the board option. It is possible to determine $ask ((x_1, y_1), (x_2, y_2)$ using dynamic programming: the answer is $1$ only when $grid [x_1] [y_1] = grid [x_2] [y_2]$ and there is a path -palindrome between a pair of $(x_1 + 1, y_1), (x_1, y_1 + 1)$ and $(x_2-1, y_2), (x_2, y_2-1)$. The second approach is a little more interesting, and it also shows why there is such a pair of cells for which the two options give different answers. Consider any path with a length of $4$ cells, denote the numbers in its cells as $c_1, c_2, c_3, c_4$. Then two of the cells of the path are black, and two are white. We know the relation between $c_1, c_3$, as well as between $c_2, c_4$ (by the relation we mean that we know are numbers in them same, or different). Suppose that the relation between $c_1, c_3$ is the same as between $c_2, c_4$. Then $ask (c_1, c_4)$ will make it possible to uniquely determine all the numbers! Indeed, if $c_1 = c_4$, then $c_2 = c_3$, and therefore the path will be palindromic. Otherwise, no path between $c_1$ and $c_4$ will be palindromic. Thus, we will be able to establish a relation between some white and some black cell, which will be enough to solve the problem. Suppose that for any path of four cells $c_1, c_2, c_3, c_4$, the relation between $c_1, c_3$ is different from the relation between $c_2, c_4$. This is equivalent to $c_1 \oplus c_2 \oplus c_3 \oplus c_4 = 1$. Suppose that for any path of four cells $\oplus$ of numbers in them is equal to $1$. Then we consider any path from the cell $(1, 1)$ to the cell $(n, n)$ of length $2n-1$. If the xor of each $4$ of neighboring cells in it is $1$, then the line is periodic with a period of $4$, but the numbers in the first and last cell in it are different from the condition! Thus, the algorithm is as follows: choose any path between $(1, 1)$ and $(4, 4)$, find on it four cells with a xor of numbers equal to $0$, and ask a question about it. Asymptotics $O (n ^ 2)$.
[ "implementation", "interactive" ]
2,400
null
1205
D
Almost All
You are given a tree with $n$ nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes $i$, $j$, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from $1$ to $\lfloor \frac{2n^2}{9} \rfloor$ has to be written on the blackboard at least once. It is guaranteed that such an arrangement exists.
First we prove the following lemma: Suppose that there are $n$ vertices in the tree $G$ with the root $v$. Let also $0 <a_1 <a_2 \dots <a_ {n-1}$ be any $n-1$ different positive numbers. Then we can arrange non-negative integers on the edges of $G$ so that the distances from $v$ to the remaining vertices of the tree are $a_1, a_2, \dots, a_{n-1}$ in some order. Proof: for example, by induction. Let $s$ be some child of $v$ in whose subtree, including $s$, there are $m$ vertices. Then we write on the edge between $(v, s)$ $a_1$, and solve the problem for the subtree $s$ and the numbers $a_2-a_1, a_3-a_1, \dots, a_m - a_1$. After that, we discard the subtree of $s$ from consideration and fill in the remaining edges for the numbers $a_{m + 1}, \dots, a_{n-1}$. Thus, the lemma is proved. Now let $c$ be the centroid of tree. Root the tree from $c$ and let $s_1, s_2, \dots, s_k$ be the sizes of the subtrees of his childs (as we know, $s_i \le \frac{n}{2}$). Divide the subtrees of the childs into two groups so that size of each group is at least $\lceil \frac{n-1}{3} \rceil$. It is possible: while there are at least $4$ subtrees, there are two for which there are no more than $\frac{n}{2}$ vertices in total, then we unite them. When we have $3$ subtrees left, we will unite two smaller ones into one group. It is easy to see that in each of the two groups there will be at least $\lceil \frac{n-1}{3} \rceil$ vertices. Let the first group have $a$ vertices and the second $b$. Then, using the lemma, we put the numbers on the edges in $a$ and between $c$ and $a$ so that the distances from $c$ to the vertices of the first group are $1, 2, \dots, a$. Similarly, we make the distance from $c$ to the vertices of the second group equal to $(a + 1), 2 (a + 1), \dots, b (a + 1)$. Then each number from $1$ to $(a + 1) (b + 1) -1$ can be obtained as the distance between some vertex from the first group and some from the second. It is easy to show that $(a + 1) (b + 1) -1$ for $a + b = n-1$ and $a, b \ge \lceil \frac{n-1}{3} \rceil$ cannot be less than $\frac {2n ^ 2} {9}$. (For example, we can say that this value is minimized at $a = \frac{n-1}{3}$ and get $(a + 1) (b + 1) -1 \ge (\frac{n + 2 }{3}) (\frac{2n + 1}{3}) - 1 = \frac{2n ^ 2 + 5n + 3}{9} - 1 \ge \frac{2n ^ 2}{9}$ for $n> 1$ (the case of $n = 1$ is obvious)). Asymptotics $O (n)$ (but a checker takes $O (n ^ 2)$)
[ "constructive algorithms", "trees" ]
2,700
null
1205
E
Expected Value Again
You are given integers $n$, $k$. Let's consider the alphabet consisting of $k$ different elements. Let \textbf{beauty} $f(s)$ of the string $s$ be the number of indexes $i$, $1\le i<|s|$, for which prefix of $s$ of length $i$ equals to suffix of $s$ of length $i$. For example, beauty of the string $abacaba$ equals $2$, as for $i = 1, 3$ prefix and suffix of length $i$ are equal. Consider all words of length $n$ in the given alphabet. Find the expected value of $f(s)^2$ of a uniformly chosen at random word. We can show that it can be expressed as $\frac{P}{Q}$, where $P$ and $Q$ are coprime and $Q$ isn't divided by $10^9 + 7$. Output $P\cdot Q^{-1} \bmod 10^9 + 7$.
Let $f_i (s)$ be a function of the string $s$ equal to $1$ if the prefix and suffix of length $i$ are equal, and equal to $0$ otherwise. We need to calculate $E ((f_1 (s) + f_2 (s) + \dots + f_{n-1}(s))^2) =$ (using linearity of expectation) $\sum_{i = 1}^{n-1} E(f_i (s) ^ 2) + \sum_{1 \le i, j \le n-1, i \neq j} E (f_i (s) f_j (s))$. We will call the number $k$ the period of the string $s$ if $s [i] = s [i + k]$ for all $1 \le i \le len (s) + 1-k$. Moreover, the length of $s$ is not required to be divided by $k$. ** Statement 1: ** $f_i (s) = 1 \iff$ $n-i$ is the period of the string is $s$. ** Proof: ** that $f_i (s) = 1$ is equivalent to $s[1]s[2] \dots s[i] = s[n + 1-i]s[n + 2 -i] \dots s[n]$, which is equivalent to the fact that $s [j] = s [j + n - i]$ for $j$ from $1$ to $i$. ** Statement 2: ** $E (f_i (s)) = k ^ {- i}$. ** Proof: ** The probability that $f_i (s) = 1$ is $k ^ {- i}$, since each of the last $i$ characters is uniquely determined from the previous ones. ** Statement 3: ** Let $i_1 = n-i, j_1 = n-j$. Then $E (f_i (s) f_j (s)) = k ^ {max (i_1 + j_1 - n, gcd (i_1, j_1)) - n}$. ** Proof: ** Assume that $f_i (s) = f_j (s) = 1$. We know that the string is $i_1$ and $j_1$-periodic. Consider a graph of $n$ string positions, and draw edges between positions at distances $i_1, j_1$. Then the number of different strings satisfying $f_i (s) = f_j (s) = 1$ is $k ^ {comps}$, where $comps$ is the number of connected components of our graph. Then $E (f_i (s) f_j (s)) = k ^ {comps-n}$. Thus, we need to show that $comps = max (i_1 + j_1 - n, gcd (i_1, j_1))$. The case of $i_1 + j_1 \le n$ is obvious: in this case, by subtracting and adding $i_1, j_1$ we can show that the string has period $gcd (i_1, j_1)$, in this case $comps = gcd (i_1, j_1 )$. We now consider the case when $i_1 + j_1> n$. Without loss of generality, $i <j \implies i_1> j_1$. We write out in a circle numbers from $1$ to $i_1$. They denote the components of connectivity when we draw only the edges connecting the positions at a distance of $i_1$. Now we need to add edges of the form $(k, k + j_1)$ for $k = 1, 2, \dots, j$ (here $i_1 + 1 = 1, \dots$). Moreover, we know that $j <i_1$. We will add these edges one at a time and observe how the connected components change. If we connected two positions that were not connected yet, then we reduced the number of connected components by $1$. Otherwise, we connected two already connected vertices and formed a cycle. When does a cycle form at all? If we consider all the edges of the form $(k, k + j_1)$, then our graph is divided into $gcd (i_1, j_1)$ cycles - components, each of which contains all positions giving the same residues when divided by $gcd (i_1, j_1)$. Thus, it is necessary to calculate how many of these cycles we form. If $t$ cycles are formed, then the number of components will be $i_1 - j + t = i_1 + j_1 - n + t$. How many cycles will we create? Let's see if the cycle consisting of positions giving the remainder $x$ when divided by $gcd (i_1, j_1)$ closes. It closes only if all its vertices are in $[1, j]$. This is equivalent to the fact that among the positions in $[j + 1, i_1]$, not a single number gives the remainder of $x$ when dividing by $gcd (i_1, j_1)$. If $i_1-j = i_1 + j_1 - n \ge gcd (i_1, j_1)$, then this cannot happen for any $x$, $t = 0$, and $comp = i_1 + j_1 - n = max (i_1 + j_1 - n, gcd (i_1, j_1)$. Otherwise, there will be exactly $gcd (i_1, j_1) - (i_1 + j_1-n)$, where $comp = i_1 + j_1 - n + gcd (i_1, j_1) - (i_1 + j_1-n) = gcd (i_1, j_1)$. Thus, the statement is proved. Further reasoning is standard. We have shown that $E (f_i (s) f_j (s))$ depends only on $i_1 + j_1$ and $gcd (i_1, j_1)$. It remains for $s, gcd$ to count the number of pairs $i_1, j_1$ such that $s = i_1 + j_1$, $gcd = gcd (i1, j1)$, $1 \le i_1, j_1 \le n-1$. We will do it as follows: if $s_2 = \frac{s}{gcd}$, $i_2 = \frac{i_1}{gcd}$, $j_2 = \frac{j_2}{gcd}$, then we rewrite it as $s_2 = i_2 + j_2$, $gcd (i_2, j_2) = 1$, $1 \le i_2, j_2 \le \lfloor \frac{n-1}{gcd} \rfloor$. Now we just need to find the number of numbers coprime to $s_2$ on the segment $[max (1, s - \lfloor \frac{n-1}{gcd} \rfloor), min (s-1, \lfloor \frac{n-1}{gcd} \rfloor)]$. This can be done for $O (2 ^ {primes})$, where $primes$ is the number of prime divisors of $s_2$. It can be shown that this gives the asymptotics of $O (n\log {n} ^ 2)$ (If you have a better one, please share in the comments!)
[ "combinatorics", "strings" ]
3,100
null
1205
F
Beauty of a Permutation
Define the beauty of a permutation of numbers from $1$ to $n$ $(p_1, p_2, \dots, p_n)$ as number of pairs $(L, R)$ such that $1 \le L \le R \le n$ and numbers $p_L, p_{L+1}, \dots, p_R$ are consecutive $R-L+1$ numbers in some order. For example, the beauty of the permutation $(1, 2, 5, 3, 4)$ equals $9$, and segments, corresponding to pairs, are $[1]$, $[2]$, $[5]$, $[4]$, $[3]$, $[1, 2]$, $[3, 4]$, $[5, 3, 4]$, $[1, 2, 5, 3, 4]$. Answer $q$ independent queries. In each query, you will be given integers $n$ and $k$. Determine if there exists a permutation of numbers from $1$ to $n$ with beauty equal to $k$, and if there exists, output one of them.
We will denote $(a, b)$ if there exists a permutation of length $a$ with beauty equal to $b$. To begin with, it is obvious that the beauty of a permutation of length $a$ is at least $a + 1$ for $a> 1$: indeed, you can take each element individually and the entire permutation completely. ** Statement 1 **: if $(a_1, b_1)$ and $(a_2, b_2)$, then $(a_1 + a_2 - 1, b_1 + b_2 - 1)$. Let $p_1, p_2, \dots, p_ {a_1}$ be a permutation of length $a_1$, whose beauty is $b_1$, and $q_1, q_2, \dots, q_ {a_2}$ be a permutation of length $a_2$, whose beauty is equal to $b_2$. Let us build from them a permutation of length $a_1 + a_2 - 1$, whose beauty is $b_1 + b_2 - 1$. We "expand" $p_1$ in the permutation $p$ to $p_1 + q_1 - 1, p_1 + q_2 - 1, \dots, p_1 + q_ {a_2} - 1$, and to the rest of the elements $p$, greater than $p_1$ , add $a_2-1$. We got a permutation of length $a_1 + a_2 - 1$. Denote it by $t$. If $t_1$ is not between $t_ {a_2}, t_ {a_2 + 1}$, then we reverse the first $a_2$ elements, and this will be done in a new permutation. Now let $t_1$ be between $t_ {a_2}$, $t_ {a_2 + 1}$. Then what good pairs do we have in $t$? There are $b_2$ good pairs among the first $a_2$ elements, there are $b_1$ good pairs if you count the first $a_2$ elements in one, and we counted the interval from the first $a_2$ elements twice, so we counted $b_1 + b_2 - 1$ pairs At the same time, this is all pairs, because if some good segment contains $t_ {a_2}$ and $t_ {a_2 + 1}$, then it must contain $t_1$ as well. Thus, this statement is proved. ** Statement 2 **: if $(a, b)$, then either $b = a + 1$, or $b = \frac{a (a + 1)}{2}$, or exist $(a_1 , b_1)$, $(a_2, b_2)$ such that $1 <a_1, a_2$, $a_1 + a_2 - 1 = a$ and $b_1 + b_2 - 1 = b$. Show it. We will call subsegments consisting of several consecutive numbers in some order good. Consider some kind of permutation of length $a$ of beauty $b$. Suppose that $b \neq a + 1$. We want to show that in the permutation there is some good $[L, R]$ subsegment of length not equal to $1$ or $a$, with the following property: for any other good $[L1, R1]$ subsegment if $[L , R]$ and $[L1, R1]$ intersect, then one of them contains the second. In this case, by analogy with the proof of Proposition 1, we can "squeeze" the segment $[L, R]$ into one element, obtaining some kind of permutation $q$. Then the number of good segments in the entire permutation will be equal to the number of good sub-segments on the segment $[L, R] +$ the number of good segments in $q$ $-1$ (since we counted the segment $[L, R]$ twice). We will call such a segment very good. Thus, if in each permutation there is a very good segment, then the statement $2$ is true. Suppose that $b \neq a + 1$, then in the permutation there is a good segment $[L, R]$ of length not equal to $1$ or $a$. Let's say he's not very good. Then there is another. We denote $(a, b)$ if there exists a permutation of length $a$ with beauty equal to $b$. To begin with, it is obvious that the beauty of a permutation of length $a$ is at least $a + 1$ for $a> 1$: indeed, you can take each element individually and the entire permutation completely. ** Statement 1 **: if $(a_1, b_1)$ and $(a_2, b_2)$, then $(a_1 + a_2 - 1, b_1 + b_2 - 1)$. Let $p_1, p_2, \ dots, p_ {a_1}$ & mdash; a permutation of length $a_1$, whose beauty is $b_1$, and $q_1, q_2, \ dots, q_ {a_2}$ & mdash; a permutation of length $a_2$, whose beauty is equal to $b_2$. Let us build from them a permutation of length $a_1 + a_2 - 1$, whose beauty is $b_1 + b_2 - 1$. We "expand" $p_1$ in the permutation $p$ to $p_1 + q_1 - 1, p_1 + q_2 - 1, \ dots, p_1 + q_ {a_2} - 1$, and to the rest of the elements $p$, greater than $p_1$ , add $a_2-1$. We got a permutation of length $a_1 + a_2 - 1$. Denote it by $t$. If $t_1$ is not between $t_ {a_2}, t_ {a_2 + 1}$, then we reverse the first $a_2$ elements, and this will be done in a new permutation. Now let $t_1$ be between $t_ {a_2}$, $t_ {a_2 + 1}$. Then what good pairs do we have in $t$? There are $b_2$ good pairs among the first $a_2$ elements, there are $b_1$ good pairs if you count the first $a_2$ elements in one, and we counted the interval from the first $a_2$ elements twice, so we counted $b_1 + b_2 - 1$ pairs At the same time, this is all pairs, because if some good segment contains $t_ {a_2}$ and $t_ {a_2 + 1}$, then it must contain $t_1$ as well. Thus, this statement is proved. ** Statement 2 **: if $(a, b)$, then either $b = a + 1$, or $b = \frac {a (a + 1)} {2}$, or $(a_1 exists , b_1)$, $(a_2, b_2)$ such that $1 <a_1, a_2$, $a_1 + a_2 - 1 = a$ and $b_1 + b_2 - 1 = b$. Show it. We will call subsegments consisting of several consecutive numbers in some order good. Consider some kind of permutation of length $a$ of beauty $b$. Suppose that $b \neq a + 1$. We want to show that in the permutation there is some good $[L, R]$ subsegment of length not equal to $1$ or $a$, with the following property: for any other good $[L1, R1]$ subsegment if $[L , R]$ and $[L1, R1]$ intersect, then one of them contains the second. In this case, by analogy with the proof of Proposition 1, we can "squeeze" the segment $[L, R]$ into one element, obtaining some kind of permutation $q$. Then the number of good segments in the entire permutation will be equal to the number of good sub-segments on the segment $[L, R] +$ the number of good segments in $q$ $-1$ (since we counted the segment $[L, R]$ twice). We will call such a segment very good. Thus, if in each permutation there is a very good segment, then the statement $2$ is true. Let $[L, R]$ be a good segment that is not very good. Then there is a good segment $[L_1, R_1]$, which intersects with $[L, R]$, but does not contain and is not contained in it. The segments $[L, R]$ and $[L_1, R_1]$ form together $3$ segments. It is easy to show that each of them is good, and the numbers in the segments go monotonously. Let us demonstrate this with an example: $p = (2, 1, 3, 5, 4)$, the first segment is $[2, 1, 3]$, the second is $[3, 5, 4]$. Then together they will give the union of three segments: $[2, 1], [3], [5, 4]$. As we can see, each of these segments is good, and also all numbers in the second segment are larger than all numbers in the first, all numbers in the third segment are larger than all numbers in the second. Let at the moment we have lined up a chain of good segments (going consecutively) $s_1, s_2, \dots, s_m$, where the union of any several consecutive ones is a good segment, as well as all the numbers in $s_ {i + 1}$ more than all the numbers in $s_i$ (or vice versa). As long as $S = s_1 + s_2 + \dots + s_m$ is not equal to the whole segment, we will do this: since $S$ is very good, there is a segment $[L, R]$ that intersects with it but is not contained in it does not contain. It is easy to see that, thanks to the segment $[L, R]$, our chain of good segments is extended. Now suppose that $s_1 + s_2 + \dots + s_m$ is the whole segment. While there is a segment of length greater than $1$ among the segments, we will do the same: if $len (s_i)> 1$, then we will find the necessary $[L, R]$ for it, then $s_i$ will be split into two smaller good segments . At the end of the process, we get $a$ good segments of length $1$ each, and the numbers are sorted monotonously. Hence, the numbers in the permutation were initially sorted monotonously, whence the number of good segments is $\frac {a (a + 1)} {2}$. The statement $2$ is proved. Now the left is easy: for each $i$ from $1$ to $100$, we calculate what beauty values can be in a permutation of length $i$ using statement $2$, storing the corresponding values $(a_1, b_1), (a_2, b_2 )$. After that, it is easy to answer the request by building a permutation of the desired beauty according to the algorithm with the approval of $1$. Asymptotics of $O (n ^ 6)$ (With an incredibly small constant, up to $n = 100$ on $Codeforces$ this works for 300 ms).
[ "constructive algorithms", "math" ]
3,400
null
1206
A
Choose Two Numbers
You are given an array $A$, consisting of $n$ positive integers $a_1, a_2, \dots, a_n$, and an array $B$, consisting of $m$ positive integers $b_1, b_2, \dots, b_m$. Choose some element $a$ of $A$ and some element $b$ of $B$ such that $a+b$ doesn't belong to $A$ and doesn't belong to $B$. For example, if $A = [2, 1, 7]$ and $B = [1, 3, 4]$, we can choose $1$ from $A$ and $4$ from $B$, as number $5 = 1 + 4$ doesn't belong to $A$ and doesn't belong to $B$. However, we can't choose $2$ from $A$ and $1$ from $B$, as $3 = 2 + 1$ belongs to $B$. It can be shown that such a pair exists. If there are multiple answers, print any. Choose and print any such two numbers.
Let $a$ be the largest number in the array $A$, $b$ be the largest number in the array $B$. Then the number $a + b$ isn't present neither in the array $A$ nor in the array $B$. Indeed, $a + b> a$, and $a$ is the largest number in the array $A$, so $a + b$ is not included in $A$. Similarly, $a + b$ is not included in $B$. Thus, you can select $a$ from $A$, $b$ from $B$. The asymptotics is $O (m \ log {m} + n \ log {n})$ if you find the largest element by sorting (which many did), or $O (m + n)$ if you find it linearly.
[ "math", "sortings" ]
800
null
1206
B
Make Product Equal One
You are given $n$ numbers $a_1, a_2, \dots, a_n$. With a cost of one coin you can perform the following operation: Choose one of these numbers and add or subtract $1$ from it. In particular, we can apply this operation to the same number several times. We want to make the product of all these numbers equal to $1$, in other words, we want $a_1 \cdot a_2$ $\dots$ $\cdot a_n = 1$. For example, for $n = 3$ and numbers $[1, -3, 0]$ we can make product equal to $1$ in $3$ coins: add $1$ to second element, add $1$ to second element again, subtract $1$ from third element, so that array becomes $[1, -1, -1]$. And $1\cdot (-1) \cdot (-1) = 1$. What is the minimum cost we will have to pay to do that?
The product of several integers is equal to one if and only if each of these numbers is $1$ or $-1$, and there must be an even number of $-1$. Then: we will have to reduce every positive $a_i$ at least to one, and we have to spend at least $a_i - 1$ coin on this. Similarly, we will have to increase every negative $a_i$ at least to $-1$, for this we will spend at least $-1 - a_i$ coins. Now we have all the numbers equal to $-1$, $0$, or $1$. Let $k$ be the number of $0$ among them. Let's analyze two cases: $k> 0$. We need to replace every zero with either $1$ or $-1$, so we will have to spend at least $k$ coins. It turns out that this is enough: change $k-1$ zeros to $1$ or $-1$ randomly, and change the last zero to $1$ or $-1$ so that the product is equal to one. $k = 0$. If the product of all numbers is $1$, we no longer need to spend coins. Otherwise, you have to change some $1$ to $-1$ or some $-1$ to $1$. This will take another $2$ coins. Asympotics $O (n)$.
[ "dp", "implementation" ]
900
null
1207
A
There Are Two Types Of Burgers
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $b$ buns, $p$ beef patties and $f$ chicken cutlets in your restaurant. You can sell one hamburger for $h$ dollars and one chicken burger for $c$ dollars. Calculate the maximum profit you can achieve. You have to answer $t$ independent queries.
In this task you just can iterate over the numbers of hamburgers and chicken burgers you want to assemble, check that you have enough ingredients and update the answer. If you want to sell $x$ hamburgers and $y$ chicken burgers then you need $x$ beef patties, $y$ chicken cutlets and $2(x+y)$ buns.
[ "brute force", "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int t; int b, p, f; int h, c; int main() { cin >> t; for(int tc = 0; tc < t; ++tc){ cin >> b >> p >> f; cin >> h >> c; b /= 2; if(h < c){ swap(h, c); swap(p, f); } int res = 0; int cnt = min(b, p); b -= cnt, p -= cnt; res += h * cnt; cnt = min(b, f); b -= cnt, f -= cnt; res += c * cnt; cout << res << endl; } return 0; }
1207
B
Square Filling
You are given two matrices $A$ and $B$. Each matrix contains exactly $n$ rows and $m$ columns. Each element of $A$ is either $0$ or $1$; each element of $B$ is initially $0$. You may perform some operations with matrix $B$. During each operation, you choose any submatrix of $B$ having size $2 \times 2$, and replace every element in the chosen submatrix with $1$. In other words, you choose two integers $x$ and $y$ such that $1 \le x < n$ and $1 \le y < m$, and then set $B_{x, y}$, $B_{x, y + 1}$, $B_{x + 1, y}$ and $B_{x + 1, y + 1}$ to $1$. Your goal is to make matrix $B$ equal to matrix $A$. Two matrices $A$ and $B$ are equal if and only if every element of matrix $A$ is equal to the corresponding element of matrix $B$. Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $B$ equal to $A$. Note that you don't have to minimize the number of operations.
It is quite obvious that we can't choose any submatrix that contains at least one zero in $A$. The contrary is also true - if a submatrix of $A$ consists of only ones, then there's no reason not to choose it (suppose there is an answer that does not choose it - then choosing this submatrix won't affect it). So we may perform an operation on every submatrix of $B$ such that the corresponding submatrix in $A$ is filled with $1$'s, and check if our answer is correct.
[ "constructive algorithms", "greedy", "implementation" ]
1,200
n, m = map(int, input().split()) a = [[] for i in range(n)] for i in range(n): a[i] = list(map(int, input().split())) ans = [] for i in range(n - 1): for j in range(m - 1): if(a[i][j] * a[i][j + 1] * a[i + 1][j] * a[i + 1][j + 1] > 0): a[i][j] = 2 a[i + 1][j] = 2 a[i][j + 1] = 2 a[i + 1][j + 1] = 2 ans.append([i, j]) cnt1 = 0 for i in range(n): for j in range(m): if(a[i][j] == 1): cnt1 += 1 if(cnt1 != 0): print(-1) else: print(len(ans)) for x in ans: print(x[0] + 1, x[1] + 1)
1207
C
Gas Pipeline
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $[0, n]$ on $OX$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $(x, x + 1)$ with integer $x$. So we can represent the road as a binary string consisting of $n$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad. Usually, we can install the pipeline along the road on height of $1$ unit with supporting pillars in each integer point (so, if we are responsible for $[0, n]$ road, we must install $n + 1$ pillars). But on crossroads we should lift the pipeline up to the height $2$, so the pipeline won't obstruct the way for cars. We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $[x, x + 1]$ with integer $x$ consisting of three parts: $0.5$ units of horizontal pipe + $1$ unit of vertical pipe + $0.5$ of horizontal. Note that if pipeline is currently on height $2$, the pillars that support it should also have length equal to $2$ units. Each unit of gas pipeline costs us $a$ bourles, and each unit of pillar — $b$ bourles. So, it's not always optimal to make the whole pipeline on the height $2$. Find the shape of the pipeline with minimum possible cost and calculate that cost. Note that you \textbf{must} start and finish the pipeline on height $1$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
This task was designed as a simple dynamic programming problem, but it also can be solved greedily. The dp solution is following: when we have already built some prefix of the pipeline all we need to know is the length of the prefix the height of the pipeline's endpoint ($1$ or $2$). So we can calculate the following dynamic programming: $d[pos][add]$ is the minimal answer for prefix of length $pos$ with pipeline at height $1 + add$. Transitions are quite straightforward: if $s[pos] = 0$ then we can either leave the pipeline on the same level, or change it. If $s[pos] = 1$ then we have to stay on the height $2$. Look at the source code for the formal transitions. The answer is $d[n][0]$. The greedy solution is based on the following fact: let's look at some subsegment consisting of $0$'s. It's always optimal either to leave this subsegment on height $1$ or raise it to height $2$. We can calculate the amount we have to pay in both cases and choose the optimal one.
[ "dp", "greedy" ]
1,500
const val INF64 = 1e18.toLong() fun main(args: Array<String>) { val tc = readLine()!!.toInt() for (t in 1..tc) { val (n, a, b) = readLine()!!.split(' ').map { it.toInt() } val s = readLine()!! val d = Array(n + 1) { arrayOf(INF64, INF64) } d[0][0] = b.toLong() for (pos in 0 until n) { if (s[pos] == '0') { d[pos + 1][0] = minOf(d[pos + 1][0], d[pos][0] + a + b) d[pos + 1][1] = minOf(d[pos + 1][1], d[pos][0] + 2 * (a + b)) d[pos + 1][1] = minOf(d[pos + 1][1], d[pos][1] + a + 2 * b) d[pos + 1][0] = minOf(d[pos + 1][0], d[pos][1] + 2 * a + b) } else { d[pos + 1][1] = minOf(d[pos + 1][1], d[pos][1] + a + 2 * b) } } println(d[n][0]) } }
1207
D
Number Of Permutations
You are given a sequence of $n$ pairs of integers: $(a_1, b_1), (a_2, b_2), \dots , (a_n, b_n)$. This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences: - $s = [(1, 2), (3, 2), (3, 1)]$ is bad because the sequence of first elements is sorted: $[1, 3, 3]$; - $s = [(1, 2), (3, 2), (1, 2)]$ is bad because the sequence of second elements is sorted: $[2, 2, 2]$; - $s = [(1, 1), (2, 2), (3, 3)]$ is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted; - $s = [(1, 3), (3, 3), (2, 2)]$ is good because neither the sequence of first elements $([1, 3, 2])$ nor the sequence of second elements $([3, 3, 2])$ is sorted. Calculate the number of permutations of size $n$ such that after applying this permutation to the sequence $s$ it turns into a good sequence. A permutation $p$ of size $n$ is a sequence $p_1, p_2, \dots , p_n$ consisting of $n$ distinct integers from $1$ to $n$ ($1 \le p_i \le n$). If you apply permutation $p_1, p_2, \dots , p_n$ to the sequence $s_1, s_2, \dots , s_n$ you get the sequence $s_{p_1}, s_{p_2}, \dots , s_{p_n}$. For example, if $s = [(1, 2), (1, 3), (2, 3)]$ and $p = [2, 3, 1]$ then $s$ turns into $[(1, 3), (2, 3), (1, 2)]$.
Let's suppose that all $n!$ permutation are good. We counted the permutations giving the sequences where the first elements are sorted (we denote the number of such permutations as $cnt_1$) and the permutations giving the sequences where the second elements are sorted (we denote the number of such permutations as $cnt_2$). Then the answer is $n! - cnt_1 - cnt_2$, right? No, because we subtracted the number of sequences where first and second elements are sorted simultaneously (we denote this number as $cnt_{12}$) twice. So, the answer is $n! - cnt_1 - cnt_2 + cnt_{12}$. How can we calculate the value of $cnt_1$? It's easy to understand that the elements having equal $a_i$ can be arranged in any order. So, $cnt_1 = c_1! ~ c_2! ~ \dots ~ c_n!$, where $c_x$ is the number of elements equal to $x$ among $a_i$. $cnt_2$ can be calculated the same way. How can we calculate the value of $cnt_{12}$? First of all, there is a case where it is impossible to arrange the elements of the sequence so that the first elements and the second elements are sorted. To check that, we may sort the given sequence comparing two elements by $a_i$, and if $a_i$ are equal - by $b_i$. If the sequence of second elements in the resulting sequence is not sorted, then $cnt_{12} = 0$. Otherwise, equal elements of the given sequence can be arranged in any order. So $cnt_{12} = c_{s_1}! ~ c_{s_2}! ~ c_{s_k}!$, where $s_1$, $s_2$, ..., $s_k$ are the elements that appear in the given sequence of pairs at least once.
[ "combinatorics" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; const int MOD = 998244353; int mul(int a, int b){ return (a * 1LL * b) % MOD; } int sum(int a, int b){ return (a + b) % MOD; } int n; pair<int, int> a[N]; int f[N]; int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d%d", &a[i].first, &a[i].second); f[0] = 1; for(int i = 1; i < N; ++i) f[i] = mul(i, f[i - 1]); int res = f[n]; for(int c = 0; c < 2; ++c){ int d = 1; sort(a, a + n); int l = 0; while(l < n){ int r = l + 1; while(r < n && a[l].first == a[r].first) ++r; d = mul(d, f[r - l]); l = r; } res = sum(res, MOD - d); for(int i = 0; i < n; ++i) swap(a[i].first, a[i].second); } sort(a, a + n); int l = 0; int d = 1; while(l < n){ int r = l + 1; while(r < n && a[l].first == a[r].first) ++r; map<int, int> m; for(int i = l; i < r; ++i) ++m[a[i].second]; for(auto p : m) d = mul(d, f[p.second]); l = r; } for(int i = 1; i < n; ++i) if(a[i - 1].second > a[i].second) d = 0; res = sum(res, d); printf("%d\n", res); return 0; }
1207
E
XOR Guessing
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307. The jury picked an integer $x$ not less than $0$ and not greater than $2^{14} - 1$. You have to guess this integer. To do so, you may ask no more than $2$ queries. Each query should consist of $100$ integer numbers $a_1$, $a_2$, ..., $a_{100}$ (each integer should be not less than $0$ and not greater than $2^{14} - 1$). In response to your query, the jury will pick one integer $i$ ($1 \le i \le 100$) and tell you the value of $a_i \oplus x$ (the bitwise XOR of $a_i$ and $x$). There is an additional constraint on the queries: all $200$ integers you use in the queries should be distinct. \textbf{It is guaranteed that the value of $x$ is fixed beforehand in each test, but the choice of $i$ in every query may depend on the integers you send.}
Suppose all integers we input in some query have the same value in the $k$-th bit. Then no matter which $i$ is chosen by the jury, we can always deduce whether the $k$-th bit in $x$ is $0$ or $1$. This leads us to a simple solution: divide $14$ bits of $x$ into two groups of size $7$. In the first query, submit $100$ integers having the same values in the bits from the first group, and deduce the values of these bits in $x$. In the second query, do the same for the second group. Be careful to avoid submitting the same integer twice.
[ "bitmasks", "interactive", "math" ]
1,900
#include<bits/stdc++.h> using namespace std; int main() { cout << "?"; for(int i = 1; i <= 100; i++) cout << " " << i; cout << endl; cout.flush(); int res1; cin >> res1; cout << "?"; for(int i = 1; i <= 100; i++) cout << " " << (i << 7); cout << endl; cout.flush(); int res2; cin >> res2; int x = 0; x |= (res1 & (((1 << 7) - 1) << 7)); x |= (res2 & ((1 << 7) - 1)); cout << "! " << x << endl; cout.flush(); return 0; }
1207
F
Remainder Problem
You are given an array $a$ consisting of $500000$ integers (numbered from $1$ to $500000$). Initially all elements of $a$ are zero. You have to process two types of queries to this array: - $1$ $x$ $y$ — increase $a_x$ by $y$; - $2$ $x$ $y$ — compute $\sum\limits_{i \in R(x, y)} a_i$, where $R(x, y)$ is the set of all integers from $1$ to $500000$ which have remainder $y$ modulo $x$. Can you process all the queries?
Let's notice that if we process the queries of type $2$ naively, then each such query consumes $O(\frac{N}{x})$ time (where $N$ is the size of the array). So queries with large $x$ can be processed naively. For queries with small $x$ ($x \le K$), we may notice two things: there are only $O(K^2)$ possible queries; each number in the array affects only $K$ possible queries. So, for small $x$, we may maintain the exact answer for each query and modify it each time we modify an element in the array. If we process naively all queries with $x > \sqrt{N}$ and maintain the answers for all queries with $x \le \sqrt{N}$, we will obtain a solution having time complexity $O(q \sqrt{N})$. Note that, as in most problems related to sqrt-heuristics, it may be optimal to choose the constant that is not exactly $\sqrt{N}$, but something similar to it (but most solutions should pass without tuning the constant).
[ "brute force", "data structures", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 500043; const int K = 750; int a[N]; int sum[K][K]; int main() { int q; scanf("%d", &q); for(int i = 0; i < q; i++) { int t, x, y; scanf("%d %d %d", &t, &x, &y); if(t == 1) { a[x] += y; for(int i = 1; i < K; i++) sum[i][x % i] += y; } else { if(x >= K) { int ans = 0; for(int i = y; i <= 500000; i += x) ans += a[i]; printf("%d\n", ans); } else printf("%d\n", sum[x][y]); } } return 0; }
1207
G
Indie Album
Mishka's favourite experimental indie band has recently dropped a new album! Songs of that album share one gimmick. Each name $s_i$ is one of the following types: - $1~c$ — a single lowercase Latin letter; - $2~j~c$ — name $s_j$ ($1 \le j < i$) with a single lowercase Latin letter appended to its end. Songs are numbered from $1$ to $n$. It's guaranteed that the first song is always of type $1$. Vova is rather interested in the new album but he really doesn't have the time to listen to it entirely. Thus he asks Mishka some questions about it to determine if some song is worth listening to. Questions have the following format: - $i~t$ — count the number of occurrences of string $t$ in $s_i$ (the name of the $i$-th song of the album) as a continuous substring, $t$ consists only of lowercase Latin letters. Mishka doesn't question the purpose of that information, yet he struggles to provide it. Can you please help Mishka answer all Vova's questions?
There is a common approach for the problem "you are given a lot of strings and texts, count the number of occurences of the strings in the texts" - build an Aho-Corasick automaton on the given strings and somehow process the texts with it. Let's see if it can handle this problem. The names of the songs can be represented as a tree. We may build an Aho-Corasick on the strings given in the queries, then try to input the names of the album into the automaton character-by-character with DFS on the aforementioned tree (feeding a character to the automaton when we enter a node, and reverting the automaton to the previous state when we leave that node). Suppose that when we are in the vertex corresponding to the $v$-th song, the automaton is in state $c$. If $c$ is a terminal state corresponding to some string from the queries, it means that the string from the query is a suffix of the $v$-th song. But some other strings can also be the suffixes of the same song - to find all such strings, we can start ascending from the state $c$ to the root of Aho-Corasick automaton using suffix links or dictionary links. Since suffix links can be represented as the edges of some rooted tree, then we can build some data structure on this tree that allows adding an integer to all vertices on the path from the root to the given vertex (for example, we can use Fenwick tree over Euler tour of the tree). Then, to check whether some string $t$ from the query is a suffix of the song $v$, we may add $1$ to all vertices on the path to state $c$, and then check the value in the state corresponding to $t$. Okay, what about counting the occurences of $t$ in $v$? Let's consider the path from the root to $v$ in the "song tree". Every vertex on this path corresponds to some prefix of the song $v$, so we can add $1$ on the path to every state corresponding to some prefix, and then extract the answer from the state corresponding to $t$. In fact, that's all we have to do to obtain a solution. Build an automaton on strings from queries, a tree of suffix links over this automaton, and a data structure on this tree; for each vertex of the song tree, store all queries to it. Then run a DFS on the song tree. When we enter some vertex, input the corresponding character into the automaton and add $1$ to all states from the root of suffix link tree to the current state; when we have to process queries to the current vertex, extract the values from the data structure; and when we leave a vertex, subtract $1$ from all states from the root of suffix link tree to the current state, and revert to the previous state. This solution has complexity of $O(T \log T)$, where $T$ is the total length of all strings in the input.
[ "data structures", "dfs and similar", "hashing", "string suffix structures", "strings", "trees" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int AL = 26; const int N = 400 * 1000 + 13; struct node{ int nxt[AL]; node(){ memset(nxt, -1, sizeof(nxt)); } int& operator [](int x){ return nxt[x]; } }; struct node_at{ int nxt[AL]; int p; char pch; int link; int go[AL]; node_at(){ memset(nxt, -1, sizeof(nxt)); memset(go, -1, sizeof(go)); link = p = -1; } int& operator [](int x){ return nxt[x]; } }; int cntnm; node trienm[N]; int cntqr; node_at trieqr[N]; int add_string(string s){ int v = 0; for (auto it : s){ int c = it - 'a'; if (trieqr[v][c] == -1){ trieqr[cntqr] = node_at(); trieqr[cntqr].p = v; trieqr[cntqr].pch = c; trieqr[v][c] = cntqr; ++cntqr; } v = trieqr[v][c]; } return v; } int go(int v, int c); int get_link(int v){ if (trieqr[v].link == -1){ if (v == 0 || trieqr[v].p == 0) trieqr[v].link = 0; else trieqr[v].link = go(get_link(trieqr[v].p), trieqr[v].pch); } return trieqr[v].link; } int go(int v, int c) { if (trieqr[v].go[c] == -1){ if (trieqr[v][c] != -1) trieqr[v].go[c] = trieqr[v][c]; else trieqr[v].go[c] = (v == 0 ? 0 : go(get_link(v), c)); } return trieqr[v].go[c]; } int add_letter(int v, int c){ if (trienm[v][c] == -1){ trienm[cntnm] = node(); trienm[v][c] = cntnm; ++cntnm; } return trienm[v][c]; } vector<int> g[N]; int tin[N], tout[N], T; void dfs_init(int v){ tin[v] = T++; for (auto u : g[v]) dfs_init(u); tout[v] = T; } int f[N]; void upd(int v, int val){ for (int i = tin[v]; i < N; i |= i + 1) f[i] += val; } int get(int x){ int sum = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) sum += f[i]; return sum; } int sum(int v){ return get(tout[v] - 1) - get(tin[v] - 1); } int n, m; int nm[N], qr[N]; vector<int> nms[N]; vector<int> reqs[N]; int ans[N]; void dfs(int v, int cur){ upd(cur, 1); for (auto it : nms[v]) for (auto q : reqs[it]) ans[q] = sum(qr[q]); forn(i, AL) if (trienm[v][i] != -1) dfs(trienm[v][i], go(cur, i)); upd(cur, -1); } int main(){ cntqr = 0; trieqr[cntqr++] = node_at(); cntnm = 0; trienm[cntnm++] = node(); char buf[N]; scanf("%d", &n); forn(i, n){ int t; scanf("%d", &t); if (t == 1){ scanf("%s", buf); nm[i] = add_letter(0, buf[0] - 'a'); } else{ int j; scanf("%d%s", &j, buf); --j; nm[i] = add_letter(nm[j], buf[0] - 'a'); } nms[nm[i]].push_back(i); } scanf("%d", &m); forn(i, m){ int j; scanf("%d%s", &j, buf); --j; reqs[j].push_back(i); qr[i] = add_string(buf); } for (int v = 1; v < cntqr; ++v) g[get_link(v)].push_back(v); T = 0; dfs_init(0); dfs(0, 0); forn(i, m) printf("%d\n", ans[i]); }
1208
A
XORinacci
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: - $f(0) = a$; - $f(1) = b$; - $f(n) = f(n-1) \oplus f(n-2)$ when $n > 1$, where $\oplus$ denotes the bitwise XOR operation. You are given three integers $a$, $b$, and $n$, calculate $f(n)$. You have to answer for $T$ independent test cases.
The sequence is $a$, $b$, $a\oplus b$, $a$, $b$, $a\oplus b$ $\cdots$ Since, the sequence has a period of $3$, $f[i] = f[i \mod 3]$.
[ "math" ]
900
#include<bits/stdc++.h> using namespace std; int main() { int test,a,b,n; cin>>test; while(test--){ cin>>a>>b>>n; switch (n%3){ case 0: cout<<a<<endl; break; case 1: cout<<b<<endl; break; default: cout<<(a^b)<<endl; } } return 0; }
1208
B
Uniqueness
You are given an array $a_{1}, a_{2}, \ldots, a_{n}$. You can remove \textbf{at most one} subsegment from it. The remaining elements should be pairwise distinct. In other words, \textbf{at most one} time you can choose two integers $l$ and $r$ ($1 \leq l \leq r \leq n$) and delete integers $a_l, a_{l+1}, \ldots, a_r$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.
After removing a sub-segment, a prefix and a suffix remain, possibly of length $0$. Let us fix the prefix which does not contain any duplicate elements and find the maximum suffix we can get without repeating the elements. We can use map/set to keep track of the elements. Time complexity: $O(n^2 \cdot log(n))$
[ "binary search", "brute force", "implementation", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 2e3 + 5; int a[N]; int main(){ int n; scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d", &a[i]); } int ans = n - 1; map<int, int> freq; for(int i = 0; i < n; ++i){ bool validPrefix = true; for(int j = 0; j < i; ++j){ freq[a[j]]++; if(freq[a[j]] == 2){ validPrefix = false; break; } } int min_index_suffix = n; for(int j = n - 1; j >= i; --j){ freq[a[j]]++; if(freq[a[j]] == 1){ min_index_suffix = j; } else break; } if(validPrefix){ ans = min(ans, min_index_suffix - i); } freq.clear(); } cout << ans << '\n';
1208
C
Magic Grid
Let us define a magic grid to be a square matrix of integers of size $n \times n$, satisfying the following conditions. - All integers from $0$ to $(n^2 - 1)$ inclusive appear in the matrix \textbf{exactly once}. - Bitwise XOR of all elements in a row or a column must be the same for each row and column. You are given an integer $n$ which is a \textbf{multiple of $4$}. Construct a magic grid of size $n \times n$.
Divide the grid into four quadrants. Assign distinct integers to the first quadrant from $0$ to $(\frac{N^2}{4} - 1)$. Copy this quadrant to the other three. This way XOR of each row and column becomes $0$. Now, to make numbers distinct among the quadrants, multiply the numbers by $4$. Add $1$, $2$, and $3$ to the numbers in $1^{st}$, $2^{nd}$ and $3^{rd}$ quadrants respectively. The XOR of each row and column would still remain $0$ as $N/2$ is also even but the elements will become distinct while being in the range $[0, N^2-1].$ Another approach in this problem is to use a $4 \times 4$ grid given in the sample itself and replicate it in $N \times N$ grid by adding $16, 32, 48 \cdots$ to make the elements distinct. Of course, there are multiple ways to solve the problem. These are just a few of them.
[ "constructive algorithms" ]
1,800
#include <bits/stdc++.h> using namespace std; #define int long long #define ld long double #define pii pair<int ,int> #define pld pair<ld ,ld> #define F first #define S second #define mod 1000000007 #define pb push_back #define mp make_pair #define all(x) x.begin(),x.end() #define mset(x) memset(x, 0, sizeof(x)); #define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); const int N = 1000; int n, grid[N][N]; void run(){ cin >> n; /* Divide Grid into Quandrants as follows: 1 | 2 ----- 3 | 4 */ int fill = 0; for(int i = 0; i < n/2; i++){ for(int j = 0; j < n/2; j++){ grid[i][j] = 4*fill + 1; // 1st quadrant grid[i][j + n/2] = 4*fill + 2; // 2nd quadrant grid[i + n/2][j] = 4*fill + 3; // 3rd quadrant grid[i + n/2][j + n/2] = 4*fill; // 4th quadrant fill++; } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cout << grid[i][j] << " "; } cout << endl; } } signed main(){ int tests = 1; // cin >> tests; for(int i = 1; i <= tests; i++) run(); return 0; }
1208
D
Restore Permutation
An array of integers $p_{1},p_{2}, \ldots,p_{n}$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3,1,2], [1], [1,2,3,4,5]$ and $[4,3,1,2]$. The following arrays are not permutations: $[2], [1,1], [2,3,4]$. There is a hidden permutation of length $n$. For each index $i$, you are given $s_{i}$, which equals to the sum of all $p_{j}$ such that $j < i$ and $p_{j} < p_{i}$. In other words, $s_i$ is the sum of elements before the $i$-th element that are smaller than the $i$-th element. Your task is to restore the permutation.
Let us fill the array with numbers from $1$ to $N$ in increasing order. $1$ will lie at the last index $i$ such that $s_{i} = 0$. Find and remove this index $i$ from the array and for all indices greater than $i$, reduce their $s_{i}$ values by $1$. Repeat this process for numbers $2, 3, ...N$. In the $i^{th}$ turn, reduce the elements by $i$. To find the last index with value zero, we can use segment tree to get range minimum query with lazy propagation. Time complexity: $O(N \cdot log(N))$ For every i from $N$ to 1, let's say the value of the $s_{i}$ is x. So it means there are $k$ smallest unused numbers whose sum is $x$. We simply put the $k+1$st number in the output permutation at this $i$, and continue to move left. This can be implemented using BIT and binary lifting. Thanks to izoomrood for expressing the solution in the above words.
[ "binary search", "data structures", "greedy", "implementation" ]
1,900
#include<bits/stdc++.h> using namespace std; const int N = 2e5 + 5; long long BIT[N], s[N]; int n; int ans[N]; void update(int x, int delta){ for(; x <= n; x += x&-x) BIT[x] += delta; } long long query(int x){ long long sum = 0; for(; x > 0; x -= x&-x) sum += BIT[x]; return sum; } int searchNumber(long long prefSum){ int num = 0; long long sum = 0; for(int i = 21; i>=0 ; --i){ if((num + (1<<i) <= n) && (sum + BIT[num + (1<<i)] <= prefSum)){ num += (1<<i); sum += BIT[num]; } } return num + 1; } int main(){ scanf("%d",&n); for(int i = 1; i <= n; ++i){ update(i, i); scanf("%lld", &s[i]); } for(int i = n; i >= 1; --i){ ans[i] = searchNumber(s[i]); update(ans[i], -ans[i]); } for(int i = 1; i <= n; ++i){ printf("%d", ans[i]); if(i < n){ printf(" "); } else printf("\n"); } }
1208
E
Let Them Slide
You are given $n$ arrays that can have different sizes. You also have a table with $w$ columns and $n$ rows. The $i$-th array is placed horizontally in the $i$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table. You need to find the maximum sum of the integers in the $j$-th column for each $j$ from $1$ to $w$ independently. \begin{center} {\small Optimal placements for columns $1$, $2$ and $3$ are shown on the pictures from left to right.} \end{center} Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.
For every array $i$ from $1$ to $N$, let us maintain 2 pointers $L[i]$ and $R[i]$, representing the range of elements in $i_{th}$ array, that can be accessed by the current column index $j$. Initially all $L[i]$ and $R[i]$ would be set equal to 0. As we move from $j_{th}$ index to $(j+1)_{th}$ index, some $L[i]$ and $R[i]$ would change. Specifically, all those arrays which have $size \ge min(j,W-j-1)$ would have their $L[i]$ and $R[i]$ change. Since overall movement of $L[i]$ and $R[i]$ would be equal to $2 \cdot$ size_of_array($i$). Overall change would be of order of $O(\sum a[i])$. For every array we need range max query in $(L[i], R[i])$. We can use multisets/ segment trees/ deques to update the answers corresponding to an array if its $L[i], R[i]$ changes. This way we can get complexity $O(N)$ or $O(N \cdot log(N))$ depending upon implementation.
[ "data structures", "implementation" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = 1e6 + 5; long long ans[N]; vector<pair<int, int> > add_element[N], remove_element[N]; multiset<int> global_ms[N]; int main(){ int n,w; scanf("%d %d", &n, &w); for(int i = 0; i < n; ++i){ int cnt; scanf("%d", &cnt); for(int j = 0; j < cnt; ++j){ int x,l,r; scanf("%d", &x); add_element[j].push_back(make_pair(x, i)); remove_element[j + w - cnt].push_back(make_pair(x, i)); } if(cnt < w){ add_element[cnt].push_back(make_pair(0, i)); remove_element[w - 1].push_back(make_pair(0, i)); add_element[0].push_back(make_pair(0, i)); remove_element[w - 1 - cnt].push_back(make_pair(0, i)); } } for(int i = 0; i < w; ++i){ for(auto j:add_element[i]){ int idx = j.second; int val = j.first; ans[i] -= (global_ms[idx].empty()? 0: *global_ms[idx].rbegin()); global_ms[idx].insert(val); ans[i] += *global_ms[idx].rbegin(); } if(i < w - 1){ ans[i + 1] = ans[i]; for(auto j:remove_element[i]){ int idx = j.second; int val = j.first; ans[i + 1] -= (*global_ms[idx].rbegin()); global_ms[idx].erase(global_ms[idx].find(val)); ans[i + 1] += (global_ms[idx].empty()? 0: *global_ms[idx].rbegin()); } } printf("%lld ",ans[i]); } printf("\n"); }
1208
F
Bits And Pieces
You are given an array $a$ of $n$ integers. You need to find the maximum value of $a_{i} | ( a_{j} \& a_{k} )$ over all triplets $(i,j,k)$ such that $i < j < k$. Here $\&$ denotes the bitwise AND operation, and $|$ denotes the bitwise OR operation.
The idea is to first fix some $a[i]$ and try to get the bits which are off in $a[i]$ from any $2$ elements to the right of $i$. Since, we need to maximize the value, we will try to get higher bits first. What we need now is, for every number $x$ from $0$ to $2^{21}-1$, the $2$ right most positions such that the bits present in $x$ are also present in the elements on those positions. This can be done by iterating over submasks(slow) or SOS-DP(fast). Once we process the positions for every $x$, let us fix some $a[i]$ and iterate over the bits which are off in $a[i]$ from the highest to the lowest. Lets say the current maximum we have got is $w$ and we are going to consider the $y^{th}$ bit. We can get this bit if the $2$ positions for $w|2^{y}$ are to the right of $i$ else we can not. The final answer would be the maximum of $a[i]|w$ over all $i$ from $1$ to $N$. Time complexity $O((M+N)\cdot logM)$ where $M$ is the max element in the array.
[ "bitmasks", "dfs and similar", "dp", "greedy" ]
2,600
#include <bits/stdc++.h> #define ll long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define vii vector<pii> #define mi map<int,int> #define mii map<pii,int> #define all(a) (a).begin(),(a).end() #define x first #define y second #define sz(x) (int)x.size() #define endl '\n' #define hell 1000000007 #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; int n,a[1000006],ans,bits; pii dp[1<<21]; void add(int mask,int w){ if(dp[mask].x==-1) dp[mask].x=w; else if(dp[mask].y==-1){ if(dp[mask].x==w) return; dp[mask].y=w; if(dp[mask].x>dp[mask].y) swap(dp[mask].x,dp[mask].y); } else{ if(dp[mask].y<w){ dp[mask].x=dp[mask].y; dp[mask].y=w; } else if(dp[mask].x<w and dp[mask].y!=w) dp[mask].x=w; } } void merge(int m1,int m2){ if(dp[m2].x!=-1) add(m1,dp[m2].x); if(dp[m2].y!=-1) add(m1,dp[m2].y); } void solve(){ memset(dp,-1,sizeof dp); cin>>n; rep(i,0,n){ cin>>a[i]; add(a[i],i); bits=max((int)log2(a[i]),bits); } bits++; rep(i,0,bits){ rep(mask,0,1<<bits){ if(mask&(1<<i)){ merge(mask^(1<<i),mask); } } } rep(i,0,n){ int cur=(1<<bits)-1-a[i]; int opt=0; for(int j=bits-1;j>=0;j--){ if((cur>>j)&1){ if(dp[opt^(1<<j)].y!=-1 and dp[opt^(1<<j)].x>i){ opt^=(1<<j); } } } if(dp[opt].y!=-1 and dp[opt].x>i) ans=max(ans,a[i]^opt); } cout<<ans<<endl; } signed main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t=1; // cin>>t; while(t--){ solve(); } return 0; }
1208
G
Polygons
You are given two integers $n$ and $k$. You need to construct $k$ regular polygons having same circumcircle, with \textbf{distinct} number of sides $l$ between $3$ and $n$. \begin{center} {\small Illustration for the first example.} \end{center} You can rotate them to minimize the total number of distinct points on the circle. Find the minimum number of such points.
If we choose a polygon with side length $l$, it is profitable to choose polygons with side lengths as divisors of $l$ as well, because this will not increase the answer. So our final set would be such that for every polygon with side length $l$, we would have polygons with side length as divisors of $l$ as well. All polygons should have at least one common point in the final arrangement, say $P$ or else we can rotate them and get such $P$. For formal proof, please refer this comment by orz. Let us represent points on the circle as the distance from point $P$. Like for $k$ sided polygon, $0$,$\frac{1}{k} ,\frac{2}{k} , \dots \frac{k-1}{k}$. Now the number of unique fractions over all the polygons would be our answer, which is equal to sum of $\phi (l)$ over all side lengths $l$ of the polygons because for $l$ sided polygon there will be $\phi(l)$ extra points required by it as compared to its divisors. One observation to get to the final solution is $\phi(l) \ge \phi(divisor(l))$. So, we can sort the side lengths by their $\phi$ values and take the smallest $k$ of them. This will minimize the number of points as well as satisfy the property of our set. NOTE: We can not consider polygon of side length $2$. This can be handled easily.
[ "greedy", "math", "number theory" ]
2,800
#include <bits/stdc++.h> using namespace std; int phi[1000006]; void process_phis(int n){ iota(phi,phi+n+1,0); for(int i = 2 ; i<=n;i++){ if(phi[i]==i){ phi[i]=i-1; for(int j=2*i;j<=n;j+=i){ phi[j]=(phi[j]/i)*(i-1); } } } } int main(){ int n,k; cin>>n>>k; if(k==1){ cout<<3<<endl; return 0; } process_phis(n); k+=2; sort(phi+1,phi+n+1); cout<<accumulate(phi+1,phi+k+1,0LL)<<endl; return 0; }
1208
H
Red Blue Tree
You are given a tree of $n$ nodes. The tree is rooted at node $1$, which is not considered as a leaf regardless of its degree. Each leaf of the tree has one of the two colors: red or blue. Leaf node $v$ initially has color $s_{v}$. The color of each of the internal nodes (including the root) is determined as follows. - Let $b$ be the number of blue immediate children, and $r$ be the number of red immediate children of a given vertex. - Then the color of this vertex is blue if and only if $b - r \ge k$, otherwise red. Integer $k$ is a parameter that is same for all the nodes. You need to handle the following types of queries: - 1 v: print the color of node $v$; - 2 v c: change the color of leaf $v$ to $c$ ($c = 0$ means red, $c = 1$ means blue); - 3 h: update the current value of $k$ to $h$.
Transform queries into two types: "change color of a leaf", and "answer color of some vertex if k is given". Note that when $k = -\infty$ all internal vertices are red. When increasing $k$, each vertex will change its color exactly once, let's call this value of $k$ as boundary value for this vertex. If we can keep boundary values for all vertices, answering queries is easy. Let's do sqrt decomposition on queries: group them in blocks and process in blocks of size $m$. When starting a block, compress the tree so that there are $O(m)$ interesting vertices: vertices involved in queries and LCAs of them. Let's call subtrees without interesting vertices as outer subtrees. We can compute the boundary values for all vertices in outer subtrees once for each block since the colors of leaves do not change. Now we should compress the paths between the interesting vertices. Note that the boundary values on a path only depend on the color of the vertex in the bottom end of the path. So for each such path compute two boundary values: if the vertex in the bottom end is red or blue. Now we can process queries by using the corresponding values of boundary values, going down-up. Straightforward implementation leads to $O(n\log{n})$ preprocessing of each block and $O(m\log{n})$ query time, meaning the overall complexity is $O((n + q) \sqrt{n + q} \log{n})$. The logarithms are from sorting and binary search, respectively, so this solution is already fast enough to get AC. To implement compression in $O(n)$ you need to go from lowest to highest possible $k$ and maintain which vertices are red in outer subtrees. Note that the number of different boundary values is $O(n)$, so you can store for each $k$ the list of vertices having this boundary value. To implement queries in $O(m)$, you need to precompute binary search outcomes for the given $O(m)$ values while computing the boundary values. This way the overall complexity becomes $O((n + q) \sqrt{n + q})$.
[ "data structures", "implementation", "trees" ]
3,500
/** * This line was copied from template * This is nk_sqrt_300.cpp * * @author: Nikolay Kalinin * @date: Fri, 23 Aug 2019 22:28:23 +0300 */ #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; using pii = pair<int, int>; using pli = pair<ll, int>; using pll = pair<ll, ll>; #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 100005; const int infk = maxn; const int BSZ = 700; vector<int> gr[maxn]; vector<int> dead_ends[maxn]; int th[maxn][2]; int threshold[maxn]; int up[maxn], fastup[maxn]; bool isleaf[maxn]; int curcnt[maxn]; int was[maxn]; int curk, curkid; int n; int timer; int c[maxn]; bool isinteresting[maxn]; vector<int> interesting; pair2<int> qs[BSZ]; vector<int> at[2 * BSZ]; queue<int> q; int path[maxn]; vector<int> ks; vector<int> cntdead[2 * BSZ]; int intid[maxn]; vector<int> order; int newid[maxn]; vector<int> grinit[maxn]; int compk[2 * infk + 5]; void leavedesc(int cur, int pr) { newid[cur] = order.size(); up[newid[cur]] = newid[pr]; order.pb(cur); for (int i = 0; i < (int)grinit[cur].size(); i++) { if (grinit[cur][i] == pr) { swap(grinit[cur][i], grinit[cur].back()); grinit[cur].pop_back(); i--; } else { leavedesc(grinit[cur][i], cur); } } } inline void computecolor(int cur) { if (was[cur] != timer) curcnt[cur] = 0; int cntred = curcnt[cur]; cntred += (int)cntdead[intid[cur]].size() <= curkid ? cntdead[intid[cur]].back() : cntdead[intid[cur]][curkid]; int cntblue = (int)gr[cur].size() - cntred; if (cntblue - cntred >= curk) c[cur] = 1; else c[cur] = 0; } inline void pushtoparent(int cur) { if (cur == 0) return; int par = fastup[cur]; int colorup = 1 - (curk >= th[cur][c[cur]]); if (was[par] != timer) { was[par] = timer; curcnt[par] = 0; } curcnt[par] += 1 - colorup; } int main() { scanf("%d%d", &n, &curk); for (int i = 0; i < n - 1; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; grinit[u].pb(v); grinit[v].pb(u); } leavedesc(0, -1); for (int i = 0; i < n; i++) { for (auto t : grinit[i]) gr[newid[i]].pb(newid[t]); } for (int i = 0; i < n; i++) scanf("%d", &c[newid[i]]); for (int i = 0; i < n; i++) if (c[i] != -1) isleaf[i] = true; int nq; scanf("%d", &nq); for (int lq = 0; lq < nq; lq += BSZ) { int rq = min(nq, lq + BSZ); memset(isinteresting, 0, sizeof isinteresting); ks.clear(); ks.pb(curk); for (int q = lq; q < rq; q++) { int t; scanf("%d", &t); if (t == 1) { int v; scanf("%d", &v); v--; v = newid[v]; isinteresting[v] = true; qs[q - lq] = {v, -1}; } else if (t == 2) { int v, newc; scanf("%d%d", &v, &newc); v--; v = newid[v]; isinteresting[v] = true; qs[q - lq] = {v, newc}; } else { int newk; scanf("%d", &newk); qs[q - lq] = {-1, newk}; ks.pb(newk); } } sort(all(ks)); ks.resize(unique(all(ks)) - ks.begin()); int kssz = ks.size(); ks.pb(infk); int curcompkid = 0; for (int i = -infk; i <= infk; i++) { compk[i + infk] = curcompkid; if (curcompkid < kssz && ks[curcompkid] == i) curcompkid++; } isinteresting[0] = true; interesting.clear(); for (int i = 0; i <= kssz; i++) at[i].clear(); for (int cur = 0; cur < n; cur++) { dead_ends[cur].clear(); path[cur] = -1; if (isinteresting[cur]) { path[cur] = -2; } } for (int cur = n - 1; cur >= 0; cur--) { int ret = -1; if (isinteresting[cur]) { intid[cur] = interesting.size(); interesting.pb(cur); cntdead[intid[cur]].clear(); cntdead[intid[cur]].pb(0); } if (path[cur] == -1) { if (isleaf[cur]) { if (c[cur] == 0) at[compk[-infk + infk]].pb(cur); else at[compk[infk + infk]].pb(cur); } else { curcnt[cur] = 0; int cntred = 0; int cntblue = gr[cur].size(); at[compk[cntblue - cntred + 1 + infk]].pb(cur); } } else if (path[cur] == -2) { ret = cur; } else { ret = path[cur]; } if (cur == 0) break; if (ret == -1) continue; if (path[up[cur]] == -1) path[up[cur]] = ret; else if (path[up[cur]] >= 0) { isinteresting[up[cur]] = true; fastup[path[up[cur]]] = up[cur]; fastup[ret] = up[cur]; path[up[cur]] = -2; } else { fastup[ret] = up[cur]; } } timer++; for (int i = 0; i <= kssz; i++) { for (auto t : at[i]) q.push(t); while (!q.empty()) { int cur = q.front(); q.pop(); if (was[cur] == timer) continue; was[cur] = timer; if (path[up[cur]] == -1) { curcnt[up[cur]]++; int cntred = curcnt[up[cur]]; int cntblue = gr[up[cur]].size() - cntred; if (cntblue - cntred + 1 <= ks[i]) q.push(up[cur]); else at[compk[cntblue - cntred + 1 + infk]].pb(up[cur]); } else if (path[up[cur]] == -2) { int id = intid[up[cur]]; while ((int)cntdead[id].size() <= i) cntdead[id].pb(cntdead[id].back()); cntdead[id].back()++; } else { // in path dead_ends[up[cur]].pb(ks[i]); } } } for (int cur = n - 1; cur >= 0; cur--) if (path[cur] != -1) { int cntchildren = gr[cur].size(); if (path[cur] == -2) { th[cur][0] = -infk; th[cur][1] = +infk; } else { th[cur][0] = cntchildren + 1; th[cur][1] = cntchildren + 1; th[cur][0] = min(th[cur][0], max(th[path[cur]][0], cntchildren - 1 - 1 + 1)); th[cur][1] = min(th[cur][1], max(th[path[cur]][1], cntchildren - 1 - 1 + 1)); for (int i = 0; i < (int)dead_ends[cur].size(); i++) { int cntred = i + 1; int cntblue = cntchildren - cntred; th[cur][0] = min(th[cur][0], max(dead_ends[cur][i], cntblue - cntred + 1)); th[cur][1] = min(th[cur][1], max(dead_ends[cur][i], cntblue - cntred + 1)); cntred = i + 1 + 1; cntblue = cntchildren - cntred; th[cur][0] = min(th[cur][0], max(max(th[path[cur]][0], dead_ends[cur][i]), cntblue - cntred + 1)); th[cur][1] = min(th[cur][1], max(max(th[path[cur]][1], dead_ends[cur][i]), cntblue - cntred + 1)); } th[path[cur]][0] = th[cur][0]; th[path[cur]][1] = th[cur][1]; } } ::curkid = lower_bound(all(ks), curk) - ks.begin(); for (int q = 0; q < rq - lq; q++) { timer++; if (qs[q].fi == -1) { curk = qs[q].se; ::curkid = lower_bound(all(ks), curk) - ks.begin(); } else if (qs[q].se != -1) c[qs[q].fi] = qs[q].se; else { for (auto v : interesting) { if (!isleaf[v]) computecolor(v); pushtoparent(v); } printf("%d\n", c[qs[q].fi]); } } } return 0; }
1209
A
Paint the Numbers
You are given a sequence of integers $a_1, a_2, \dots, a_n$. You need to paint elements in colors, so that: - If we consider any color, all elements of this color must be divisible by the minimal element of this color. - The number of used colors must be minimized. For example, it's fine to paint elements $[40, 10, 60]$ in a single color, because they are all divisible by $10$. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive. For example, if $a=[6, 2, 3, 4, 12]$ then two colors are required: let's paint $6$, $3$ and $12$ in the first color ($6$, $3$ and $12$ are divisible by $3$) and paint $2$ and $4$ in the second color ($2$ and $4$ are divisible by $2$). For example, if $a=[10, 7, 15]$ then $3$ colors are required (we can simply paint each element in an unique color).
Consider the smallest element $x$ in the array. We need to paint it in some color, right? Observe, that we can paint all elements divisible by $x$ in that color as well. So we can perform the following while the array is not empty: find the minimum element $x$, assign new color and remove all elements divisible by $x$ Complexity: $\mathcal{O}(n^2)$.
[ "greedy", "implementation", "math" ]
800
null
1209
B
Koala and Lights
It is a holiday season, and Koala is decorating his house with cool lights! He owns $n$ lights, all of which flash periodically. After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $a_i$ and $b_i$. Light with parameters $a_i$ and $b_i$ will toggle (on to off, or off to on) every $a_i$ seconds starting from the $b_i$-th second. In other words, it will toggle at the moments $b_i$, $b_i + a_i$, $b_i + 2 \cdot a_i$ and so on. You know for each light whether it's initially on or off and its corresponding parameters $a_i$ and $b_i$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. \begin{center} {\small Here is a graphic for the first example.} \end{center}
Because each individual light flashes periodically, all the lights together are periodic as well. Therefore, we can simulate the lights up to the period to get the answer. The actual period can be calculated as follows: If a light toggles every $t$ seconds, its period is $2t$. The overall period is the least common multiple of the individual periods $2,4,6,8,10$, which is $120$. There is also a "pre-period" of $5$ since lights can start toggling at time 5 in the worst case, so the time we need to simulate is bounded by $125$ However, computing the actual period is not necessary and a very large number will work (like $1000$). Challenge: Can we bound the time even more?
[ "implementation", "math", "number theory" ]
1,300
null
1209
C
Paint the Digits
You are given a sequence of $n$ digits $d_1d_2 \dots d_{n}$. You need to paint all the digits in two colors so that: - each digit is painted either in the color $1$ or in the color $2$; - if you write in a row from left to right all the digits painted in the color $1$, and then after them all the digits painted in the color $2$, then the resulting sequence of $n$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $d=914$ the only valid coloring is $211$ (paint in the color $1$ two last digits, paint in the color $2$ the first digit). But $122$ is not a valid coloring ($9$ concatenated with $14$ is not a non-decreasing sequence). It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions. Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.
The sequence must split into two non-decreasing where the end of the first $\le$ start of the second. Let's bruteforce the value $x$, so that all elements $< x$ go to the color $1$, all elements $> x$ go to the color $2$, and for $=x$ we are not sure. Actually, we can say that all elements equal to $x$, which go before the first element $> x$ can safely go to the color $2$, while the rest can only go to the color $1$. So we colored our sequence and we now only need to check whether this coloring is fine. Complexity is $10 \cdot n$.
[ "constructive algorithms", "greedy", "implementation" ]
1,500
null
1209
D
Cow and Snacks
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo! There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: - First, Bessie will line up the guests in some way. - Then in this order, guests will approach the snacks one by one. - Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.
Since every animal has exactly two favorite snacks, this hints that we should model the problem as a graph. The nodes are the snacks, and the edges are animals with preferences connecting snack nodes. Let's consider a connected component of the graph with size greater than $1$. The first animal (edge) in that component to eat must take two snacks (nodes), all other snack nodes will be eaten by exactly one animal edge. It is always possible to find an order so that no other animals takes two snacks (for example, BFS order). Thus, a connected component with $c$ vertices can satisfy at most $c-1$ animals. Let $N$ be the number of snacks, $M$ be the number of animals, and $C$ be the number of connected components (including those of size 1). The number of satisfied animals is $N-C$, so the number of of unhappy animals is $M-(N-C)$. Complexity: $\mathcal{O}(n+m)$
[ "dfs and similar", "dsu", "graphs" ]
1,700
null
1209
E1
Rotate Columns (easy version)
This is an easier version of the next problem. The difference is only in constraints. You are given a rectangular $n \times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times. After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $i$-th row it is equal $r_i$. What is the maximal possible value of $r_1+r_2+\ldots+r_n$?
There many approaches possible, let's describe one of them. Let's change the problem to the following: Rotate columns any way you want. Select in each row one value, maximizing the sum. This can be done with a dp, states are (prefix of columns, mask of taken columns). Basically at each step we are rotating the current column and fixing values for some of the rows. The most simple way to write this makes $3^n \cdot m \cdot n^2$ (for every submask->mask transition iterate over all possible shifts and elements to consider in cost function). But if we precalculate the cost function in advance, we will have $\mathcal{O}((3^n + 2^n n^2) \cdot m)$.
[ "bitmasks", "brute force", "dp", "greedy", "sortings" ]
2,000
null
1209
E2
Rotate Columns (hard version)
This is a harder version of the problem. The difference is only in constraints. You are given a rectangular $n \times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times. After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $i$-th row it is equal $r_i$. What is the maximal possible value of $r_1+r_2+\ldots+r_n$?
The previous solution is slightly too slow to pass the large constraints. Let's sort columns by the maximum element in them. Observe, that it is surely unoptimal to use columns which go after first $n$ columns in sorted order (we could've replaced them with some unused column). So we can solve the hard version with previous solution in which we consider only best $n$ columns. Complexity $\mathcal{O}((3^n + 2^n \cdot n^2) \cdot n + T(sort))$
[ "bitmasks", "dp", "greedy", "sortings" ]
2,500
null
1209
F
Koala and Notebook
Koala Land consists of $m$ bidirectional roads connecting $n$ cities. The roads are numbered from $1$ to $m$ by order in input. It is guaranteed, that one can reach any city from every other city. Koala starts traveling from city $1$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number. Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it? Since these numbers may be quite large, print their remainders modulo $10^9+7$. Please note, that you need to compute the remainder of the minimum possible number, \textbf{not} the minimum possible remainder.
First split all edges into directed edges with single digit labels, creating $\mathcal{O}(m\log{m})$ dummy vertices if necessary. Since the first edge will not be zero (no leading zeros), longer paths are always greater. With a BFS, this reduces the problem to finding lexicographical minimal paths in a DAG. To avoid needing to compare long sequences, we will instead visit all the vertices in order by their lexicographical minimal path. This can be done efficiently by something like BFS/DFS. The main idea is to visit sets of vertices at a time. If we have a set of vertices whose minimal paths are $P$, we can find the set of vertices whose minimal paths are $P0$ by following all outgoing $0$ edges. Then, we find the set of vertices whose minimal paths are $P1$ by following all outgoing $1$ edges, and so on for all digits. Since we ignore vertices once they are visited, this is $\mathcal{O}(m\log{m})$
[ "data structures", "dfs and similar", "graphs", "shortest paths", "strings", "trees" ]
2,600
null
1209
G1
Into Blocks (easy version)
This is an easier version of the next problem. In this version, $q = 0$. A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value. You are given a sequence of integers $a_1, a_2, \ldots, a_n$ and $q$ updates. Each update is of form "$i$ $x$" — change $a_i$ to $x$. Updates are not independent (the change stays for the future). Print the difficulty of the initial sequence and of the sequence after every update.
Let's solve easier version first (we will reuse core ideas in hard version as well). Clearly, if some two integers are ``hooked'' like in $1 \ldots 2 \ldots 1 \ldots 2$, then they will end up being turned into the same integer. So when we see integer $x$ with first occurrence at $a$ and last at $b$, let's mark segment $[a; b]$ as blocked. E.g. for array $[3, 3, 1, 2, 1, 2]$ we have not blocked only the bar between $3$ and $1$, that is we have $|3, 3 | 1, 2, 1, 2|$. Now for every such segment we have to change all elements into a common element. So the answer for a segment is segment length minus the number of occurrences of the most frequent element. One easy implementation is as follows: blocking is "+= 1 on segment" (can be done easily in $\mathcal{O}{(n + operations)}$ in offline, then for an element $x$, put the number of it's occurrences in the position of first occurrences. Now we only need to compute max on disjoint segments, so it can be done in a naive way. Complexity: $\mathcal{O}(n)$.
[ "data structures", "dsu", "greedy", "implementation", "two pointers" ]
2,000
null
1209
G2
Into Blocks (hard version)
This is a harder version of the problem. In this version $q \le 200\,000$. A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value. You are given a sequence of integers $a_1, a_2, \ldots, a_n$ and $q$ updates. Each update is of form "$i$ $x$" — change $a_i$ to $x$. Updates are not independent (the change stays for the future). Print the difficulty of the initial sequence and of the sequence after every update.
To adjust the solution for many queries we need to create some sophisticated data structure. E.g. we all know that mentioned above "+= 1 on a segment" is easily done with a segtree. If we maintain for every value $a_i$ the corresponding set of occurrences, it's easy to update mentioned above ``number of occurrences in the first position''. So what we need to do now? We need to dynamically recalculate the sum of minimums (and the set segments to calculate minimum can change quite much due to updates). You probably also now that we can design a segtree which supports range increments and query (minimum, number of minimums) on the segment. In a similar way we can build a structure which returns (minimum, number of minimums, the sum of largest stored counts between minimums). Just maintain a few values in each node and do lazy propagation. Complexity $\mathcal{O}(q \log n)$.
[ "data structures" ]
3,200
null
1209
H
Moving Walkways
Airports often use moving walkways to help you walking big distances faster. Each such walkway has some speed that effectively increases your speed. You can stand on such a walkway and let it move you, or you could also walk and then your effective speed is your walking speed plus walkway's speed. Limak wants to get from point $0$ to point $L$ on a straight line. There are $n$ disjoint walkways in between. The $i$-th walkway is described by two integers $x_i$ and $y_i$ and a real value $s_i$. The $i$-th walkway starts at $x_i$, ends at $y_i$ and has speed $s_i$. Every walkway is located inside the segment $[0, L]$ and no two walkways have positive intersection. However, they can touch by endpoints. Limak needs to decide how to distribute his energy. For example, it might make more sense to stand somewhere (or to walk slowly) to then have a lot of energy to walk faster. Limak's initial energy is $0$ and it must never drop below that value. At any moment, he can walk with any speed $v$ in the interval $[0, 2]$ and it will cost him $v$ energy per second, but he continuously recovers energy with speed of $1$ energy per second. So, when he walks with speed $v$, his energy increases by $(1-v)$. Note that negative value would mean losing energy. In particular, he can walk with speed $1$ and this won't change his energy at all, while walking with speed $0.77$ effectively gives him $0.23$ energy per second. Limak can choose his speed arbitrarily (any real value in interval $[0, 2]$) at every moment of time (including the moments when he is located on non-integer positions). Everything is continuous (non-discrete). What is the fastest time Limak can get from $0$ to $L$?
Some minor tips: Everything is a walkway. When there is no walkway, it is a walkway of speed $0$. You can increase all speeds by $1$ and assume that you own speed is in $[-1; +1]$ Energy is an entity which is $\delta$ speed $\times$ time, which is distance. Also if you spend $x$ energy per segment of len $l$ and speed $v$, it is not important how exactly you will distribute it over the walking process. In any way, you will walk by feet $l - x$ meters in time $(l - x) / v$. So it turns out it's better to distribute more energy to low-speeded walkways (because the denominator is smaller). Assume that you (by default) save up all energy on any non-feet path (for feet path it's always optimal to walk with speed $\ge 1$ ($\ge 0$ after speeds hack), so now save up's). Build an energy graphic where the Ox axis will correspond to the point you are in (not time). It will be a piecewise linear function, so it is enough to store it's value only in points corresponding to points between walkways. Iterate over walkways in the order of speed and try to steal as much energy as possible to the current walkway. What are the limits of stealing energy? there is a restriction based on $l$ and $v$ (if you take too much energy, you wouldn't be able to fully walk it up) the graphic must still be able above $0$ at all points. The latter condition is just a suffix minima on a segment tree. Complexity: $\mathcal{O}(n \log n)$.
[ "data structures", "greedy", "math" ]
3,300
null
1210
A
Anadi and Domino
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every $a$ and $b$ such that $1 \leq a \leq b \leq 6$, there is exactly one domino with $a$ dots on one half and $b$ dots on the other half. The set contains exactly $21$ dominoes. Here is an exact illustration of his set: Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph. When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots. How many dominoes at most can Anadi place on the edges of his graph?
We can imagine writing an integer from $1$ to $6$ in each vertex - if we write an integer $x$ in vertex $v$, then we want each half of the domino directed toward vertex $v$ to have exactly $x$ dots. Then, it's easy to calculate the result - we should place as many different dominoes as possible according to the written numbers so that we won't place any domino multiple times. If $n \leq 6$, then it's optimal to write different numbers everywhere, so the result will be equal to $m$ (the number of edges). If $n=7$, then it's optimal to use only two equal numbers and it doesn't matter which number appears twice. Then, we can iterate over the pair of vertices with the same number and then easily calculate the result.
[ "brute force", "graphs" ]
1,700
null
1210
B
Marcin and Training Camp
Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other. Let's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two integers $a_i$ and $b_i$; $b_i$ is equal to the skill level of the $i$-th student (the higher, the better). Also, there are $60$ known algorithms, which are numbered with integers from $0$ to $59$. If the $i$-th student knows the $j$-th algorithm, then the $j$-th bit ($2^j$) is set in the binary representation of $a_i$. Otherwise, this bit is not set. Student $x$ thinks that he is better than student $y$ if and only if $x$ knows some algorithm which $y$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group. Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?
If there are multiple people with the same set of skills (i.e., the same values of $a$), it's optimal to take each of them to the camp as they won't think they're better than everyone else. Now consider a person $i$ which has a different set of skills than everyone else. If they have a strictly smaller set of skills than someone already in the group, they can safely be included in the group. If they don't, we can prove that they can't ever be included in the group. This allows us to implement a simple $O(n^2)$ solution: first take all people that have an equal set of skills as someone else, and then include everyone else who has a strictly smaller set of skills than someone already in the group.
[ "brute force", "greedy" ]
1,700
null
1210
C
Kamil and Making a Stream
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $100$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him? You're given a tree — a connected undirected graph consisting of $n$ vertices connected by $n - 1$ edges. The tree is rooted at vertex $1$. A vertex $u$ is called an ancestor of $v$ if it lies on the shortest path between the root and $v$. In particular, a vertex is an ancestor of itself. Each vertex $v$ is assigned its beauty $x_v$ — a non-negative integer not larger than $10^{12}$. This allows us to define the beauty of a path. Let $u$ be an ancestor of $v$. Then we define the beauty $f(u, v)$ as the greatest common divisor of the beauties of all vertices on the shortest path between $u$ and $v$. Formally, if $u=t_1, t_2, t_3, \dots, t_k=v$ are the vertices on the shortest path between $u$ and $v$, then $f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$. Here, $\gcd$ denotes the greatest common divisor of a set of numbers. In particular, $f(u, u) = \gcd(x_u) = x_u$. Your task is to find the sum $$ \sum_{u\text{ is an ancestor of }v} f(u, v). $$ As the result might be too large, please output it modulo $10^9 + 7$. Note that for each $y$, $\gcd(0, y) = \gcd(y, 0) = y$. In particular, $\gcd(0, 0) = 0$.
Let's prove the following observation: Fix a vertex $v$ (the bottom end of the path), and consider all its ancestors $u$. The number of distinct values of $f(u,v)$ is at most $\log_2(10^{12})$. To prove this observation, consider the ancestors of $v$ in the order from the bottom-most to top-most: $v=u_0, u_1, u_2, u_3, \dots, u_k=1$. Notice that $f(u_i, v) = \gcd(x_{u_0}, x_{u_1}, x_{u_2}, \dots, x_{u_i})$. Therefore, each consecutive $u_i$ adds another value $x_{u, i}$ to the gcd of all numbers. If a gcd of all numbers changes, it must be a divisor of the previous gcd. Therefore, it's easy to see that it can change at most $\log_2(10^{12})$ times. We can now implement a depth-first search. If we invoke a recursive call in vertex $v$, we will receive the multiset of values $\{f(u, v) \mid u\text{ is an ancestor of }v\}$. We add all these values to the result and run the recursive calls in the children. This is currently $O(n^2)$ or $O(n^2\log n)$, but we can improve it by actually using a map from the distinct values in the multiset to the number of their occurrences. Then each map will have no more than $O\log_2(10^{12})$ elements. As we need to compute $\gcd$'s throughout the algorithm, this solution allows us to solve the problem in $O(n\log^2(10^{12}))$ time and in $O(n \log(10^{12}))$ memory. It's also possible to solve the problem using jump-pointers. Each jump-pointer will additionally hold the greatest common divisor of all the numbers we jump over when following the pointer.
[ "math", "number theory", "trees" ]
2,000
null
1210
D
Konrad and Company Evaluation
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company. There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company — initially, the $i$-th person earns $i$ rubles per day. On each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again. Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$. At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?
Let's imagine that the graph is directed as in the sample explanation (and edge $u\to v$ exists if $u$ brags to $v$). We have to deal with two kinds of queries: Count the number of three-vertex directed paths. Change the direction of a single edge in the graph. If we remember indegrees $\mathrm{indeg}$ and outdegrees $\mathrm{outdeg}$ for each vertex, then we can see that the result for the first query is $\sum_{v} \mathrm{indeg}(v) \cdot \mathrm{outdeg}(v)$. It's also easy to maintain the in- and outdegrees for each vertex when updating the graph using the second query. Let's get back to the original problem. If a person $v$ becomes the best-paid employee in the company, we can model it as taking all the edges ending at $v$, and reversing their direction. It turns out that throughout the whole simulation, this edge-reversal won't happen too many times! Let's sort the vertices from left to right by their degree in the decreasing order. It now turns out that each vertex is adjacent with at most $\sqrt{2m}$ vertices to its left: if there were more, it would mean that there exist more that $\sqrt{2m}$ vertices with their degrees larger than $\sqrt{2m}$. It would mean that the sum of degrees of all the vertices in the graph is more than $\sqrt{2m} \cdot \sqrt{2m} = 2m$ - a contradiction. Define the potential of the graph as the number of edges which point from left to right. If we revise the salary for employee $v$, we might need to flip many edges, but at most $\sqrt{2m}$ new edges will start pointing from left to right. The remaining edges incident to $v$ will now point from right to left. Therefore, we do the number of swaps proportional to the change of the potential, and the potential at each query can increase at most by $\sqrt{2m}$. The potential at the beginning could be as high as $m$, and therefore the total number of swaps throughout the algorithm is at most $m + q\sqrt{2m}$. The algorithm can be therefore implemented in $O(n + m + q\sqrt{m})$ time. Note that we should store the adjacency list of the directed graph in vectors - when we revise the salary of employee $v$, we should process all edges entering $v$ and simply clear the corresponding vector. Storing the graph in sets or hashsets has worse complexity or a huge constant factor and will likely time out.
[ "graphs" ]
2,400
null
1210
E
Wojtek and Card Tricks
Wojtek has just won a maths competition in Byteland! The prize is admirable — a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!' The first chapter of the book is 'How to Shuffle $k$ Cards in Any Order You Want.' It's basically a list of $n$ intricate methods of shuffling the deck of $k$ cards in a deterministic way. Specifically, the $i$-th recipe can be described as a permutation $(P_{i,1}, P_{i,2}, \dots, P_{i,k})$ of integers from $1$ to $k$. If we enumerate the cards in the deck from $1$ to $k$ from top to bottom, then $P_{i,j}$ indicates the number of the $j$-th card from the top of the deck after the shuffle. The day is short and Wojtek wants to learn only some of the tricks today. He will pick two integers $l, r$ ($1 \le l \le r \le n$), and he will memorize each trick from the $l$-th to the $r$-th, inclusive. He will then take a sorted deck of $k$ cards and repeatedly apply random memorized tricks until he gets bored. He still likes maths, so he started wondering: how many different decks can he have after he stops shuffling it? Wojtek still didn't choose the integers $l$ and $r$, but he is still curious. Therefore, he defined $f(l, r)$ as the number of different decks he can get if he memorizes all the tricks between the $l$-th and the $r$-th, inclusive. What is the value of $$\sum_{l=1}^n \sum_{r=l}^n f(l, r)?$$
Let's first enumerate all permutations by integers from $0$ to $k!-1$. Now, we can memoize all possible compositions of two permutations in an $k! \times k!$ array. This will allow us to compose any two permutations in constant time. Let $l$ and $r$ be the left and right ends of any interval. We'll compute the sum in the problem statement for each $r$ separately. Set some $r$. Notice that if there are multiple occurrences of the same permutation before $r$, only the latest occurrence is important for us - any earlier occurrences won't help us create any new decks. Therefore, for each of $k!$ possible permutations, we can maintain its latest occurrence before $r$. We can also maintain a sorted list of such latest occurrences among all the permutations - from the latest to the earliest. This creates $k!$ intervals of value $l$ where the number of possible decks can't change. Now, we only need to be able to maintain the set of decks (permutations) we can generate using the tricks we already know. Initially, we can generate only one deck (with the cards in sorted order). When learning a new trick, one of two things can happen: If a single application of the new trick generates a deck we can already create using previous tricks, this trick gives us nothing - we can simply simulate this new trick by a sequence of old tricks. If this trick $T$ creates a brand-new deck of cards, we need to recalculate the set of achievable permutations. We maintain a set of generators $\{g_1, g_2, \dots, g_a\}$, $g_a = T$ (these are the tricks that have increased the number of decks we can generate). Now, each deck in the new set of decks can be created using this repeatedly applying the generators from this set. We can use BFS/DFS to compute the new decks. This is obviously a correct algorithm, but why does it work fast enough? If you know some abstract algebra, then you can notice that what we're computing here is a chain of subgroups in a symmetric group $S_k$ (a group of all permutations of $k$ elements). By Lagrange's theorem, if a group $G$ is a subgroup of a finite group $H$, then $|H|$ is a multiple of $|G|$. Therefore, each new set of achievable decks is at least twice as large as the previous one. It means that: The set of generators is always at most as large as $\log_2(k!)$, The time needed to compute all the subgroups can be bounded by $\log_2(k!)$ times the sizes of all subgroups in the chain. As the sizes are growing exponentially large, the sum of sizes is at most $O(k!)$. Therefore, all the additions take at most $O(k! \log k)$ time. The time complexity of the intended solution was therefore $O((k!)^2 + nk!k)$. The solution can be sped up significantly by computing all possible sets of achievable decks (i.e., all subgroups of $S_k$) - for $k = 5$, there are only $156$ of them. Some preprocessing will then allow us to add a single element to the subgroup in constant time. This was however not necessary to get AC.
[ "math" ]
2,700
null
1210
F1
Marek and Matching (easy version)
This is an easier version of the problem. In this version, $n \le 6$. Marek is working hard on creating strong testcases to his new algorithmic problem. You want to know what it is? Nah, we're not telling you. However, we can tell you how he generates the testcases. Marek chooses an integer $n$ and $n^2$ integers $p_{ij}$ ($1 \le i \le n$, $1 \le j \le n$). He then generates a random bipartite graph with $2n$ vertices. There are $n$ vertices on the left side: $\ell_1, \ell_2, \dots, \ell_n$, and $n$ vertices on the right side: $r_1, r_2, \dots, r_n$. For each $i$ and $j$, he puts an edge between vertices $\ell_i$ and $r_j$ with probability $p_{ij}$ percent. It turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur? It can be shown that this value can be represented as $\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q \not\equiv 0 \pmod{10^9+7}$. Let $Q^{-1}$ be an integer for which $Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$. Print the value of $P \cdot Q^{-1}$ modulo $10^9+7$.
Let's first discuss one of possible solutions for the easy subtask. Let's assume that $n=6$ (all smaller $n$'s can be easily reduced to this case). There are two layers of vertices: left $L = \{\ell_1, \ell_2, \dots, \ell_6\}$ and right $R = \{r_1, r_2, \dots, r_6\}$. Let's do meet-in-the-middle on the right layer: $R_a = \{r_1, r_2, r_3\}$ and $R_b = \{r_4, r_5, r_6\}$. Consider two parts of the graph: between $L$ and $R_a$, and between $L$ and $R_b$. Each of them has $n \cdot \frac{n}{2} = 18$ edges, so we can try all subsets of edges in each of them separately. For each such subset: Compute the probability that we'll generate exactly this subset of edges. Find all $3$-element subsets of $L$ which can match perfectly with the currently considered half of $R$. This can be done easily in $2^{18} \times \mathrm{poly}(n)$ time. Now, here's a trick - there are only ${6 \choose 3} = 20$ three-element subsets of $L$! Therefore, for each $20$-element mask $M$, we can find: $p_a(M)$ - the probability that the set of three-element subsets of $L$ matching perfectly with $R_a$ is exactly $M$, $p_b(M)$ - the probability that the set of three-element subsets of $L$ whose complements match perfectly with $R_b$ is exactly $M$. Let's find the probability that there is no perfect matching in the graph. We can see that it's $\sum_{A \cap B = \varnothing} p_a(A) p_b(B)$ where $A$ and $B$ are $20$-element masks. This can be solved easily using SOS dynamic programming technique. If we let $q_b(X) := \sum_{Y \subseteq X} p_b(X)$, then the required sum is $\sum_{A \subseteq [20]} p_a(A) q_b([20] \setminus A)$ where $[20] = \{1,2,3,\dots,20\}$. Therefore, this algorithm allows us to solve the easy version of the problem in $2^{18} \cdot \mathrm{poly}(n) + 2^{20} \cdot 20$ time.
[ "brute force", "probabilities" ]
3,100
null
1210
F2
Marek and Matching (hard version)
This is a harder version of the problem. In this version, $n \le 7$. Marek is working hard on creating strong test cases to his new algorithmic problem. Do you want to know what it is? Nah, we're not telling you. However, we can tell you how he generates test cases. Marek chooses an integer $n$ and $n^2$ integers $p_{ij}$ ($1 \le i \le n$, $1 \le j \le n$). He then generates a random bipartite graph with $2n$ vertices. There are $n$ vertices on the left side: $\ell_1, \ell_2, \dots, \ell_n$, and $n$ vertices on the right side: $r_1, r_2, \dots, r_n$. For each $i$ and $j$, he puts an edge between vertices $\ell_i$ and $r_j$ with probability $p_{ij}$ percent. It turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur? It can be shown that this value can be represented as $\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q \not\equiv 0 \pmod{10^9+7}$. Let $Q^{-1}$ be an integer for which $Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$. Print the value of $P \cdot Q^{-1}$ modulo $10^9+7$.
Let's consider another approach that can solve the hard subtask as well. In the algorithm above, we computed all $k$-element subsets of $L$, $|L|=n$, that can match perfectly with some fixed $k$ vertices on the right. It turns out that not all families of subsets can be generated - for instance, if two sets: $\{\ell_1, \ell_2\}$ and $\{\ell_3, \ell_4\}$ can both match perfectly with $\{r_1, r_2\}$, then one of the following subsets: $\{\ell_1, \ell_3\}$ and $\{\ell_1, \ell_4\}$ must match perfectly as well. We'll try to use this observation to solve the problem. Let's add the vertices of $R$ one by one. After adding vertices $r_1, r_2, \dots, r_k$, consider all families of $k$-element subsets of $L$ which can match perfectly with $\{r_1, r_2, \dots, r_k\}$ in any generated graph. Now try adding $r_{k+1}$. Check all $2^n$ ways of randomly drawing a subset of $n$ edges incident to $r_{k+1}$. For each such subset and for each family $\mathcal{F}_k$ of $k$-element subsets computed previously, we need to compute the new family $\mathcal{F}_{k+1}$ of $(k+1)$-element subsets of $L$ matching perfectly with $\{r_1, r_2, \dots, r_{k+1}\}$. We can do it in a straightforward way - iterate over all $(k+1)$-element subsets $S \subseteq L$. If $S$ matches perfectly with $k+1$ vertices on the right, then $r_{k+1}$ must be connected to some vertex $\ell \in S$, and $\{r_1, \dots, r_k\}$ must match perfectly with $S \setminus \{\ell\}$. This allows us to solve the whole problem in $O(n \cdot \text{max number of families at any moment} \cdot 2^n)$ time. It turns out that for $n=7$, here are at most $\sim 30\,000$ families for any value of $k$. This allows to solve the problem in a reasonable time. The model solution finishes within $1.5$ seconds, but some breathing space was added so that some less efficient implementations will pass as well.
[ "brute force", "probabilities" ]
3,200
null
1210
G
Mateusz and Escape Room
Mateusz likes to travel! However, on his $42$nd visit to Saint Computersburg there is not much left to sightsee. That's why he decided to go to an escape room with his friends! The team has solved all riddles flawlessly. There is only one riddle remaining — a huge circular table! There are $n$ weighing scales lying on top of the table, distributed along the circle. Each scale is adjacent to exactly two other scales: for each $i \in \{1, 2, \dots, n-1\}$, the $i$-th and the $(i+1)$-th scales are adjacent to each other, as well as the first and the $n$-th scale. The $i$-th scale initially contains $a_i$ heavy coins. Mateusz can perform moves — each move consists of fetching a single coin from one scale and putting it on any adjacent scale. It turns out that the riddle will be solved when there is a specific amount of coins on each of the scales. Specifically, each scale has parameters $l_i$ and $r_i$. If each coin lies on a single scale and for each $i$, the $i$-th scale contains at least $l_i$ and at most $r_i$ coins, the riddle will be solved and Mateusz's team will win! Mateusz is aiming for the best possible time. Therefore, he wants to solved the riddle as quickly as possible. What is the minimum possible number of moves required to fulfill all the conditions?
Let's introduce the variables $x_1, x_2, \dots, x_n$ where $x_i$ is the number of coins passed from the $i$-th to the $(i+1)$-th scale (or, $x_i < 0$, it means that $-x_i$ coins are passed from the $(i+1)$-th to the $i$-th scale). We can now create the following conditions regarding the final number of stones on each scale: $a_i - x_i + x_{i - 1} \in [l_i, r_i] \qquad \text{for all } i.$ It turns out that for any sequence integers $x_1, \dots, x_n$ satisfying the inequalities before, we can create a sequence of $|x_1| + |x_2| + \dots + |x_n|$ moves satisfying all the conditions in the statement! In order to see this, consider a few cases: If $x_1, x_2, \dots, x_n > 0$, then we take any coin and make a full lap with it along the circle in the order of increasing $i$'s. We can now decrease each $x_i$ by one. If $x_1, x_2, \dots, x_n < 0$, we can do the similar thing, but we're decreasing $i$'s. In the remaining cases, we can pick a scale $i$ that won't receive coins anymore (that is, $x_i \geq 0$ and $x_{i-1} \leq 0$) and it still has some coins to distribute ($x_i > 0$ or $x_{i-1} < 0$). If $x_i > 0$, take a single coin, put it on the $(i+1)$-th scale, and decrease $x_i$ by one. If $x_{i-1} < 0$, take a coin, put it on the $(i-1)$-th scale, and increase $x_i$ by one. By following these operations, we will create the final configuration in $|x_1| + \dots + |x_n|$ moves. Therefore, we need to minimize this value. Let's try to guess $x_1$ and try to optimize $|x_1| + |x_2| + \dots + |x_n|$ for some fixed $x_1$. The simplest way is to write a dynamic programming: $dp(i, x_i) =$ the minimum value of $|x_1| + |x_2| + \dots + |x_i|$ given a value of $x_i$ and such that the final numbers of stones on the second, third, fourth, $\dots$, $i$-th scale are satisfied. To progress, we iterate over the possible values $x_{i+1}$ such that $a_i - x_i + x_{i - 1} \in [l_i, r_i]$ and compute the best value of $dp(i+1, x_{i+1})$. Notice that the initial state is $dp(1, x_1) = |x_1|$ and $dp(1, \star) = +\infty$ everywhere else. To compute the result, we must take the minimum value $dp(n, x_n)$ for $x_n$ satisfying $a_1 - x_1 + x_n \in [l_1, r_1]$. How to improve this DP? First of all, we'll try to maintain the $dp(i, x_i)$ as a function on $x_i$. In order to compute $dp(i+1, x)$ from $dp(i, x)$, we'll need to: Shift the function (left or right). Given a function $f$ and a constant $t$, compute $g(x) := \min_{y \in [x, x+t]} f(x)$. Given a function $f$, compute $g(x) := f(x) + |x|$. It turns out that after each of these operations, the function remains convex. We can therefore say that the function is linear on some segments with increasing slopes. Therefore, we can maintain a function as a set of segments, each segment described by its length and its slope. How to describe the second operation? We can see that it's actually adding a segment with slope $0$ and length $t$ to the function. Meanwhile, the third operation is splitting the function into two parts: for negative and positive $x$. We need to decrease the slopes in the first part by $1$, and increase the slopes in the second part by $1$. All these operations can be implemented on any balanced BST in $O(\log n)$ time. Therefore, the whole subproblem (for fixed $x_1$) can be solved in $O(n \log n)$ time. How to solve the general problem? It turns out that... Lemma. The function $F$ mapping $x_1$ into the optimal result for a fixed $x_1$ is convex. Proof will be added if anyone requests it. The basic idea is to prove that: (1) the answer won't change if $x_i$ could be any arbitrary real values, (2) if $(a_1, \dots, a_n)$ and $(b_1, \dots, b_n)$ are good candidates for $(x_1, \dots, x_n)$, so is $\left(\frac{a_1+b_1}{2}, \dots, \frac{a_n+b_n}{2}\right)$. We can use that to show that $\frac{F(a_1) + F(b_1)}{2} \ge F\left(\frac{a_1+b_1}{2}\right)$. Therefore, we can run a ternary search on $x_1$ to find the optimal result for any $x_1$. This ternary search takes $O(\log(\sum a_i))$ iterations, so the final time complexity is $O(n \log n \log(\sum a_i))$ with a rather large constant.
[ "dp" ]
3,500
null
1213
A
Chips Moving
You are given $n$ chips on a number line. The $i$-th chip is placed at the integer coordinate $x_i$. Some chips \textbf{can have equal coordinates}. You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: - Move the chip $i$ by $2$ to the left or $2$ to the right \textbf{for free} (i.e. replace the current coordinate $x_i$ with $x_i - 2$ or with $x_i + 2$); - move the chip $i$ by $1$ to the left or $1$ to the right and pay \textbf{one coin} for this move (i.e. replace the current coordinate $x_i$ with $x_i - 1$ or with $x_i + 1$). Note that it's allowed to move chips to any integer coordinate, including negative and zero. Your task is to find the minimum total number of coins required to move all $n$ chips to the same coordinate (i.e. all $x_i$ should be equal after some sequence of moves).
We can see that the only information we need is the parity of the coordinate of each chip (because we can move all chips that have the same parity to one coordinate for free). So if the number of chips with odd coordinate is $cnto$ then the answer is $min(cnto, n - cnto)$.
[ "math" ]
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; cin >> n; int cnto = 0; for (int i = 0; i < n; ++i) { int x; cin >> x; cnto += x & 1; } cout << min(cnto, n - cnto) << endl; return 0; }
1213
B
Bad Prices
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $n$ last days: $a_1, a_2, \dots, a_n$, where $a_i$ is the price of berPhone on the day $i$. Polycarp considers the price on the day $i$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $n=6$ and $a=[3, 9, 4, 6, 7, 5]$, then the number of days with a bad price is $3$ — these are days $2$ ($a_2=9$), $4$ ($a_4=6$) and $5$ ($a_5=7$). Print the number of days with a bad price. You have to answer $t$ independent data sets.
Let $minPrice_i$ be the minimum price of the berPhone during days $i, i + 1, \dots, n$. We can precalculate this array moving from right to left and carrying the minimum price we met (in other words, if we iterate over all $i$ from $n$ to $1$ then $minPrice_i = a_i$ if $i = n$ otherwise $minPrice_i = min(a_i, minPrice_{i + 1})$). Then the answer is the number of such days $i$ from $1$ to $n-1$ that $a_i > minPrice_{i + 1}$.
[ "data structures", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; int ans = 0; int right_min = INT_MAX; for (int i = n - 1; i >= 0; i--) { if (a[i] > right_min) ans++; right_min = min(right_min, a[i]); } cout << ans << endl; } }
1213
C
Book Reading
Polycarp is reading a book consisting of $n$ pages numbered from $1$ to $n$. Every time he finishes the page with the number divisible by $m$, he writes down the last digit of this page number. For example, if $n=15$ and $m=5$, pages divisible by $m$ are $5, 10, 15$. Their last digits are $5, 0, 5$ correspondingly, their sum is $10$. Your task is to calculate the sum of all digits Polycarp has written down. You have to answer $q$ independent queries.
Let $k = \lfloor\frac{n}{m}\rfloor$ be the number of integers from $1$ to $n$ divisible by $m$. We can notice that because we write down only the last digit of each number divisible by $m$ then the length of the "cycle" of digits does not exceed $10$. In fact, we can always suppose that it is $10$ because $i \cdot m \% 10 = (10 + i) \cdot m \% 10$ for all $i$ from $0$ to $9$. So let $cycle_i = m * (i + 1) \% 10$ for all $i$ from $0$ to $9$. Then the answer is $\lfloor\frac{k}{10}\rfloor \cdot \sum\limits_{i=0}^{9} cycle_i + \sum\limits_{i=0}^{k \% 10} cycle_i$.
[ "math" ]
1,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int q; cin >> q; forn(i, q) { long long n, m; cin >> n >> m; n = n / m; vector<int> digits(10); forn(i, 10) digits[i] = ((i + 1) * m) % 10; long long sum = 0; forn(i, n % 10) sum += digits[i]; cout << sum + n / 10 * accumulate(digits.begin(), digits.end(), 0LL) << endl; } }
1213
D1
Equalizing by Division (easy version)
\textbf{The only difference between easy and hard versions is the number of elements in the array}. You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$). You can perform such an operation \textbf{any} (possibly, zero) number of times with \textbf{any} $a_i$. Your task is to calculate the minimum possible number of operations required to obtain at least $k$ equal numbers in the array. \textbf{Don't forget that it is possible to have $a_i = 0$ after some operations, thus the answer always exists}.
Let $x$ be the number such that after some sequence of moves there will be at least $k$ elements $x$ in the array. We can see that there is always $O(n \log n)$ possible candidates because all values $x$ are among all possible values of $\lfloor\frac{a_i}{2^m}\rfloor$ for some $m$ from $0$ to $18$. So we need to check each candidate separately and try to update the answer with it. How to do this? Let the current number we trying to obtain is $x$. Then let's iterate over all $a_i$ in any order. Let $y$ be the current value of $a_i$. Let's divide it by $2$ while its value is greater than $x$ and carry the number of divisions we made $cur$. If after all divisions $y=x$ then let's remember the value of $cur$ in some array $cnt$. If after iterating over all $n$ elements of $a$ the size of $cnt$ is greater than or equal to $k$ then let's sort it and update the answer with the sum of $k$ smallest values of $cnt$. Time complexity: $O(n^2 \log^2max(a_i) \log(n \log max(a_i)))$ or $O(n^2 \log^2max(a_i))$, depends on sorting method.
[ "brute force", "implementation" ]
1,500
#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]; } vector<int> poss; for (int i = 0; i < n; ++i) { int x = a[i]; while (x > 0) { poss.push_back(x); x /= 2; } } int ans = 1e9; for (auto res : poss) { vector<int> cnt; for (int i = 0; i < n; ++i) { int x = a[i]; int cur = 0; while (x > res) { x /= 2; ++cur; } if (x == res) { cnt.push_back(cur); } } if (int(cnt.size()) < k) continue; sort(cnt.begin(), cnt.end()); ans = min(ans, accumulate(cnt.begin(), cnt.begin() + k, 0)); } cout << ans << endl; return 0; }
1213
D2
Equalizing by Division (hard version)
\textbf{The only difference between easy and hard versions is the number of elements in the array}. You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$). You can perform such an operation \textbf{any} (possibly, zero) number of times with \textbf{any} $a_i$. Your task is to calculate the minimum possible number of operations required to obtain at least $k$ equal numbers in the array. \textbf{Don't forget that it is possible to have $a_i = 0$ after some operations, thus the answer always exists}.
In this problem we need to write almost the same solution as in the previous one (easy version) but faster. Observe that we calculate the value of $\lfloor\frac{a_i}{2^m}\rfloor$ too many times. Let $vals_x$ for all $x$ from $1$ to $2 \cdot 10^5$ be the array of numbers of divisions we need to obtain $x$ from every possible $a_i$ from which we can. We can calculate these arrays in time $O(n \log n)$. How? Let's iterate over all $a_i$ and divide it by $2$ while it is positive (and carry the number of divisions $cur$). Then let's add to the array $vals_{a_i}$ the number $cur$ before each division. Then we can see that we obtain the array $cnt$ from the tutorial of the previous problem for each $x$ from $1$ to $2 \cdot 10^5$. Let's iterate over all possible values of $x$ and try to update the answer with the sum of $k$ smallest values of $vals_x$ if there is at least $k$ elements in this array. Time complexity: $O(n \log n \log(n \log n))$ or $O(n \log n)$, depends on sorting method.
[ "brute force", "math", "sortings" ]
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, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<vector<int>> vals(200 * 1000 + 11); for (int i = 0; i < n; ++i) { int x = a[i]; int cur = 0; while (x > 0) { vals[x].push_back(cur); x /= 2; ++cur; } } int ans = 1e9; for (int i = 0; i <= 200 * 1000; ++i) { sort(vals[i].begin(), vals[i].end()); if (int(vals[i].size()) < k) continue; ans = min(ans, accumulate(vals[i].begin(), vals[i].begin() + k, 0)); } cout << ans << endl; return 0; }
1213
E
Two Small Strings
You are given two strings $s$ and $t$ \textbf{both of length $2$} and both consisting only of characters 'a', 'b' and 'c'. Possible examples of strings $s$ and $t$: "ab", "ca", "bb". You have to find a string $res$ consisting of $3n$ characters, $n$ characters should be 'a', $n$ characters should be 'b' and $n$ characters should be 'c' and $s$ and $t$ should not occur in $res$ as substrings. A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc". If there are multiple answers, you can print any of them.
We can check the following solution by stress-testing (or maybe prove it somehow): let's iterate over all possible permutations of the string "abc". Let the first character of the current permutation be $c_1$, the second one be $c_2$ and the third one be $c_3$. Then let's add the following two candidates to the answer: "c_1 c_2 c_3 c_1 c_2 c_3 ... c_1 c_2 c_3" (the string consisting of $n$ copies of "c_1 c_2 c_3") and "c_1 ... c_1 c_2 ... c_2 c_3 ... c_3" (exactly $n$ copies of $c_1$ then exactly $n$ copies of $c_2$ and exactly $n$ copies of $c_3$). Then the answer will be among these $12$ strings and we can check each of them naively.
[ "brute force", "constructive algorithms" ]
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; string s, t; cin >> n >> s >> t; string abc = "abc"; vector<string> res; do { string cur; for (int i = 0; i < n; ++i) cur += abc; res.push_back(cur); res.push_back(string(n, abc[0]) + string(n, abc[1]) + string(n, abc[2])); } while (next_permutation(abc.begin(), abc.end())); for (auto str : res) { if (str.find(s) == string::npos && str.find(t) == string::npos) { cout << "YES" << endl << str << endl; return 0; } } assert(false); cout << "NO" << endl; return 0; }