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
1732
A
Bestie
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \ldots, a_n$. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to $1$. In one operation, you can do the following: - Select an arbitrary index in the array $1 \leq i \leq n$; - Make $a_i = \gcd(a_i, i)$, where...
Let's make an important observation: $\gcd(n - 1, n) = 1$ for any value of $n$. Moreover, choosing $i = n - 1$ and $i = n$ are the cheapest operations. From this we can conclude that the answer is $\leq 3$. Let $g$ be the $\gcd$ of all numbers in the array. Then we have the following cases: If $g = 1$, then the operati...
[ "brute force", "combinatorics", "constructive algorithms", "implementation", "math", "number theory" ]
1,000
null
1732
B
Ugu
A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $s_1 s_2 \ldots s_n$. It is necessary to make this string non-decreasing in the least number of operations. In other words, each character should be not less than the previous. In one operation, you can do the following...
Let's mentally imagine the following array of length $n - 1$: $a_i = 0$ if $s_i = s_{i+1}$, and $1$ otherwise. Note that if we apply the operation to the index $i$, then all the values of the array $a$ do not change, except for $a_{i - 1}$. Let's look at this in more detail: For $i \leq j$, note that the $j$th and $(j+...
[ "brute force", "dp", "greedy", "implementation" ]
900
null
1732
C1
Sheikh (Easy version)
\textbf{This is the easy version of the problem. The only difference is that in this version $q = 1$.} You are given an array of integers $a_1, a_2, \ldots, a_n$. The cost of a subsegment of the array $[l, r]$, $1 \leq l \leq r \leq n$, is the value $f(l, r) = \operatorname{sum}(l, r) - \operatorname{xor}(l, r)$, whe...
Note that $f(l, r) \leq f(l, r + 1)$. To prove this fact, let's see how the sum and xor change when the element $x$ is added. The sum will increase by $x$, but $xor$ cannot increase by more than $x$. Then it was possible to use two pointers or binary search to solve the problem. If you solve the problem in the second w...
[ "binary search", "bitmasks", "greedy", "two pointers" ]
1,800
null
1732
C2
Sheikh (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that in this version $q = n$.} You are given an array of integers $a_1, a_2, \ldots, a_n$. The cost of a subsegment of the array $[l, r]$, $1 \leq l \leq r \leq n$, is the value $f(l, r) = \operatorname{sum}(l, r) - \operatorname{xor}(l, r)$, whe...
Note that $f(l, r) \leq f(l, r + 1)$. To prove this fact, let's see how the sum and xor change when the element $x$ is added. The sum will increase by $x$, but $xor$ cannot increase by more than $x$. From this we obtain that the maximum value of $f$ is reached on the entire subsegment. Next, let's see in which case $xo...
[ "binary search", "bitmasks", "brute force", "greedy", "implementation", "two pointers" ]
2,100
null
1732
D1
Balance (Easy version)
\textbf{This is the easy version of the problem. The only difference is that in this version there are no "remove" queries.} Initially you have a set containing one element — $0$. You need to handle $q$ queries of the following types: - + $x$ — add the integer $x$ to the set. It is guaranteed that this integer is not...
Let's look at a stupid solution and try to improve it. In a stupid solution, we can simply add to the set, and when answering a query, iterate over the numbers ${0, k, 2k, 3k, \ldots}$ and so on until we find the answer. This solution will take a long time if the answer is $c \cdot k$, where $c$ is large. We will impro...
[ "brute force", "data structures", "implementation", "number theory" ]
1,500
null
1732
D2
Balance (Hard version)
\textbf{This is the hard version of the problem. The only difference is that in this version there are remove queries.} Initially you have a set containing one element — $0$. You need to handle $q$ queries of the following types: - + $x$ — add the integer $x$ to the set. It is guaranteed that this integer is not cont...
Let's look at a stupid solution and try to improve it. In a stupid solution, we can simply add and remove elements from the set, and when answering a query, iterate over the numbers ${0, k, 2k, 3k, \ldots}$ and so on until we find the answer. This solution will take a long time if the answer is $c \cdot k$, where $c$ i...
[ "brute force", "data structures", "number theory" ]
2,400
null
1732
E
Location
You are given two arrays of integers $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$. You need to handle $q$ queries of the following two types: - $1$ $l$ $r$ $x$: assign $a_i := x$ for all $l \leq i \leq r$; - $2$ $l$ $r$: find the minimum value of the following expression among all $l \leq i \leq r$: $$\frac{\op...
Tasks of this kind, as a rule, are solved using data structures, and this one is no exception. Since the constraints in the problem are not large enough, it is logical to think in the direction of root optimizations. Let's divide the array into blocks of length $k$, we will have about $\frac{n}{k}$ such blocks. For eac...
[ "data structures", "dp", "math", "number theory" ]
2,800
null
1733
A
Consecutive Sum
You are given an array $a$ with $n$ integers. You can perform the following operation at most $k$ times: - Choose two indices $i$ and $j$, in which $i \,\bmod\, k = j \,\bmod\, k$ ($1 \le i < j \le n$). - Swap $a_i$ and $a_j$. After performing all operations, you have to select $k$ consecutive elements, and the sum o...
$i$-th element moves only to $(i + xk)$-th position ($x$ is integer). We cannot select $a_i$ and $a_{i + xk}$ simultaneously. In other words, if we can swap $a_i$ and $a_j$, we cannot select $a_i$ and $a_j$ simultaneously. Among all elements $a_{i + xk}$ for each $i$ ($1 \le i \le k$), only one element is selected. For...
[ "greedy", "sortings" ]
800
#import<bits/stdc++.h> #define endl '\n' using namespace std; long long k, n, s, t, x, a[100005]; int main() { ios::sync_with_stdio(0); cin.tie(0); for(cin >> t; t--;) { cin >> n >> k; for(int i = 1; i <= n; i++) { cin >> x; a[i % k] = max(a[i % k], x); } s = 0; for(int i = 0; i < k; i++)s += a[i]...
1733
B
Rule of League
There is a badminton championship in which $n$ players take part. The players are numbered from $1$ to $n$. The championship proceeds as follows: player $1$ and player $2$ play a game, then the winner and player $3$ play a game, and then the winner and player $4$ play a game, and so on. So, $n-1$ games are played, and...
Because one of player $1$ and player $2$ win $0$ games and the other win at least $1$ game, $\min(x, y) = 0$ and $\max(x, y) > 0$ must be true in order to generate a valid result. There are one winner and one loser for every match. So the sum of winning count and the sum of losing count are same. The sum of winning cou...
[ "constructive algorithms", "math" ]
900
#import<bits/stdc++.h> #define endl '\n' using namespace std; int k, n, t, x, y; int main() { ios::sync_with_stdio(0); cin.tie(0); for(cin >> t; t--;) { cin >> n >> x >> y; if(x > y)swap(x, y); if(x || !y || (n - 1) % y) { cout << -1 << endl; continue; } for(int k = 2; k <= n; k += y) { for(i...
1733
C
Parity Shuffle Sorting
You are given an array $a$ with $n$ non-negative integers. You can apply the following operation on it. - Choose two indices $l$ and $r$ ($1 \le l < r \le n$). - If $a_l + a_r$ is odd, do $a_r := a_l$. If $a_l + a_r$ is even, do $a_l := a_r$. Find any sequence of at most $n$ operations that makes $a$ non-decreasing. ...
If all elements are equal, that array is also non-decreasing. For each operation, one element is changed. Because we have to use at most $n$ operations, an element change occurs at most $n$ times. Considering that the initial array can be decreasing, at least $n - 1$ operations can be needed in some cases. If $n = 1$, ...
[ "constructive algorithms", "sortings" ]
1,300
#import<bits/stdc++.h> #define endl '\n' using namespace std; int n, t, x, a[100005]; int main() { ios::sync_with_stdio(0); cin.tie(0); for(cin >> t; t--;) { cin >> n; for(int i = 1; i <= n; i++)cin >> a[i]; cout << n - 1 << endl; if(n > 1)cout << 1 << ' ' << n << endl; x = (a[1] + a[n]) % 2 ? a[1] : a[...
1733
D1
Zero-One (Easy Version)
\textbf{This is the easy version of the problem. In this version, $n \le 3000$, $x \ge y$ holds. You can make hacks only if both versions of the problem are solved.} You are given two binary strings $a$ and $b$, both of length $n$. You can do the following operation any number of times (possibly zero). - Select two i...
Consider $c$ is another binary string, in which $c_i = a_i \oplus b_i$. We have to make $c$ equal to $000 \ldots 000$ using the operation. Because the operation does not change the parity of the number of $1$ in $c$, the answer is $-1$ if $c$ has odd number of $1$. If the number of $1$ in $c$ is $d$ (now assume that $d...
[ "constructive algorithms", "greedy", "math" ]
1,400
#import<bits/stdc++.h> #define endl '\n' using namespace std; long long d, n, t, x, y; string a, b; int main() { ios::sync_with_stdio(0); cin.tie(0); for(cin >> t; t--;) { cin >> n >> x >> y >> a >> b; d = 0; for(int i = 0; i < n; i++) { a[i] ^= b[i]; d += a[i]; } if(d % 2) { cout << -1 << en...
1733
D2
Zero-One (Hard Version)
\textbf{This is the hard version of this problem. In this version, $n \le 5000$ holds, and this version has no restriction between $x$ and $y$. You can make hacks only if both versions of the problem are solved.} You are given two binary strings $a$ and $b$, both of length $n$. You can do the following operation any n...
Greedy solution used in D1 doesn't work in this version. The restriction accepts normal $O(n^2)$ solution. (Continued from D1 editorial) If $x < y$, greedy approach used in D1 doesn't work. Let's use DP. Define $z0[i][j]$ as the minimal cost when there is $j$ $1$s in first $i$ elements of $c$ and $c_i = 0$, and $z1[i][...
[ "dp", "greedy" ]
2,000
#import<bits/stdc++.h> #define endl '\n' using namespace std; long long d, n, t, x, y, z0[5004][5004], z1[5004][5004]; string a, b; int main() { ios::sync_with_stdio(0); cin.tie(0); for(cin >> t; t--;) { cin >> n >> x >> y >> a >> b; d = 0; for(int i = 0; i < n; i++) { a[i] ^= b[i]; d += a[i]; } i...
1733
E
Conveyor
There is a conveyor with $120$ rows and $120$ columns. Each row and column is numbered from $0$ to $119$, and the cell in $i$-th row and $j$-th column is denoted as $(i, j)$. The top leftmost cell is $(0, 0)$. Each cell has a belt, and all belts are initially facing to the right. Initially, a slime ball is on the belt...
Each second, slime ball moves to next diagonal. Every slime always locates in different diagonal. No two slime ball will merge forever. If $t < x + y$, the answer should be "NO". In the conveyor, cells with same $(i + j)$ value consists a diagonal ($i$ is row number, $j$ is column number). Let's call them $(i + j)$-th ...
[ "constructive algorithms", "dp", "math" ]
2,700
#import<bits/stdc++.h> #define endl '\n' using namespace std; typedef long long LL; LL px, py, q, t, x, y, a[240], b[240]; int main() { ios::sync_with_stdio(0); cin.tie(0); for(cin >> q; q--;) { cin >> t >> x >> y; if(t < x + y) { cout << "NO" << endl; continue; } fill(a, a + 240, 0); fill(b, b + ...
1734
A
Select Three Sticks
You are given $n$ sticks with positive integral length $a_1, a_2, \ldots, a_n$. You can perform the following operation any number of times (possibly zero): - choose one stick, then either increase or decrease its length by $1$. After each operation, all sticks should have positive lengths. What is the minimum numbe...
We first sort the array $a$ in non-decreasing order. Denote the indices of the elements that we choose from $a$ to be $x$, $y$, and $z$, where $1 \le x < y < z \le n$, and the final value (after performing the operations) of the concerned elements to be $v$. The minimum required number of operations is then $|a_x-v|+|a...
[ "brute force", "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin>>n; int a[n+1]; for (int i=1; i<=n; i++){ cin>>a[i]; } sort(a+1,a+n+1); int ans=2e9; for (int i=3; i<=n; i++){ ans=min(ans,a[i]-a[i-2]); } cout<<ans<<'\n'; } int main(){ int t; cin>>t; for (int i=1; i<=t; i++){ solve(); } }
1734
B
Bright, Nice, Brilliant
There is a pyramid which consists of $n$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $i$-th floor consists of $i$ rooms. Denote the $j$-th room on the $i$-th floor as $(i,j)$. For all positive integers $i$ and $j$ such that $1 \le j \le i < n$, there are $2$ \textbf{one-...
Note that the brightnesses of the rooms on the $i$-th floor is at most $i$. This is because in room $(i,1)$, only $i$ rooms, namely, $(1,1)$, $(2,1)$, $\ldots$, $(i,1)$ can reach to $(i,1)$ through some number of staircases. It is also possible to find a configuration of torches in the pyramid such that the brightnesse...
[ "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { cout << (j == 1 || j == i) << ' '; } cout << '\n'; } ...
1734
C
Removing Smallest Multiples
You are given a set $S$, which contains the first $n$ positive integers: $1, 2, \ldots, n$. You can perform the following operation on $S$ any number of times (possibly zero): - Choose a positive integer $k$ where $1 \le k \le n$, such that there exists a multiple of $k$ in $S$. Then, delete the \textbf{smallest} mul...
One operation should be used to remove every element not belonging to $T$. Let $v$ be an element not belonging to $T$. Suppose a $x$-cost operation removes value $v$, then $v$ must be divisible by $x$. Furthermore, the multiples $x,2x,\cdots (k-1)x$ must have been already removed from $S$, where we write $v = kx$. Sinc...
[ "greedy", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; bool a[n + 1]; string str; cin >> str; for (int i = 1; i <= n; i++) { a[i] = (str[i - 1] == '1'); } long long ans = 0; int cost[n + 1]; for (int i = n; i >= 1; i--) { for (int j = i; j <...
1734
D
Slime Escape
You are playing a game called Slime Escape. The game takes place on a number line. Initially, there are $n$ slimes. For all positive integers $i$ where $1 \le i \le n$, the $i$-th slime is located at position $i$ and has health $a_i$. You are controlling the slime at position $k$. There are two escapes located at posi...
Let's call a group of slime good if their total health is at least $0$, or if defeating this group allows you to reach the exits. We partition the slimes into good groups in a two-pointer like manner. To form the groups to the right, start from position $k$, then find the smallest position $r$ such that slimes from $k+...
[ "data structures", "dp", "greedy", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; void solve() { long long n, k, P; cin >> n >> k; k--; long long L[n]; for (int i = 0; i < n; i++) cin >> L[i]; P = L[k]; L[k] = 0; long long ps[n + 1]; ps[0] = 0; for (int i = 1; i <= n; i++) ps[i] = ps[i - 1] + L[i - 1]; int l = ...
1734
E
Rectangular Congruence
You are given a \textbf{prime} number $n$, and an array of $n$ integers $b_1,b_2,\ldots, b_n$, where $0 \leq b_i < n$ for each $1 \le i \leq n$. You have to find a matrix $a$ of size $n \times n$ such that all of the following requirements hold: - $0 \le a_{i,j} < n$ for all $1 \le i, j \le n$. - $a_{r_1, c_1} + a_{r...
We say a matrix to be good if it satisfies the congruence condition (the second condition). When we have a good matrix, we can add any value $c$ to a whole row while maintaining the congruence relation. The same is true for adding the same value to a whole column. Suppose we have any good matrix $A$, then by adding $b_...
[ "constructive algorithms", "number theory" ]
2,100
#include <bits/stdc++.h> using namespace std; int want[355]; int board[355][355]; int main() { int n; cin >> n; for(int i = 0; i < n ; i ++){ cin >> want[i]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = (i * j) % n; } } for(...
1734
F
Zeros and Ones
Let $S$ be the Thue-Morse sequence. In other words, $S$ is the $0$-indexed binary string with infinite length that can be constructed as follows: - Initially, let $S$ be "0". - Then, we perform the following operation infinitely many times: concatenate $S$ with a copy of itself with flipped bits.For example, here are ...
Observe that the $i$-th character is `1' if and only if $i$ has an odd number of set bits in its binary representation. Both solutions make use of this fact. The constraints allows solutions of up to $\Theta(q \log^3 n)$. Yet, both of the model solution runs in $\Theta(\log n)$. The question can be reformulated as foll...
[ "bitmasks", "divide and conquer", "dp", "math" ]
2,500
import random cache = {} def popcount(n): res = 0 while n: res += 1 n &= n - 1 return res def solve(n, k): if k == 0: return 0 if k == 1: return popcount(n) & 1 if k % 2 == 1: t = solve(n, k - 1) x = popcount((k - 1) ^ (n + k - 1)) & 1 #...
1735
A
Working Week
Your working week consists of $n$ days numbered from $1$ to $n$, after day $n$ goes day $1$ again. And $3$ of them are days off. One of the days off is the last day, day $n$. You have to decide when the other two are. Choosing days off, you pursue two goals: - No two days should go one after the other. Note that you ...
Let's consider that $l_1$, $l_2$, and $l_3$ are sorted working segments. Can we explicitly say something about one of them? $l_1$ must be equal to $1$. Let's consider that $l_1$, $l_2$, and $l_3$ are sorted working segments. If $l_1$ is not equal to $1$ then we can decrease $l_1$ by $1$ and increase $l_3$ by $1$. So we...
[ "constructive algorithms", "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int l_2 = (n - 3) / 3; int ans = l_2 - 1; cout << ans << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while (t--) solve(); return 0; }
1735
B
Tea with Tangerines
There are $n$ pieces of tangerine peel, the $i$-th of them has size $a_i$. In one step it is possible to divide one piece of size $x$ into two pieces of positive integer sizes $y$ and $z$ so that $y + z = x$. You want that for each pair of pieces, their sizes differ \textbf{strictly} less than twice. In other words, t...
Is there a way to cut pieces to save the minimum value and satisfy required conditions? What is the minimum possible number of operations to perform it? Is there any better solution? Let's start with a simple solution. Let's choose the minimum piece from $a$ and assume that it will remain the minimum until the end. As ...
[ "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; int n; vector<int> a; void solve() { cin >> n; a.resize(n); int ans = 0; for (auto &i : a) { cin >> i; ans += (i - 1) / (2 * a[0] - 1); } cout << ans << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; cin >> t; w...
1735
C
Phase Shift
There was a string $s$ which was supposed to be encrypted. For this reason, all $26$ lowercase English letters were arranged in a circle in some order, afterwards, each letter in $s$ was replaced with the one that follows in clockwise order, in that way the string $t$ was obtained. You are given a string $t$. Determin...
What is the first letter in the answer? $a$ if $t$ doesn't start with $a$ and $b$ otherwise. Ask the same question as Hint1 for each position. When we can't choose the minimum unused letter? If we form a circle of size less then $26$. Maintain any structure to check it. First of all, the encryption process is reversibl...
[ "dfs and similar", "dsu", "graphs", "greedy", "implementation", "strings" ]
1,400
#include <bits/stdc++.h> using namespace std; void solve() { int n; string t; cin >> n; cin >> t; vector<int> edge(26, -1); vector<int> redge(26, -1); auto get_path_end = [&](int c) { int len = 0; int cur = c; while (edge[cur] != -1) len++, cur = edge[cur]; return make_pair(cur, len); }; vec...
1735
D
Meta-set
You like the card board game "Set". Each card contains $k$ features, each of which is equal to a value from the set $\{0, 1, 2\}$. The deck contains all possible variants of cards, that is, there are $3^k$ different cards in total. A feature for three cards is called good if it is the same for these cards or pairwise ...
How many sets can fit in $5$ cards? At most two. If there are two sets among $5$ cards, there will be a central card. Consider each card as a central card. For every two cards, there is always a single card that forms a set with them. [1] That means that two sets can share at most one card. Let's prove that there are n...
[ "brute force", "combinatorics", "data structures", "hashing", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<int, int> pii; const long long kk = 1000; const long long ml = kk * kk; const long long mod = ml * kk + 7; const long long inf = ml * ml...
1735
E
House Planning
There are $n$ houses in your city arranged on an axis at points $h_1, h_2, \ldots, h_n$. You want to build a new house for yourself and consider two options where to place it: points $p_1$ and $p_2$. As you like visiting friends, you have calculated in advance the distances from both options to all existing houses. Mo...
How many possible options are there for the distance between $p_1$ and $p_2$. We can limit it with $2 \cdot n$ options. Consider options $d_1[1] + d_2[i]$, $|d_1[1] - d_2[i]|$. Solve each one in linear(almost) time. Consider the biggest distance among $d_1$ and $d_2$. Can we match it with something? Remove them one by ...
[ "constructive algorithms", "data structures", "graph matchings", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<int, int> pii; const long long kk = 1000; const long long ml = kk * kk; const long long mod = ml * kk + 7; const long long inf = ml * ml...
1735
F
Pebbles and Beads
There are two currencies: pebbles and beads. Initially you have $a$ pebbles, $b$ beads. There are $n$ days, each day you can exchange one currency for another at some exchange rate. On day $i$, you can exchange $-p_i \leq x \leq p_i$ pebbles for $-q_i \leq y \leq q_i$ beads or vice versa. It's allowed not to perform ...
Draw currencies on 2D plane. Assume that you can throw out any amount of money at any moment. What will an area of possible points look like? It will look like a convex polygon in the upper-right quarter. Keep its edges. How does the structure change when a new day comes? A new segment is added. A prefix of old segment...
[ "data structures", "geometry" ]
2,900
#include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<int, int> pii; const long long kk = 1000; const long long ml = kk * kk; const long long mod = ml * kk + 7; const long long inf = ml * ml...
1736
A
Make A Equal to B
You are given two arrays $a$ and $b$ of $n$ elements, each element is either $0$ or $1$. You can make operations of $2$ kinds. - Pick an index $i$ and change $a_i$ to $1-a_i$. - Rearrange the array $a$ however you want. Find the minimum number of operations required to make $a$ equal to $b$.
It is easy to observe that the second operation needs to be performed at most once. Now, we just need to check $2$ cases, one in which the re-arrangement operation is used, and one in which it is not. If the re-arrangement operation is to be used, then we just need to make the counts of $0$s and $1$s in $a$ equal to th...
[ "brute force", "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; ll sum=0,ans=0; vector<ll> a(n),b(n); for(auto &it:a){ cin>>it; sum+=it; } for(auto &it:b){ cin>>it; sum-=it; } for(ll i=0;i<n;i++){ ans+=(a[i]^b[i]...
1736
B
Playing with GCD
You are given an integer array $a$ of length $n$. Does there exist an array $b$ consisting of $n+1$ positive integers such that $a_i=\gcd (b_i,b_{i+1})$ for all $i$ ($1 \leq i \leq n$)? Note that $\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
Take $a_0 = a_{n+1} = 1$. Now take $b_i=lcm(a_{i-1},a_i)$ for $1 \leq i \leq n+1$. If $b$ gives us $a$ after performing the $\gcd$ operations, then the answer is YES, otherwise the answer is NO. (When answer is NO, we would get a case like $\gcd(b_i, b_{i + 1}) = k \cdot a_i$(where $k > 1$ for some $i$). Suppose $c$ is...
[ "math", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; #define ll long long ll lcm(ll a,ll b){ ll g=__gcd(a,b); return (a*b/g); } void solve(){ ll n; cin>>n; vector<ll> a(n+2,1); for(ll i=1;i<=n;i++){ cin>>a[i]; } vector<ll> b(n+2,1); for(ll i=1;i<=n+1;i++){ b[i]=lcm(a[i],a[i...
1736
C1
Good Subarrays (Easy Version)
This is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved. An array $b$ of length $m$ is good if for all $i$ the $i$-th element is greater than or equal to $i$. In other wo...
Suppose $l[i]$ represents the leftmost point such that subarray $a[l[i],i]$ is good. Notice that the array $l$ is non-decreasing. So suppose $dp[i]$ denotes the length of longest good subarray which ends at index $i$. Take $dp[0]=0$. Now $dp[i]=min(dp[i-1]+1,a[i])$. Suppose $a[i] \geq dp[i-1]+1$. Now we claim that $dp[...
[ "binary search", "data structures", "schedules", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; vector<ll> dp(n+5,0); ll ans=0; for(ll i=1;i<=n;i++){ ll x; cin>>x; dp[i]=min(dp[i-1]+1,x); ans+=dp[i]; } cout<<ans<<"\n"; } int main() ...
1736
C2
Good Subarrays (Hard Version)
This is the hard version of this problem. In this version, we have queries. Note that we do not have multiple test cases in this version. You can make hacks only if both versions of the problem are solved. An array $b$ of length $m$ is good if for all $i$ the $i$-th element is greater than or equal to $i$. In other wo...
Let us continue the idea of C1. Suppose $track[i]$ denotes $\sum_{j=i}^{n} dp[j]$ if $dp[i]=a[i]$. We can precalculate array $track$. Now suppose $a_p$ is changed to $x$ and $adp[i]$ denotes the length of longest good subarray which ends at index $i$ in the updated array. It is easy to see that $adp[i]=dp[i]$ for $1 \l...
[ "binary search", "data structures", "dp", "two pointers" ]
2,400
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long const ll INF_MUL=1e13; const ll INF_ADD=1e18; #define pb push_back #define mp make_pair #define nline "\n" ...
1736
D
Equal Binary Subsequences
Everool has a binary string $s$ of length $2n$. Note that a binary string is a string consisting of only characters $0$ and $1$. He wants to partition $s$ into two \textbf{disjoint equal} subsequences. He needs your help to do it. You are allowed to do the following operation \textbf{exactly} once. - You can choose a...
It is easy to see that a necessary condition for a solution to exist is that the number of $1$ in $s$ should be even. It turns out that this condition is sufficient too. Here is one valid construction: We make $n$ pairs of the form $(s[2i-1],s[2i])$ for $(1 \leq i \leq n)$. Assume we have $x$ pairs in which both elemen...
[ "constructive algorithms", "geometry", "greedy", "implementation", "strings" ]
2,200
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; string s; cin>>s; ll freq=0; vector<ll> ans; ll need=0; for(ll i=0;i<2*n;i+=2){ if(s[i]!=s[i+1]){ freq++; ans.push_back(i+1); if(s[i]-'0'!=need){ ...
1736
E
Swap and Take
You're given an array consisting of $n$ integers. You have to perform $n$ turns. Initially your score is $0$. On the $i$-th turn, you are allowed to leave the array as it is or swap any one pair of $2$ adjacent elements in the array and change exactly one of them to $0$(and leave the value of other element unchanged)...
As the constraints suggest, we should use dp to solve this problem. Let's write the original indices of the array that are added during this process - $p_1, p_2, \ldots, p_n$. None of added numbers are zeroed in an optimal answer. It gives that $p_1 \le p_2 \le \ldots \le p_n$ and the answer is equal to the sum of $a[p...
[ "dp", "greedy" ]
2,600
#include <bits/stdc++.h> using namespace std; const int MAX=505; vector<vector<vector<int>>> dp(MAX,vector<vector<int>>(MAX,vector<int>(MAX,-(int)(1e9)))); int main() { int n; cin>>n; vector<int> a(n+5); fo...
1737
A
Ela Sorting Books
\begin{tabular}{ll} & Ela loves reading a lot, just like her new co-workers in DTL! On her first day after becoming an engineer in DTL, she is challenged by a co-worker to sort a heap of books into different compartments on the shelf. \ \end{tabular} $n$ books must be split into $k$ compartments on the bookshelf ($n$ ...
We'll iterate through compartments from $1$ to $K$. we'll try to put 1 'a' book in it, so the MEX in that compartment will not be 'a'. If any compartment can't be filled by 'a' because we ran out of 'a', the MEX of that compartment will have to be 'a'. The same logic applies to 'b', 'c', 'd', ..., where for each compar...
[ "greedy", "implementation", "strings" ]
900
... void execute(int test_number) { cin>>n>>k>>str; vector <int> count_char(26, 0); for (char c: str) count_char[c - 'a']++; string ans = ""; for (int i = 0; i < min(25, n/k); i++) { while (k - ans.size() > count_char[i]) { ans.push_back(i + 'a'); } } char c = 'a' + min(n / k, 25); while ...
1737
B
Ela's Fitness and the Luxury Number
\begin{tabular}{ll} & While working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football. \ \end{tabular} Since she started engaging in sports activities, Ela switches to trying a new sport on days she considers being "Luxury" days. Sh...
We shift the perspective to see the pattern from $\lfloor \sqrt{x} \rfloor$, instead of $x$, to see what kind of patterns are needed so $x$ can be luxurious. Note that: ${(a + 1)}^2 - 1 = a * (a + 2)$. Therefore, every half-closed segment $[a^2, (a + 1) ^ 2)$ contains exactly $3$ luxurious number: $a^2$, $a * (a + 1)$ ...
[ "binary search", "implementation", "math" ]
1,300
... ll l, r; ll bs_sqrt(ll x) { ll left = 0, right = 2000000123; while (right > left) { ll mid = (left + right) / 2; if (mid * mid > x) right = mid; else left = mid + 1; } return left - 1; } // main solution goes here: void execute(int test_number) { cin >> l >> r; ll sql = bs_sqr...
1737
C
Ela and Crickets
\begin{tabular}{ll} & Ela likes Chess a lot. During breaks, she usually challenges her co-worker in DTL to some chess games. She's not an expert at classic chess, but she's very interested in Chess variants, where she has to adapt to new rules and test her tactical mindset to win the game. \ \end{tabular} The problem,...
The initial configuration will have one central piece and 2 non-central pieces. The central piece is the one on the square that shares the edges with both of the 2 other squares. As the crickets are standing next to each other, we can prove that each of them can only jump into another square with the same color of the ...
[ "constructive algorithms", "games", "implementation", "math" ]
1,500
... int n; int x[3], y[3]; int u, v; pii centralSquare() { int a = (x[0] == x[1]) ? x[0] : x[2]; int b = (y[0] == y[1]) ? y[0] : y[2]; return {a, b}; } // main solution goes here: void execute(int test_number) { cin>>n; for (int i=0; i<3; i++) cin>>x[i]>>y[i]; cin>>u>>v; int cx = centralSquare().first, ...
1737
D
Ela and the Wiring Wizard
Ela needs to send a large package from machine $1$ to machine $n$ through a network of machines. Currently, with the network condition, she complains that the network is too slow and the package can't arrive in time. Luckily, a Wiring Wizard offered her a helping hand. The network can be represented as an \textbf{undi...
Note that you can turn $(u, v)$ edge into a self loop $(u, u)$ in a single operation. We can prove that it is always better to make an edge directly connect $1$ and $n$. Denote the index of that edge as $i$, and $\text{dist}[u][v]$ as the shortest path from $u$ to $v$ on the unweighted version of the input graph. There...
[ "brute force", "dp", "graphs", "greedy", "implementation", "shortest paths" ]
2,200
#include <bits/stdc++.h> #define ll long long #define db long double #define ull unsigned long long #define x first #define y second #define mp make_pair #define pb push_back #define all(a) a.begin(), a.end() using namespace std; #define pper(a) cerr << #a << " = " << a << endl; void per() { cerr << endl; } template...
1737
E
Ela Goes Hiking
\begin{tabular}{ll} & Ela likes to go hiking a lot. She loves nature and exploring the various creatures it offers. One day, she saw a strange type of ant, with a \textbf{cannibalistic} feature. More specifically, an ant would eat any ants that it sees which is smaller than it.Curious about this feature from a new crea...
The first ant will die if there are more than $1$ ants since it doesn't have any way to eat other ants (initially no ants have a weight less than it, and no ants are on the left of it). Call $f(i)$ the probability for the $i$-th ants to be the last one standing in the ants from $1$ to $2i - 1$. $i$ will be the last one...
[ "combinatorics", "dp", "math", "probabilities" ]
2,500
... // data preprocessing: (e.g.: divisor generating, prime sieve) ll POW2[mn]; void preprocess() { POW2[0] = 1; for (int i = 1; i < mn; i++) POW2[i] = POW2[i &mdash; 1] * 2 % mod; } // global variables: ll n; ll POW(ll u, ll v) { if (v == 0) return 1; ll mid = POW(u, v / 2); mid = (mid * mid) % mod; re...
1737
F
Ela and Prime GCD
\begin{tabular}{ll} & After a long, tough, but fruitful day at DTL, Ela goes home happily. She entertains herself by solving Competitive Programming problems. She prefers short statements, because she already read too many long papers and documentation at work. The problem of the day reads: \ \end{tabular} You are giv...
Author: constructive Observation: Assume that x is composite number and divisor of n. Among all the multiples of x, the number of the divisor of n must be less than or equal to m/2. First, factorize n. Assume that w is divisor of n. If w is in the form of a^4, a^3b^2, or a^2b^2c^2, it can be proved that there is no ans...
[ "constructive algorithms", "math", "number theory" ]
3,300
#import<bits/stdc++.h> #define endl '\n' using namespace std; int m, t, b[18], check[18], cnt[5]; vector<int>v; vector<vector<int>>a; void initialize(int m) { fill(b, b + m + 1, 0); fill(check, check + m + 1, 0); fill(cnt, cnt + 5, 0); v.clear(); a.clear(); } void insert1(int p1, int c1) { v[p1] = c1; a.push_b...
1737
G
Ela Takes Dancing Class
\begin{tabular}{ll} & DTL engineers love partying in the weekend. Ela does, too! Unfortunately, she didn't know how to dance yet. Therefore, she decided to take a dancing class. \ \end{tabular} There are $n$ students in the dancing class, including Ela. In the final project, $n$ students will participate in a choreogr...
Note that the immovable dancers don't change their positions during transformations. Let's pretend that all immovable dancers disappeared. We denote an arrangement as "good" if the dancer in the first step jump over any other dancers (the new placement of the first dancer is greater than the position of any other dance...
[ "binary search", "data structures" ]
3,500
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() using namespace std; #ifdef LOCAL #include "debug.h" #else #define debug(...) 42 #endif using ll = long long; using ld = long double; template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true)...
1738
A
Glory Addicts
The hero is addicted to glory, and is fighting against a monster. The hero has $n$ skills. The $i$-th skill is of type $a_i$ (either \textbf{fire} or \textbf{frost}) and has initial damage $b_i$. The hero can perform all of the $n$ skills in any order (with each skill performed exactly \textbf{once}). When performing...
Suppose the first skill to be performed is fixed. Then it is optimal to use the following greedy strategy. If possible, perform a skill of a different type from the last skill. If there are multiple skills of a different type from the last skill, choose the one with the largest initial damage. Inspired by the above obs...
[ "greedy", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; scanf("%d", &n); vector<int> a(n), b(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n; ++i) scanf("%d", &b[i]); vector<vector<long long>> v(2); for (int i = 0; i < n; ++i) v[a[i]].push_back(b[i]); for (int i = 0; ...
1738
B
Prefix Sum Addicts
Suppose $a_1, a_2, \dots, a_n$ is a sorted \textbf{integer} sequence of length $n$ such that $a_1 \leq a_2 \leq \dots \leq a_n$. For every $1 \leq i \leq n$, the prefix sum $s_i$ of the first $i$ terms $a_1, a_2, \dots, a_i$ is defined by $$ s_i = \sum_{k=1}^i a_k = a_1 + a_2 + \dots + a_i. $$ Now you are given the l...
If $k = 1$, it is always possible, so the answer is "YES". In the following, we assume that $k \geq 2$. Here, we are given $s_{n-k+1}, \dots, s_n$. We can resume $a_{n-k+2}, \dots, a_{n}$ by letting $a_{i} = s_{i} - s_{i-1}$ for every $n-k+2 \leq i \leq n$. If the known elements of $a_i$ cannot form a sorted array, i.e...
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; vector<long long> s(n + 1); for (int i = n - k + 1; i <= n; ++i) cin >> s[i]; if (k == 1) { cout << "YES" << endl; return; } vector<long long> a(n + 1); for (int i = n - k + 2; i <= n; ++i) a[i] = s[i] - s[i - 1];...
1738
C
Even Number Addicts
Alice and Bob are playing a game on a sequence $a_1, a_2, \dots, a_n$ of length $n$. They move in turns and \textbf{Alice moves first}. In the turn of each player, he or she should select an integer and remove it from the sequence. The game ends when there is no integer left in the sequence. Alice wins if the sum of ...
We only need to consider the case that $a_i =$ 0 or 1. Suppose there are $a$ 0's and $b$ 1's in total. Consider the following cases: $b \equiv 2 \pmod 4$. Bob has a winning strategy: Always choose the number that Alice chooses in her last move. This strategy keeps the invariant that Alice and Bob have the same number o...
[ "dp", "games", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; int u[111][111][2]; int dp[111][111][2]; int go(int x, int y, int z) { if (x + y == 0) return z == 0; int& res = dp[x][y][z]; if (u[x][y][z]) return res; u[x][y][z] = 1; if (x > 0) res |= 1 - go(x - 1, y, (z + y + 1) % 2); if (y > 0) res |= 1 - go(x, y - 1...
1738
D
Permutation Addicts
Given a permutation $a_1, a_2, \dots, a_n$ of integers from $1$ to $n$, and a threshold $k$ with $0 \leq k \leq n$, you compute a sequence $b_1, b_2, \dots, b_n$ as follows. For every $1 \leq i \leq n$ in increasing order, let $x = a_i$. - If $x \leq k$, set $b_{x}$ to the last element $a_j$ ($1 \leq j < i$) that $a_...
For readability and convenience of the readers who are interested in the checker of this problem, we consider this problem without assuming the existence of the threshold $k$ and permutation $a_1, a_2, \dots, a_n$. Let's first determine the value of $k$. A valid sequence $b$ must satisfy that For every $i \leq k$, we h...
[ "constructive algorithms", "data structures", "dfs and similar", "dsu", "graphs", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; void solve() { int n; scanf("%d", &n); vector<int> b(n + 1); int k = 0; for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (b[i] > i) k = i; } vector<vector<int>> v(n + 2); for (int i = 1; i <= n; ++i) v[b[i]].push_back(i); int root = v[0].size() ...
1738
E
Balance Addicts
Given an integer sequence $a_1, a_2, \dots, a_n$ of length $n$, your task is to compute the number, modulo $998244353$, of ways to partition it into several \textbf{non-empty} \textbf{continuous} subsequences such that the sums of elements in the subsequences form a \textbf{balanced} sequence. A sequence $s_1, s_2, \d...
Let $f(i, j)$ be the answer to the problem for the subsequence $a_i, a_{i+1}, \dots, a_j$. And we want to find $f(1, n)$. For every $1 \leq i \leq j \leq n$, we consider the following cases. $a_i = \dots = a_j = 0$. In this case, every partition produces a balanced sequence, thereby $f(i, j) = 2^{j-i}$. $a_i = a_j = 0$...
[ "combinatorics", "dp", "math", "two pointers" ]
2,300
#include <bits/stdc++.h> using namespace std; constexpr long long MOD = 998244353; long long power(long long a, long long b) { if (b == 0) return 1; long long t = power(a, b / 2); t = t * t % MOD; if (b % 2 == 1) t = t * a % MOD; return t; } void solve() { int n; scanf("%d", &n); vector<long long> a(n +...
1738
F
Connectivity Addicts
\textbf{This is an interactive problem}. Given a simple undirected graph with $n$ vertices numbered from $1$ to $n$, your task is to color all the vertices such that for every color $c$, the following conditions hold: - The set of vertices with color $c$ is \textbf{connected}; - $s_c \leq n_c^2$, where $n_c$ is the n...
Let's consider the following BFS-like algorithm. Repeat the following procedure until all vertices are visited. Choose an unvisited vertex $u$ with the largest degree. Let $S$ be a set of vertices, initially consisting of the only vertex $u$. For every neighbor vertex $v$ of vertex $u$, If vertex $v$ is visited, color ...
[ "constructive algorithms", "dsu", "graphs", "greedy", "interactive", "shortest paths", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> d(n + 1); for (int i = 1; i <= n; ++i) cin >> d[i]; auto query = [&](int x) { cout << "? " << x << endl; int y; cin >> y; return y; }; vector<int> visited(n + 1); vector<int> res(n + 1); int color_cnt = 0...
1738
G
Anti-Increasing Addicts
You are given an $n \times n$ grid. We write $(i, j)$ to denote the cell in the $i$-th row and $j$-th column. For each cell, you are told whether yon can delete it or not. Given an integer $k$, you are asked to delete \textbf{exactly} $(n-k+1)^2$ cells from the grid such that the following condition holds. - You can...
Consider increasing diagonals (sets of cells $(x, y)$ for which $x - y = c$ for some fixed $c$). Clearly, from the diagonal of length $t$, we have to delete at least $\max(0, t - (k-1))$ cells. There are $2$ diagonals of length $i$ for each $i$ from $1$ to $n-1$ and one diagonal of length $n$, so we have to delete at l...
[ "constructive algorithms", "dp", "greedy", "math" ]
2,900
#include <bits/stdc++.h> using namespace std; int n, k; pair<int, int> cell(int diag, int pos) { int st_x = 0; int st_y = 0; if (diag <= n - 1) st_y = (n - 1) - diag; if (diag >= n - 1) st_x = diag - (n - 1); return pair<int, int>(st_x + pos, st_y + pos); } void solve() { cin >> n >> k; ...
1738
H
Palindrome Addicts
Your task is to maintain a queue consisting of lowercase English letters as follows: - "push $c$": insert a letter $c$ at the back of the queue; - "pop": delete a letter from the front of the queue. Initially, the queue is empty. After each operation, you are asked to count the number of \textbf{distinct} palindromi...
To count the number of distinct palindromic substrings, we adopt the powerful data structure called eertree (also known as palindromic tree or palindromic automaton). The number of distinct palindromic substrings of a string $s$ is related to the number of nodes in the eertree of $s$. See Wikipedia for its standard ope...
[ "data structures", "strings" ]
3,300
#include <bits/stdc++.h> using namespace std; template<int alpha> class EerQueue { static_assert(alpha > 0); public: struct Node { std::array<Node*, alpha> next; Node* pre, * fail; int len; int rightmost_occurence, second_rightmost_occurence; // The (second) rightmost occurence of the palindrome associ...
1739
A
Immobile Knight
There is a chess board of size $n \times m$. The rows are numbered from $1$ to $n$, the columns are numbered from $1$ to $m$. Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular...
Let's consider some cases. If at least one of $n$ or $m$ are $1$, then all cells are isolated. A knight can't move one in a perpendicular direction. If at least one of $n$ or $m$ are at least $4$, then the knight always has at least one move. No matter where you place it, it can move two cells along the greater of the ...
[ "implementation" ]
800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int t; scanf("%d", &t); forn(_, t){ int n, m; scanf("%d%d", &n, &m); int svx = 1, svy = 1; for (int x = 1; x <= n; ++x){ for (int y = 1; y <= m; ++y){ bool ok = true; for (int dx : {-2...
1739
B
Array Recovery
For an array of \textbf{non-negative} integers $a$ of size $n$, we construct another array $d$ as follows: $d_1 = a_1$, $d_i = |a_i - a_{i - 1}|$ for $2 \le i \le n$. Your task is to restore the array $a$ from a given array $d$, or to report that there are multiple possible arrays.
Note that $a_i = a_{i-1} + d_i$ or $a_i= a_{i-1} - d_i$. Since there is no upper bound for the values of $a_i$, the case where $a_i = a_{i-1} + d_i$ for all $i$ always exists. It remains to check if there are other ways. To do this, it is enough to check whether there is such a position $pos$ that: $pos > 1$; $d_{pos} ...
[ "constructive algorithms", "greedy", "math" ]
1,100
for _ in range(int(input())): n = int(input()) ans = [0] for x in map(int, input().split()): if x != 0 and ans[-1] - x >= 0: print(-1) break else: ans.append(ans[-1] + x) else: print(*ans[1:])
1739
C
Card Game
Consider a game with $n$ cards ($n$ is even). Each card has a number written on it, between $1$ and $n$. All numbers on the cards are different. We say that a card with number $x$ is stronger than a card with number $y$ if $x > y$. Two players, Alex and Boris, play this game. In the beginning, each of them receives ex...
The example tests suggest that there is only one possible distribution with a draw. Let's find out why it is so. We will use a process similar to induction/recursion to distribute the cards between the two players so that the game ends in a draw: suppose Alex receives the card $n$. Then he wins since he can play it imm...
[ "combinatorics", "constructive algorithms", "dp", "games" ]
1,500
def fact(n): return 1 if n == 0 else n * fact(n - 1) def choose(n, k): return fact(n) // fact(k) // fact(n - k) def calc(n): if n == 2: return [1, 0, 1] else: a = calc(n - 2) return [choose(n - 1, n // 2) + a[1], choose(n - 2, n // 2) + a[0], 1] t = int(input()) for i in range...
1739
D
Reset K Edges
You are given a rooted tree, consisting of $n$ vertices. The vertices are numbered from $1$ to $n$, the root is the vertex $1$. You can perform the following operation \textbf{at most} $k$ times: - choose an edge $(v, u)$ of the tree such that $v$ is a parent of $u$; - remove the edge $(v, u)$; - add an edge $(1, u)$...
Start with the following. Let's look at the input format and consider what the operation actually does to it. Since it only changes the parent of some vertex, it modifies only one value in it. Moreover, it just assigns it to $1$. Thus, the goal is to assign at most $k$ values of parents to $1$ to minimize the resulting...
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
1,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n; vector<vector<int>> g; vector<int> st; vector<int> pd; void init(int v, int d){ st.push_back(v); if (int(st.size()) - d >= 0) pd[v] = st[st.size() - d]; for (int u : g[v]) init(u, d); st.pop_back(); } ...
1739
E
Cleaning Robot
Consider a hallway, which can be represented as the matrix with $2$ rows and $n$ columns. Let's denote the cell on the intersection of the $i$-th row and the $j$-th column as $(i, j)$. The distance between the cells $(i_1, j_1)$ and $(i_2, j_2)$ is $|i_1 - i_2| + |j_1 - j_2|$. There is a cleaning robot in the cell $(1...
Why did the author choose the width of the hallway to be only $2$? Well, in that case you can show that the robot will never move to the left while cleaning. That is not true on width $3$ already. When does the robot break? Let the robot currently be in the cell $(j, i)$ ($0$-indexed) and the next column with a dirty c...
[ "bitmasks", "dp" ]
2,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int INF = 1e9; int main(){ int n; cin >> n; vector<string> s(2); forn(i, 2) cin >> s[i]; vector<array<array<int, 2>, 2>> dp(n + 1); forn(i, n + 1) forn(j, 2) forn(k, 2) dp[i][j][k] = -INF; dp[0][0][s[1][0]...
1739
F
Keyboard Design
Monocarp has a dictionary of $n$ words, consisting of $12$ first letters of the Latin alphabet. The words are numbered from $1$ to $n$. In every pair of adjacent characters in each word, the characters are different. For every word $i$, Monocarp also has an integer $c_i$ denoting how often he uses this word. Monocarp ...
For each word, let's consider a graph on $12$ vertices where the $i$-th and the $j$-th vertices are connected by an edge iff the $i$-th character of the alphabet is adjacent to the $j$-th character of the alphabet in this string. Obviously, this graph is connected (except for the isolated vertices). If there is a verte...
[ "bitmasks", "data structures", "dp", "string suffix structures", "strings" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 10043; const int K = 12; int tsz = 0; int trie[N][K]; int aut[N][K]; int lnk[N]; int p[N]; int pchar[N]; int cost[N]; int ncost[N]; int newNode() { lnk[tsz] = -1; ncost[tsz] = -1; cost[tsz] = 0; for(int i = 0; i < K; i++) { trie[...
1740
A
Factorise N+M
Pak Chanek has a prime number$^\dagger$ $n$. Find a prime number $m$ such that $n + m$ is not prime. $^\dagger$ A prime number is a number with \textbf{exactly} $2$ factors. The first few prime numbers are $2,3,5,7,11,13,\ldots$. In particular, $1$ is \textbf{not} a prime number.
There are multiple solutions for this problem. We will discuss two of them. One solution is to choose $m = n$. This always guarantees that $m$ is prime, because $n$ is always prime. And we can see that $n + m = n + n = 2n$, which is always not prime, because $n > 1$ always holds. Another solution is to choose $m=7$. If...
[ "constructive algorithms", "number theory" ]
800
null
1740
B
Jumbo Extra Cheese 2
Pak Chanek has $n$ two-dimensional slices of cheese. The $i$-th slice of cheese can be represented as a rectangle of dimensions $a_i \times b_i$. We want to arrange them on the two-dimensional plane such that: - Each edge of each cheese is parallel to either the x-axis or the y-axis. - The bottom edge of each cheese i...
According to the problem, the arrays $a$ and $b$ denote the dimensions of the rectangles. Define arrays $c$ and $d$ as a certain orientation configuration of the rectangles with $c_i$ denoting the width and $d_i$ denoting the height. Define arrays $e$ and $f$ as a certain permutation of the orientation configuration su...
[ "geometry", "greedy", "sortings" ]
800
null
1740
C
Bricks and Bags
There are $n$ bricks numbered from $1$ to $n$. Brick $i$ has a weight of $a_i$. Pak Chanek has $3$ bags numbered from $1$ to $3$ that are initially empty. For each brick, Pak Chanek must put it into one of the bags. After this, each bag must contain at least one brick. After Pak Chanek distributes the bricks, Bu Deng...
Firstly, sort $a$. From now on, we will always refer to the sorted array $a$. Let $p_j$ be the index of the brick taken by Bu Dengklek from bag $j$. The configuration of $p_1,p_2,p_3$ must be in the form of one of the following: $p_1 < p_2 < p_3$ $p_1 > p_2 > p_3$ $p_2 < \min(p_1, p_3)$ $p_2 > \max(p_1, p_3)$ Let's loo...
[ "constructive algorithms", "games", "greedy", "sortings" ]
1,400
null
1740
D
Knowledge Cards
Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $n$ rows and $m$ columns. Let $(r, c)$ represent the cell in the $r$-th row and the $c$-th column. Initially, there are $k$ cards stacked in cell $(1, 1)$. Each card has an integer from $1$ to $k$ writ...
Let card $c$ be the card with number $c$ written on it. Notice that we must put the cards into the stack in $(n,m)$ in order from card $k$, card $k-1$, card $k-2$, and so on until card $1$. The key observation for this problem is that, under given constraints, if we ignore cells $(1,1)$ and $(n,m)$ we can always move a...
[ "constructive algorithms", "data structures" ]
1,500
null
1740
E
Hanging Hearts
Pak Chanek has $n$ blank heart-shaped cards. Card $1$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $i$ ($i > 1$) is hanging onto card $p_i$ ($p_i < i$). In the very beginning, Pak Chanek must write one integer number on e...
The cards form a rooted tree with card $i$ being the root, where for each $i$ ($i>1$), the parent of card $i$ is $p_i$. Let $w_i$ be the number on card $i$ when it is about to get removed. To remove card $i$, we must previously remove all cards in the subtree of $i$ other than $i$ itself. Thus, we can see that $w_i$ is...
[ "constructive algorithms", "data structures", "dfs and similar", "dp", "greedy", "trees" ]
1,800
null
1740
F
Conditional Mix
Pak Chanek is given an array $a$ of $n$ integers. For each $i$ ($1 \leq i \leq n$), Pak Chanek will write the one-element set $\{a_i\}$ on a whiteboard. After that, in one operation, Pak Chanek may do the following: - Choose two different sets $S$ and $T$ on the whiteboard such that $S \cap T = \varnothing$ ($S$ and ...
Let $cnt_i$ denote the number of occurrences of element $i$ in array $a$. Claim: A multiset $M$ of size $n$, $M_1,M_2,\ldots,M_n$ where $M_1 \geq M_2 \geq \ldots \geq M_n \geq 0$ is good if and only if $\sum_{i=1}^{n} M_i=n$ and $\sum_{i=1}^k M_i \leq \sum_{i=1}^n \min(k,cnt_i)$ for every $1 \leq k \leq n$. The proof o...
[ "combinatorics", "dp", "math" ]
2,600
null
1740
G
Dangerous Laser Power
Pak Chanek has an $n \times m$ grid of portals. The portal on the $i$-th row and $j$-th column is denoted as portal $(i,j)$. The portals $(1,1)$ and $(n,m)$ are on the north-west and south-east corner of the grid respectively. The portal $(i,j)$ has two settings: - \textbf{Type} $t_{i,j}$, which is either $0$ or $1$....
Claim: There is a construction where all portals are good. We will proceed with the construction. The key observation of the problem is that for a portal $(i,j)$ to consume energy, the laser must not enter a portal with a strength greater than or equal to $s_{i,j}$ before going through portal $(i,j)$. Let's say we alre...
[ "constructive algorithms", "dsu", "sortings" ]
3,100
null
1740
H
MEX Tree Manipulation
Given a rooted tree, define the value of vertex $u$ in the tree recursively as the MEX$^\dagger$ of the \textbf{values of its children}. Note that it is only the children, not all of its descendants. In particular, the value of a leaf is $0$. Pak Chanek has a rooted tree that initially only contains a single vertex wi...
Define $\text{MEX}_i(A)$ of a certain array $A$ as the $i$-th smallest non-negative integer that does not belong to the array. Let's solve a simpler problem. Imagine that you are given an array $A$, you are asked to append a new element $x$ to the array, and you need to calculate the MEX of the array after the operatio...
[ "data structures", "trees" ]
3,300
null
1740
I
Arranging Crystal Balls
In the world of Compfestnesia, Pak Chanek discovers a secret underground dungeon. Inside it, there is a treasure chest that is surrounded by $n$ statues that are arranged in a circular manner. The statues are numbered from $0$ to $n-1$ with statue $i$ being to the left of statue $i+1$ and statue $n-1$ being to the left...
Let's simplify the problem such that the only possible operation for each $k$ chosen statues is $a_i := (a_i - 1) \bmod m$. To solve this, we first define $c_i$ as the number of times we do that operation for the statues $i, (i-1) \bmod n, (i-2) \bmod n, (i-3) \bmod n, \ldots, (i-k+1) \bmod n$. We can see that in the o...
[ "data structures", "divide and conquer", "dp", "geometry", "graphs", "number theory" ]
3,500
null
1741
A
Compare T-Shirt Sizes
Two T-shirt sizes are given: $a$ and $b$. The T-shirt size is either a string M or a string consisting of several (possibly zero) characters X and one of the characters S or L. For example, strings M, XXL, S, XXXXXXXS could be the size of some T-shirts. And the strings XM, LL, SX are not sizes. The letter M stands fo...
Let $sa$, $sb$ are the last characters of lines $a$ and $b$ respectively. And $|a|, |b|$ are the sizes of these strings. $sa \neq sb$: then the answer depends only on $sa$ and $sb$ and is uniquely defined as the inverse of $sa$ to $sb$ ("<" if $sa > sb$, ">" if $sa < sb$, since the characters S, M, L are in reverse ord...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void ct(char c) { cout << c << '\n'; } void solve() { string a,b; cin >> a >> b; char ca = a.back(); char cb = ...
1741
B
Funny Permutation
A sequence of $n$ numbers is called permutation if it contains all numbers from $1$ to $n$ exactly once. For example, the sequences $[3, 1, 4, 2]$, [$1$] and $[2,1]$ are permutations, but $[1,2,1]$, $[0,1]$ and $[1,3,4]$ are not. For a given number $n$ you need to make a permutation $p$ such that two requirements are ...
We cannot make a funny permutation only when $n = 3$, because one of the neighboring elements of $3$ must be equal to $2$. Any permutation made in this way will not satisfy the conditions: The permutation [$3, 2, 1$] will have a fixed point $p_2 = 2$. The permutation [$1, 3, 2$] will have a fixed point $p_1 = 1$. The p...
[ "constructive algorithms", "math" ]
800
#include "bits/stdc++.h" using namespace std; void solve(){ int n; cin >> n; if(n == 3){ cout << -1 << endl; } else{ for(int i = 3; i <= n; i++) cout << i << ' '; cout << 2 << ' ' << 1 << endl; } } int main(){ int t; cin >> t; while(t--){ solve(); ...
1741
C
Minimize the Thickness
You are given a sequence $a=[a_1,a_2,\dots,a_n]$ consisting of $n$ \textbf{positive} integers. Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $a[l,r]$ a segment of the sequence $a$ with the left end...
Let's iterate over the length of the first segment of the split. Having fixed it, we actually fixed the sum that needs to be collected on all other segments. Since each element must belong to exactly one segment, we can build other segments greedily. If we have found a solution, we will remember the length of the longe...
[ "brute force", "greedy", "math", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAXN = 2020; int n; int arr[MAXN]; int go(int i, int sum) { if (i == n) return 0; for (int j = i + 1, cur = 0; j <= n; ++j) { cur += arr[j - 1]; if (cur > sum) return n; if (cur == sum) return max(j - i, go(j, sum)); } return n; } int solve() { int...
1741
D
Masha and a Beautiful Tree
The girl named Masha was walking in the forest and found a complete binary tree of height $n$ and a permutation $p$ of length $m=2^n$. A complete binary tree of height $n$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $n...
Let some vertex be responsible for a segment of leaves $[l..r]$. Then her left son is responsible for the segment $[l..\frac{l+r-1}{2}]$, and the right for the segment $[\frac{l+r+1}{2}..r]$. Note that if we do not apply the operation to this vertex, then it will not be possible to move some element from the right son'...
[ "dfs and similar", "divide and conquer", "graphs", "sortings", "trees" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAXM = 300300; int n, m; int arr[MAXM]; int solve(int l, int r) { if (r - l == 1) return 0; int mid = (l + r) >> 1; int mal = *max_element(arr + l, arr + mid); int mar = *max_element(arr + mid, arr + r); int ans = 0; if (mal > mar) { ++ans; for (int ...
1741
E
Sending a Sequence Over the Network
The sequence $a$ is sent over the network as follows: - sequence $a$ is split into segments (each element of the sequence belongs to exactly one segment, each segment is a group of consecutive elements of sequence); - for each segment, its length is written next to it, either to the left of it or to the right of it; -...
Let's introduce the dynamics. $dp[i] = true$ if on the prefix $i$ the answer is Yes. Then in this sequence $b$ the numbers corresponding to the sizes of the segments from the partition $a$ into subsegments will be called interesting. A number at position $i$ in the sequence $b$, if it is interesting, is either to the r...
[ "dp" ]
1,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void solve() { int n; cin >> n; vector<int> a(n+1); for (int i = 1; i <= n; ++i) { cin >> a[i]; } vecto...
1741
F
Multi-Colored Segments
Dmitry has $n$ segments of different colors on the coordinate axis $Ox$. Each segment is characterized by three integers $l_i$, $r_i$ and $c_i$ ($1 \le l_i \le r_i \le 10^9, 1 \le c_i \le n$), where $l_i$ and $r_i$ are are the coordinates of the ends of the $i$-th segment, and $c_i$ is its color. Dmitry likes to find ...
Let's go through the segments $2$ times: in non-decreasing coordinates of the left end, and then - in non-increasing coordinates of the right end. To walk a second time, just multiply the coordinates of the left and right borders by $-1$, and then swap them and walk from left to right. Going through the segments in non...
[ "binary search", "data structures", "math", "sortings" ]
2,000
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <queue> using namespace std; int n; vector<int> calc(vector<vector<int>> a) { vector<pair<int, int>> l(n), r(n); for (int i = 0; i < n; ++i) { l[i] = {a[i][0], i}; r[i] = {a[i][1], i}; } sort(l.begin(),...
1741
G
Kirill and Company
Kirill lives on a connected undirected graph of $n$ vertices and $m$ edges at vertex $1$. One fine evening he gathered $f$ friends, the $i$-th friend lives at the vertex $h_i$. So all friends are now in the vertex $1$, the $i$-th friend must get to his home to the vertex $h_i$. The evening is about to end and it is ti...
To begin with, let's learn how to find possible sets of friends for the vertex, whom he can give a ride, in the form of masks. Let's use a breadth first search, every time we find the shortest path to the vertex $u$ with the previous vertex $v$, we will add the masks of the vertex $v$ to the masks of the vertex $u$, up...
[ "bitmasks", "brute force", "dfs and similar", "dp", "flows", "graphs", "shortest paths" ]
2,200
from collections import deque def solve(): n, m = map(int, input().split()) sl = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) u -= 1 v -= 1 sl[u] += [v] sl[v] += [u] f = int(input()) h = [int(x) - 1 for x in input().split()] ...
1742
A
Sum
You are given three integers $a$, $b$, and $c$. Determine if one of them is the sum of the other two.
You only need to write an if statement and check if any of these are true: $a+b=c$, $b+c=a$, $c+a=b$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int a, b, c; cin >> a >> b >> c; cout << ((a + b == c || c + a == b || b + c == a) ? "YES\n" : "NO\n"); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i =...
1742
B
Increasing
You are given an array $a$ of $n$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $a_1 < a_2 < \dots < a_n$ holds.
If there are two elements with the same value, then the answer is NO, because neither of these values is less than the other. Otherwise, the answer is YES, since we can just sort the array. The time complexity is $\mathcal{O}(n \log n)$ or $\mathcal{O}(n)$ depending on the implementation.
[ "greedy", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int x[n]; set<int> a; for(int i = 0; i < n; i++) { cin >> x[i]; } for(int i = 0; i < n; i++) { if(a.find(x[i]) != a.end()) { cout << "NO" << endl; return; ...
1742
C
Stripes
On an $8 \times 8$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes. Determine which color was used last. \begin{center...
Note that if a stripe is painted last, then the entire stripe appears in the final picture (because no other stripe is covering it). Since rows are only painted red and columns are only painted blue, we can just check if any row contains 8 Rs. If there is such a row, then red was painted last; otherwise, blue was paint...
[ "implementation" ]
900
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { char g[8][8]; vector<int> r; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cin >> g[i][j]; if (g[i][j] == 'R') {r.push_back(i);} } } for (int i : r) { bool ok = true; ...
1742
D
Coprime
Given an array of $n$ positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$). Find the maximum value of $i + j$ such that $a_i$ and $a_j$ are coprime,$^{\dagger}$ or $-1$ if no such $i$, $j$ exist. For example consider the array $[1, 3, 5, 2, 4, 7, 7]$. The maximum value of $i + j$ that can be obtained is $5 ...
Note that the array has at most $1000$ distinct elements, since $a_i \leq 1000$. For each value, store the largest index it is in. Then we can brute force all pairs of values, and find the coprime pair with largest sum of indices. The time complexity is $\mathcal{O}(a_i^2 \log a_i + n)$ per testcase.
[ "brute force", "greedy", "number theory" ]
1,100
#include "bits/stdc++.h" using namespace std; #define ll long long #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1742
E
Scuza
Timur has a stairway with $n$ steps. The $i$-th step is $a_i$ meters higher than its predecessor. The first step is $a_1$ meters higher than the ground, and the ground starts at $0$ meters. \begin{center} {\small The stairs for the first test case.} \end{center} Timur has $q$ questions, each denoted by an integer $k_...
Let's compute the prefix sums of the array $a$: let $b_i = a_1 + \dots + a_i$. Rephrasing the problem: for each question containing an integer $k$, we need to find the largest $a_i$ such that $a_1, \dots, a_i$ are all at most $k$, and then output $b_i$. In other words, $\max(a_1, \dots, a_i) \leq k$. Let's make the pre...
[ "binary search", "greedy", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n, q; cin >> n >> q; vector<long long> pref; pref.push_back(0); vector<int> prefmax; for(int i = 0; i < n; i++) { int x; cin >> x; pref.push_back(pref.back()+x); if(i == 0) { ...
1742
F
Smaller
Alperen has two strings, $s$ and $t$ which are both initially equal to "a". He will perform $q$ operations of two types on the given strings: - $1 \;\; k \;\; x$ — Append the string $x$ exactly $k$ times at the end of string $s$. In other words, $s := s + \underbrace{x + \dots + x}_{k \text{ times}}$. - $2 \;\; k \;\...
First of all, let's think about how we should rearrange the two strings in such a way that $a < b$ (if that is ever possible). It's always optimal to arrange $a$'s characters increasingly in lexicographic order and $b$'s characters decreasingly. Since initially both $a$ and $b$ contain a character "a", the first time $...
[ "constructive algorithms", "greedy", "strings" ]
1,500
#include "bits/stdc++.h" using namespace std; #define ll long long #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1742
G
Orray
You are given an array $a$ consisting of $n$ nonnegative integers. Let's define the prefix OR array $b$ as the array $b_i = a_1~\mathsf{OR}~a_2~\mathsf{OR}~\dots~\mathsf{OR}~a_i$, where $\mathsf{OR}$ represents the bitwise OR operation. In other words, the array $b$ is formed by computing the $\mathsf{OR}$ of every pr...
Note that in this context $maxval$ denotes $10^9$. We can make the observation that only the first $log_2(maxval)$ elements matter, since after placing them optimally we can be sure all bits that could be set in the prefix OR would have already been set. So, we can brute force the optimal choice $log_2(maxval)$ times (...
[ "bitmasks", "brute force", "greedy", "math", "sortings" ]
1,500
#include "bits/stdc++.h" using namespace std; #define ll long long #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1743
A
Password
Monocarp has forgotten the password to his mobile phone. The password consists of $4$ digits from $0$ to $9$ (note that it can start with the digit $0$). Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers s...
There are two possible solutions for the problem. The first solution is basically brute force. Each password can be obtained from an integer from $0$ to $9999$. If the number is from $1000$ to $9999$, then it's already a password of length $4$. Otherwise, you have to prepend it with enough zeros so that it becomes leng...
[ "brute force", "combinatorics", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int n; inline void read() { cin >> n; int x; for (int i = 0; i < n; ++i) cin >> x; } inline int fac(int n) { int res = 1; for (int i = 2; i <= n; i++) { res *= i; } return res; } inline int c(int n, int k) { return fac(n...
1743
B
Permutation Value
You are given an integer $n$. You have to construct a permutation of size $n$. A \textbf{permutation} is an array where each integer from $1$ to $s$ (where $s$ is the size of permutation) occurs exactly once. For example, $[2, 1, 4, 3]$ is a permutation of size $4$; $[1, 2, 4, 5, 3]$ is a permutation of size $5$; $[1,...
The subsegment $[1]$, as well as the whole permutation, will always be a permutation, so the value is at least $2$. Let's try to find a way to generate a permutation of $n$ elements with value equal to $2$. Every permutation must contain the number $1$. Let's try to construct the answer in such a way that if a subsegme...
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; cout << 1; for(int i = n; i >= 2; i--) cout << " " << i; cout << endl; } int main() { int t; cin >> t; for(int i = 0; i < t; i++) solve(); }
1743
C
Save the Magazines
Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $n$ boxes, arranged in a row. The $i$-th box contains $a_i$ magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to s...
Let's process the boxes from left to right. Consider the first box. If it has a lid, then you can just add the number of magazines in it to the answer and forget about this box. To be exact, proceed to solve the problem with the first box removed. If it doesn't have a lid, then look at the next box. If it doesn't have ...
[ "constructive algorithms", "dp", "greedy" ]
1,100
for _ in range(int(input())): n = int(input()) s = '0' + input() a = [0] + list(map(int, input().split())) ans = 0 i = 0 while i <= n: mn = a[i] sm = a[i] j = i + 1 while j <= n and s[j] == '1': mn = min(mn, a[j]) sm += a[j] j += 1 ans += sm - mn i = j print(ans)
1743
D
Problem with Random Tests
You are given a string $s$ consisting of $n$ characters. Each character of $s$ is either 0 or 1. A substring of $s$ is a contiguous subsequence of its characters. You have to choose two substrings of $s$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing th...
The first observation we need is that we can choose two prefixes of $s$ as the substrings used in forming the results. This can be proved easily: suppose we chose a substring which does not contain the leftmost character of $s$; if we expand it to the left, the answer won't become worse. So, it is optimal to choose two...
[ "brute force", "dp", "greedy", "probabilities" ]
1,700
#include<bits/stdc++.h> using namespace std; char buf[1000043]; string normalize(const string& v) { int cnt = 0; while(cnt < v.size() && v[cnt] == '0') cnt++; if(cnt == v.size()) return "0"; return v.substr(cnt, int(v.size()) - cnt); } string operator |(const string& a, const string& b) { int sz...
1743
E
FTL
Monocarp is playing a video game. In the game, he controls a spaceship and has to destroy an enemy spaceship. Monocarp has two lasers installed on his spaceship. Both lasers $1$ and $2$ have two values: - $p_i$ — the power of the laser; - $t_i$ — the reload time of the laser. When a laser is fully charged, Monocarp ...
At any time, we have three possible choices: wait and shoot the first laser, the second laser and both lasers. Sometimes it makes sense to wait to both because you can deal $s$ more damage than you would do by shooting both lasers separately. The first claim: greedy won't work. Maybe there is a sufficiently smart greed...
[ "binary search", "dp" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const long long INF64 = 1e18; int main() { vector<int> ps(2); vector<long long> ts(2); int h, s; forn(i, 2) scanf("%d%lld", &ps[i], &ts[i]); scanf("%d%d", &h, &s); long long ans = INF64; vector<long long> dp(h +...
1743
F
Intersection and Union
You are given $n$ segments on the coordinate axis. The $i$-th segment is $[l_i, r_i]$. Let's denote the set of all integer points belonging to the $i$-th segment as $S_i$. Let $A \cup B$ be the union of two sets $A$ and $B$, $A \cap B$ be the intersection of two sets $A$ and $B$, and $A \oplus B$ be the symmetric diff...
We will use the Contribution to the Sum technique to solve this problem: for every integer from $0$ to $300000$, let's calculate the number of ways to choose the operators so it belongs to the result, and add all of the results. For a fixed integer $x$, the number of ways to choose the operators so that $x$ belongs to ...
[ "data structures", "dp", "matrices", "probabilities" ]
2,300
#include<bits/stdc++.h> using namespace std; const int N = 300043; typedef array<int, 2> vec; typedef array<vec, 2> mat; const int MOD = 998244353; mat operator*(const mat& a, const mat& b) { mat c; for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) c[i][j] = 0; for(int i = 0; i ...
1743
G
Antifibonacci Cut
\textbf{Note that the memory limit is unusual.} Let's define the sequence of Fibonacci strings as follows: $f_0$ is 0, $f_1$ is 1, $f_i$ is $f_{i-1} + f_{i-2}$ for $i>1$ ($+$ denotes the concatenation of two strings). So, for example, $f_2$ is 10, $f_3$ is 101, $f_4$ is 10110. For a given string $s$, let's define $g(...
The first idea that comes to mind is running some sort of dynamic programming: $dp_i$ - the number of ways to cut the string consisting of the first $i$ characters. When we calculate $dp_i$, we need to take the sum of the previous values of $dp$, and then subtract $dp_j$ for every $j$ such that the string from the $j$-...
[ "bitmasks", "combinatorics", "constructive algorithms", "data structures", "dp", "hashing", "math" ]
3,000
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int sub(int x, int y) { return add(x, MOD - y); } int expected(int mask) { if(mask & 2) return 0; return 1; } int last_bi...
1744
A
Number Replacement
An integer array $a_1, a_2, \ldots, a_n$ is being transformed into an array of lowercase English letters using the following prodecure: While there is at least one number in the array: - Choose any number $x$ from the array $a$, and any letter of the English alphabet $y$. - Replace all occurrences of number $x$ with ...
Let's note that if $a_i = a_j$, then $s_i$ must be equal to $s_j$, since we must change the same value to the same letter. If we check this for all pairs of $i$ and $j$ and find no such contradictions, then the answer is "YES", otherwise "NO". We got the solution for $O(n^2)$ for one test case.
[ "greedy", "implementation" ]
800
null
1744
B
Even-Odd Increments
You are given $n$ of integers $a_1, a_2, \ldots, a_n$. Process $q$ queries of two types: - query of the form "0 $x_j$": add the value $x_j$ to all even elements of the array $a$, - query of the form "1 $x_j$": add the value $x_j$ to all odd elements of the array $a$. Note that when processing the query, we look speci...
Let $\mathit{sum}$ - the initial sum in the array, $\mathit{cnt}_0$ - the number of even numbers, $\mathit{cnt}_1$ - the number of odd numbers. Let's see how these values change with each action. In fact, we can consider four main options: Add an even number $x$ to all even numbers. Then $\mathit{sum}$ will increase by...
[ "implementation", "math" ]
800
null
1744
C
Traffic Light
You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $n$ seconds and at the $i$-th second the color $s_i$ is on. That way, the order of the colors is described by a...
Let's note that for each second of color $c$ in the traffic light, we need to find the rightmost green time, and then find the largest distance between color $c$ and the nearest green. Also, let's not forget that traffic light states are cyclical. To get rid of cyclicity, you can write the string $s$ twice and for each...
[ "binary search", "implementation", "two pointers" ]
1,000
null
1744
D
Divisibility by 2^n
You are given an array of positive integers $a_1, a_2, \ldots, a_n$. Make the product of all the numbers in the array (that is, $a_1 \cdot a_2 \cdot \ldots \cdot a_n$) divisible by $2^n$. You can perform the following operation as many times as you like: - select an arbitrary index $i$ ($1 \leq i \leq n$) and replac...
Let's notice that if we multiply the numbers $a_1 \cdot a_2 \cdot \ldots \cdot a_n$, then the power of two of the product is equal to the sum of the powers of two in each of the numbers. Let's calculate the initial sum of the powers of twos in the product. This can be done as follows: let's take the element $a_i$ and d...
[ "greedy", "math", "sortings" ]
1,200
null
1744
E2
Divisible Numbers (hard version)
\textbf{This is an hard version of the problem. The only difference between an easy and a hard version is the constraints on $a$, $b$, $c$ and $d$.} You are given $4$ positive integers $a$, $b$, $c$, $d$ with $a < c$ and $b < d$. Find any pair of numbers $x$ and $y$ that satisfies the following conditions: - $a < x \...
Let's look at the slow solution first, which will lead us to the full one. Let's iterate over the number $x$ from $a + 1$ to $c$. Given a number $x$, we want to find a $y$ from $b + 1$ to $d$ such that $x \cdot y$ is divisible by $a \cdot b$. Since $x \cdot y$ must be divisible by $a \cdot b$, the following conclusion ...
[ "brute force", "math", "number theory" ]
1,900
null
1744
F
MEX vs MED
You are given a permutation $p_1, p_2, \ldots, p_n$ of length $n$ of numbers $0, \ldots, n - 1$. Count the number of subsegments $1 \leq l \leq r \leq n$ of this permutation such that $mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r)$. $mex$ of $S$ is the smallest non-negative integer that does not occu...
Let's learn how to count the number of subsegments where $\mathit{mex} > \mathit{mid}$ for a fixed value of $\mathit{mex}$. Let's understand on which subsegments $\mathit{mex}$ has such a value. We understand that the numbers $0, 1, \ldots, \mathit{mex} - 1$ should be in this subsegment, the number $\mathit{mex}$ - sho...
[ "math", "two pointers" ]
2,000
null
1746
A
Maxmina
You have an array $a$ of size $n$ consisting only of zeroes and ones and an integer $k$. In one operation you can do one of the following: - Select $2$ consecutive elements of $a$ and replace them with their minimum (that is, let $a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}]$ for ...
step 1: It's obvious that the answer is "NO" if $a_{i} = 0$ for all $1 \le i \le n$. step 2: Lets prove that the answer is "YES" if $a_{i} = 1$ for at least one $1 \le i \le n$. step 3: If size of $a$ is equal to $k$, just use second type operation once and we are done. step 4: Otherwise (if $|a| > k$), there will be t...
[ "constructive algorithms", "greedy" ]
800
// In the name of God #include <iostream> using namespace std; int main() { int t; cin >> t; while(t--) { int n, k; cin >> n >> k; int sum = 0; for(int i = 0 ; i < n ; i++){ int a; cin >> a; sum += a; } if(sum > 0) c...
1746
B
Rebellion
You have an array $a$ of size $n$ consisting only of zeroes and ones. You can do the following operation: - choose two indices $1 \le i , j \le n$, $i \ne j$, - add $a_{i}$ to $a_{j}$, - remove $a_{i}$ from $a$. Note that elements of $a$ can become bigger than $1$ after performing some operations. Also note that $n$ ...
step 1: Assume that $a_{i} = 0$ for each $1 \le i \le n$, what should we do? Nothing! The array is already sorted and the answer is $0$. step 2: After sorting the array, consider the first non-zero element of $a$, how many elements after that are equal to zero? In other words, consider smallest $i$ such that $a_{i} > 0...
[ "constructive algorithms", "greedy", "two pointers" ]
800
/// In the name of God #include <iostream> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; int A[n], cnt[2][n+1]; cnt[0][0] = cnt[1][0] = 0; for(int i = 0; i < n; i++) { cin >> A[i]; cnt[0][i+1] = cnt[0][i]+(A[i]==0?1:0); cnt[1][i+1] = cnt[1][i]+(A[i]==1?1:0...
1746
C
Permutation Operations
You are given a permutation $a$ of size $n$ and you should perform $n$ operations on it. In the $i$-th operation, you can choose a non-empty suffix of $a$ and increase all of its elements by $i$. How can we perform the operations to minimize the number of inversions in the final array? Note that you can perform operat...
step 1: Try to prove that the answer is always zero. Or in other words, we can always make the array $a$ non-decreasing. We will prove this fact in next steps. step 2: If some array $a$ is non-decreasing, what can we say about array $d=[a_{2}-a_{1}, a_{3}-a_{2}, ... a_{n}-a_{n-1}]$? It's obvious that all elements of ar...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,300
/// In the name of God #include <bits/stdc++.h> using namespace std; inline void solve() { int n; cin >> n; int permutation[n], location[n]; for(int i = 0; i < n; i++) { cin >> permutation[i]; permutation[i]--; location[permutation[i]] = i; } for(int i = 0; i < n; i++) { if(location[i] == n-1) cout...
1746
D
Paths on the Tree
You are given a rooted tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$, and the root is the vertex $1$. You are also given a score array $s_1, s_2, \ldots, s_n$. A multiset of $k$ simple paths is called valid if the following two conditions are both true. - Each path starts from $1$. - Let ...
Define $f(u, cnt)$ represents the maximum score of $cnt$ balls passing through the subtree of node $u$. Define $num$ as the number of the sons of node $u$. The transition is only related to $\lceil cnt / num \rceil$ and $\lfloor cnt / num \rfloor$ two states of the subtree. For each node $u$, $cnt$ can only be two adja...
[ "dfs and similar", "dp", "greedy", "sortings", "trees" ]
1,900
/// In the name of God #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 200000; ll V[N], dp[N]; int dad[N]; vector<int> child[N]; vector<pair<int, ll>> answers[N]; inline ll DP(int v, ll k) { for(auto [kp, ans]: answers[v]) if(k == kp) return ans; ll cnt_child = (ll)child[v].si...
1746
E1
Joking (Easy Version)
The only difference between this problem and the hard version is the maximum number of questions. This is an interactive problem. There is a hidden integer $1 \le x \le n$ which you have to find. In order to find it you can ask at most $\mathbf{82}$ questions. In each question you can choose a non-empty integer set ...
step 1: How can we make sure that some statement is not joking? If something is told for two times in a row, we can be sure that it's true. For example if we are told that $x \ne 3$ in two consecutive questions, we can be sure that it's true. Because at least one of those questions is answered correctly and that's enou...
[ "binary search", "constructive algorithms", "interactive", "ternary search" ]
2,500
/// In the name of God #pragma GCC optimize("Ofast","unroll-loops","O3") #include <bits/stdc++.h> using namespace std; inline bool get_answer(){string s; cin >> s; return s == "YES";} inline bool f(int i){return i&1;} inline bool g(int i){return i&2;} void solve(const vector<int> &Valid) { if(Valid.size() < 3u)...
1746
E2
Joking (Hard Version)
The only difference between this problem and the hard version is the maximum number of questions. This is an interactive problem. There is a hidden integer $1 \le x \le n$ which you have to find. In order to find it you can ask at most $\mathbf{53}$ questions. In each question you can choose a non-empty integer set ...
step 1: First note that in any question we ask, a set will be introduced as the set that contains $x$. If the answer is "YES", then the set that we asked is introduced and otherwise, its complement. Assume that our current search domain is some set $V$. In addition, assume that $V = A \cup B$ such that set $A$ is the s...
[ "dp", "interactive" ]
3,200
/// In the name of God #pragma GCC optimize("Ofast","unroll-loops","O3") #include <bits/stdc++.h> using namespace std; const int SUM = 50; int dp[SUM][SUM]; pair<int,int> updater[SUM][SUM]; map<pair<int,int>, int> Dp; map<pair<int,int>, pair<int,int>> Updater; inline void preprocess() { for(int i = 0; i < SUM; i...
1746
F
Kazaee
You have an array $a$ consisting of $n$ positive integers and you have to handle $q$ queries of the following types: - $1$ $i$ $x$: change $a_{i}$ to $x$, - $2$ $l$ $r$ $k$: check if the number of occurrences of every positive integer in the subarray $a_{l}, a_{l+1}, \ldots a_{r}$ is a multiple of $k$ (check the examp...
step 1: First of all, we can compress $a_{i}$'s and $x$'s (in second type query). so we can assume that all numbers are less than $n+q \le 6 \cdot 10^5$. step 2: Lets first solve the problem for smaller constrains. We can use data structures like fenwick tree or segment tree to count the number of occurrences of each n...
[ "data structures", "hashing", "probabilities" ]
2,800
#include <bits/stdc++.h> using namespace std; typedef long long int ll; mt19937 rnd(time(0)); const int N = 300'000 + 5; const int Q = 300'000 + 5; const int T = 50; bitset<N+Q> RandomSet[T]; unordered_map<int, int> id; int cnt_id = 0; int n, q, A[N]; struct fenwick { int PartialSum[N]; fenwick() { for...
1746
G
Olympiad Training
Anton decided to get ready for an Olympiad in Informatics. Ilya prepared $n$ tasks for him to solve. It is possible to submit the solution for the $i$-th task in the first $d_{i}$ days only. Anton \textbf{cannot} solve more than one task a day. Ilya estimated the usefulness of the $i$-th tasks as $r_{i}$ and divided th...
Consider all subsets of the original set in which tasks can be performed in some order to satisfy the constraints on their completion, and also that the size of each of them does not exceed $a+b+c$. It is easy to show that this set is a weighted matroid. This means that the optimal set of tasks can be found using a gre...
[ "binary search", "data structures", "dp", "flows", "geometry", "implementation", "sortings" ]
3,500
#include <bits/stdc++.h> using namespace std; #ifdef SG #include <debug.h> #else template<typename T> struct outputer; struct outputable {}; #define PRINT(...) #define OUTPUT(...) #define show(...) #define debug(...) #define deepen(...) #define timer(...) #define fbegin(...) #define fend #define pbegin(.....
1747
A
Two Groups
You are given an array $a$ consisting of $n$ integers. You want to distribute these $n$ integers into two groups $s_1$ and $s_2$ (groups can be empty) so that the following conditions are satisfied: - For each $i$ $(1 \leq i \leq n)$, $a_i$ goes into exactly one group. - The value $|sum(s_1)| - |sum(s_2)|$ is the maxi...
How about putting all positive numbers in one group and negative in second group Let $S$ denotes sum of element of array $a$. Claim: Answer is $|S|$. Proof: Let sum of all positive elements is $S_{pos}$ and sum of all negative elements $S_{neg}$. Put all positive numbers in first group and negative numbers in second gr...
[ "constructive algorithms", "greedy" ]
800
// Jai Shree Ram #include<bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int i=a;i<n;i++) #define ll long long #define int long long #define pb push_back #define all(v) v.begin(),v.end() #define endl "\n" #define x first #define y ...
1747
B
BAN BAN
You are given an integer $n$. Let's define $s(n)$ as the string "BAN" concatenated $n$ times. For example, $s(1)$ = "BAN", $s(3)$ = "BANBANBAN". Note that the length of the string $s(n)$ is equal to $3n$. Consider $s(n)$. You can perform the following operation on $s(n)$ any number of times (possibly zero): - Select...
Instead of subsequences solve for substrings. That is there should not be any substring $\texttt{BAN}$ after performing operations. In one operation you can destroy atmost $2$ substrings. Find minimum operations to destroy $n$ substrings. $\left \lceil\frac{n}{2}\right \rceil$ Congrats, you have solved for subsequences...
[ "constructive algorithms" ]
900
// Jai Shree Ram #include<bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int i=a;i<n;i++) #define ll long long #define int long long #define pb push_back #define all(v) v.begin(),v.end() #define endl "\n" #define x first #define y ...
1747
C
Swap Game
Alice and Bob are playing a game on an array $a$ of $n$ positive integers. Alice and Bob make alternating moves with Alice going first. In his/her turn, the player makes the following move: - If $a_1 = 0$, the player loses the game, otherwise: - Player chooses some $i$ with $2\le i \le n$. Then player decreases the v...
Case 1: $a_1 \gt \min(a)$ $\texttt{Alice}$ can force the $\texttt{Bob}$ to always decrease the minimum element by always choosing minimum element of $a$ in her turn. Where as $\texttt{Bob}$ can not do much, all other elements he would swap with would be greater than or equal to $\min(a)$. Even if there exists multiple ...
[ "games" ]
1,200
// Jai Shree Ram #include<bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int i=a;i<n;i++) #define ll long long #define int long long #define pb push_back #define all(v) v.begin(),v.end() #define endl " " #define x first #define y ...
1747
D
Yet Another Problem
You are given an array $a$ of $n$ integers $a_1, a_2, a_3, \ldots, a_n$. You have to answer $q$ independent queries, each consisting of two integers $l$ and $r$. - Consider the subarray $a[l:r]$ $=$ $[a_l, a_{l+1}, \ldots, a_r]$. You can apply the following operation to the subarray any number of times (possibly zero...
Forget queries, they are just here to make problem look complicated. Solve for $q = 1$. XOR of array does not change after operations. Hence if initially XOR is not equal to $0$, answer is $-1$. Is this condition sufficient? No, We need one more condition There must exist some prefix of odd size, such that xor of eleme...
[ "binary search", "bitmasks", "constructive algorithms", "data structures" ]
1,900
#include<bits/stdc++.h> using namespace std ; #define ll long long #define pb push_back #define all(v) v.begin(),v.end() #define sz(a) (ll)a.size() #define F first #define S second #define INF 2000000000000000000 #define popcount(x) ...