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
1895
B
Points and Minimum Distance
You are given a sequence of integers $a$ of length $2n$. You have to split these $2n$ integers into $n$ pairs; each pair will represent the coordinates of a point on a plane. Each number from the sequence $a$ should become the $x$ or $y$ coordinate of exactly one point. Note that some points can be equal. After the po...
Since the order of $a_i$ does not matter, let's sort them for convenience. Let's treat the resulting path as two one-dimensional paths: one path $x_1 \rightarrow x_2 \rightarrow \dots \rightarrow x_n$ and one path $y_1 \rightarrow y_2 \rightarrow \dots \rightarrow y_n$. The length of the path $s$ is equal to the sum of...
[ "greedy", "math", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int n; vector<int> a; inline void read() { cin >> n; a.clear(); for (int i = 0; i < 2 * n; i++) { int x; cin >> x; a.pb(x); } } inline void solve() { sort(all(a)); vector<pair<int, int> > pts; for (int i = 0; i < n; i++) { pt...
1895
C
Torn Lucky Ticket
A ticket is a non-empty string of digits from $1$ to $9$. A lucky ticket is such a ticket that: - it has an even length; - the sum of digits in the first half is equal to the sum of digits in the second half. You are given $n$ ticket pieces $s_1, s_2, \dots, s_n$. How many pairs $(i, j)$ (for $1 \le i, j \le n$) are...
There is an obvious $O(n^2)$ approach: iterate over the first part, the second part and check the sum. In order to improve it, let's try to get rid of the second iteration. Consider the case where the first part is longer or equal than the second part. So, we still iterate over the first part in $O(n)$. However, instea...
[ "brute force", "dp", "hashing", "implementation", "math" ]
1,400
n = int(input()) s = input().split() ans = 0 cnt = [[0 for k in range(46)] for k in range(6)] for y in s: cnt[len(y)][sum([int(c) for c in y])] += 1 for L in s: for lenr in range(len(L) % 2, len(L) + 1, 2): l = len(L) + lenr suml = sum([int(c) for c in L[:l // 2]]) sumr = sum([int(c) for...
1895
D
XOR Construction
You are given $n-1$ integers $a_1, a_2, \dots, a_{n-1}$. Your task is to construct an array $b_1, b_2, \dots, b_n$ such that: - every integer from $0$ to $n-1$ appears in $b$ exactly once; - for every $i$ from $1$ to $n-1$, $b_i \oplus b_{i+1} = a_i$ (where $\oplus$ denotes the bitwise XOR operator).
We can see that the first element of the array $b$ determines all other values, $b_{i + 1} = b_1 \oplus a_1 \cdots \oplus a_i$. So let's iterate over the value of $b_1$. For every value of $b_1$, we need to check whether it produces correct permutation or not (i. e. all $b_i < n$). To do it in a fast way, we can genera...
[ "bitmasks", "constructive algorithms", "data structures", "math", "string suffix structures", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; const int LOG = 20; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a(n); for (int i = 1; i < n; ++i) { cin >> a[i]; a[i] ^= a[i - 1]; } vector<array<int, 2>> t({{-1, -1}}); auto add = [&](int x) { int v = 0...
1895
E
Infinite Card Game
Monocarp and Bicarp are playing a card game. Each card has two parameters: an attack value and a defence value. A card $s$ beats another card $t$ if the attack of $s$ is strictly greater than the defence of $t$. Monocarp has $n$ cards, the $i$-th of them has an attack value of $\mathit{ax}_i$ and a defence value of $\...
Let's restate the game in game theory terms. The state of the game can be just the card that is currently on top, since none of the previously played cards matter. A move is still a card beating another card, so these are the edges of the game graph. Now we can solve this as a general game. Mark all trivial winning and...
[ "binary search", "brute force", "data structures", "dfs and similar", "dp", "dsu", "games", "graphs", "greedy", "sortings", "two pointers" ]
2,300
// #include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct card{ int x, y; card() {} card(int x, int y) : x(x), y(y) {} }; void dfs(int v, const vector<int> &g, vector<int> &res, vector<char> &used){ if (used[v]) return; used[v] = true; dfs(g[v], g, res,...
1895
F
Fancy Arrays
Let's call an array $a$ of $n$ non-negative integers fancy if the following conditions hold: - at least one from the numbers $x$, $x + 1$, ..., $x+k-1$ appears in the array; - consecutive elements of the array differ by at most $k$ (i.e. $|a_i-a_{i-1}| \le k$ for each $i \in [2, n]$). You are given $n$, $x$ and $k$. ...
It is difficult to directly calculate the number of arrays that satisfy both conditions. So let's calculate the opposite value - the number of arrays, where only the second condition is holds, and the first is necessarily violated. Using the fact that the array can contain integers from two sets $[0, x)$ and $[x + k, \...
[ "combinatorics", "dp", "math", "matrices" ]
2,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) const int MOD = 1e9 + 7; const int N = 40; using mat = array<array<int, N>, N>; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; if (x < 0) x += MOD; return x; } int mul(int x, int y) { return x * 1...
1895
G
Two Characters, Two Colors
You are given a string consisting of characters 0 and/or 1. You have to paint every character of this string into one of two colors, red or blue. If you paint the $i$-th character red, you get $r_i$ coins. If you paint it blue, you get $b_i$ coins. After coloring the string, you remove every \textbf{blue} character f...
This problem requires partitioning some object into two parts, and imposes different costs depending on how we perform the partition. Let's try to model it with minimum cuts. Create a flow network with $n+2$ vertices: a vertex for every character of the string, a source and a sink. Using the edges of the network, we wi...
[ "binary search", "data structures", "dp", "flows", "greedy" ]
3,100
#include<bits/stdc++.h> using namespace std; mt19937 rnd(42); struct node { long long x; int y; int cnt; int sum; int push; node* l; node* r; node() {}; node(long long x, int y, int cnt, int sum, int push, node* l, node* r) : x(x), y(y), cnt(cnt), sum(sum), push(push), l(l), r(r) {}; }; typedef no...
1896
A
Jagged Swaps
You are given a permutation$^\dagger$ $a$ of size $n$. You can do the following operation - Select an index $i$ from $2$ to $n - 1$ such that $a_{i - 1} < a_i$ and $a_i > a_{i+1}$. Swap $a_i$ and $a_{i+1}$. Determine whether it is possible to sort the permutation after a finite number of operations. $^\dagger$ A per...
Look at the samples. Observe that since we are only allowed to choose $i \ge 2$ to swap $a_i$ and $a_{i+1}$, it means that $a_1$ cannot be modified by the operation. Hence, $a_1 = 1$ must hold. We can prove that as long as $a_1 = 1$, we will be able to sort the array. Consider the largest element of the array. Let its ...
[ "sortings" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <ll> vi; int main() { int t; cin >> t; while (t --> 0) { int n; cin >> n; vi arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } if (arr[0] == 1) { co...
1896
B
AB Flipping
You are given a string $s$ of length $n$ consisting of characters $A$ and $B$. You are allowed to do the following operation: - Choose an index $1 \le i \le n - 1$ such that $s_i = A$ and $s_{i + 1} = B$. Then, swap $s_i$ and $s_{i+1}$. You are only allowed to do the operation \textbf{at most once} for each index $1 ...
What happens when $s$ starts with some $\texttt{B}$ and ends with some $\texttt{A}$? If the string consists of only $\texttt{A}$ or only $\texttt{B}$, no operations can be done and hence the answer is $0$. Otherwise, let $x$ be the smallest index where $s_x = \texttt{A}$ and $y$ be the largest index where $x_y = \textt...
[ "greedy", "strings", "two pointers" ]
900
#include <bits/stdc++.h> using namespace std; char s[200005]; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc, n; cin >> tc; while (tc--) { cin >> n; s[n + 1] = 'C'; for (int i = 1; i <= n; ++i) cin >> s[i]; int pt1 = 1, pt2 = 1, ans = 0; while (s[pt1] == 'B') ++pt1, ++pt2;...
1896
C
Matching Arrays
You are given two arrays $a$ and $b$ of size $n$. The beauty of the arrays $a$ and $b$ is the number of indices $i$ such that $a_i > b_i$. You are also given an integer $x$. Determine whether it is possible to rearrange the elements of $b$ such that the beauty of the arrays becomes $x$. If it is possible, output one v...
Consider a greedy algorithm. For simplicity, assume that both arrays $a$ and $b$ are sorted in increasing order. The final answer can be obtained by permuting the answer array using the same permutation to permute sorted array $a$ to the original array $a$. Claim: If the rearrangement $b_{x + 1}, b_{x + 2}, \ldots, b_n...
[ "binary search", "constructive algorithms", "greedy", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; #define REP(i, s, e) for (int i = (s); i < (e); i++) #define RREP(i, s, e) for (int i = (s); i >= (e); i--) const int INF = 1000000005; const int MAXN = 200005; int t; int n, x; int a[MAXN], b[MAXN], aid[MAXN]; int ans[MAXN]; int main() { ios::sync_with_stdio(0...
1896
D
Ones and Twos
You are given a $1$-indexed array $a$ of length $n$ where each element is $1$ or $2$. Process $q$ queries of the following two types: - "1 s": check if there exists a subarray$^{\dagger}$ of $a$ whose sum equals to $s$. - "2 i v": change $a_i$ to $v$. $^{\dagger}$ An array $b$ is a subarray of an array $a$ if $b$ ca...
Consider some small examples and write down every possible value of subarray sums. Can you see some patterns? Denote $s[l,r]$ as the sum of subarray from $l$ to $r$. Claim: If there is any subarray with sum $v\ge 2$, we can find a subarray with sum $v-2$. Proof: Suppose $s[l,r]=v$, consider 3 cases: $a[l]=2$, we have $...
[ "binary search", "data structures", "divide and conquer", "math", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { int n, q; cin >> n >> q; vector<int> a(n); set<int> pos; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] == 1) pos.insert(i)...
1896
E
Permutation Sorting
You are given a permutation$^\dagger$ $a$ of size $n$. We call an index $i$ good if $a_i=i$ is satisfied. After each second, we rotate all indices that are not good to the right by one position. Formally, - Let $s_1,s_2,\ldots,s_k$ be the indices of $a$ that are \textbf{not} good in increasing order. That is, $s_j < s...
For each index $i$ from $1$ to $n$, let $h_i$ denote the number of cyclic shifts needed to move $a_i$ to its correct spot. In other words, $h_i$ is the minimum value such that $(i + h_i - 1)\ \%\ n + 1 = a_i$. How can we get the answer from $h_i$? For convenience, we will assume that the array is cyclic, so $a_j = a_{(...
[ "data structures", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; #define REP(i, s, e) for (int i = (s); i < (e); i++) #define RREP(i, s, e) for (int i = (s); i >= (e); i--) #define ALL(_a) _a.begin(), _a.end() #define SZ(_a) (int) _a.size() const int INF = 1000000005; const int MAXN = 1000005; int t; int n; int p[MAXN]; int ans[MA...
1896
F
Bracket Xoring
You are given a binary string $s$ of length $2n$ where each element is $\mathtt{0}$ or $\mathtt{1}$. You can do the following operation: - Choose a balanced bracket sequence$^\dagger$ $b$ of length $2n$. - For every index $i$ from $1$ to $2n$ in order, where $b_i$ is an open bracket, let $p_i$ denote the minimum index...
The operation is equivalent to toggling $s$ at every odd $i$ where $b_i$ is an open bracket and every even $i$ where $b_i$ is a closed bracket. Suppose there are $x$ open brackets and $y$ close brackets between positions $1$ and $i$. Note that $x \ge y$ by definition of balanced bracket sequences. - Case 1: $b_i$ is an...
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,600
#include <bits/stdc++.h> using namespace std; void solve(int n, string s) { vector<int> a; for (char &i : s) { a.push_back(i & 1); } if (a.front() != a.back()) { cout << -1 << endl; return ; } if (count(a.begin(), a.end(), 1) % 2) { cout << -1 << endl; return ; } bool flipped = false; if (a.fr...
1896
G
Pepe Racing
This is an interactive problem. There are $n^2$ pepes labeled $1, 2, \ldots, n^2$ with \textbf{pairwise distinct} speeds. You would like to set up some races to find out the relative speed of these pepes. In one race, you can choose exactly $n$ distinct pepes and make them race against each other. After each race, yo...
Find the fastest pepe in $n + 1$ queries. Divide $n^2$ pepes into $n$ groups $G_1, G_2, \dots, G_n$. For each group $G_i$, use $1$ query to find the fastest pepe in the group, let's call him the head of $G_i$. Finally, use $1$ query to find the fastest pepe of all the heads. After knowing the fastest pepe, find the sec...
[ "constructive algorithms", "implementation", "interactive", "sortings" ]
3,200
#include <bits/stdc++.h> using namespace std; #define int long long #define ll long long #define ii pair<ll,ll> #define iii pair<ii,ll> #define fi first #define se second #define debug(x) cout << #x << ": " << x << endl #define pub push_back #define pob pop_back #define puf push_front #define pof pop_front #define lb...
1896
H2
Cyclic Hamming (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $k$. You can make hacks only if all versions of the problem are solved.} In this statement, all strings are $0$-indexed. For two strings $a$, $b$ of the same length $p$, we define the following definitio...
For any $c$ which is a cyclic shift of $t$, what will happen if $h(s,c)>2^k$? Try finding some useful relationship between $1$-s of $s$ and $1$-s of $c$. There are exactly $n/2$ positions $i$ such that $s[i]=c[i]=1$. Think about polynomial multiplication. Consider $S\cdot T$, where $S=\sum s[i]x^i$ and $T=\sum t[2n-i-1...
[ "brute force", "dp", "fft", "math", "number theory" ]
3,500
null
1898
A
Milica and String
Milica has a string $s$ of length $n$, consisting only of characters A and B. She wants to modify $s$ so it contains \textbf{exactly} $k$ instances of B. In one operation, she can do the following: - Select an integer $i$ ($1 \leq i \leq n$) and a character $c$ ($c$ is equal to either A or B). - Then, replace \textbf{...
In one move, Milica can replace the whole string with $\texttt{AA} \ldots \texttt{A}$. In her second move, she can replace a prefix of length $k$ with $\texttt{BB} \ldots \texttt{B}$. The process takes no more than $2$ operations. The question remains - when can we do better? In the hint section, we showed that the min...
[ "brute force", "implementation", "strings" ]
800
null
1898
B
Milena and Admirer
Milena has received an array of integers $a_1, a_2, \ldots, a_n$ of length $n$ from a secret admirer. She thinks that making it non-decreasing should help her identify the secret admirer. She can use the following operation to make this array non-decreasing: - Select an element $a_i$ of array $a$ and an integer $x$ s...
Try a greedy approach. That is, split each $a_i$ only as many times as necessary (and try to create almost equal parts). We will iterate over the array from right to left. Then, as described in the hint section, we will split the current $a_i$ and create almost equal parts. For example, $5$ split into three parts forms...
[ "greedy", "math" ]
1,500
null
1898
C
Colorful Grid
Elena has a grid formed by $n$ horizontal lines and $m$ vertical lines. The horizontal lines are numbered by integers from $1$ to $n$ from top to bottom. The vertical lines are numbered by integers from $1$ to $m$ from left to right. For each $x$ and $y$ ($1 \leq x \leq n$, $1 \leq y \leq m$), the notation $(x, y)$ den...
The solution does not exist only for "small" $k$ or when $n+m-k$ is an odd integer. Try to find a construction otherwise. Read the hint for the condition of the solution's existence. We present a single construction that solves the problem for each valid $k$. One can verify that the pattern holds in general. How would ...
[ "constructive algorithms" ]
1,700
null
1898
D
Absolute Beauty
Kirill has two integer arrays $a_1,a_2,\ldots,a_n$ and $b_1,b_2,\ldots,b_n$ of length $n$. He defines the absolute beauty of the array $b$ as $$\sum_{i=1}^{n} |a_i - b_i|.$$ Here, $|x|$ denotes the absolute value of $x$. Kirill can perform the following operation \textbf{at most once}: - select two indices $i$ and $j...
If $a_i > b_i$, swap them. Imagine the pairs $(a_i,b_i)$ as intervals. How can we visualize the problem? The pair $(a_i,b_i)$ represents some interval, and $|a_i - b_i|$ is its length. Let us try to maximize the sum of the intervals' lengths. We present three cases of what a swap does to two arbitrary intervals. Notice...
[ "greedy", "math" ]
1,900
null
1898
E
Sofia and Strings
Sofia has a string $s$ of length $n$, consisting only of lowercase English letters. She can perform operations of the following types with this string. - Select an index $1 \le i \le |s|$ and remove the character $s_i$ from the string. - Select a pair of indices $(l, r)$ ($1 \le l \le r \le |s|$) and sort the substrin...
Notice how sorting only the substrings of length $2$ is enough. Try a greedy approach. We sort only the substrings of length $2$. We can swap two adjacent characters if the first is greater than or equal to the second. Let us fix some character $s_i$ and presume we want to change its position to $j$. We have to perform...
[ "data structures", "greedy", "sortings", "strings", "two pointers" ]
2,200
null
1898
F
Vova Escapes the Matrix
Following a world tour, Vova got himself trapped inside an $n \times m$ matrix. Rows of this matrix are numbered by integers from $1$ to $n$ from top to bottom, and the columns are numbered by integers from $1$ to $m$ from left to right. The cell $(i, j)$ is the cell on the intersection of row $i$ and column $j$ for $1...
To solve the problem for matrices of $3$-rd type, find the shortest path to $2$ closest exits with a modification of BFS. Block all cells not belonging to the path with obstacles. For a matrix of type $1$, Misha can block all empty cells (except the one Vova stands on). For a matrix of type $2$, Misha finds the shortes...
[ "brute force", "dfs and similar", "divide and conquer", "shortest paths" ]
2,600
null
1899
A
Game with Integers
Vanya and Vova are playing a game. Players are given an integer $n$. On their turn, the player can add $1$ to the current integer or subtract $1$. The players take turns; Vanya starts. If \textbf{after} Vanya's move the integer is divisible by $3$, then he wins. If $10$ moves have passed and Vanya has not won, then Vov...
Consider the remainder from dividing $n$ by $3$ before the first move. If it is equal to $1$ or $2$, then Vanya can make the number $n$ divisible by $3$ after the first move, i.e. he wins. Let the remainder be $0$, then Vanya must change the number after which it will not be divisible by $3$. Then Vova can do the same ...
[ "games", "math", "number theory" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; if (n % 3) { cout << "First\n"; } else { cout << "Second\n"; } } int main() { int t; cin >> t; while (t--) { solve(); } }
1899
B
250 Thousand Tons of TNT
Alex is participating in the filming of another video of BrMeast, and BrMeast asked Alex to prepare 250 thousand tons of TNT, but Alex didn't hear him well, so he prepared $n$ boxes and arranged them in a row waiting for trucks. The $i$-th box from the left weighs $a_i$ tons. All trucks that Alex is going to use hold ...
Solution #1: Since $k$ is a divisor of $n$, there are $O(\sqrt[3]{n})$ such $k$. We can enumerate all k, calculate a given value in $O(n)$, and take the maximum of them. Total complexity - $O(n \cdot \sqrt[3]{n})$. Solution #2: Without using the fact that $k$ is a divisor of $n$, we can simply loop over $k$ and then ca...
[ "brute force", "implementation", "number theory" ]
1,100
#include<bits/stdc++.h> using namespace std; using ll = long long; #define all(x) x.begin(), x.end() void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; ll ans = -1; for (int d = 1; d <= n; ++d) { if (n % d == 0) { ll mx = -1e18, mn ...
1899
C
Yarik and Array
A subarray is a continuous part of array. Yarik recently found an array $a$ of $n$ elements and became very interested in finding the maximum sum of a \textbf{non empty} subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjace...
There are "bad" positions in the array, i.e., those on which two numbers of the same parity are next to each other. Note that all matching segments cannot contain such positions, in other words, we need to solve the problem of finding a sub segment with maximal sum on some number of non-intersecting sub segments of the...
[ "dp", "greedy", "two pointers" ]
1,100
#include <iostream> #include <vector> #include <algorithm> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int ans = a[0]; int mn = min(0, a[0]), sum = a[0]; for (int i = 1; i < n; ++i) { if (abs(a[i]...
1899
D
Yarik and Musical Notes
Yarik is a big fan of many kinds of music. But Yarik loves not only listening to music but also writing it. He likes electronic music most of all, so he has created his own system of music notes, which, in his opinion, is best for it. Since Yarik also likes informatics, in his system notes are denoted by integers of $...
The problem requires to count the number of pairs of indices $(i, j)$ ($i < j$) such that $(2^a)^{(2^b)} = (2^b)^{(2^a)}$, where $a = b_i, b = b_j$. Obviously, when $a = b$ this equality is satisfied. Let $a \neq b$, then rewrite the equality: $(2^a)^{(2^b)} = (2^b)^{(2^a)} \Leftrightarrow 2^{(a \cdot 2^b)} = 2^{(b \cd...
[ "hashing", "math", "number theory" ]
1,300
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; cin >> n; vector<int> a(n); for (int& x : a) cin >> x; ll ans = 0; map<int, int> cnt; for (int i = 0; i < n; i++) { ans += cnt[a[i]]; if (a[i] == 1) ans += cnt[2]; else if (a[i] == 2) ans += cnt[1]; cnt[a[i]]++; ...
1899
E
Queue Sort
Vlad found an array $a$ of $n$ integers and decided to sort it in non-decreasing order. To do this, Vlad can apply the following operation any number of times: - Extract the first element of the array and insert it at the end; - Swap \textbf{that} element with the previous one until it becomes the first or until it b...
Consider the position of the first minimum in the array, let it be equal to $k$. All elements standing on positions smaller than $k$ are strictly greater, so we must apply operations to them, because otherwise the array will not be sorted. Suppose we have applied operations to all such elements, they have taken some po...
[ "greedy", "implementation", "sortings" ]
1,300
def solve(): n = int(input()) a = [int(x) for x in input().split()] fm = 0 for i in range(n): if a[i] < a[fm]: fm = i for i in range(fm + 1, n): if a[i] < a[i - 1]: print(-1) return print(fm) for _ in range(int(input())): solve()
1899
F
Alex's whims
Tree is a connected graph without cycles. It can be shown that any tree of $n$ vertices has exactly $n - 1$ edges. Leaf is a vertex in the tree with exactly one edge connected to it. Distance between two vertices $u$ and $v$ in a tree is the minimum number of edges that must be passed to come from vertex $u$ to verte...
This problem can be solved in several similar ways, one of them is given below. First, it is most convenient to take a bamboo - vertices from $1$ to $n$ connected in order. Then, we will maintain the following construction. At each moment of time, vertices $1$ and $2$ will be connected by an edge, from vertex $2$ there...
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "trees" ]
1,600
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> b1, b2; for (int i = 0; i < n; ++i) { b1.push_back(i); } b2.push_back(1); for (int i = 1; i < n; ++i) { cout << i << ' ' << i + 1 << endl; } int q; cin >> q; while (q--) ...
1899
G
Unusual Entertainment
A tree is a connected graph without cycles. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[5, 1, 3, 2, 4]$ is a permutation, but $[2, 1, 1]$ is not a permutation (as $1$ appears twice in the array) and $[1, 3, 2, 5]$ is also not a permutation (as $n = 4$, but...
Let's start the depth-first search from vertex $1$ and write out the entry and exit times for each vertex. Then, the fact that vertex $b$ is a descendant of vertex $a$ is equivalent to the fact that $\mathrm{tin}[a] \leq \mathrm{tin}[b] \leq \mathrm{tout}[b] \leq \mathrm{tout}[b] \leq \mathrm{tout}[a]$, where $\mathrm{...
[ "data structures", "dfs and similar", "dsu", "shortest paths", "sortings", "trees", "two pointers" ]
1,900
#include <bits/stdc++.h> using namespace std; #define sz(x) (int)x.size() #define all(x) x.begin(), x.end() struct SegmentTree { int n; vector<vector<int>> tree; void build(vector<int> &a, int x, int l, int r) { if (l + 1 == r) { tree[x] = {a[l]}; return; } ...
1900
A
Cover in Water
Filip has a row of cells, some of which are blocked, and some are empty. He wants all empty cells to have water in them. He has two actions at his disposal: - $1$ — place water in an empty cell. - $2$ — remove water from a cell and place it in any other empty cell. If at some moment cell $i$ ($2 \le i \le n-1$) is em...
Assume that cells $i-1$, $i$, and $i+1$ are covered in water. What happens if you remove water from cell $i$? The water at position $i$ is replaced as both cells $i-1$ and $i+1$ have water in them. Read the hints. If there are 3 consecutive empty cells $i-1$, $i$, $i+1$, we can place water in cells $i-1$ and $i+1$ and ...
[ "constructive algorithms", "greedy", "implementation", "strings" ]
800
null
1900
B
Laura and Operations
Laura is a girl who does not like combinatorics. Nemanja will try to convince her otherwise. Nemanja wrote some digits on the board. All of them are either $1$, $2$, or $3$. The number of digits $1$ is $a$. The number of digits $2$ is $b$ and the number of digits $3$ is $c$. He told Laura that in one operation she can...
Check if only digits $1$ can remain. The situation is similar for checking if only digits $2$ or only digits $3$ can remain. Try to find something that stays the same after each operation. Look at the parity of the numbers. The parity of each number changes after an operation. That means that if $2$ numbers have the sa...
[ "dp", "math" ]
900
null
1900
C
Anji's Binary Tree
Keksic keeps getting left on seen by Anji. Through a mutual friend, he's figured out that Anji really likes binary trees and decided to solve her problem in order to get her attention. Anji has given Keksic a binary tree with $n$ vertices. Vertex $1$ is the root and does not have a parent. All other vertices have exac...
Solve the problem if all of the characters on vertices are 'U'. We can run DFS from the root. Using it we can calculate the number of edges that we have to traverse to get to every edge. Just output the smallest value among all the leaves. Modify the DFS such that it takes into account that traversing some edges does n...
[ "dfs and similar", "dp", "trees" ]
1,300
null
1900
D
Small GCD
Let $a$, $b$, and $c$ be integers. We define function $f(a, b, c)$ as follows: Order the numbers $a$, $b$, $c$ in such a way that $a \le b \le c$. Then return $\gcd(a, b)$, where $\gcd(a, b)$ denotes the greatest common divisor (GCD) of integers $a$ and $b$. So basically, we take the $\gcd$ of the $2$ smaller values ...
Let $m$ be the biggest value in the array. Calculate array $x$ such that $x_i$ ($1 \le i \le m$) is the number of triples which have $\gcd$ of $i$. Then the answer is the sum of $i \cdot x_i$ over all $i$ ($1 \le i \le m$). Value of $\lfloor \frac{m}{1} \rfloor + \lfloor \frac{m}{2} \rfloor + \lfloor \frac{m}{3} \rfloo...
[ "bitmasks", "brute force", "dp", "math", "number theory" ]
2,000
null
1900
E
Transitive Graph
You are given a \textbf{directed} graph $G$ with $n$ vertices and $m$ edges between them. Initially, graph $H$ is the same as graph $G$. Then you decided to perform the following actions: - If there exists a triple of vertices $a$, $b$, $c$ of $H$, such that there is an edge from $a$ to $b$ and an edge from $b$ to $c...
Try to simplify graph $H$. Look at strongly connected components of $G$, and what happens with them. Use dp to find the answer. The main observation is what $H$ looks like. All the strongly connected components (SCC) in $G$ will become fully connected subgraphs in $H$. Secondly, take any two vertices $a$ and $b$ such t...
[ "dfs and similar", "dp", "dsu", "graphs", "implementation" ]
2,100
null
1900
F
Local Deletions
For an array $b_1, b_2, \ldots, b_m$, for some $i$ ($1 < i < m$), element $b_i$ is said to be a local minimum if $b_i < b_{i-1}$ and $b_i < b_{i+1}$. Element $b_1$ is said to be a local minimum if $b_1 < b_2$. Element $b_m$ is said to be a local minimum if $b_m < b_{m-1}$. For an array $b_1, b_2, \ldots, b_m$, for som...
Solve the problem for $q=1$. We can just simulate the process. Each operation removes at least half of the elements, meaning that we will perform at most $log n$ operations. Solve the problem if each $l_i = 1$. So basically, solve the problem for each prefix. Keep values that are in the array after $1$, $2$, $3$, $\cdo...
[ "binary search", "data structures", "implementation" ]
2,800
null
1901
A
Line Trip
There is a road, which can be represented as a number line. You are located in the point $0$ of the number line, and you want to travel from the point $0$ to the point $x$, and back to the point $0$. You travel by car, which spends $1$ liter of gasoline per $1$ unit of distance travelled. When you start at the point $...
We can iterate over the volume of the gas tank from $1$ to $\infty$ (in fact $200$ is enough due to problem limitations) and check whether it's enough to travel from the point $0$ to the point $x$, and back. Let the volume be $V$, then all the following inequalities (which correspond to the ability to travel from the c...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n, x; cin >> n >> x; int prev = 0, ans = 0; for (int i = 0; i < n; ++i) { int a; cin >> a; ans = max(ans, a - prev); prev = a; } an...
1901
B
Chip and Ribbon
There is a ribbon divided into $n$ cells, numbered from $1$ to $n$ from left to right. Initially, an integer $0$ is written in each cell. Monocarp plays a game with a chip. The game consists of several turns. During the first turn, Monocarp places the chip in the $1$-st cell of the ribbon. During each turn \textbf{exc...
At first, let's change the statement a bit: instead of teleporting our chip into cell $x$, we create a new chip in cell $x$ (it means that the chip does not disappear from the cell where it was located). And when we want to move a chip, we move any chip to the next cell. Then, $c_i$ will be the number of times a chip a...
[ "greedy", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; const int N = 200'000; int t; int main() { cin >> t; for (int tc = 0; tc < t; ++tc) { int n; cin >> n; vector <int> cnt(n); long long res = 0; int cur = 0; for (int i = 0; i < n; ++i) { cin >> cnt[i...
1901
C
Add, Divide and Floor
You are given an integer array $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$). In one operation, you can choose an integer $x$ ($0 \le x \le 10^{18}$) and replace $a_i$ with $\lfloor \frac{a_i + x}{2} \rfloor$ ($\lfloor y \rfloor$ denotes rounding $y$ down to the nearest integer) for all $i$ from $1$ to $n$. Pay attenti...
Sort the array. Notice how applying the operation doesn't change the order of the elements, regardless of $x$. It means that it's enough to make the initial minimum and maximum equal to make all elements equal. Consider the difference between the minimum and the maximum values. What happens to it after an operation? Le...
[ "constructive algorithms", "greedy", "math" ]
1,400
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) x, y = min(a), max(a) res = [] while x != y: res.append(x % 2) x = (x + res[-1]) // 2 y = (y + res[-1]) // 2 print(len(res)) if len(res) <= n: print(*res)
1901
D
Yet Another Monster Fight
Vasya is a sorcerer that fights monsters. Again. There are $n$ monsters standing in a row, the amount of health points of the $i$-th monster is $a_i$. Vasya is a very powerful sorcerer who knows many overpowered spells. In this fight, he decided to use a chain lightning spell to defeat all the monsters. Let's see how ...
Let's start with a naive solution. Let $i$ be the index of the monster we started with. Let's make sure that we can kill all monsters, starting with monster $i$. Suppose we have chosen spell power $x$. How to check if all monsters will be definitely killed? Let's iterate on each monster $j$ and calculate the minimum po...
[ "binary search", "dp", "greedy", "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); for (auto &it : a) cin >> it; vector<int> pref(n), suf(n); for (int i = 0; i < n; ++i) { ...
1901
E
Compressed Tree
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$. You can perform the following operation any number of times (possibly zero): - choose a vertex which has \textbf{at most $1$} incident edge and remove this vertex from the tree. Note that ...
We can use dynamic programming on tree to solve this problem. After we're done removing vertices, a vertex will be left in the tree after the compression process if and only if its degree is not $2$. So, we can try to choose the number of children for each vertex in dynamic programming, and depending on this number of ...
[ "dfs and similar", "dp", "graphs", "greedy", "sortings", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; using li = long long; const li INF = 1e18; const int N = 555555; int n; int a[N]; vector<int> g[N]; li dp[N]; li ans; void calc(int v, int p) { vector<li> sum(4, -INF); sum[0] = 0; for (int u : g[v]) if (u != p) { calc(u, v); for (int i = 3; i >= 0; ...
1901
F
Landscaping
You are appointed to a very important task: you are in charge of flattening one specific road. The road can be represented as a polygonal line starting at $(0, 0)$, ending at $(n - 1, 0)$ and consisting of $n$ vertices (including starting and ending points). The coordinates of the $i$-th vertex of the polyline are $(i...
Let's say that we are searching for the best line that contains the best segment. Observation $1$: the best line touches at least one vertex of the polyline. Otherwise, you can push it down until it touches polyline. Observation $2$: the best line touches two vertices of the polyline. Suppose it touches only one vertex...
[ "binary search", "geometry", "two pointers" ]
2,900
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostre...
1902
A
Binary Imbalance
You are given a string $s$, consisting only of characters '0' and/or '1'. In one operation, you choose a position $i$ from $1$ to $|s| - 1$, where $|s|$ is the current length of string $s$. Then you insert a character between the $i$-th and the $(i+1)$-st characters of $s$. If $s_i = s_{i+1}$, you insert '1'. If $s_i ...
If the string consists of all ones, then it's always impossible. Any operation will only add more ones to the string. Otherwise, let's show that it's always possible. If the string consists of all zeroes, no operations are required. Otherwise, there always exists a pair of adjacent zero and one. Applying an operation b...
[ "constructive algorithms" ]
800
for _ in range(int(input())): n = int(input()) s = input() print("NO" if s.count('1') == n else "YES")
1902
B
Getting Points
Monocarp is a student at Berland State University. Due to recent changes in the Berland education system, Monocarp has to study only one subject — programming. The academic term consists of $n$ days, and in order not to get expelled, Monocarp has to earn at least $P$ points during those $n$ days. There are two ways to...
Firstly, let $c$ be the total number of tasks in the term. Then $c = \left\lceil\frac{n}{7}\right\rceil = \left\lfloor \frac{n + 6}{7} \right\rfloor$. Suppose, Monocarp will study exactly $k$ days. How many points will he get? He gets $k \cdot l$ for attending lessons and, since he can complete at most $2$ tasks per da...
[ "binary search", "brute force", "greedy" ]
1,100
fun main(args: Array<String>) { repeat(readln().toInt()) { val (n, p, l, t) = readln().split(' ').map { it.toLong() } val cntTasks = (n + 6) / 7 fun calc(k: Long) = k * l + minOf(2 * k, cntTasks) * t var lf = 0L var rg = n while (rg - lf > 1) { va...
1902
C
Insert and Equalize
You are given an integer array $a_1, a_2, \dots, a_n$, all its elements are distinct. First, you are asked to insert one more integer $a_{n+1}$ into this array. $a_{n+1}$ should not be equal to any of $a_1, a_2, \dots, a_n$. Then, you will have to make all elements of the array equal. At the start, you choose a \text...
Let's start by learning how to calculate the function without the insertion. Since $x$ can only be positive, we will attempt to make all elements equal to the current maximum value in the array. Pick some $x$. Now, how to check if it's possible to make every element equal to the maximum? Well, for one element, the diff...
[ "brute force", "constructive algorithms", "greedy", "math", "number theory" ]
1,300
from math import gcd for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) g = 0 for i in range(n - 1): g = gcd(g, a[i + 1] - a[i]) g = max(g, 1) a.sort() j = n - 1 res = a[-1] while True: while j >= 0 and a[j] > res: j -= 1 if j < 0 or a[j] != res: break res -= g ...
1902
D
Robot Queries
There is an infinite $2$-dimensional grid. Initially, a robot stands in the point $(0, 0)$. The robot can execute four commands: - U — move from point $(x, y)$ to $(x, y + 1)$; - D — move from point $(x, y)$ to $(x, y - 1)$; - L — move from point $(x, y)$ to $(x - 1, y)$; - R — move from point $(x, y)$ to $(x + 1, y)$...
Let's divide the path of the robot into three parts: points before the $l$-th operation; points from the $l$-th to the $r$-th operations; points after the $r$-th operation; The first and the third parts are pretty simple to check because the reverse of the substring $(l, r)$ does not affect them. So we can precompute a...
[ "binary search", "data structures", "dp", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; #define x first #define y second using pt = pair<int, int>; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q; cin >> n >> q; string s; cin >> s; vector<pt> pos(n + 1); for (int i = 0; i < n; ++i) { pos[i + 1].x = pos[i].x + (s[i] == '...
1902
E
Collapsing Strings
You are given $n$ strings $s_1, s_2, \dots, s_n$, consisting of lowercase Latin letters. Let $|x|$ be the length of string $x$. Let a collapse $C(a, b)$ of two strings $a$ and $b$ be the following operation: - if $a$ is empty, $C(a, b) = b$; - if $b$ is empty, $C(a, b) = a$; - if the last letter of $a$ is equal to th...
Let's suppose that when we calculate the collapse of two strings $a$ and $b$, we reverse the string $a$ first, so that instead of checking and removing the last letters of $a$, we do this to the first letters of $a$. Then, $|C(a,b)| = |a| + |b| - 2|LCP(a', b)|$, where $LCP(a', b)$ is the longest common prefix of $a'$ (...
[ "data structures", "strings", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = int(1e6) + 99; int nxt; int to[N][26]; int sum[N]; long long res; void add(const string& s) { int v = 0; ++sum[v]; for (auto c : s) { int i = c - 'a'; if (to[v][i] == -1) to[v][i] = nxt++; v = to[v][i]; ...
1902
F
Trees and XOR Queries Again
You are given a tree consisting of $n$ vertices. There is an integer written on each vertex; the $i$-th vertex has integer $a_i$ written on it. You have to process $q$ queries. The $i$-th query consists of three integers $x_i$, $y_i$ and $k_i$. For this query, you have to answer if it is possible to choose a set of ve...
This problem requires working with XOR bases, so let's have a primer on them. Suppose you want to solve the following problem: given a set of integers $x_1, x_2, \dots, x_k$ and another integer $y$, check whether it is possible to choose several (maybe zero) integers from the set such that their XOR is $y$. It can be s...
[ "data structures", "dfs and similar", "divide and conquer", "graphs", "implementation", "math", "trees" ]
2,400
#include<bits/stdc++.h> using namespace std; const int N = 200043; const int K = 20; typedef array<int, K> base; int a[N]; vector<int> g[N]; vector<int> path_up[N]; int tin[N], tout[N]; int T = 0; int fup[N][K]; base make_empty() { base b; for(int i = 0; i < K; i++) b[i] = 0; return b; } i...
1903
A
Halloumi Boxes
Theofanis is busy after his last contest, as now, he has to deliver many halloumis all over the world. He stored them inside $n$ boxes and each of which has some number $a_i$ written on it. He wants to sort them in non-decreasing order based on their number, however, his machine works in a strange way. It can only rev...
If the array is already sorted or $k > 1$ then there is always a way (reverse of size $2 =$ swap consecutive elements). Else it is not possible since when $k = 1$ the array remains the same.
[ "brute force", "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n,k; cin>>n>>k; int arr[n]; for(int i = 0;i < n;i++){ cin>>arr[i]; } if(is_sorted(arr,arr+n) || k > 1){ cout<<"YES\n"; } else{ ...
1903
B
StORage room
In Cyprus, the weather is pretty hot. Thus, Theofanis saw this as an opportunity to create an ice cream company. He keeps the ice cream safe from other ice cream producers by locking it inside big storage rooms. However, he forgot the password. Luckily, the lock has a special feature for forgetful people! It gives yo...
Solution: Initially, we set all $a_i = 2^{30} - 1$ (all bits on). You can through every $i$,$j$ such that $i \neq j$ and do $a_i \&= M_{i,j}$ and $a_j \&= M_{i,j}$. Then we check if $M_{i,j} = a_i | a_j$ for all pairs. If this holds you found the array else the answer is NO. Proof: Initially, all elements have all thei...
[ "bitmasks", "brute force", "constructive algorithms", "greedy" ]
1,200
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--){ int n; cin>>n; int m[n][n]; int arr[n]; for(int i = 0;i < n;i++){ arr[i] = (1<<30) - 1; } for(int i = 0;i...
1903
C
Theofanis' Nightmare
Theofanis easily gets obsessed with problems before going to sleep and often has nightmares about them. To deal with his obsession he visited his doctor, Dr. Emix. In his latest nightmare, he has an array $a$ of size $n$ and wants to divide it into non-empty subarrays$^{\dagger}$ such that every element is in exactly ...
Let $suf_i$ be the suffix sum of the array (from the $i^{th}$ position to the $n^{th}$). $ans =$ sum of $suf_{L_i}$ where $L_i$ is the leftmost element of the $i^{th}$ subarray. Definitely, $L_1 = 1$ and we can take any other we want (at most once). So we start with $ans = suf_1$ and for every $i > 1$ we add $suf_i$ if...
[ "constructive algorithms", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; long long suf[n+1] = {0}; for(int i = 0;i < n;i++){ cin>>arr[i]; } for(int i =...
1903
D1
Maximum And Queries (easy version)
\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$ and $q$, the memory and time limits. You can make hacks only if all versions of the problem are solved.} Theofanis really likes to play with the bits of numbers. He has an array $a$ of size $n$ and an...
Construct the answer by iterating through every single bit from large to small ($2^{60}$ to $2^0$). Denote $x$ a the current answer and $b$ a the bit we want to add. For each $i$ ($1 \le i \le n$) if the $b$-th bit in $a_i$ is on we do not need to use any operations. If the $b$-th bit in $a_i$ is 0 then we need to incr...
[ "binary search", "bitmasks", "brute force", "greedy" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define rep(a, b) for(int a = 0; a < (b); ++a) #define st first #define nd second #define pb push_back #define all(a) a.begin(), a.end() const int LIM=1e5+7; ll T[LIM], P[LIM], n, k; void solve() { rep(i, n) T[i]=P[i]; ll ans...
1903
D2
Maximum And Queries (hard version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$ and $q$, the memory and time limits. You can make hacks only if all versions of the problem are solved.} Theofanis really likes to play with the bits of numbers. He has an array $a$ of size $n$ and an...
Let $S = \sum (2^{20} - a_i)$. If $k \ge S$ then the answer is $2^{20} + \lfloor \frac{k-S}{n} \rfloor$. Similarly to D1 let's construct the answer bit by bit. Let $x$ be the current answer and $b$ be the bit we want to add. Let's look at the amount of operations we need to do on the $i$-th element to change our answer...
[ "bitmasks", "divide and conquer", "dp", "greedy" ]
2,500
#include<bits/stdc++.h> using namespace std; typedef long double ld; typedef long long ll; #define rep(a, b) for(ll a = 0; a < (b); ++a) #define st first #define nd second #define pb push_back #define all(a) a.begin(), a.end() const int LIM=1e6+7; ll dpsum[1<<20][20], dpcnt[1<<20], T[LIM]; int main() { ios_base::sync...
1903
E
Geo Game
This is an interactive problem. Theofanis and his sister are playing the following game. They have $n$ points in a 2D plane and a starting point $(s_x,s_y)$. Each player (starting from the first player) chooses one of the $n$ points that wasn't chosen before and adds to the sum (which is initially $0$) the \textbf{sq...
If we went from point $(a,b)$ to $(c,d)$ then we will add to the sum $a^2 + c^2 - 2ac + b^2 + d^2 - 2bd$ which is equal to $a \oplus b \oplus c \oplus d$ mod $2$ ($\oplus$ is bitwise xor). For each point, we find ($x$ mod $2$) $\oplus$ ($y$ mod $2$). Let $p_0 =$ the number of ($x$ mod $2$) $\oplus$ ($y$ mod $2$) $== 0$...
[ "greedy", "interactive", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int sx,sy; cin>>sx>>sy; int x[n],y[n]; set<int>p[2]; for(int i = 0;i < n;i++){ cin>>x[i]>>y[i]; p[(x[i] % 2) ^ (y[i] % 2)].inser...
1903
F
Babysitting
Theofanis wants to play video games, however he should also take care of his sister. Since Theofanis is a CS major, he found a way to do both. He will install some cameras in his house in order to make sure his sister is okay. His house is an undirected graph with $n$ nodes and $m$ edges. His sister likes to play at t...
We can solve this problem using 2-sat and binary search the answer. In order to have a vertex cover we should have $(u_i | v_i)$. And if we want to check if the answer is greater or equal to $mid$ we want to have $(!x | !y)$ for all pairs $1\le x, y \le n$ such that $|x - y| < mid$. However, this way we will have too m...
[ "2-sat", "binary search", "data structures", "graphs", "trees" ]
2,500
#pragma GCC optimize("O3") #include "bits/stdc++.h" using namespace std; #define all(x) begin(x),end(x) template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_sa...
1904
A
Forked!
Lunchbox is done with playing chess! His queen and king just got forked again! In chess, a fork is when a knight attacks two pieces of higher value, commonly the king and the queen. Lunchbox knows that knights can be tricky, and in the version of chess that he is playing, knights are even trickier: instead of moving $...
There are at most $8$ positions of the knight that can attack a single cell. Therefore, we can find all $8$ positions that attack the king and the $8$ positions that attack the queen and count the number of positions that appear in both of these lists. 1904B - Collecting Game
[ "brute force", "implementation" ]
900
#include <bits/stdc++.h> using namespace std; int dx[4] = {-1, 1, -1, 1}, dy[4] = {-1, -1, 1, 1}; int main(){ int t; cin >> t; for(int i = 0; i < t; i++){ int a, b; cin >> a >> b; int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; set<pair<int, int>> st1, st2; for(int j = 0; j ...
1904
B
Collecting Game
You are given an array $a$ of $n$ positive integers and a score. If your score is greater than or equal to $a_i$, then you can increase your score by $a_i$ and remove $a_i$ from the array. For each index $i$, output the maximum number of additional array elements that you can remove if you remove $a_i$ and then set yo...
Let's sort array $a$. The answer for the largest element is $n-1$ because the score, which is $a_n$, cannot be smaller than any of the other elements. Now, consider the second largest element. The answer is at least $n-2$ because every element that is not greater than $a_{n-1}$ can be taken. Then, we check if the score...
[ "binary search", "dp", "greedy", "sortings", "two pointers" ]
1,100
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define pb push_back #define ff first #define ss second typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pa...
1904
C
Array Game
You are given an array $a$ of $n$ positive integers. In one operation, you must pick some $(i, j)$ such that $1\leq i < j\leq |a|$ and append $|a_i - a_j|$ to the end of the $a$ (i.e. increase $n$ by $1$ and set $a_n$ to $|a_i - a_j|$). Your task is to minimize and print the minimum value of $a$ after performing $k$ op...
If $k\geq 3$, the answer is equal to $0$ since after performing an operation on the same pair $(i, j)$ twice, performing an operation on the two new values (which are the same) results in $0$. Therefore, let's consider the case for $1\leq k\leq 2$. For $k=1$, it is sufficient to sort the array and output the minimum be...
[ "binary search", "brute force", "data structures", "sortings", "two pointers" ]
1,400
#include <bits/stdc++.h> using namespace std; #define int long long signed main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; if (k >= 3) { cout << 0 << endl; continue;...
1904
D2
Set To Max (Hard Version)
\textbf{This is the hard version of the problem. The only differences between the two versions of this problem are the constraints on $n$ and the time limit. You can make hacks only if all versions of the problem are solved.} You are given two arrays $a$ and $b$ of length $n$. You can perform the following operation ...
Can we reduce the number of intervals we want to apply an operation on? What is the necessary condition to perform an operation on an interval If $b_i < a_i$ for any $i$, then it is clearly impossible. In order for $a_i$ to become $b_i$, $i$ must be contained by an interval that also contains a $j$ where $a_j = b_i$. N...
[ "constructive algorithms", "data structures", "divide and conquer", "greedy", "implementation", "sortings" ]
1,800
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define pb push_back #define ff first #define ss second typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pa...
1904
E
Tree Queries
\begin{quote} Those who don't work don't eat. Get the things you want with your own power. But believe, the earnest and serious people are the ones who have the last laugh... But even then, I won't give you a present. \hfill —Santa, Hayate no Gotoku! \end{quote} Since Hayate didn't get any Christmas presents from Sant...
The solution doesn't involve virtual tree What is an easy way to represent the tree? Consider the Euler tour of the tree where $in[u]$ is the entry time of each node and $out[u]$ is the exit time. The interval $[in[u], out[u]]$ corresponds to the subtree of $u$. Removing a node is equivalent to blocking some intervals ...
[ "data structures", "dfs and similar", "graphs", "implementation", "trees" ]
2,500
#include <bits/stdc++.h> #define sz(x) ((int)(x.size())) #define all(x) x.begin(), x.end() #define pb push_back #define eb emplace_back const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; //lca template start vector<int> dep, sz, par, head, tin, tout, tour; vector<vector<int>> adj; int n, ind, q; voi...
1904
F
Beautiful Tree
Lunchbox has a tree of size $n$ rooted at node $1$. Each node is then assigned a value. Lunchbox considers the tree to be beautiful if each value is distinct and ranges from $1$ to $n$. In addition, a beautiful tree must also satisfy $m$ requirements of $2$ types: - "1 a b c" — The node with the smallest value on the ...
Can we represent the conditions as a graph? Lets rewrite the condition that node $a$ must be smaller than node $b$ as a directed edge from $a$ to $b$. Then, we can assign each node a value based on the topological sort of this new directed graph. If this directed graph had a cycle, it is clear that there is no way to o...
[ "data structures", "dfs and similar", "graphs", "implementation", "trees" ]
2,800
#pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx,avx2,fma") #pragma GCC target("sse4,popcnt,abm,mmx,tune=native") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define pb push_back #define ff first ...
1905
A
Constructive Problems
Gridlandia has been hit by flooding and now has to reconstruct all of it's cities. Gridlandia can be described by an $n \times m$ matrix. Initially, all of its cities are in economic collapse. The government can choose to rebuild certain cities. Additionally, any collapsed city which has at least one vertically neighb...
We can observe an invariant given by the problem is that every time we apply adjacent aid on any state of the matrix, the sets of rows that have at least one rebuilt city, respectively the sets of columns that appear that have at least one rebuilt city remain constant. Therefore, if we want to have a full matrix as con...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> #define all(x) (x).begin(),(x).end() using namespace std; using ll = long long; using ld = long double; //#define int ll #define sz(x) ((int)(x).size()) using pii = pair<int,int>; using tii = tuple<int,int,int>; const int nmax = 1e6 + 5; const int inf = 1e9 + 5; int n, k, m, q; vector<int> ...
1905
B
Begginer's Zelda
You are given a tree$^{\dagger}$. In one zelda-operation you can do follows: - Choose two vertices of the tree $u$ and $v$; - Compress all the vertices on the path from $u$ to $v$ into one vertex. In other words, all the vertices on path from $u$ to $v$ will be erased from the tree, a new vertex $w$ will be created. T...
We can prove by induction that on any tree with $K$ leaves, the answer is $[{\frac{K + 1}{2}}]$, where with $[x]$ we denote the greatest integer smaller than $x$. This can be proven by induction, we will give an overview of what a proof would look like: For two leaves, the answer is clearly $1$. For three leaves, the a...
[ "greedy", "trees" ]
1,100
#include <cmath> #include <functional> #include <fstream> #include <iostream> #include <vector> #include <algorithm> #include <string> #include <set> #include <map> #include <list> #include <time.h> #include <math.h> #include <random> #include <deque> #include <queue> #include <unordered_map> #include <unordered_set> #...
1905
C
Largest Subsequence
Given is a string $s$ of length $n$. In one operation you can select the lexicographically largest$^\dagger$ subsequence of string $s$ and cyclic shift it to the right$^\ddagger$. Your task is to calculate the minimum number of operations it would take for $s$ to become sorted, or report that it never reaches a sorted...
We can notice that this operation will ultimately reverse the lexicographically largest subset of the initial string. Thus, we can easily check if the string is sortable, and for finding the number of operations we will subtract the length of the largest prefix of equal values of the subset from its length. This soluti...
[ "greedy", "strings" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(nullptr)->sync_with_stdio(false); int q; cin >> q; while (q--) { int n; string s; cin >> n >> s; s = '$' + s; vector<int> subset; for (int i = 1; i <= n; ++i) { whil...
1905
D
Cyclic MEX
For an array $a$, define its cost as $\sum_{i=1}^{n} \operatorname{mex} ^\dagger ([a_1,a_2,\ldots,a_i])$. You are given a permutation$^\ddagger$ $p$ of the set $\{0,1,2,\ldots,n-1\}$. Find the maximum cost across all cyclic shifts of $p$. $^\dagger\operatorname{mex}([b_1,b_2,\ldots,b_m])$ is the smallest non-negative...
Let's analyze how the values of each prefix mex changes upon performing a cyclic shift to the left: The first prefix mex is popped. Each prefix mex with a value less than $p_1$ doesn't change. Each prefix mex with a value greater than $p_1$ becomes $p_1$. $n$ is appended to the back. Let's keep our prefix mexes compres...
[ "data structures", "implementation", "math", "two pointers" ]
2,000
#include <bits/stdc++.h> #define int long long using namespace std; int32_t main() { cin.tie(nullptr)->sync_with_stdio(false); int q; cin >> q; while (q--) { int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; ++i) { cin >> a[i]; } deque<pair<int, int>> dq; vector<int> f(n + 1); ...
1905
E
One-X
In this sad world full of imperfections, ugly segment trees exist. A segment tree is a tree where each node represents a segment and has its number. A segment tree for an array of $n$ elements can be built in a recursive manner. Let's say function $\operatorname{build}(v,l,r)$ builds the segment tree rooted in the nod...
Let's try to solve a slightly easier problem first: changing the coefficient of the label to be the msb of the label. We can note that at each depth, every label will have the same number of digits ( in base 2 ), thus the same msb. And we can notice that for each depth there are at most $2$ different interval lengths. ...
[ "combinatorics", "dfs and similar", "dp", "math", "trees" ]
2,400
#include <bits/stdc++.h> #define int long long using namespace std; const int mod = 998244353; struct Mint { int val; Mint(long long x = 0) { val = x % mod; } Mint operator+(Mint oth) { return val + oth.val; } Mint operator-(Mint oth) { return val - oth.val + ...
1905
F
Field Should Not Be Empty
You are given a permutation$^{\dagger}$ $p$ of length $n$. We call index $x$ good if for all $y < x$ it holds that $p_y < p_x$ and for all $y > x$ it holds that $p_y > p_x$. We call $f(p)$ the number of good indices in $p$. You can perform the following operation: pick $2$ \textbf{distinct} indices $i$ and $j$ and sw...
The key observation to this problem is that most swaps are useless. In fact, we can find that only $2n$ swaps can increase our initial cost: The first type of meaningful swaps is $(i,p_i)$ For each $1 < i < n$, consider $k$ and $l$ such that $p_k = max(p_1,p_2,...,p_{i-1})$ and $p_l = min(p_{i+1},p_{i+2},...,p_n)$. The...
[ "brute force", "data structures", "divide and conquer" ]
2,600
#include <bits/stdc++.h> using namespace std; struct aint { vector<pair<int, int>> a; vector<int> lazy; void resize(int n) { a = vector<pair<int, int>>(4 * n); lazy = vector<int>(4 * n); } void init(int node, int left, int right) { a[node].second = (right - left + 1);...
1907
A
Rook
As you probably know, chess is a game that is played on a board with 64 squares arranged in an $8\times 8$ grid. Columns of this board are labeled with letters from \textbf{a} to \textbf{h}, and rows are labeled with digits from \textbf{1} to \textbf{8}. Each square is described by the row and column it belongs to. Th...
The answer includes all cells that share the same column or row with the given cell. Let's iterate through all the columns, keeping the row constant, and vice versa, iterate through the rows without changing the column. To ensure that the input cell is not included in the answer, you can either skip it or add all posit...
[ "implementation" ]
800
for _ in range(int(input())): s = input() for c in "abcdefgh": if c != s[0]: print(c + s[1], end=' ') for c in "12345678": if c != s[1]: print(s[0] + c, end=' ') print()
1907
B
YetnotherrokenKeoard
Polycarp has a problem — his laptop keyboard is broken. Now, when he presses the 'b' key, it acts like an unusual backspace: it deletes the last (rightmost) lowercase letter in the typed string. If there are no lowercase letters in the typed string, then the press is completely ignored. Similarly, when he presses the...
To solve the problem, it was necessary to quickly support deletions. For this, one could maintain two stacks: one with the positions of uppercase letters and one with the positions of lowercase letters. Then, when deleting, one needs to somehow mark that the character at this position should not be output. Alternativel...
[ "data structures", "implementation", "strings" ]
1,000
for _ in range(int(input())): s = list(input()) n = len(s) upper = [] lower = [] for i in range(n): if s[i] == 'b': s[i] = '' if lower: s[lower.pop()] = '' continue if s[i] == 'B': s[i] = '' if upper: ...
1907
C
Removal of Unattractive Pairs
Vlad found a string $s$ consisting of $n$ lowercase Latin letters, and he wants to make it as short as possible. To do this, he can remove \textbf{any} pair of adjacent characters from $s$ any number of times, provided they are \textbf{different}. For example, if $s$=racoon, then by removing one pair of characters he ...
Consider a finite string; obviously, all characters in it are the same, as otherwise, we could remove some pair of characters. If some character occurs in the string more than $\lfloor \frac{n}{2} \rfloor$ times, then the final string will always consist only of it, because with one deletion we can only get rid of one ...
[ "constructive algorithms", "greedy", "math", "strings" ]
1,200
orda = ord('a') def solve(): n = int(input()) cnt = [0] * 26 for c in input(): cnt[ord(c) - orda] += 1 mx = max(cnt) print(max(n % 2, 2 * mx - n)) for _ in range(int(input())): solve()
1907
D
Jumping Through Segments
Polycarp is designing a level for a game. The level consists of $n$ segments on the number line, where the $i$-th segment starts at the point with coordinate $l_i$ and ends at the point with coordinate $r_i$. The player starts the level at the point with coordinate $0$. In one move, they can move to any point that is ...
First, let's note that if we can pass a level with some value of $k$, then we can make all the same moves and pass it with a larger value. This allows us to use binary search for the answer. To check whether it is possible to pass the level with a certain $k$, we will maintain a segment in which we can find ourselves. ...
[ "binary search", "constructive algorithms" ]
1,400
def solve(): n = int(input()) seg = [list(map(int, input().split())) for x in range(n)] def check(k): ll, rr = 0, 0 for e in seg: ll = max(ll - k, e[0]) rr = min(rr + k, e[1]) if ll > rr: return False return True l, r = -1, 10...
1907
E
Good Triples
Given a non-negative integer number $n$ ($n \ge 0$). Let's say a triple of non-negative integers $(a, b, c)$ is good if $a + b + c = n$, and $digsum(a) + digsum(b) + digsum(c) = digsum(n)$, where $digsum(x)$ is the sum of digits of number $x$. For example, if $n = 26$, then the pair $(4, 12, 10)$ is good, because $4 +...
A triplet is considered good only if each digit of the number $n$ was obtained without carrying over during addition. For example, consider $a=2$, $b=7$, $c=4$; the sum of the digits is $2 + 7 + 4 = 13$, and the sum of the digits of their sum is $1 + 3 = 4$. This means that whenever there is a carry in one of the digit...
[ "brute force", "combinatorics", "number theory" ]
1,600
t = int(input()) for _ in range(t): n = int(input()) cnt = 1 while n > 0: d = n % 10 n //= 10 mul = 0 for i in range(d + 1): for j in range(d + 1): if d - i - j >= 0: mul += 1 cnt *= mul print(cnt)
1907
F
Shift and Reverse
Given an array of integers $a_1, a_2, \ldots, a_n$. You can make two types of operations with this array: - Shift: move the last element of array to the first place, and shift all other elements to the right, so you get the array $a_n, a_1, a_2, \ldots, a_{n-1}$. - Reverse: reverse the whole array, so you get the arra...
In this problem, there are several possible sequences of actions from which the optimal one must be chosen. For brevity, let's denote the reverse by the letter "R", and the shift by the letter "S": SS$\dots$SS RS$\dots$SR RS$\dots$SS SS$\dots$SR Let's write out the array twice and count the segments on which it increas...
[ "greedy", "sortings" ]
1,800
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) a = list(reversed(a))*2 p = [0] q = [0] for i in range(n*2-1): p.append(p[-1]+1 if a[i]>=a[i+1] else 0) q.append(q[-1]+1 if a[i]<=a[i+1] else 0) minn = 1000000 for i in range(n-1,len(...
1907
G
Lights
In the end of the day, Anna needs to turn off the lights in the office. There are $n$ lights and $n$ light switches, but their operation scheme is really strange. The switch $i$ changes the state of light $i$, but it also changes the state of some other light $a_i$ (change the state means that if the light was on, it g...
Let's construct a directed graph where an edge originates from vertex $i$ to vertex $a_i$. In such a graph, exactly one edge originates from each vertex, and there is exactly one cycle in each connected component. First, we will turn off all the lights that are not part of the cycles; the sequence of such turn-offs is ...
[ "brute force", "constructive algorithms", "dfs and similar", "graphs", "greedy", "implementation" ]
2,200
#include <bits/stdc++.h> #define long long long int #define DEBUG using namespace std; // @author: pashka void solve(){ int n; cin >> n; vector<bool> s(n); { string ss; cin >> ss; for (int i = 0; i < n; i++) { s[i] = ss[i] == '1'; } } vector<int> a(...
1909
A
Distinct Buttons
\begin{quote} Deemo - Entrance \hfill ⠀ \end{quote} You are located at the point $(0, 0)$ of an infinite Cartesian plane. You have a controller with $4$ buttons which can perform one of the following operations: - $U$: move from $(x, y)$ to $(x, y+1)$; - $R$: move from $(x, y)$ to $(x+1, y)$; - $D$: move from $(x, y)...
Suppose you can only use $\texttt{U}$, $\texttt{R}$, $\texttt{D}$. Which cells can you reach? If you only use buttons $\texttt{U}$, $\texttt{R}$, $\texttt{D}$, you can never reach the points with $x < 0$. However, if all the special points have $x \geq 0$, you can reach all of them with the following steps: visit all t...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
1909
B
Make Almost Equal With Mod
\begin{quote} xi - Solar Storm \hfill ⠀ \end{quote} You are given an array $a_1, a_2, \dots, a_n$ of distinct positive integers. You have to do the following operation \textbf{exactly once}: - choose a positive integer $k$; - for each $i$ from $1$ to $n$, replace $a_i$ with $a_i \text{ mod } k^\dagger$. Find a value...
Find a value of $k$ that works in many cases. $k = 2$ works in many cases. What if it does not work? If $k = 2$ does not work, either all the numbers are even or all the numbers are odd. Which $k$ can you try now? Let $f(k)$ be the number of distinct values after the operation, using $k$. Let's try $k = 2$. It works in...
[ "bitmasks", "constructive algorithms", "math", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
1909
C
Heavy Intervals
\begin{quote} Shiki - Pure Ruby \hfill ⠀ \end{quote} You have $n$ intervals $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$, such that $l_i < r_i$ for each $i$, and all the endpoints of the intervals are distinct. The $i$-th interval has weight $c_i$ per unit length. Therefore, the weight of the $i$-th interval is $c_i \...
Assign bigger costs to shorter intervals. Solve the problem with $n = 2$. Solve the following case: $l = [1, 2]$, $r = [3, 4]$, $c = [1, 2]$. Can you generalize it? You have to match each $l_i$ with some $r_j > l_i$. Construct $v = {l_1, l_2, \dots, l_n, r_1, r_2, \dots, r_n}$ and sort it. If you replace every $l_i$ wi...
[ "constructive algorithms", "data structures", "dsu", "greedy", "math", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
1909
D
Split Plus K
\begin{quote} eliteLAQ - Desert Ruins \hfill ⠀ \end{quote} There are $n$ positive integers $a_1, a_2, \dots, a_n$ on a blackboard. You are also given a positive integer $k$. You can perform the following operation some (possibly $0$) times: - choose a number $x$ on the blackboard; - erase one occurrence of $x$; - wri...
Solve the problem with $k = 0$. Solve the problem with generic $k$. When is the answer $-1$? Do you notice any similarities between the cases with $k = 0$ and with generic $k$? Consider the "shifted" problem, where each $x$ on the blackboard (at any moment) is replaced with $x' = x-k$. Now, the operation becomes "repla...
[ "greedy", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
1909
E
Multiple Lamps
\begin{quote} Kid2Will - Fire Aura \hfill ⠀ \end{quote} You have $n$ lamps, numbered from $1$ to $n$. Initially, all the lamps are turned off. You also have $n$ buttons. The $i$-th button toggles all the lamps whose index is a multiple of $i$. When a lamp is toggled, if it was off it turns on, and if it was on it tur...
Find a strategy that turns "few" lamps on in most cases. Pressing all the buttons turns $\lfloor \sqrt n \rfloor$ lamps on. If the strategy in Hint 2 does not work, at most $3$ lamps must be on at the end. Iterate over all subsets of at most $3$ lamps that must be on at the end. If you press all the buttons, lamp $i$ i...
[ "bitmasks", "brute force", "constructive algorithms", "math", "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 #define DEN 5 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !...
1909
F2
Small Permutation Problem (Hard Version)
\begin{quote} Andy Tunstall - MiniBoss \hfill ⠀ \end{quote} \textbf{In the easy version, the $a_i$ are in the range $[0, n]$; in the hard version, the $a_i$ are in the range $[-1, n]$ and the definition of good permutation is slightly different. You can make hacks only if all versions of the problem are solved.} You ...
Find a clean way to visualize the problem. Draw a $n \times n$ grid, with tokens in $(i, p_i)$. Which constraints on the tokens do you have? You have some "L" shapes, and each of them must contain a fixed number of tokens (in 1909F1 - Small Permutation Problem (Easy Version) the shapes are $1$ cell wide and must contai...
[ "combinatorics", "dp", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 200010 ll fc[maxn], nv[maxn]; ll fxp(ll b, ll e) { ll r = 1, k = b; while (e != 0) { i...
1909
G
Pumping Lemma
\begin{quote} Tanchiky & Siromaru - Crystal Gravity \hfill ⠀ \end{quote} You are given two strings $s$, $t$ of length $n$, $m$, respectively. Both strings consist of lowercase letters of the English alphabet. Count the triples $(x, y, z)$ of strings such that the following conditions are true: - $s = x+y+z$ (the sym...
If you remove the condition $s = x+y+z$, the problem becomes harder. Solve for a fixed $|y|$ (length of $y$). Suppose you have found a valid $y$. Shift it one position to the right. When is it still valid? The valid $y$ with $|y| = l$ start in consecutive positions. Using the same idea of the proof of Hint 4, you can f...
[ "hashing", "strings" ]
3,000
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
1909
H
Parallel Swaps Sort
\begin{quote} Dubmood - Keygen 8 \hfill ⠀ \end{quote} You are given a permutation $p_1, p_2, \dots, p_n$ of $[1, 2, \dots, n]$. You can perform the following operation some (possibly $0$) times: - choose a subarray $[l, r]$ of even length; - swap $a_l$, $a_{l+1}$; - swap $a_{l+2}$, $a_{l+3}$ (if $l+3 \leq r$); - $\do...
Find a strategy which is as simple and "easy to handle" as possible. Only perform operations such that all swapped pairs have $a_i > a_{i+1}$. Let's call such subarrays "swappable". First, for each $i$ from left to right, do the operation on $[j, i]$, where $j$ is the minimum index such that $[j, i]$ is swappable. Repe...
[ "constructive algorithms", "data structures" ]
3,500
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <algorithm> #include <cassert> #include <functional> #include <vector> #ifdef _MSC_VER #include <intrin.h> #endif #if __cplusplus >= 202002L #include <bit> #endif namespace atcoder { namespace internal { #if __cpluspl...
1909
I
Short Permutation Problem
\begin{quote} Xomu - Last Dance \hfill ⠀ \end{quote} You are given an integer $n$. For each $(m, k)$ such that $3 \leq m \leq n+1$ and $0 \leq k \leq n-1$, count the permutations of $[1, 2, ..., n]$ such that $p_i + p_{i+1} \geq m$ for exactly $k$ indices $i$, modulo $998\,244\,353$.
Insert the elements into the permutation in some comfortable order. Suppose $m$ is even. You can insert elements in the order $[m/2, m/2 - 1, m/2 + 1, m/2 - 2, \dots]$. You can solve for a single $m$ with DP. Can you calculate the DP for multiple $m$ simultaneously? The first part of the DP (where you insert both "smal...
[ "combinatorics", "dp", "fft", "math" ]
1,900
#include <algorithm> #include <array> #include <cassert> #include <type_traits> #include <vector> #ifdef _MSC_VER #include <intrin.h> #endif #if __cplusplus >= 202002L #include <bit> #endif namespace atcoder { namespace internal { #if __cplusplus >= 202002L using std::bit_ceil; #else u...
1913
A
Rating Increase
Monocarp is a great solver of adhoc problems. Recently, he participated in an Educational Codeforces Round, and gained rating! Monocarp knew that, before the round, his rating was $a$. After the round, it increased to $b$ ($b > a$). He wrote both values one after another to not forget them. However, he wrote them so ...
Since the length of the string is pretty small, it's possible to iterate over all possible cuts of $ab$ into $a$ and $b$. First, you have to check if $b$ has a leading zero. If it doesn't, compare integer representations of $a$ and $b$. In order to get an integer from a string, you can use stoi(s) for C++ or int(s) for...
[ "implementation" ]
800
for _ in range(int(input())): ab = input() for i in range(1, len(ab)): if ab[i] != '0' and int(ab[:i]) < int(ab[i:]): print(ab[:i], ab[i:]) break else: print(-1)
1913
B
Swap and Delete
You are given a binary string $s$ (a string consisting only of 0-s and 1-s). You can perform two types of operations on $s$: - delete one character from $s$. This operation costs $1$ coin; - swap any pair of characters in $s$. This operation is free (costs $0$ coins). You can perform these operations any number of t...
Let's count the number of 0-s and 1-s in $s$ as $cnt_0$ and $cnt_1$ correspondingly. Since $t$ consists of characters from $s$ then $t$ will contain no more than $cnt_0$ zeros and $cnt_1$ ones. Let's build $t$ greedily, since we always compare $t$ with prefix of $s$. Suppose the length of $t$ is at least one, it means ...
[ "strings" ]
1,000
for _ in range(int(input())): s = input() cnt = [0, 0] for i in range(len(s)): cnt[int(s[i])] += 1 for i in range(len(s) + 1): if (i == len(s) or cnt[1 - int(s[i])] == 0): print(len(s) - i) break cnt[1 - int(s[i])] -= 1
1913
C
Game with Multiset
In this problem, you are initially given an empty multiset. You have to process two types of queries: - ADD $x$ — add an element equal to $2^{x}$ to the multiset; - GET $w$ — say whether it is possible to take the sum of some subset of the current multiset and get a value equal to $w$.
We are given a classic knapsack problem. There are items with certain weights and a total weight that we want to achieve. If the weights were arbitrary, we would need dynamic programming to solve it. However, this variation of the knapsack problem can be solved greedily. What makes it special? If we arrange the weights...
[ "binary search", "bitmasks", "brute force", "greedy" ]
1,300
from sys import stdin, stdout LOG = 30 cnt = [0 for i in range(LOG)] ans = [] for _ in range(int(stdin.readline())): t, v = map(int, stdin.readline().split()) if t == 1: cnt[v] += 1 else: nw = 0 for i in range(LOG): r = (v % (2 << i)) // (1 << i) if r > nw + ...
1913
D
Array Collapse
You are given an array $[p_1, p_2, \dots, p_n]$, where all elements are distinct. You can perform several (possibly zero) operations with it. In one operation, you can choose a \textbf{contiguous subsegment} of $p$ and remove \textbf{all} elements from that subsegment, \textbf{except for} the minimum element on that s...
Let's rephrase the problem a bit. Instead of counting the number of arrays, let's count the number of subsequences of elements that can remain at the end. One of the classic methods for counting subsequences is dynamic programming of the following kind: $\mathit{dp}_i$ is the number of subsequences such that the last t...
[ "data structures", "divide and conquer", "dp", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int normalize(long long x) { x %= MOD; if (x < 0) x += MOD; return x; } int main() { int t; cin >> t; for (int tc = 0; tc < t; ++tc) { int n; cin >> n; vector <int> a(n); vector <int> nex...
1913
E
Matrix Problem
You are given a matrix $a$, consisting of $n$ rows by $m$ columns. Each element of the matrix is equal to $0$ or $1$. You can perform the following operation any number of times (possibly zero): choose an element of the matrix and replace it with either $0$ or $1$. You are also given two arrays $A$ and $B$ (of length...
There are many ways to solve this problem (even if all of them are based on minimum cost flows), but in my opinion, the most elegant one is the following one. Let us build another matrix $b$ of size $n \times m$ that meets the following requirements: the sum in the $i$-th row of the matrix $b$ is $A_i$; the sum in the ...
[ "flows", "graphs" ]
2,400
#include<bits/stdc++.h> using namespace std; const int N = 111; struct edge { int y, c, w, f; edge() {}; edge(int y, int c, int w, int f) : y(y), c(c), w(w), f(f) {}; }; vector<edge> e; vector<int> g[N]; int rem(int x) { return e[x].c - e[x].f; } void add_edge(int x, int y, int c, int w) { g[x...
1913
F
Palindromic Problem
You are given a string $s$ of length $n$, consisting of lowercase Latin letters. You are allowed to replace at most one character in the string with an arbitrary lowercase Latin letter. Print the lexicographically minimal string that can be obtained from the original string and contains the maximum number of palindro...
Let's recall the algorithm for counting the number of palindromes in a string. For each position, we can calculate the longest odd and even palindromes with centers at that position (the right one for even). Then sum up all the values. If we forget about the complexity, we can consider the following algorithm for solvi...
[ "binary search", "data structures", "hashing", "string suffix structures", "strings" ]
2,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define x first #define y second using namespace std; struct sparse_table { vector<vector<int>> st; vector<int> pw; sparse_table() {} sparse_table(const vector<int> &a) { int n = a.size(); int logn ...
1914
A
Problemsolving Log
Monocarp is participating in a programming contest, which features $26$ problems, named from 'A' to 'Z'. The problems are sorted by difficulty. Moreover, it's known that Monocarp can solve problem 'A' in $1$ minute, problem 'B' in $2$ minutes, ..., problem 'Z' in $26$ minutes. After the contest, you discovered his con...
For each problem, we will calculate the total number of minutes Monocarp spent on it. Then we will compare it to the minimum required time for solving the problem. One of the possible implementations is as follows. Create a string $t =$"ABC ... Z" in the program. Then problem $t_i$ can be solved in $i + 1$ minutes. We ...
[ "implementation", "strings" ]
800
for _ in range(int(input())): n = int(input()) s = input() print(sum([s.count(chr(ord('A') + i)) >= i + 1 for i in range(26)]))
1914
B
Preparing for the Contest
Monocarp is practicing for a big contest. He plans to solve $n$ problems to make sure he's prepared. Each of these problems has a difficulty level: the first problem has a difficulty level of $1$, the second problem has a difficulty level of $2$, and so on, until the last ($n$-th) problem, which has a difficulty level ...
The examples give a pretty big hint to the solution: to get $k = 0$, we have to order all problems from the hardest to the easiest one, and to get $k = n - 1$, we have to order them from the easiest to the hardest problem. Let's try to combine them for the general case. Let's start by placing the problems from the hard...
[ "constructive algorithms", "math" ]
800
#include<bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; vector<int> a(n); for(int i = 0; i < n; i++) a[i] = n - i; reverse(a.end() - k - 1, a.end()); for(int i = 0; i < n; i++) { if(i) cout << " "; cout << a[i]; } cout << endl; } int main() { int t; cin >> t; for(int i...
1914
C
Quests
Monocarp is playing a computer game. In order to level up his character, he can complete quests. There are $n$ quests in the game, numbered from $1$ to $n$. Monocarp can complete quests according to the following rules: - the $1$-st quest is always available for completion; - the $i$-th quest is available for complet...
Let's iterate over the number of quests that have been completed at least once (denote it as $i$). It remains to complete $k-i$ quests more, and we are allowed to complete any of the first $i$ quests again. It is obvious that we would like to complete quests with the largest value of $b_i$ among the first $i$ of them. ...
[ "greedy", "math" ]
1,100
fun main() = repeat(readLine()!!.toInt()) { val (n, k) = readLine()!!.split(" ").map { it.toInt() } val a = readLine()!!.split(" ").map { it.toInt() } val b = readLine()!!.split(" ").map { it.toInt() } var (res, sum, mx) = intArrayOf(0, 0, 0) for (i in 0 until minOf(n, k)) { sum += a[i] mx = maxOf(mx,...
1914
D
Three Activities
Winter holidays are coming up. They are going to last for $n$ days. During the holidays, Monocarp wants to try all of these activities \textbf{exactly once} with his friends: - go skiing; - watch a movie in a cinema; - play board games. Monocarp knows that, on the $i$-th day, exactly $a_i$ friends will join him for ...
The main idea of the problem is that almost always you can take the maximum in each array. And when you can't, you don't need to look at a lot of smaller numbers. In particular, it is enough to consider the three largest numbers from each array. Let's show the correctness of this for the first array. There always exist...
[ "brute force", "dp", "greedy", "implementation", "sortings" ]
1,200
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = list(map(int, input().split())) def get_best3(a): mx1, mx2, mx3 = -1, -1, -1 for i in range(len(a)): if mx1 == -1 or a[i] > a[mx1]: mx3 = mx2 mx2 = mx1 mx1 = i elif mx2...
1914
E2
Game with Marbles (Hard Version)
\textbf{The easy and hard versions of this problem differ only in the constraints on the number of test cases and $n$. In the hard version, the number of test cases does not exceed $10^4$, and the sum of values of $n$ over all test cases does not exceed $2 \cdot 10^5$. Furthermore, there are no additional constraints o...
Let's change the game in the following way: Firstly, we'll let Bob make all moves. It means that for each color $i$ Bob discarded one marble, while Alice discarded all her marbles. So the score $S$ will be equal to $0 - \sum_{i}{(b_i - 1)}$. Alice makes the first move by choosing some color $i$ and "takes back color $i...
[ "games", "greedy", "sortings" ]
1,400
#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()) typedef long long li; // S = sum a_i - sum b_i // if Bob made all steps: then S = 0 - sum (b_i - 1) // each Alice step: S += (a_i - 1) + (b_i - 1) i. e. the bigger (a_i + b_i) th...
1914
F
Programming Competition
BerSoft is the biggest IT corporation in Berland. There are $n$ employees at BerSoft company, numbered from $1$ to $n$. The first employee is the head of the company, and he does not have any superiors. Every other employee $i$ has exactly one direct superior $p_i$. Employee $x$ is considered to be a superior (direct...
Note that the problem basically states the following: you are given a rooted tree; you can pair two vertices $x$ and $y$ if neither $x$ is an ancestor of $y$ nor $y$ is an ancestor of $x$. Each vertex can be used in at most one pair. Calculate the maximum possible number of pairs you can make. Let's look at subtrees of...
[ "dfs and similar", "dp", "graph matchings", "greedy", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 222222; int n; int sz[N]; vector<int> g[N]; void init(int v) { sz[v] = 1; for (int u : g[v]) { init(u); sz[v] += sz[u]; } } int calc(int v, int k) { int tot = 0, mx = -1; for (int u : g[v]) { tot += sz[u]; if (mx == -1 || sz...
1914
G2
Light Bulbs (Hard Version)
\textbf{The easy and hard versions of this problem differ only in the constraints on $n$. In the hard version, the sum of values of $n$ over all test cases does not exceed $2 \cdot 10^5$. Furthermore, there are no additional constraints on the value of $n$ in a single test case}. There are $2n$ light bulbs arranged in...
Let's call a contiguous segment of lamps closed if the number of lamps for each color is either $0$ or $2$ in this segment. For example, a segment of lamps $[3, 2, 1, 2, 1, 3]$ is closed. Furthermore, let's say that a closed segment of lamps is minimal if it is impossible to split it into multiple closed segments. For ...
[ "combinatorics", "data structures", "dfs and similar", "dp", "graphs", "hashing" ]
2,300
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { return (((x + y) % MOD) + MOD) % MOD; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } mt19937_64 rnd(98275314); long long gen() { long long x = 0; while(x == 0) x = rnd(); return x; } vector<int>...
1915
A
Odd One Out
You are given three digits $a$, $b$, $c$. Two of them are equal, but the third one is different from the other two. Find the value that occurs exactly once.
You can write three if-statements to find the equal pair, and output the correct answer. A shorter solution: output the bitwise $\textsf{XOR}$ of $a$, $b$, and $c$. It works, since any number $\textsf{XOR}$ed with itself is $0$, so the two equal numbers will "cancel" and you will be left with the odd number out.
[ "bitmasks", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int a, b, c; cin >> a >> b >> c; cout << (a ^ b ^ c) << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve...
1915
B
Not Quite Latin Square
A Latin square is a $3 \times 3$ grid made up of the letters $A$, $B$, and $C$ such that: - in each row, the letters $A$, $B$, and $C$ each appear once, and - in each column, the letters $A$, $B$, and $C$ each appear once. For example, one possible Latin square is shown below. $$\begin{bmatrix} A & B & C \\ C & A & B...
There are many solutions. For example, look at the row with the question mark, and write some if statements to check the missing letter. A shorter solution: find the count of each letter. The one that appears only twice is the missing one.
[ "bitmasks", "brute force", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int cnt[3] = {}; for (int i = 0; i < 9; i++) { char c; cin >> c; if (c != '?') {cnt[c - 'A']++;} } for (int i = 0; i < 3; i++) { if (cnt[i] < 3) {cout << (char)('A' + i) << '\n';} } } i...
1915
C
Can I Square?
Calin has $n$ buckets, the $i$-th of which contains $a_i$ wooden squares of side length $1$. Can Calin build a square using \textbf{all} the given squares?
You should add up all the values to get the sum $s$. Then we just need to check if $s$ is a perfect square. There are many ways, for example you can use inbuilt sqrt function or binary search. Be careful with precision errors, since sqrt function might return a floating-point type.
[ "binary search", "implementation" ]
800
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() bool is_square(ll x) { ll l = 1...
1915
D
Unnatural Language Processing
Lura was bored and decided to make a simple language using the five letters $a$, $b$, $c$, $d$, $e$. There are two types of letters: - vowels — the letters $a$ and $e$. They are represented by $\textsf{V}$. - consonants — the letters $b$, $c$, and $d$. They are represented by $\textsf{C}$. There are two types of syll...
There are many solutions. Below is the simplest one: Go through the string in reverse (from right to left). If the last character is a vowel, it must be part of $\textsf{CV}$ syllable - else, $\textsf{CVC}$ syllable. So we can go back $2$ or $3$ characters appropriately, insert $\texttt{.}$, and continue. The complexit...
[ "greedy", "implementation", "strings" ]
900
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int n; cin >> n; string s; cin >> s; string res = ""; while (!s.empty()) { int x; if (s.back() == 'a' || s.back() == 'e') {x = 2;} else {x = 3;} while (x--) { res += s.back(); s...
1915
E
Romantic Glasses
Iulia has $n$ glasses arranged in a line. The $i$-th glass has $a_i$ units of juice in it. Iulia drinks only from odd-numbered glasses, while her date drinks only from even-numbered glasses. To impress her date, Iulia wants to find a contiguous subarray of these glasses such that both Iulia and her date will have the ...
Let's rewrite the given equation: $a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r} = a_{l + 1} + a_{l + 3} + \dots + a_{r-1}$ as $a_l - a_{l+1} + a_{l + 2} - a_{l+3} + a_{l + 4} + \dots - a_{r-1} + a_{r} = 0.$ How to check this? Let's flip all elements on even indices $a_2 \to -a_2, a_4 \to -a_4, \dots$. Then alternating s...
[ "data structures", "greedy", "math" ]
1,300
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() void solve() { int n; cin >> n;...
1915
F
Greetings
There are $n$ people on the number line; the $i$-th person is at point $a_i$ and wants to go to point $b_i$. For each person, $a_i < b_i$, and the starting and ending points of all people are distinct. (That is, all of the $2n$ numbers $a_1, a_2, \dots, a_n, b_1, b_2, \dots, b_n$ are distinct.) All the people will sta...
Let's consider two persons $1$ and $2$. When do they meet each other? We can treat a person traveling from point $a$ to point $b$ as a segment $[a, b]$. Notice that they meet when $a_1 < a_2$ and $b_2 < b_1$, or $a_2 < a_1$ and $b_1 < b_2$; or in other words, when one segment contains another. We can count the number o...
[ "data structures", "divide and conquer", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> typedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ordered_set; int t, n; vector<pair<int, int>> arr;...
1915
G
Bicycles
All of Slavic's friends are planning to travel from the place where they live to a party using their bikes. And they all have a bike except Slavic. There are $n$ cities through which they can travel. They all live in the city $1$ and want to go to the party located in the city $n$. The map of cities can be seen as an u...
We can build a graph with $n \cdot 1000$ nodes, where each node is responsible for the pair $(i, s)$, where $i$ is the index of the city and $s$ is the speed we have when we are at this city. Then, we can use Dijkstra's algorithm to compute the shortest path on this graph by considering all edges of node $i$ (when we a...
[ "graphs", "greedy", "implementation", "shortest paths", "sortings" ]
1,800
#include "bits/stdc++.h" const int64_t inf = 1e18; void solve() { int n, m; std::cin >> n >> m; std::vector<std::pair<int, int>> adj[n]; for(int i = 0; i < m; ++i) { int u, v, w; std::cin >> u >> v >> w; --u, --v; adj[u].emplace_back(v, w); adj[v].emplace_back(u, w); } std:...