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 ⌀ |
|---|---|---|---|---|---|---|---|
1872 | G | Replace With Product | Given an array $a$ of $n$ positive integers. You need to perform the following operation \textbf{exactly} once:
- Choose $2$ integers $l$ and $r$ ($1 \le l \le r \le n$) and replace the subarray $a[l \ldots r]$ with the single element: the product of all elements in the subarray $(a_l \cdot \ldots \cdot a_r)$.
For ex... | Key observation: if the product of all elements in the array is sufficiently large, it is always optimal to perform the operation on the entire array, except for a possible prefix/suffix consisting of ones. You can estimate sufficiently large, for example, with the number $2^{60}$ (in reality, $2 \cdot n$ will be suffi... | [
"brute force",
"greedy",
"math"
] | 2,000 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
MAXP = 2 * n
prod = 1
for x in a:
prod *= x
if prod > MAXP:
break
if prod > MAXP:
l = 0
r = n - 1
while l < n and a[l] == 1:
l += 1
while r >... |
1873 | A | Short Sort | There are three cards with letters $a$, $b$, $c$ placed in a row in some order. You can do the following operation \textbf{at most once}:
- Pick two cards, and swap them.
Is it possible that the row becomes $abc$ after the operation? Output "YES" if it is possible, and "NO" otherwise. | There are only $6$ possible input strings, and they are all given in the input, so you can just output NO if $s$ is $\texttt{bca}$ or $\texttt{cab}$ and YES otherwise. Another way to solve it is to count the number of letters in the wrong position. A swap changes $2$ letters, so if at most two letters are in the wrong ... | [
"brute force",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
string alph = "abc";
void solve() {
string s;
cin >> s;
int cnt = 0;
for (int i = 0; i < 3; i++) {
cnt += (s[i] != alph[i]);
}
cout << (cnt <= 2 ? "YES\n" : "NO\n");
}
int main() {
ios::sync_with_stdio(f... |
1873 | B | Good Kid | Slavic is preparing a present for a friend's birthday. He has an array $a$ of $n$ digits and the present will be the product of all these digits. Because Slavic is a good kid who wants to make the biggest product possible, he wants to add $1$ to exactly one of his digits.
What is the maximum product Slavic can make? | Just brute force all possibilties for the digit to increase, and check the product each time. The complexity is $\mathcal{O}(n^2)$ per testcase. You can make it faster if you notice that it's always optimal to increase the smallest digit (why?), but it wasn't necessary to pass. | [
"brute force",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
vector<int> a(n);
int ans = 1;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a.begin(), a.end());
a[0]++;
for(int i = 0; i < n; i++)
{
ans*=a[i];
}
cout << ans << endl;
... |
1873 | C | Target Practice | A $10 \times 10$ target is made out of five "rings" as shown. Each ring has a different point value: the outermost ring — 1 point, the next ring — 2 points, ..., the center ring — 5 points.
Vlad fired several arrows at the target. Help him determine how many points he got. | You can just hardcode the values in the array below, and iterate through the grid; if it is an $\texttt{X}$, we add the value to our total. See the implementation for more details. $\begin{bmatrix} 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ 1 & 2 & 2 & 2 & 2 & 2 & 2 & 2 & 2 & 1 \\ 1 & 2 & 3 & 3 & 3 & 3 & 3 & 3 & 2 & 1 \\... | [
"implementation",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
int score[10][10] = {
{1,1,1,1,1,1,1,1,1,1},
{1,2,2,2,2,2,2,2,2,1},
{1,2,3,3,3,3,3,3,2,1},
{1,2,3,4,4,4,4,3,2,1},
{1,2,3,4,5,5,4,3,2,1},
{1,2,3,4,5,5,4,3,2,1},
{1,2,3,4,4,4,4,3,2,1},
{1,2,3,3,3,3,3,3,2,1},
{... |
1873 | D | 1D Eraser | You are given a strip of paper $s$ that is $n$ cells long. Each cell is either black or white. In an operation you can take any $k$ consecutive cells and make them all white.
Find the minimum number of operations needed to remove all black cells. | The key idea is greedy. Let's go from the left to the right, and if the current cell is black, we should use the operation starting at this cell (it may go off the strip, but that's okay, we can always shift it leftwards to contain all the cells we need it to). We can implement this in $\mathcal{O}(n)$: iterate from le... | [
"greedy",
"implementation",
"two pointers"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200'007;
const int MOD = 1'000'000'007;
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int res = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'B') {
res++; i += k - 1;
}
}
cout << res << '\n';
}
int main() {
ios::sync_wit... |
1873 | E | Building an Aquarium | You love fish, that's why you have decided to build an aquarium. You have a piece of coral made of $n$ columns, the $i$-th of which is $a_i$ units tall. Afterwards, you will build a tank around the coral as follows:
- Pick an integer $h \geq 1$ — the height of the tank. Build walls of height $h$ on either side of the ... | We need to find the maximum height with a certain upper bound - this is a tell-tale sign of binary search. If you don't know what that is, you should read this Codeforces EDU article. For a given value of $h$, in the $i$-th column we will need $h - a_i$ units of water if $h \geq a_i$, or $0$ units otherwise. (This is e... | [
"binary search",
"sortings"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200'007;
const int MOD = 1'000'000'007;
void solve() {
int n;
long long x;
cin >> n >> x;
long long a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
long long lo = 0, hi = 2'000'000'007;
while (lo < hi) {
long long mid = lo + (hi - lo + 1... |
1873 | F | Money Trees | Luca is in front of a row of $n$ trees. The $i$-th tree has $a_i$ fruit and height $h_i$.
He wants to choose a contiguous subarray of the array $[h_l, h_{l+1}, \dots, h_r]$ such that for each $i$ ($l \leq i < r$), \textbf{$h_i$ is divisible$^{\dagger}$ by $h_{i+1}$}. He will collect all the fruit from each of the tree... | Let's compute $len_l$ for each $l \leq n$, the maximum $r$ such that the subarray $[h_l \dots h_r]$ satisfies the height divisibility condition. Now let's do a binary search on the $size$ of the segment, where we check every $i$ such that $len_i \geq i+size-1$. Check the sum between $i$ and $i+size-1$ using a prefix su... | [
"binary search",
"greedy",
"math",
"two pointers"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int N = 200'000;
int n, k;
int a[N+5], h[N+5], pref[N+5], length[N+5];
bool get(int dist)
{
bool found = false;
for(int i = 0; i < n-dist+1; i++)
{
if(length[i] < dist){continue;}
int sum = pref[i+dist]-pref[i];
if(sum <= k)
... |
1873 | G | ABBC or BACB | You are given a string $s$ made up of characters $A$ and $B$. Initially you have no coins. You can perform two types of operations:
- Pick a substring$^\dagger$ $AB$, change it to $BC$, and get a coin.
- Pick a substring$^\dagger$ $BA$, change it to $CB$, and get a coin.
What is the most number of coins you can obtai... | Preface Before we get into the editorial, I want to make a note that this type of problem is not traditional for Div. 4 on purpose, and is a lot more ad-hoc than usual. My goal was to make a sort of "introductory" ad-hoc problem, and I hope you enjoyed it. The editorial is a bit long, mainly because I want to go into a... | [
"constructive algorithms",
"greedy"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200'007;
const int MOD = 1'000'000'007;
void solve() {
string s;
cin >> s;
int n = s.length(), cnt = 0;
bool all = (s[0] == 'B' || s[n - 1] == 'B');
for (int i = 0; i < n - 1; i++) {
if (s[i] == s[i + 1] && s[i] == 'B') {all = true;}
}
vector<... |
1873 | H | Mad City | Marcel and Valeriu are in the mad city, which is represented by $n$ buildings with $n$ two-way roads between them.
Marcel and Valeriu start at buildings $a$ and $b$ respectively. Marcel wants to catch Valeriu, in other words, be in the same building as him or meet on the same road.
During each move, they choose to go... | Because we have a tree with an additional edge, our graph has exactly one cycle. If Marcel and Valeriu share the same starting building then the answer is "NO". If we do a depth-first search from Valeriu's node, when we encounter an already visited node that is not the current node's parent, the node is part of the cyc... | [
"dfs and similar",
"dsu",
"games",
"graphs",
"shortest paths",
"trees"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
vector<int> adj[N];
vector<bool> vis(N);
int entry_node = -1;
vector<int> path;
bool dfs1(int u, int p)
{
vis[u] = true;
for(auto v : adj[u])
{
if(v != p && vis[v])
{
entry_node = v;
return ... |
1874 | A | Jellyfish and Game | Jellyfish has $n$ green apples with values $a_1, a_2, \dots, a_n$ and Gellyfish has $m$ green apples with values $b_1,b_2,\ldots,b_m$.
They will play a game with $k$ rounds. For $i=1,2,\ldots,k$ in this order, they will perform the following actions:
- If $i$ is odd, Jellyfish can choose to swap one of her apples wit... | Let us define $\min(a)$ to be the minimum value of $a$ in the current round, $\max(a)$ to be the maximum value of $a$ in the current round, $\min(b)$ to be the minimum value of $b$ in the current round, $\max(b)$ to be the maximum value of $b$ in the current round, $\text{MIN}$ to be the minimum value of all the apples... | [
"brute force",
"games",
"greedy",
"implementation"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 1000 + 5;
int n = 0, m = 0, k = 0, x = 0, y = 0, a[N] = {}, b[N] = {};
inline void solve(){
scanf("%d %d %d", &n, &m, &k); k --;
for(int i = 0 ; i < n ; i ++) scanf("%d", &a[i]);
for(int i = 0 ; i < m ; i ++) scanf("%d", &b[i]);
x = y = 0;
for(int i = 1... |
1874 | B | Jellyfish and Math | Jellyfish is given the non-negative integers $a$, $b$, $c$, $d$ and $m$. Initially $(x,y)=(a,b)$. Jellyfish wants to do several operations so that $(x,y)=(c,d)$.
For each operation, she can do one of the following:
- $x := x\,\&\,y$,
- $x := x\,|\,y$,
- $y := x \oplus y$,
- $y := y \oplus m$.
Here $\&$ denotes the b... | First of all, since $\text{and}, \text{or}, \text{xor}$ are all bitwise operations, each bit is independent of the other. We define $a_i$ as the $i$-th bit of $a$, $b_i$ as the $i$-th bit of $b$, $c_i$ as the $i$-th bit of $c$, $d_i$ as the $i$-th bit of $d$, $m_i$ as the $i$-th bit of $m$, $x_i$ as the $i$-th bit of $... | [
"bitmasks",
"brute force",
"dfs and similar",
"dp",
"graphs",
"shortest paths"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
const int S = 4e5 + 5, Inf = 0x3f3f3f3f;
int pw5[10] = {}, dp[S] = {};
queue<int> Q;
inline void checkmin(int &x, int y){
if(y < x) x = y;
}
inline int w(int mask, int i){
return (mask / pw5[i]) % 5;
}
inline int f(int a, int b, int m){
return (a << 2) | (b << 1) | m... |
1874 | C | Jellyfish and EVA | Monsters have invaded the town again! Asuka invites her good friend, Jellyfish, to drive EVA with her.
There are $n$ cities in the town. All the monsters are in city $n$. Jellyfish and Asuka are currently in city $1$ and need to move to city $n$ to defeat the monsters.
There are $m$ roads. The $i$-th road allows one ... | Let's solve this problem by dynamic programming, Let $f_u$ represents the max probability of reaching city $n$ starting from city $u$. The problem is how to transition. for city $u$, we assume that there are $d$ roads from city $u$, the $i$-th road from city $u$ is to city $v_i$. Let's sort $v$ by using $f_v$ as the ke... | [
"dp",
"graphs",
"greedy",
"math",
"probabilities"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
const int N = 5000 + 5;
int n = 5000, m = 0;
vector<vector<int> > G(N), Gx(N);
long double f[N] = {}, g[N][N] = {};
inline bool cmp(int u, int v){
return f[u] > f[v];
}
inline void work(int u){
if(u == n){
f[u] = 1.00;
return;
}
sort(G[u].begin(), G[u].end(), cmp... |
1874 | D | Jellyfish and Miku | There are $n + 1$ cities with numbers from $0$ to $n$, connected by $n$ roads. The $i$-th $(1 \leq i \leq n)$ road connects city $i-1$ and city $i$ bi-directionally. After Jellyfish flew back to city $0$, she found out that she had left her Miku fufu in city $n$.
Each road has a \textbf{positive integer} level of beau... | Let's assume that $a$ is given. We can use dynamic programming to solve the problem. Let's define $f_i$ as the expected number of days Jellyfish needs to reach city $i$ from city $0$. We will have: $f_0=0, f_1=1$ $f_0=0, f_1=1$ $\forall i > 1, f_i=f_{i-1}+1+\frac {a_{i-1}} {a_{i-1}+a_i} \times (f_i - f_{i-2})$ $\forall... | [
"divide and conquer",
"dp",
"math",
"probabilities"
] | 2,800 | #include<bits/stdc++.h>
using namespace std;
const int N = 3000 + 5;
const long double Inf = 1e18;
int n = 0, m = 0;
long double dp[N][N] = {};
int main(){
scanf("%d %d", &n, &m);
for(int i = 0 ; i <= n ; i ++) for(int x = 0 ; x <= m ; x ++) dp[i][x] = Inf;
dp[0][0] = 0.00;
for(int i = 1 ; i <= n ; i ++) for(int... |
1874 | E | Jellyfish and Hack | It is well known that quick sort works by randomly selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. But Jellyfish thinks that choosing a random element is just a waste of time, so she always chooses the... | Firstly, if $lim > \frac {n(n+1)} 2$, the answer will be $0$. So we only need to solve the problem which satisfies $lim \leq \frac{n(n+1)} 2$. We can use dynamic programming to solve the problem: Let's define $dp_{i, a}$ means the number of the permutations $P$ of $[1, 2, \dots, i]$, satisfying $\mathrm{fun(P)} = a$. S... | [
"dp",
"math"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 200 + 5, Mod = 1e9 + 7;
inline ll power(ll x, ll y){
ll ret = 1;
while(y){
if(y & 1) ret = ret * x % Mod;
x = x * x % Mod, y >>= 1;
}
return ret;
}
ll n = 0, k = 0, lim = 0;
ll C[N][N] = {}, pw[N * N][N] = {}, iv[N * N] = {}, if... |
1874 | F | Jellyfish and OEIS | Jellyfish always uses OEIS to solve math problems, but now she finds a problem that cannot be solved by OEIS:
Count the number of permutations $p$ of $[1, 2, \dots, n]$ such that for all $(l, r)$ such that $l \leq r \leq m_l$, the subarray $[p_l, p_{l+1}, \dots, p_r]$ is not a permutation of $[l, l+1, \dots, r]$.
Sin... | Let's call a section $[l, r]$ bad if $[p_l, p_{l+1}, \dots, p_{r-1}, p_r]$ is a permutation of $[l, l + 1, \dots, r - 1, r]$ and $l \leq r \leq m_l$. Let's call a section $[l, r]$ primitive if it's a bad section and there are no section $[l', r']$ satisfying $[l', r']$ is also a bad section and $[l, r]$ covers $[l', r'... | [
"dp"
] | 3,500 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 200 + 5, Mod = 1e9 + 7;
ll n = 0, m[N] = {}, fac[N] = {}, f[N][N] = {}, g[N][N][N] = {};
int main(){
scanf("%lld", &n);
for(ll i = 1 ; i <= n ; i ++) scanf("%lld", &m[i]);
if(m[1] == n){
printf("0");
return 0;
}
fac[0] = 1;
for... |
1874 | G | Jellyfish and Inscryption | Jellyfish loves playing a game called "Inscryption" which is played on a directed acyclic graph with $n$ vertices and $m$ edges. All edges $a \to b$ satisfy $a < b$.
You need to move from vertex $1$ to vertex $n$ along the directed edges, and then fight with the final boss.
You will collect \textbf{cards} and \textbf... | For convenience, let's define $k = \max(a, b, x, y)$, use operation 1 for "You will get a card with $a$ HP, and $b$ damage", operation 2 for "If you have at least one card, choose one of your cards and increase its HP by $x$" and operation 3 for "If you have at least one card, choose one of your cards and increase its ... | [
"dp"
] | 3,500 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 200 + 5;
const ll lim = 1e9;
inline void checkmax(int &x, int y){
if(y > x) x = y;
}
inline void checkmax(ll &x, ll y){
if(y > x) x = y;
}
inline void checkmax(pair<int, int> &x, pair<int, int> y){
if(y > x) x = y;
}
int n = 0, m ... |
1875 | A | Jellyfish and Undertale | Flowey has planted a bomb in Snowdin!
The bomb has a timer that is initially set to $b$. Every second, the timer will decrease by $1$. When the timer reaches $0$, the bomb will explode! To give the residents of Snowdin enough time to evacuate, you will need to delay the bomb from exploding for as long as possible.
Yo... | We can use one tool each time the timer reaches to $1$, then the answer will be $\sum_{i=1}^n \min(a - 1, x_i) + b$. This can prove to be optimal. Because for each tool, if we use it when the timer is $c$, its contribution to the answer is $\min(x_i, a - c)$. We can't use the tool when the timer is less than or equal t... | [
"brute force",
"greedy"
] | 900 | #include<bits/stdc++.h>
using namespace std;
int n = 0, a = 0, b = 0;
long long ans = 0;
inline void solve(){
scanf("%d %d %d", &a, &b, &n);
ans = b;
for(int i = 0, x = 0 ; i < n ; i ++){
scanf("%d", &x);
ans += min(a - 1, x);
}
printf("%lld\n", ans);
}
int T = 0;
int main(){
scanf("%d", &T);
for(int i ... |
1875 | C | Jellyfish and Green Apple | Jellyfish has $n$ green apple pieces. Each green apple piece weighs $1~\text{kg}$. Jellyfish wants to divide these green apple pieces \textbf{equally} among $m$ people.
Jellyfish has a magic knife. Each time Jellyfish can choose one piece of green apple and divide it into two smaller pieces, with each piece having hal... | Firstly, if $n \geq m$, we can make the problem transform $n < m$ by giving each person an apple at a time until there are not enough apples. We can calculate the mass of apples that each person ends up with as $\frac n m$. Since it's cut in half every time, if $\frac m {\gcd(n, m)}$ is not an integral power of $2$, th... | [
"bitmasks",
"greedy",
"math",
"number theory"
] | 1,400 | #include<bits/stdc++.h>
using namespace std;
int n = 0, m = 0;
inline void solve(){
scanf("%d %d", &n, &m); n %= m;
int a = n / __gcd(n, m), b = m / __gcd(n, m);
if(__builtin_popcount(b) > 1) printf("-1\n");
else printf("%lld\n", 1ll * __builtin_popcount(a) * m - n);
}
int T = 0;
int main(){
scanf("%d", &T);
... |
1875 | D | Jellyfish and Mex | You are given an array of $n$ nonnegative integers $a_1, a_2, \dots, a_n$.
Let $m$ be a variable that is initialized to $0$, Jellyfish will perform the following operation $n$ times:
- select an index $i$ ($1 \leq i \leq |a|$) and delete $a_i$ from $a$.
- add $\operatorname{MEX}(a)^{\dagger}$ to $m$.
Now Jellyfish w... | We only care about the operation before $\text{MEX}(a)$ reaches $0$, because after that, $m$ will never change. Lemma. Before $\text{MEX}(a)$ reaches $0$, we will choose a positive integer $x$ at a time that satisfies $x < \text{MEX}(a)$, and delete all $x$ from $a$, the $\text{MEX}(a)$ will become $x$. Proof. Because ... | [
"dp"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 5000 + 5, Inf = 0x3f3f3f3f3f3f3f3f;
ll n = 0, m = 0, a[N] = {}, dp[N] = {};
inline void init(){
for(ll i = 0 ; i <= n ; i ++) a[i] = 0, dp[i] = Inf;
n = m = 0;
}
inline void solve(){
scanf("%lld", &n);
for(ll i = 1, x = 0 ; i <= n ;... |
1876 | A | Helmets in Night Light | Pak Chanek is the chief of a village named Khuntien. On one night filled with lights, Pak Chanek has a sudden and important announcement that needs to be notified to all of the $n$ residents in Khuntien.
First, Pak Chanek shares the announcement directly to one or more residents with a cost of $p$ for each person. Aft... | Notice that since there are $n$ residents, there must be $n$ shares. There are two types of shares. A share directly by Pak Chanek to a resident, and a share by a resident to another resident. A share by Pak Chanek is unlimited, while a share by a resident is limited by $a_i$. So there are unlimited shares with cost $p... | [
"greedy",
"sortings"
] | 1,000 | null |
1876 | B | Effects of Anti Pimples | Chaneka has an array $[a_1,a_2,\ldots,a_n]$. Initially, all elements are white. Chaneka will choose one or more different indices and colour the elements at those chosen indices black. Then, she will choose all white elements whose indices are multiples of the index of \textbf{at least one} black element and colour tho... | For some value $w$, let $f(w)$ be the number of different ways to choose the black indices such that the score is exactly $w$ and let $g(w)$ be the number of different ways to choose the black indices such that the score is at most $w$. Then $f(w) = g(w) - g(w-1)$. Let's try to calculate $g(w)$. First, group the elemen... | [
"combinatorics",
"number theory",
"sortings"
] | 1,500 | null |
1876 | C | Autosynthesis | Chaneka writes down an array $a$ of $n$ positive integer elements. Initially, all elements are not circled. In one operation, Chaneka can circle an element. It is possible to circle the same element more than once.
After doing all operations, Chaneka makes a sequence $r$ consisting of all \textbf{uncircled} elements o... | Let's say we have coloured each element of $a$ into black or white and we want to find a sequence of operations that results in all black elements being circles and all white elements being uncircled. Notice that such a sequence exists if and only if the following holds: For each black element, there must exist at leas... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"sortings"
] | 2,100 | null |
1876 | D | Lexichromatography | Pak Chanek loves his faculty, the Faculty of Computer Science, University of Indonesia (Fasilkom). He wants to play with the colours of the faculty's logo, blue and red.
There is an array $a$ consisting of $n$ elements, element $i$ has a value of $a_i$. Pak Chanek wants to colour each element in the array blue or red ... | There are two conditions in the problem. The lexicography condition and the imbalanced subarrays condition. Let's look at the imbalanced subarrays condition. Consider some value $k$ and consider all elements in $a$ with a value of $k$. In order to satisfy this condition, those elements must be coloured blue and red alt... | [
"combinatorics",
"dfs and similar",
"dsu",
"graphs",
"two pointers"
] | 2,500 | null |
1876 | E | Ball-Stackable | With a problem title like that, there is no way this is going to be a graph problem.
Chaneka has a graph with $n$ vertices and $n-1$ edges. Some of the edges are directed and some of the edges are undirected. Edge $i$ connects vertex $u_i$ to vertex $v_i$. If $t_i=0$, edge $i$ is undirected. If $t_i=1$, edge $i$ is di... | Let's try to solve the problem if all edges are directed. First, assign some arbitrary vertex $x$ as the root of the tree. Consider all walks that start from $x$. Notice that for a fixed vertex $y$, no matter how Chaneka walks from $x$, when she reaches $y$, the number of balls in the stack will always be the same. Mor... | [
"constructive algorithms",
"data structures",
"dp",
"trees"
] | 3,300 | null |
1876 | F | Indefinite Clownfish | Pak Chanek has just bought an empty fish tank and he has been dreaming to fill it with his favourite kind of fish, clownfish. Pak Chanek likes clownfish because of their ability to change their genders on demand. Because of the size of his fish tank, Pak Chanek wants to buy exactly $k$ clownfish to fill the tank.
Pak ... | We want to find two disjoint subsequences (for the females and the males) such that: The female subsequence contains consecutively increasing values. The male subsequence contains consecutively decreasing values The total length is exactly $k$. The mean values of both subsequences are the same. For a group of consecuti... | [
"binary search",
"graphs"
] | 3,500 | null |
1876 | G | Clubstep | There is an extremely hard video game that is one of Chaneka's favourite video games. One of the hardest levels in the game is called Clubstep. Clubstep consists of $n$ parts, numbered from $1$ to $n$. Chaneka has practised the level a good amount, so currently, her familiarity value with each part $i$ is $a_i$.
After... | Let's try to solve a single query $(l,r,x)$ in $O(n)$. It is clear that in the optimal strategy, we do not want to do any attempts that die on parts to the left of $l$ or to the right of $r$. There are two cases: If $a_r\geq x$, then we can ignore index $r$ and solve the query for $(l,r-1,x)$. If $a_r<x$, then it is op... | [
"binary search",
"brute force",
"data structures",
"greedy",
"trees"
] | 3,500 | null |
1877 | A | Goals of Victory | There are $n$ teams in a football tournament. Each pair of teams match up once. After every match, Pak Chanek receives two integers as the result of the match, the number of goals the two teams score during the match. The efficiency of a team is equal to the total number of goals the team scores in each of its matches ... | Notice that each goal increases the efficiency of the team that scores by $1$. But it also simultaneously decreases the efficiency of the opposite team by $1$. This means, if we maintain the sum of efficiency for all teams, each goal does not change the sum. Therefore, the sum must be $0$. In order to make the sum to b... | [
"math"
] | 800 | null |
1877 | C | Joyboard | Chaneka, a gamer kid, invented a new gaming controller called joyboard. Interestingly, the joyboard she invented can only be used to play one game.
The joyboard has a screen containing $n+1$ slots numbered from $1$ to $n+1$ from left to right. The $n+1$ slots are going to be filled with an array of non-negative intege... | There are only a few cases. If $a_{n+1}=0$, then every value of $a_i$ is $0$. So there is only $1$ distinct value. If $1\leq a_{n+1}\leq n$, then there exists an index $p$ ($p=a_{n+1}$) such that $a_i=a_{n+1}$ for all indices $p+1\leq i\leq n+1$ and $a_i=0$ for all $1\leq i\leq p$. So there are $2$ distinct values. If ... | [
"math",
"number theory"
] | 1,200 | null |
1878 | A | How Much Does Daytona Cost? | We define an integer to be the most common on a subsegment, if its number of occurrences on that subsegment is larger than the number of occurrences of any other integer in that subsegment. A subsegment of an array is a consecutive segment of elements in the array $a$.
Given an array $a$ of size $n$, and an integer $k... | It's enough to check if there even exists the element equals to $K$, since $K$ is obviously the most common element in the subsegment of length $1$ which contains it. | [
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; //read the number of test cases
cin >> t;
while(t--){
int n, k;
cin >> n >> k; //read n and k
bool ys=0; //bool value if true then there exists a subsegment which satisfies the condition, else it doesn't exist
for(int i=0; i< n; i++){
int ... |
1878 | B | Aleksa and Stack | After the Serbian Informatics Olympiad, Aleksa was very sad, because he didn't win a medal (he didn't know stack), so Vasilije came to give him an easy problem, just to make his day better.
Vasilije gave Aleksa a positive integer $n$ ($n \ge 3$) and asked him to construct a strictly increasing array of size $n$ of pos... | There are many solutions to this problem, but the intended one is the following: By selecting the first $n$ odd positive integers $1, 3, 5, \dots, 2n - 1$, we find that $3\cdot a_{i + 2}$ is also an odd number, while the number $a_i + a_{i + 1}$ is even, and an odd number can never be divisible by an even number, so th... | [
"constructive algorithms",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; //read the number of test cases
cin >> t;
while(t--){
int n; //read n
cin >> n;
for(int i=0; i< n; i++)cout << i*2+1 << " "; //write the first n odd numbers in order
cout << '\n';
}
} |
1878 | C | Vasilije in Cacak | Aca and Milovan, two fellow competitive programmers, decided to give Vasilije a problem to test his skills.
Vasilije is given three positive integers: $n$, $k$, and $x$, and he has to determine if he can choose $k$ distinct integers between $1$ and $n$, such that their sum is equal to $x$.
Since Vasilije is now in th... | It is clear that the minimum sum is obtained for the numbers $1, 2, 3, \dots, k$, and its value is $\frac{k\cdot(k+1)}{2}$ (the sum of the first $k$ natural numbers). Furthermore, it is evident that the maximum sum is achieved for the numbers $n, n-1, n-2, \dots, n-k+1$, and its value is $\frac{n\cdot(n+1)-(n-k)\cdot(n... | [
"math"
] | 900 | #include <iostream>
using namespace std;
int main(){
int t; //read the number of test cases
cin >> t;
while(t--){
long long n, x, k; //read n, x, k for each test case
cin >> n >> x >> k;
if(2*k>=x*(x+1) && 2*k<=n*(n+1)-(n-x)*(n-x+1)){ //check if k is between the minimum and maximum sum
cout << "YES\n";
... |
1878 | D | Reverse Madness | You are given a string $s$ of length $n$, containing lowercase Latin letters.
Next you will be given a positive integer $k$ and two arrays, $l$ and $r$ of length $k$.
It is guaranteed that the following conditions hold for these 2 arrays:
- $l_1 = 1$;
- $r_k = n$;
- $l_i \le r_i$, for each positive integer $i$ such ... | Observation 1: if we look at [$l_i, r_i$] as subsegments for each $i$, notice that they are disjoint, and that two modifications do not interfere with each other if they are from different subsegments. Because of this observation we can basically treat subsegments as separate test cases. Now, without loss of generality... | [
"data structures",
"greedy"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; //number of test cases
cin >> t;
while(t--){
int n, k; //read the input
cin >> n >> k;
string s;
cin >> s;
int a[k]; int b[k];
for(int i=0; i< k; i++){cin >> a[i]; a[i]--;}
for(int i=0; i< k; i++){cin >> b[i]; b[i]--;}
int q;
cin ... |
1878 | E | Iva & Pav | Iva and Pav are a famous Serbian competitive programming couple. In Serbia, they call Pav "papuca" and that's why he will make all of Iva's wishes come true.
Iva gave Pav an array $a$ of $n$ elements.
Let's define $f(l, r) = a_l \ \& \ a_{l+1} \ \& \dots \& \ a_r$ (here $\&$ denotes the bitwise AND operation).
\text... | We can, for each bit, calculate the prefix sums of the array ($pref[i][j]$ is the number of occurrences of the $j$-th bit in the first $i$ elements of the array. This can be calculated in $\mathcal{O}(n \log(max(a)))$. We know that if $pref[r][j] - pref[l - 1][j] = r - l + 1$, then the $j$-th bit is present in all elem... | [
"binary search",
"bitmasks",
"data structures",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N =200003;
const int bits=30;
int pref[N][bits];
int a[N];
void Buildprefix(int n){ //Builds the prefix sums for each bit
for(int i=0; i< n; i++){
for(int j=0; j<30; j++){
if(a[i]&(1<<j)){
pref[i+1]... |
1878 | F | Vasilije Loves Number Theory | Vasilije is a smart student and his discrete mathematics teacher Sonja taught him number theory very well.
He gave Ognjen a positive integer $n$.
Denote $d(n)$ as the number of positive integer divisors of $n$, and denote $gcd(a, b)$ as the largest integer $g$ such that $a$ is divisible by $g$ and $b$ is divisible by... | Answer: a solution exists if and only if $d(n)$ divides $n$. Proof: consider the prime factorization of the number $n = p_1^{\alpha_1} \cdot p_2^{\alpha_2} \cdots p_k^{\alpha_k}$, where $p_i$ represents the $i$-th prime number, and $\alpha_i$ represents the highest power of the $i$-th prime number such that $p_i^{\alph... | [
"brute force",
"math",
"number theory"
] | 1,900 | #include <bits/stdc++.h>
using ll = long long;
using namespace std;
const int N = 1000003;
map<int, int> powers; //key is a prime number, value is te highest powert
map<int, int> original_divisors; //same as map powers but isn't updated during queries, it's used to reset the powers
int smallest_divisor[N]; //precalcu... |
1878 | G | wxhtzdy ORO Tree | After (finally) qualifying for the IOI 2023, wxhtzdy was very happy, so he decided to do what most competitive programmers do: trying to guess the problems that will be on IOI. During this process, he accidentally made a problem, which he thought was really cool.
You are given a tree (a connected acyclic graph) with $... | Observation 1: it's enough to only consider $2 \cdot \log(max(a))$ vertices on the shortest path from $x$ to $y$ as candidates for $z$ for each query. Why? Because at most $\log(max(a))$ vertices can add a bit to $g(x, z)$ and we only need to maximize the number of bits in $g(x, z)$ + the number of bits in $g(y, z)$, a... | [
"binary search",
"bitmasks",
"brute force",
"data structures",
"dfs and similar",
"implementation",
"trees"
] | 2,300 | #include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
#define int long long
const int maxn = 2e5 + 69;
const int k = 19;
const int bits = 30;
vector<int> g[maxn];
int n, q, a[maxn], up[maxn][k], tin[maxn], tout[maxn], timer, d[maxn];
int r[maxn][k];
int bst[maxn][bits];
void dfs(int v, int p, v... |
1879 | A | Rigged! | Monocarp organizes a weightlifting competition. There are $n$ athletes participating in the competition, the $i$-th athlete has strength $s_i$ and endurance $e_i$. The $1$-st athlete is Monocarp's friend Polycarp, and Monocarp really wants Polycarp to win.
The competition will be conducted as follows. The jury will ch... | Let's figure out the optimal value of $w$. If $w > s_1$, then Polycarp cannot lift the barbell. If $w < s_1$, then some athletes having less strength than Polycarp might be able to lift the barbell. So the optimal value of $w$ is $s_1$. All that's left to do is check that there are such athletes who are able to lift we... | [
"greedy"
] | 800 |
#include <bits/stdc++.h>
using namespace std;
const int N = 109;
int t;
int n;
int s[N], e[N];
int main() {
cin >> t;
for (int tc = 0; tc < t; ++tc) {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> s[i] >> e[i];
}
bool ok = true;
for (int i = 1... |
1879 | B | Chips on the Board | You are given a board of size $n \times n$ ($n$ rows and $n$ colums) and two arrays of positive integers $a$ and $b$ of size $n$.
Your task is to place the chips on this board so that the following condition is satisfied for every cell $(i, j)$:
- there exists at least one chip in the same column or in the same row a... | Let's note that to maintain the rule for all cells in a certain row, one of two conditions must hold: either the row contains at least one chip, or each column contains at least one chip. Let's apply this observation to all rows of the board. If we consider all rows, this observation means that the placement of chips s... | [
"constructive algorithms",
"greedy"
] | 900 |
#include <bits/stdc++.h>
using namespace std;
using li = long long;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<li> a(n), b(n);
for (auto& x : a) cin >> x;
for (auto& x : b) cin >> x;
li mnA = *min_element(a.begin(), a... |
1879 | C | Make it Alternating | You are given a binary string $s$. A binary string is a string consisting of characters 0 and/or 1.
You can perform the following operation on $s$ any number of times \textbf{(even zero)}:
- choose an integer $i$ such that $1 \le i \le |s|$, then erase the character $s_i$.
You have to make $s$ alternating, i. e. aft... | Firstly, let's divide the string $s$ into blocks of equal characters. For example, if $s = 000100111$, then we divide it into four blocks: $000$, $1$, $00$, $111$. Let's denote the length of $i$-th block as $len_i$, and the number of blocks as $k$. To obtain the longest alternating string we can get, we should choose e... | [
"combinatorics",
"dp",
"greedy"
] | 1,300 |
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998'244'353;
void upd(int &a, int b) {
a = (a * 1LL * b) % MOD;
}
int t;
string s;
int main() {
cin >> t;
for (int tc = 0; tc < t; ++tc) {
cin >> s;
int res = 1;
int k = s.size();
int n = s.size();
for (int l = 0; l < n;... |
1879 | D | Sum of XOR Functions | You are given an array $a$ of length $n$ consisting of non-negative integers.
You have to calculate the value of $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l, r) \cdot (r - l + 1)$, where $f(l, r)$ is $a_l \oplus a_{l+1} \oplus \dots \oplus a_{r-1} \oplus a_r$ (the character $\oplus$ denotes bitwise XOR).
Since the answer can ... | Let's solve this problem for each bit separately. When we fix a bit (let's denote it as $b$), all we have to do is solve the original problem for a binary string (let's denote this string as $s$). Note that if there is an odd number of $1$'s on a segment, the value of XOR on the segment is $1$, otherwise it's $0$. So, ... | [
"bitmasks",
"combinatorics",
"divide and conquer",
"dp",
"math"
] | 1,700 |
#include <bits/stdc++.h>
using namespace std;
const int N = 300005;
const int MOD = 998244353;
int n;
int a[N];
void add(int &a, int b) {
a += b;
if (a >= MOD)
a -= MOD;
}
int sum(int a, int b) {
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
return a;
}
int m... |
1879 | E | Interactive Game with Coloring | \textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentati... | First of all, we need to analyze how we can win the game. Since we have to reach the root from a vertex with distance $d$ in exactly $d$ moves, every move we make should be towards the root. So, for each vertex, knowing the colors of adjacent edges, we need to uniquely determine the color we choose to go up. This means... | [
"brute force",
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation",
"interactive",
"trees"
] | 2,400 |
#include<bits/stdc++.h>
using namespace std;
const int N = 123;
int n;
int color[N];
int countColors[N][N];
int p[N];
vector<int> g[N];
int deg[N];
void add_edge(int x, int y)
{
g[x].push_back(y);
g[y].push_back(x);
}
bool tryTwoColors()
{
int v1 = n + 1;
int v2 = n + 2;
for(int i = 2; i <= n; i++)
{
if(p... |
1879 | F | Last Man Standing | There are $n$ heroes in a videogame. Each hero has some health value $h$ and initial armor value $a$. Let the current value of armor be $a_{\mathit{cur}}$, initially equal to $a$.
When $x$ points of damage are inflicted on a hero, the following happens: if $x < a_{\mathit{cur}}$, then $x$ gets subtracted from $a_{\mat... | For each $x$, we can easily tell how many rounds each hero will last. That is equal to $\lceil \frac{a}{x} \rceil \cdot h$. The last hero to die is the one with the maximum of this value. And the number of rounds he will be the only hero alive is determined by the second maximum. Also notice that all $x$ that are great... | [
"brute force",
"data structures",
"number theory"
] | 2,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);
while (t--){
int n;
scanf("%d", &n);
vector<int> h(n), a(n);
forn(i, n) scanf("%d", &h[i]);
forn(i, n) scanf("%d", &a[i]);
int mxa = *max_element(a.begin(), a.end()) ... |
1881 | A | Don't Try to Count | Given a string $x$ of length $n$ and a string $s$ of length $m$ ($n \cdot m \le 25$), consisting of lowercase Latin letters, you can apply any number of operations to the string $x$.
In one operation, you append the current value of $x$ to the end of the string $x$. Note that the value of $x$ will change after this.
... | Note that the answer is always not greater than $5$. When $n=1$, $m=25$, the answer is either $5$ or $-1$, it is easy to see that the answer cannot be greater. This allows us to simply iterate over the number of operations, each time checking if $s$ occurs in $x$. The time complexity of this solution is $O(2^5\cdot n \... | [
"brute force",
"strings"
] | 800 | def solve():
n, m = map(int, input().split())
x = input()
s = input()
for i in range(6):
if s in x:
print(i)
return
x += x
print(-1)
for _ in range(int(input())):
solve() |
1881 | B | Three Threadlets | Once upon a time, bartender Decim found three threadlets and a pair of scissors.
In one operation, Decim chooses any threadlet and cuts it into two threadlets, whose lengths are \textbf{positive integers} and their sum is \textbf{equal} to the length of the threadlet being cut.
For example, he can cut a threadlet of ... | If the lengths of the threadlets are equal, the answer is "YES". Otherwise, let's denote the length of the minimum threadlet as $a$. If we cut it, we will have only two operations, which is not enough. Therefore, the desired length should be equal to $a$. If $b$ or $c$ are not divisible by $a$, the answer is "NO". Othe... | [
"math"
] | 900 | for _ in range(int(input())):
a, b, c = sorted(map(int, input().split()))
if a == b and b == c:
print('YES')
elif b % a == 0 and c % a == 0 and (b // a - 1) + (c // a - 1) <= 3:
print('YES')
else:
print('NO') |
1881 | C | Perfect Square | Kristina has a matrix of size $n$ by $n$, filled with lowercase Latin letters. The value of $n$ is \textbf{even}.
She wants to change some characters so that her matrix becomes a perfect square. A matrix is called a perfect square if it remains unchanged when rotated $90^\circ$ clockwise \textbf{once}.
Here is an exa... | When rotating a matrix of size $n$ by $n$ by $90$ degrees: element $a[i][j]$ takes the position of element $a[j][n - 1 - i]$; element $a[n - 1 - j][i]$ takes the position of element $a[i][j]$; element $a[n - 1 - i][n - 1 - j]$ takes the position of element $a[n - 1 - j][i]$. In order for the matrix to be a perfect squa... | [
"brute force",
"implementation"
] | 1,200 | #include <bits/stdc++.h>
#define all(arr) arr.begin(), arr.end()
using namespace std;
const int MAXN = 1010;
int n;
string A[MAXN];
int solve() {
int ans = 0;
for (int i = 0; i * 2 < n; ++i)
for (int j = 0; j * 2 < n; ++j) {
vector<char> M {A[i][j], A[n - 1 - j][i], A[n - 1 - i][n - 1 - ... |
1881 | D | Divide and Equalize | You are given an array $a$ consisting of $n$ positive integers. You can perform the following operation on it:
- Choose a pair of elements $a_i$ and $a_j$ ($1 \le i, j \le n$ and $i \neq j$);
- Choose one of the divisors of the integer $a_i$, i.e., an integer $x$ such that $a_i \bmod x = 0$;
- Replace $a_i$ with $\fra... | To solve the problem, we need to decompose all numbers in the array into prime divisors. After that, let's calculate the number of each divisor, summarizing the decompositions of all numbers. If each divisor enters $k\cdot n$ times, where $k$ is a natural number, then we can equalize all the numbers in the array: we wi... | [
"math",
"number theory"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
const int maxv = 1000000;
void add_divs(int x, map<int, int>&divs){
int i = 2;
while(i * i <= x){
while (x % i == 0){
divs[i]++;
x /= i;
}
i++;
}
if(x > 1) divs[x]++;
}
bool solve(){
int n;
cin >> n;
... |
1881 | E | Block Sequence | Given a sequence of integers $a$ of length $n$.
A sequence is called beautiful if it has the form of a series of blocks, each starting with its length, i.e., first comes the length of the block, and then its elements. For example, the sequences [$\textcolor{red}{3},\ \textcolor{red}{3},\ \textcolor{red}{4},\ \textcolo... | Let's use the dynamic programming approach: let $dp[i]$ be the number of operations required to make the segment from $i$ to $n$ beautiful. There are two possible ways to achieve this: Remove the element at position $i$ and make the segment from $i + 1$ to $n$ beautiful, then $dp[i] = dp[i+1] + 1$; Make the segment fro... | [
"dp"
] | 1,500 | def solve():
n = int(input())
a = [int(x) for x in input().split()]
dp = [n + 1] * n
def get(pos):
if pos > n:
return n + 1
if pos == n:
return 0
return dp[pos]
dp[-1] = 1
for i in range(n - 2, -1, -1):
dp[i] = min(dp[i + 1] + 1, get(i + ... |
1881 | F | Minimum Maximum Distance | You have a tree with $n$ vertices, some of which are marked. A tree is a connected undirected graph without cycles.
Let $f_i$ denote the maximum distance from vertex $i$ to any of the marked vertices.
Your task is to find the minimum value of $f_i$ among all vertices.
For example, in the tree shown in the example, v... | Let's run a breadth-first traversal from any labeled vertex $v_1$ and find the farthest other labeled vertex $v_2$ from it. Then we run a traversal from $v_2$ and find the farthest labeled vertex $v_3$ from it (it may coincide with $v_1$). Then the answer is $\lceil \frac{d}{2} \rceil$, where $d$ is the distance betwee... | [
"dfs and similar",
"dp",
"graphs",
"shortest paths",
"trees"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
int n;
vector<vector<int>> g;
void dfs(int v, int p, vector<int> &d){
if(p != -1) d[v] = d[p] + 1;
for(int u: g[v]){
if(u != p){
dfs(u, v, d);
}
}
}
int main(){
int t;
cin>>t;
while(t--){
int k;
cin>>n>>k;
g.assign(n, vector<int>(0));
vector<in... |
1881 | G | Anya and the Mysterious String | Anya received a string $s$ of length $n$ brought from Rome. The string $s$ consists of lowercase Latin letters and at first glance does not raise any suspicions. An instruction was attached to the string.
Start of the instruction.
A palindrome is a string that reads the same from left to right and right to left. For ... | Let's make two obvious observations about palindromes of length at least $2$: Palindromes of length $2n$ contain a palindrome substring $[n \ldots n + 1]$; Palindromes of length $2n + 1$ contain a palindrome substring $[n \ldots n + 2]$. Now we need to learn how to track only palindromes of length $2$ and $3$. Let's ca... | [
"binary search",
"data structures"
] | 2,000 | #include <iostream>
#include <string>
#include <set>
#include <cstring>
#define int long long
using namespace std;
const int L = 26;
const int MAXN = 200200;
int n, m;
string s;
set<int> M2, M3;
int fen[MAXN];
void fenadd(int i, int x) {
x = (x % L + L) % L;
for (; i < n; i |= (i + 1))
fen[i] = (fen[i] + x) % L... |
1882 | A | Increasing Sequence | You are given a sequence $a_{1}, a_{2}, \ldots, a_{n}$. A sequence $b_{1}, b_{2}, \ldots, b_{n}$ is called good, if it satisfies all of the following conditions:
- $b_{i}$ is a positive integer for $i = 1, 2, \ldots, n$;
- $b_{i} \neq a_{i}$ for $i = 1, 2, \ldots, n$;
- $b_{1} < b_{2} < \ldots < b_{n}$.
Find the mini... | Greedy solution. Continue constructing $b$ as small as possible. If $a_{1} = 1$, $b_{1} = 2$. Else, $b_{1} = 1$. For $i \ge 2$, if $a_{i} = b_{i-1} + 1$, $b_{i} = b_{i-1} + 2$. Else, $b_{i} = b_{i-1} + 1$. $b_{n}$ calculated by this process is the answer. Time complexity is $\mathcal{O}(n)$ per test case. | [
"greedy"
] | 800 | null |
1882 | B | Sets and Union | You have $n$ sets of integers $S_{1}, S_{2}, \ldots, S_{n}$. We call a set $S$ attainable, if it is possible to choose some (possibly, none) of the sets $S_{1}, S_{2}, \ldots, S_{n}$ so that $S$ is equal to their union$^{\dagger}$. If you choose none of $S_{1}, S_{2}, \ldots, S_{n}$, their union is an empty set.
Find ... | Sorry for everyone who got FSTs :( We tried our best to make pretest strong especially for this problem, but it wasn't enough. Denote $T = S_{1} \cup S_{2} \cup \cdots \cup S_{n}$, then $S \subset T$. Since $S \neq T$, $i \in T$ and $i \notin S$ for some $i$. Given an integer $i$, can you calculate the maximum size of ... | [
"bitmasks",
"brute force",
"constructive algorithms",
"greedy"
] | 1,300 | null |
1882 | C | Card Game | There are $n$ cards stacked in a deck. Initially, $a_{i}$ is written on the $i$-th card from the top. The value written on a card does not change.
You will play a game. Initially your score is $0$. In each turn, you can do \textbf{one} of the following operations:
- Choose an odd$^{\dagger}$ positive integer $i$, whi... | Fix the topmost card you'll pick in the initial deck. Let's denote $i$-th card in the initial deck as card $i$. Let the topmost card you'll pick in the initial deck as card $i$. For all cards under card $i$ in initial deck, you can choose all and only cards with the positive value at odd index. Proof: Here is the strat... | [
"brute force",
"greedy"
] | 1,500 | null |
1882 | D | Tree XOR | You are given a tree with $n$ vertices labeled from $1$ to $n$. An integer $a_{i}$ is written on vertex $i$ for $i = 1, 2, \ldots, n$. You want to make all $a_{i}$ equal by performing some (possibly, zero) spells.
Suppose you root the tree at some vertex. On each spell, you can select any vertex $v$ and any non-negati... | Try to solve the problem for single root. For any vertex $v$ which isn't the root, denote $par_{v}$ as the parent of $v$. Then value of $a_{v} \oplus a_{par_{v}}$ only changes if we perform the operation on $v$. Since $x_{1} \oplus x_{2} \oplus \cdots \oplus x_{m} \le x_{1} + x_{2} + \cdots + x_{m}$ for any numbers $x_... | [
"bitmasks",
"dfs and similar",
"dp",
"greedy",
"trees"
] | 1,900 | null |
1882 | E1 | Two Permutations (Easy Version) | \textbf{This is the easy version of the problem. The difference between the two versions is that you do not have to minimize the number of operations in this version. You can make hacks only if both versions of the problem are solved.}
You have two permutations$^{\dagger}$ $p_{1}, p_{2}, \ldots, p_{n}$ (of integers $1... | Let's think two permutations independently. The goal is to make sequence of operations for each permutation which have same parity of number of operations. Try to sort single permutation of length $N$, using at most $3N$ operations. It is always possible. If the permutation's length is odd, you can perform operation at... | [
"brute force",
"constructive algorithms",
"greedy",
"number theory"
] | 2,400 | null |
1882 | E2 | Two Permutations (Hard Version) | \textbf{This is the hard version of the problem. The difference between the two versions is that you have to minimize the number of operations in this version. You can make hacks only if both versions of the problem are solved.}
You have two permutations$^{\dagger}$ $p_{1}, p_{2}, \ldots, p_{n}$ (of integers $1$ to $n... | The solution is completely different from E1. A brilliant idea is required. Maybe the fact that checker is implemented in linear time might be the hint. Find a way changing the operation to 'swap'. Add an extra character. Add an extra character '$X$' in front of the permutation. Here position of $X$ won't be changed by... | [
"constructive algorithms"
] | 3,100 | null |
1883 | A | Morning | You are given a four-digit pin code consisting of digits from $0$ to $9$ that needs to be entered. Initially, the cursor points to the digit $1$. In one second, you can perform exactly one of the following two actions:
- Press the cursor to display the current digit,
- Move the cursor to any adjacent digit.
The image... | Let's represent our pin code as a set of digits $a$, $b$, $c$, $d$. Replace all $0$s with $10$ and notice that the answer is equal to $|a - 1|$ + $|b - a|$ + $|c - b|$ + $|d - c|$. | [
"math"
] | 800 | null |
1883 | B | Chemistry | You are given a string $s$ of length $n$, consisting of lowercase Latin letters, and an integer $k$.
You need to check if it is possible to remove \textbf{exactly} $k$ characters from the string $s$ in such a way that the remaining characters can be rearranged to form a palindrome. Note that you can reorder the remain... | Let's remember under what conditions we can rearrange the letters of a word to form a palindrome. This can be done if the number of letters with odd occurrences is not greater than $1$. In our problem, it is sufficient to check that the number of letters with odd occurrences (denoted as $x$) is not greater than $k + 1$... | [
"strings"
] | 900 | null |
1883 | C | Raspberries | You are given an array of integers $a_1, a_2, \ldots, a_n$ and a number $k$ ($2 \leq k \leq 5$). In one operation, you can do the following:
- Choose an index $1 \leq i \leq n$,
- Set $a_i = a_i + 1$.
Find the minimum number of operations needed to make the product of all the numbers in the array $a_1 \cdot a_2 \cdot... | Let's notice that if $k = 2, 3, 5$, since these are prime numbers, the product of the numbers will be divisible by $k$ if any number in the array is divisible by $k$. From this, we can conclude that it is advantageous to perform operations only on one number. If $k = 4$, we have several cases, and we need to take the m... | [
"dp",
"math"
] | 1,000 | null |
1883 | D | In Love | Initially, you have an empty multiset of segments. You need to process $q$ operations of two types:
- $+$ $l$ $r$ — Add the segment $(l, r)$ to the multiset,
- $-$ $l$ $r$ — Remove \textbf{exactly} one segment $(l, r)$ from the multiset. It is guaranteed that this segment exists in the multiset.
After each operation,... | Let's learn how to solve the problem for a fixed set. The claim is that if the answer exists, we can take the segment with the minimum right boundary and the maximum left boundary (let's denote these boundaries as $r$ and $l$). Therefore, if $r < l$, it is obvious that this pair of segments is suitable for us. Otherwis... | [
"data structures",
"greedy"
] | 1,500 | null |
1883 | E | Look Back | You are given an array of integers $a_1, a_2, \ldots, a_n$. You need to make it non-decreasing with the minimum number of operations. In one operation, you do the following:
- Choose an index $1 \leq i \leq n$,
- Set $a_i = a_i \cdot 2$.
An array $b_1, b_2, \ldots, b_n$ is non-decreasing if $b_i \leq b_{i+1}$ for all... | Let's come up with a naive solution - we could go from left to right and multiply the element at index $i$ by $2$ until it is greater than or equal to the previous element. But this solution will take a long time, as the numbers can become on the order of $2^n$ during the operations. Let's not explicitly multiply our n... | [
"bitmasks",
"greedy"
] | 1,700 | null |
1883 | F | You Are So Beautiful | You are given an array of integers $a_1, a_2, \ldots, a_n$. Calculate the number of \textbf{subarrays} of this array $1 \leq l \leq r \leq n$, such that:
- The array $b = [a_l, a_{l+1}, \ldots, a_r]$ occurs in the array $a$ as a \textbf{subsequence} exactly once. In other words, there is exactly one way to select a se... | Note that a subarray suits us if $a_l$ is the leftmost occurrence of the number $a_l$ in the array and $a_r$ is the rightmost occurrence of the number $a_r$ in the array. Let's create an array $b_r$ filled with zeros and set $b_r = 1$ if $a_r$ is the rightmost occurrence of the number $a_r$ in the array (this can be do... | [
"data structures"
] | 1,400 | null |
1883 | G2 | Dances (Hard Version) | \textbf{This is the hard version of the problem. The only difference is that in this version $m \leq 10^9$.}
You are given two arrays of integers $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$. Before applying any operations, you can reorder the elements of each array as you wish. Then, in one operation, you will... | Let's learn how to solve the problem for a fixed value of $a_1$. Notice that we can perform a binary search on the answer. Let's learn how to check if we can remove $k$ elements from both arrays such that $a_i < b_i$ holds for the remaining elements. It will be advantageous to sort both arrays, remove the $k$ largest e... | [
"binary search",
"greedy",
"sortings",
"two pointers"
] | 1,900 | null |
1884 | A | Simple Design | A positive integer is called $k$-beautiful, if the digit sum of the decimal representation of this number is divisible by $k^{\dagger}$. For example, $9272$ is $5$-beautiful, since the digit sum of $9272$ is $9 + 2 + 7 + 2 = 20$.
You are given two integers $x$ and $k$. Please find the smallest integer $y \ge x$ which ... | Let $y$ be the answer to the problem. Note that $y - x \leq 18$ and the problem can be solved by brute force. We will prove this fact. If the difference between two numbers is greater than $18$, then there will definitely be a sequence of $10$ numbers where only the last digit differs. Therefore, if the sum of the digi... | [
"brute force",
"greedy",
"math"
] | 800 | null |
1884 | B | Haunted House | You are given a number in binary representation consisting of exactly $n$ bits, possibly, with leading zeroes. For example, for $n = 5$ the number $6$ will be given as $00110$, and for $n = 4$ the number $9$ will be given as $1001$.
Let's fix some integer $i$ such that $1 \le i \le n$. In one operation you can swap an... | In order for a number to be divisible by $2^i$, the last $i$ bits of its binary representation must be equal to $0$. For convenience, let's reverse the binary representation of the number so that our operations aim to zero out the first $i$ bits. Let $zero$ be the number of bits equal to $0$ in the original string. If ... | [
"binary search",
"greedy",
"math",
"two pointers"
] | 1,100 | null |
1884 | C | Medium Design | The array $a_1, a_2, \ldots, a_m$ is initially filled with zeroes. You are given $n$ pairwise distinct segments $1 \le l_i \le r_i \le m$. You have to select an arbitrary subset of these segments (in particular, you may select an empty set). Next, you do the following:
- For each $i = 1, 2, \ldots, n$, if the segment ... | Let $x$ be the position of the maximum element in the array $a$ in the optimal answer. Notice that in this case, we can select all the segments where $l \leq x \leq r$, because if the position of the minimum element is outside of this segment, we increase the answer by $+1$, and if it is inside, we do not worsen the an... | [
"brute force",
"data structures",
"dp",
"greedy",
"sortings"
] | 1,700 | null |
1884 | D | Counting Rhyme | You are given an array of integers $a_1, a_2, \ldots, a_n$.
A pair of integers $(i, j)$, such that $1 \le i < j \le n$, is called good, if there \textbf{does not exist} an integer $k$ ($1 \le k \le n$) such that $a_i$ is divisible by $a_k$ and $a_j$ is divisible by $a_k$ at the same time.
Please, find the number of g... | Note that if $a_i$ is divisible by $a_k$ and $a_j$ is divisible by $a_k$, then $\gcd(a_i, a_j)$ is divisible by $a_k$. Let's calculate the number of pairs from the array for each $g$, such that the $\gcd$ is equal to $g$. To do this, we will create $dp_g$ - the number of pairs in the array with $\gcd$ equal to $g$. For... | [
"dp",
"math",
"number theory"
] | 2,100 | null |
1884 | E | Hard Design | Consider an array of integers $b_0, b_1, \ldots, b_{n-1}$. Your goal is to make all its elements equal. To do so, you can perform the following operation several (possibly, zero) times:
- Pick a pair of indices $0 \le l \le r \le n-1$, then for each $l \le i \le r$ increase $b_i$ by $1$ (i. e. replace $b_i$ with $b_i ... | Let's learn how to solve a problem for a given array. Notice that we want to make all elements equal to the maximum value in the array. For convenience, let's solve a similar problem that is easier to implement. We'll create an array $b_i = \max(a) - a_i$. Then, instead of performing an addition operation, we'll perfor... | [
"greedy",
"implementation",
"math"
] | 2,800 | null |
1886 | A | Sum of Three | Monocarp has an integer $n$.
He wants to represent his number as a sum of three \textbf{distinct} positive integers $x$, $y$, and $z$. Additionally, Monocarp wants none of the numbers $x$, $y$, and $z$ to be divisible by $3$.
Your task is to help Monocarp to find any valid triplet of distinct positive integers $x$, $... | You can solve this problem with some case analysis, but I'll describe another solution. Suppose we want to iterate on every $x$, and then on every $y$, and then calculate $z$ and check that everything's OK. Obviously, this is too slow. But we can speed this up: we don't have to iterate on all possible values of $x$ and... | [
"brute force",
"constructive algorithms",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int n;
inline void read() {
cin >> n;
}
inline void solve() {
for (int x = 1; x <= 20; x++) {
for (int y = 1; y <= 20; y++) {
if (x + y >= n || x == y) continue;
int z = n - x - y;
if (z == x || z == y) continue;
if (x % 3 == 0... |
1886 | B | Fear of the Dark | Monocarp tries to get home from work. He is currently at the point $O = (0, 0)$ of a two-dimensional plane; his house is at the point $P = (P_x, P_y)$.
Unfortunately, it is late in the evening, so it is very dark. Monocarp is afraid of the darkness. He would like to go home along a path illuminated by something.
Than... | There are only two major cases: both points $O$ and $P$ lie inside the same circle, or the point $O$ lies inside one of the circles and $P$ lies inside the other circle. Let's denote the distance between the points $P$ and $Q$ as $d(P, Q)$. Let's look at the first case, when the points $O$ and $P$ lie inside the circle... | [
"binary search",
"geometry",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
auto dist = [](int x1, int y1, int x2, int y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
};
int t;
cin >> t;
while (t--) {
int px, py, ax, ay, bx, by;
cin >> px >> py >> ax >> ay >> bx >> by;
double pa = dist(... |
1886 | C | Decreasing String | Recall that string $a$ is lexicographically smaller than string $b$ if $a$ is a prefix of $b$ (and $a \ne b$), or there exists an index $i$ ($1 \le i \le \min(|a|, |b|)$) such that $a_i < b_i$, and for any index $j$ ($1 \le j < i$) $a_j = b_j$.
Consider a sequence of strings $s_1, s_2, \dots, s_n$, each consisting of ... | Let's analyze in which order the characters should be removed from the given string. Suppose we want to remove a character so that the resulting string is lexicographically smallest. We can show that the best option is to find the leftmost pair of adjacent characters $S_i, S_{i+1}$ such that $S_i > S_{i+1}$: removing $... | [
"implementation",
"strings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
const int N = 200000;
int t;
int main() {
cin >> t;
for (int tc = 0; tc < t; ++tc) {
string s;
long long pos;
cin >> s >> pos;
--pos;
int curLen = s.size();
vector <char> st;
bool ok = pos < curLen... |
1886 | D | Monocarp and the Set | Monocarp has $n$ numbers $1, 2, \dots, n$ and a set (initially empty). He adds his numbers to this set $n$ times in some order. During each step, he adds a new number (which has not been present in the set before). In other words, the sequence of added numbers is a permutation of length $n$.
Every time Monocarp adds a... | The key observation to this problem is that it's much easier to consider the process in reverse. Suppose Monocarp has a set of integers $1, 2, \dots, n$, and starts removing elements from it one by one. During the $i$-th deletion, if $s_{n-i}$ is <, he removes the minimum element; if $s_{n-i}$ is >, he removes the maxi... | [
"combinatorics",
"data structures",
"math"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 300009;
int bp(int a, int n) {
int res = 1;
while(n > 0) {
if (n & 1)
res = (res * 1LL * a) % MOD;
a = (a * 1LL * a) % MOD;
n >>= 1;
}
return res;
}
int n, m;
string s;
int inv... |
1886 | E | I Wanna be the Team Leader | Monocarp is a team leader in a massive IT company.
There are $m$ projects his team of programmers has to complete, numbered from $1$ to $m$. The $i$-th project has a difficulty level $b_i$.
There are $n$ programmers in the team, numbered from $1$ to $n$. The $j$-th programmer has a stress tolerance level $a_j$.
Mono... | Let's start by arranging the programmers in the increasing order of their stress tolerance level. Not obvious what it achieves at first, but it always helps to sort, doesn't it? Now, consider some assignment of the programmers to the projects. Notice how it's always optimal to take the suffix of the programmers. If the... | [
"bitmasks",
"constructive algorithms",
"dp",
"greedy",
"math",
"sortings",
"two pointers"
] | 2,400 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int n, m;
scanf("%d%d", &n, &m);
vector<int> a(n), b(m);
forn(i, n) scanf("%d", &a[i]);
forn(i, m) scanf("%d", &b[i]);
vector<int> ord(n);
iota(ord.begin(), ord.end(), 0);
sort(ord.begin(), ord.e... |
1886 | F | Diamond Theft | Monocarp is the most famous thief in Berland. This time, he decided to steal two diamonds. Unfortunately for Monocarp, there are $n$ cameras monitoring the diamonds. Each camera has two parameters, $t_i$ and $s_i$. The first parameter determines whether the camera is monitoring the first diamond only ($t_i=1$), the sec... | In this editorial, we will denote the number of cameras of type $i$ as $k_i$. Without loss of generality, we can assume that our sequence of actions will look as follows: hack all cameras of type $1$, some cameras of type $2$ and all cameras of type $3$ in some order (let's call it the first block of actions); steal th... | [
"data structures",
"greedy"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
const int N = 3003;
int n;
int k[4];
vector<int> a[4];
struct segtree {
int sz;
int tot;
vector<int> t, p;
segtree(int sz) : sz(sz) {
tot = 0;
t = vector<int>(4 * sz);
p = vector<int>(4 * sz);
build(0, 0, sz);
}
void build(int v, in... |
1887 | B | Time Travel | Berland is a country with ancient history, where roads were built and destroyed for centuries. It is known that there always were $n$ cities in Berland. You also have records of $t$ key moments in the history of the country, numbered from $1$ to $t$. Each record contains a list of \textbf{bidirectional} roads between s... | Let $d_{v}$ denote the minimum number of moves required to reach vertex $v$. Initially, $d_{v} = \infty$ for all vertices except $1$, where $d_{1} = 0$. We will gradually mark the vertices for which we know the optimal answer. Similar to Dijkstra's algorithm, at each iteration, we will select the vertex $v$ with the mi... | [
"binary search",
"graphs",
"shortest paths"
] | 1,900 | null |
1887 | C | Minimum Array | Given an array $a$ of length $n$ consisting of integers. Then the following operation is sequentially applied to it $q$ times:
- Choose indices $l$ and $r$ ($1 \le l \le r \le n$) and an integer $x$;
- Add $x$ to all elements of the array $a$ in the segment $[l, r]$. More formally, assign $a_i := a_i + x$ for all $l \... | Let $u$ be a difference array of an array $v$, i.e. $u_0 = v_0$, $u_i = v_i - v_{i-1}$ for all $i \ge 1$. Note that minimizing an array is equivalent to minimizing its difference array. Let's see how the difference array changes: when asked, adding the number $add$ on the segment $[l; r]$ only 2 elements are updated in... | [
"binary search",
"brute force",
"constructive algorithms",
"data structures",
"greedy",
"hashing",
"two pointers"
] | 2,400 | null |
1887 | D | Split | Let's call an array $b_1, b_2, \ldots, b_m$ ($m \ge 2$) good if it can be split into two parts such that all elements in the left part are strictly smaller than all elements in the right part. In other words, there must exist an index $1 \le i < m$ such that every element from $b_1, \ldots, b_i$ is strictly smaller tha... | Let's fix element $i$. Let's find all intervals $[l, r]$ for which this element can be the maximum in the left part of a valid cut. Let $x_l$ be the nearest element to the left of $i$ greater than $a_i$, and $x_r$ be the nearest element to the right of $i$ greater than $a_i$. Then, for $i$ to be the maximum element in ... | [
"binary search",
"data structures",
"divide and conquer",
"dsu",
"math",
"trees",
"two pointers"
] | 2,700 | null |
1887 | E | Good Colorings | Alice suggested Bob to play a game. Bob didn't like this idea, but he couldn't refuse Alice, so he asked you to write a program that would play instead of him.
The game starts with Alice taking out a grid sheet of size $n \times n$, the cells of which are \textbf{initially not colored}. After that she colors some $2n$... | Let's consider a bipartite graph with $n$ rows and $n$ columns. The cells will correspond to the edges. According to the problem statement, we need to find a pair of rows $\{ u, v \}$ and a pair of columns $\{ x, y \}$ such that cells $(u,x), (u,y), (v, x), (v, y)$ have different colors. Notice that in graph terms, thi... | [
"binary search",
"constructive algorithms",
"graphs",
"interactive"
] | 3,100 | null |
1887 | F | Minimum Segments | You had a sequence $a_1, a_2, \ldots, a_n$ consisting of integers from $1$ to $n$, not necessarily distinct. For some unknown reason, you decided to calculate the following characteristic of the sequence:
- Let $r_i$ ($1 \le i \le n$) be the smallest $j \ge i$ such that on the subsegment $a_i, a_{i+1}, \ldots, a_j$ al... | Let's consider a sequence $a_1, a_2, \ldots, a_n$. Let $nxt_i$ be the smallest $j > i$ such that $a_j = a_i$, or $n+1$ if such $j$ does not exist. It is claimed that the characteristic of the sequence can be uniquely determined from the values of $nxt_1, nxt_2, \ldots, nxt_n$. Let's write down the conditions on $nxt_i$... | [
"constructive algorithms"
] | 3,400 | null |
1889 | A | Qingshan Loves Strings 2 | Qingshan has a string $s$ which only contains $0$ and $1$.
A string $a$ of length $k$ is good if and only if
- $a_i \ne a_{k-i+1}$ for all $i=1,2,\ldots,k$.
{\small For Div. 2 contestants, note that this condition is different from the condition in problem B.}
For example, $10$, $1010$, $111000$ are good, while $11... | First, there is no solution when the number of 0's and 1's are different. Otherwise, the construction follows: If the $s_1 \ne s_n$ now, we can ignore $s_1$ and $s_n$, and consider $s_{2..n-1}$ as a new $s$. If $s$ is empty, the algorithm ends. Now $s_1=s_n$. If they are 1, insert 01 to the front; otherwise, insert 01 ... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,300 | #include <bits/stdc++.h>
bool ok(std::string s) {
for (size_t i = 1; i < s.length(); ++i)
if (s[i] == s[i - 1])
return false;
return true;
}
std::string s;
void solve() {
int n; std::cin >> n;
std::cin >> s;
int cnt0 = 0, cnt1 = 0;
for (int i = 0; i < s.length(); ++i) {
cnt0 += s[i] == '0';... |
1889 | B | Doremy's Connecting Plan | Doremy lives in a country consisting of $n$ cities numbered from $1$ to $n$, with $a_i$ people living in the $i$-th city. It can be modeled as an undirected graph with $n$ nodes.
Initially, there are no edges in the graph. Now Doremy wants to make the graph connected.
To do this, she can add an edge between $i$ and $... | First, we can just solve $c=1$. Because letting $a_i' = \frac{a_i}{c}$ reduces $c\ne 1$ to $c=1$. For convenience, let $s_i = \sum a_j$, where $j$ is currently connected with $i$. Let's see if you can add an edge between $i$ and $j$ ($i \ne 1, j \ne 1$) right now, it means $s_i + s_j \ge i \cdot j \ge i+j$ This actuall... | [
"constructive algorithms",
"greedy",
"math",
"sortings"
] | 1,700 | #include<bits/stdc++.h>
using i64 = long long;
using namespace std;
const int N = 5e5 + 7;
int T, n, C, p[N]; i64 a[N];
void solve () {
cin >> n >> C;
for (int i = 1; i <= n; i ++) cin >> a[i];
iota (p + 1, p + n + 1, 1);
sort (p + 1, p + n + 1, [&] (const int &u, const int &v) {
return 1ll * u * C - a[u] < 1ll *... |
1889 | C1 | Doremy's Drying Plan (Easy Version) | \textbf{The only differences between the two versions of this problem are the constraint on $k$, the time limit and the memory limit. You can make hacks only if all versions of the problem are solved.}
Doremy lives in a rainy country consisting of $n$ cities numbered from $1$ to $n$.
The weather broadcast predicted t... | We consider a brute force solution first. At the beginning, we calculate number of intervals that cover position $i$ for each $i=1,2,\ldots,n$ by prefix sum. Now we can know the number uncovered positions. Let it be $A$. Then we need to calculate the number of new uncovered position after removing two intervals. Let it... | [
"brute force",
"data structures",
"dp",
"greedy",
"sortings"
] | 2,000 | null |
1889 | C2 | Doremy's Drying Plan (Hard Version) | \textbf{The only differences between the two versions of this problem are the constraint on $k$, the time limit and the memory limit. You can make hacks only if all versions of the problem are solved.}
Doremy lives in a rainy country consisting of $n$ cities numbered from $1$ to $n$.
The weather broadcast predicted t... | $k$ is bigger in this version. However, it is still small, which leads us to a DP approach. Let $dp_{i,j}$ be the number of uncovered positions in $[1,i]$, and the last uncovered position is $i$, and the number of deleted intervals is $j$. For transition, we need to get all the intervals that covers position $i$. We've... | [
"data structures",
"dp"
] | 2,600 | #include <bits/stdc++.h>
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define LL long long
const int MX = 2e5 + 23;
const int INF = 1e9;
void chkmax(int &x, int y) {
x = std::max(x, y);
}
struct Interval {
int l, r;
} I[MX];
bool cmp(int x, int y) {
return I[x].l > I[y].l;
}
std::vector<int> add[MX], del... |
1889 | D | Game of Stacks | You have $n$ stacks $r_1,r_2,\ldots,r_n$. Each stack contains some positive integers ranging from $1$ to $n$.
Define the following functions:
\begin{verbatim}
function init(pos):
stacks := an array that contains n stacks r[1], r[2], ..., r[n]
return get(stacks, pos)
function get(stacks, pos):
if stacks[pos] is empty... | Let's first consider an easy version of the problem: what if there is only one element in each stack? Let $p_i$ be the element in stack $i$. If we link $i \to p_i$, these edges will form several directed pseudo trees. For each pseudo tree, there is a cycle. It's not hard to find that those cycles actually can be ignore... | [
"brute force",
"dfs and similar",
"graphs",
"implementation",
"trees"
] | 3,000 | #include<stack>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=100005;
stack<int>s[maxn];
int re[maxn],st[maxn],vis[maxn],tp;
int dfs(int u){
if(re[u])
return re[u];
if(s[u].empty())
return u;
if(vis[u]){
st[tp+1]=0;
... |
1889 | E | Doremy's Swapping Trees | Consider two undirected graphs $G_1$ and $G_2$. Every node in $G_1$ and in $G_2$ has a label. Doremy calls $G_1$ and $G_2$ similar if and only if:
- The labels in $G_1$ are distinct, and the labels in $G_2$ are distinct.
- The set $S$ of labels in $G_1$ coincides with the set of labels in $G_2$.
- For every pair of tw... | We can construct a new directed graph, where we can consider each edge in $T_1$ and $T_2$ as a node. Let the node representing the edge $(u,v)$ in tree $T_i$ be $N(u,v,T_i)$. For each node $N(u,v,T_1)$, let the simple path between $u$ and $v$ in $T_2$ be $(u_1,v_1),\dots,(u_m,v_m)$, and for all $1\le i\le m$ we add an ... | [
"dfs and similar",
"graphs",
"trees"
] | 3,500 | #include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=100005;
struct Edge{
int v,nt;
Edge(int v=0,int nt=0):
v(v),nt(nt){}
}eG[maxn*160];
int hdG[maxn*40],numG;
void qwqG(int u,int v){
eG[++numG]=Edge(v,hdG[u]);hdG[u]=numG;
}
i... |
1889 | F | Doremy's Average Tree | Doremy has a rooted tree of size $n$ whose root is vertex $r$. Initially there is a number $w_i$ written on vertex $i$. Doremy can use her power to perform this operation \textbf{at most} $k$ times:
- Choose a vertex $x$ ($1 \leq x \leq n$).
- Let $s = \frac{1}{|T|}\sum_{i \in T} w_i$ where $T$ is the set of all verti... | Let $f_{i,j}$ be the array with the smallest lexicographical order if you do at most $j$ operations in the subtree of $i$ (only consisting of the elements in the subtree of $i$). Let $g_{i,j}$ be the first position $k$ where $f_{i,j}[k]$ is different from $f_{i,j-1}[k]$. To get the answer, we just need to calculate $g_... | [
"data structures",
"dp",
"greedy",
"trees"
] | 3,500 | #include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(f=1,c=ch();c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch()){x=x*10+(c&15);}x*=f;
}
templ... |
1890 | A | Doremy's Paint 3 | An array $b_1, b_2, \ldots, b_n$ of positive integers is good if all the sums of two adjacent elements are equal to the same value. More formally, the array is good if there exists a $k$ such that $b_1 + b_2 = b_2 + b_3 = \ldots = b_{n-1} + b_n = k$.
Doremy has an array $a$ of length $n$. Now Doremy can permute its el... | Statement says $b_1 + b_2 = b_2 + b_3 = \ldots = b_{n-1} + b_n = k$. Let's write it as $b_i + b_{i+1} = b_{i+1} + b_{i+2}$. This is just $b_i = b_{i+2}$, which means the positions with the same parity should contain same value. $b_1 = b_3 = b_5 = \cdots \\ b_2 = b_4 = b_6 = \cdots$ We know that there are $\lceil \frac{... | [
"constructive algorithms"
] | 800 | // Time complexity O(nlogn) because of map
#include <bits/stdc++.h>
const int MX = 100 + 5;
int main() {
int t;
std::cin >> t;
while (t--) {
int n;
std::cin >> n;
std::map<int ,int> occ;
for (int i = 1; i <= n; ++i) {
int x;
std::cin >> x;
occ[x]++;
}
if (occ.size() >= ... |
1890 | B | Qingshan Loves Strings | Qingshan has a string $s$, while Daniel has a string $t$. Both strings only contain $0$ and $1$.
A string $a$ of length $k$ is good if and only if
- $a_i \ne a_{i+1}$ for all $i=1,2,\ldots,k-1$.
For example, $1$, $101$, $0101$ are good, while $11$, $1001$, $001100$ are not good.
Qingshan wants to make $s$ good. To ... | There are three circumstances where the answer is "Yes". $s$ is good initially. $t$ is good, $t=$ "10...01", and there is no substring 11 in $s$. $t$ is good, $t=$ "01...10", and there is no substring 00 in $s$. | [
"constructive algorithms",
"implementation"
] | 800 | #include <bits/stdc++.h>
bool ok(std::string s) {
for (size_t i = 1; i < s.length(); ++i)
if (s[i] == s[i - 1])
return false;
return true;
}
void solve() {
std::string s, t;
int l1, l2;
std::cin >> l1 >> l2;
std::cin >> s >> t;
if (ok(s)) {
std::cout << "Yes" << std::endl;
return;
}
... |
1891 | A | Sorting with Twos | You are given an array of integers $a_1, a_2, \ldots, a_n$. In one operation, you do the following:
- Choose a non-negative integer $m$, such that $2^m \leq n$.
- Subtract $1$ from $a_i$ for all integers $i$, such that $1 \leq i \leq 2^m$.
Can you sort the array in non-decreasing order by performing some number (poss... | Look at the difference array $b$. $b_i$ = $a_{i + 1} - a_{i}$ for each $i < n$. If array is sorted, its difference array has all of its elements non-negative. And operation is adding $1$ to $b_i$ if $i$ is a power of $2$. So look at difference array. If there is such $i$ that $i$ is not a power of $2$ and $b_i < 0$ the... | [
"constructive algorithms",
"sortings"
] | 800 | null |
1891 | B | Deja Vu | You are given an array $a$ of length $n$, consisting of positive integers, and an array $x$ of length $q$, also consisting of positive integers.
There are $q$ modification. On the $i$-th modification ($1 \leq i \leq q$), for each $j$ ($1 \leq j \leq n$), such that $a_j$ is divisible by $2^{x_i}$, you add $2^{x_i-1}$ t... | Let a number be divisible by $2^x$. Then after applying the operation it is no longer divisible by $2^x$. From this we can conclude that if we apply the operation $x_i$, and there is such an operation $j<i$ that $x_j < x_i$, then the operation $x_i$ does not change the array. So, it is useless and can be simply not pro... | [
"brute force",
"math",
"sortings"
] | 1,100 | null |
1891 | C | Smilo and Monsters | A boy called Smilo is playing a new game! In the game, there are $n$ hordes of monsters, and the $i$-th horde contains $a_i$ monsters. The goal of the game is to destroy all the monsters. To do this, you have two types of attacks and a combo counter $x$, initially set to $0$:
- The first type: you choose a number $i$ ... | Note that if the second operation were free, we would need $\lceil \frac{sum}{2} \rceil$ operations to get rid of all the monsters. Indeed, when we kill one monster, we can kill a second monster for free with a second operation. But the second operation is not free. So we need to use the second operation as little as p... | [
"binary search",
"constructive algorithms",
"greedy",
"sortings",
"two pointers"
] | 1,500 | null |
1891 | D | Suspicious logarithms | Let $f$($x$) be the floor of the binary logarithm of $x$. In other words, $f$($x$) is largest non-negative integer $y$, such that $2^y$ does not exceed $x$.
Let $g$($x$) be the floor of the logarithm of $x$ with base $f$($x$). In other words, $g$($x$) is the largest non-negative integer $z$, such that ${f(x)}^{z}$ doe... | First, let us estimate the number of such $i$ that $g(i) \neq g(i+1)$. This can happen if $f(i) \neq f(i+1)$, but it happens rarely (about $log n$ times). And if f(i) is equal, we can see that $f(i) \geq 2$ for any $4 \leq i$, and on a segment with equal $f(i)$ transitions will be $O(log n)$, where $n$ is the length of... | [
"binary search",
"brute force",
"math"
] | 1,900 | null |
1891 | E | Brukhovich and Exams | The boy Smilo is learning algorithms with a teacher named Brukhovich.
Over the course of the year, Brukhovich will administer $n$ exams. For each exam, its difficulty $a_i$ is known, which is a non-negative integer.
Smilo doesn't like when the greatest common divisor of the difficulties of two consecutive exams is eq... | Consider that every $a_i \neq 1$. Then, we can split our array into blocks in which each adjacent element has $gcd = 1$. For example, consider $a =$[$2$, $3$, $4$, $5$, $5$, $6$, $7$], then the array divides into two blocks: [$2$, $3$, $4$, $5$] and [$5$, $6$, $7$]. Notice that if the lenght of a block is $len$, then i... | [
"brute force",
"greedy",
"implementation",
"math",
"sortings"
] | 2,500 | null |
1891 | F | A Growing Tree | You are given a rooted tree with the root at vertex $1$, initially consisting of a single vertex. Each vertex has a numerical value, initially set to $0$. There are also $q$ queries of two types:
- The first type: add a child vertex with the number $sz + 1$ to vertex $v$, where $sz$ is the current size of the tree. Th... | Let's parse all the queries and build the tree. We can easily support subtree addition queries using segment tree on Euler tour of the tree. And when we add new vertex, we just need to set its value to zero. How to do it? You can get the value in this vertex now (by get query from the segment tree), let it be $x$. Then... | [
"data structures",
"dfs and similar",
"trees"
] | 2,000 | null |
1893 | A | Anonymous Informant | You are given an array $b_1, b_2, \ldots, b_n$.
An anonymous informant has told you that the array $b$ was obtained as follows: initially, there existed an array $a_1, a_2, \ldots, a_n$, after which the following two-component operation was performed $k$ times:
- A fixed point$^{\dagger}$ $x$ of the array $a$ was cho... | The key idea is that after applying an operation with the number $x$, the last element of the resulting array will be equal to $x$. Since after $x$ cyclic shifts, the array $[a_1, a_2, \ldots, a_n]$ will become $[a_{x+1}, \ldots, a_n, a_1, \ldots, a_x]$, and $a_x = x$, as $x$ was a fixed point of the array $a$. From th... | [
"brute force",
"dfs and similar",
"graphs",
"implementation"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
k = min(k, n);
int last = n - 1;
for (int _ = 0; _ < k; _++) {
if (a[last] > n) {
cout << "No\n";
return;
}
last += n - a[l... |
1893 | B | Neutral Tonality | You are given an array $a$ consisting of $n$ integers, as well as an array $b$ consisting of $m$ integers.
Let $\text{LIS}(c)$ denote the length of the longest increasing subsequence of array $c$. For example, $\text{LIS}([2, \underline{1}, 1, \underline{3}])$ = $2$, $\text{LIS}([\underline{1}, \underline{7}, \underli... | First observation: $\text{LIS}(c) \geq \text{LIS}(a)$. This is true because the array $c$ will always contain $a$ as a subsequence, and therefore any subsequence of $a$ as well. Notice that it is always possible to achieve $\text{LIS}(c) \leq \text{LIS}(a) + 1$. Let $b_1 \geq \ldots \geq b_m$. This can be achieved by i... | [
"constructive algorithms",
"greedy",
"sortings",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
#define pb push_back
#define all(x) x.begin(), (x).end()
#define rall(x) x.rbegin(), (x).rend()
using namespace std;
void solve() {
int n, m;
cin >> n >> m;
vector<int> a(n), b(m), c(n + m);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < m; i++) {
cin >... |
1893 | C | Freedom of Choice | Let's define the anti-beauty of a multiset $\{b_1, b_2, \ldots, b_{len}\}$ as the number of occurrences of the number $len$ in the multiset.
You are given $m$ multisets, where the $i$-th multiset contains $n_i$ distinct elements, specifically: $c_{i, 1}$ copies of the number $a_{i,1}$, $c_{i, 2}$ copies of the number ... | Note that after performing all operations, the multiset $X$ can have any integer size from $\sum l_i$ to $\sum r_i$. And the number of distinct numbers that can potentially be in $X$ is definitely not greater than $\sum n_i$. Therefore, if $\sum r_i - \sum l_i > \sum n_i$, there will always be a number from $\sum l_i$ ... | [
"brute force",
"greedy",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
#define pb push_back
#define int long long
#define all(x) x.begin(), (x).end()
using namespace std;
void solve() {
int m;
cin >> m;
vector<int> n(m), l(m), r(m);
vector<vector<int>> a(m);
vector<vector<int>> c(m);
vector<int> sumc(m);
int suml = 0, sumr = 0, sumn = 0;
for (i... |
1893 | D | Colorful Constructive | You have $n$ colored cubes, the $i$-th cube has color $a_i$.
You need to distribute all the cubes on shelves. There are a total of $m$ shelves, the $i$-th shelf can hold $s_i$ cubes. Also, $s_1 + s_2 + \ldots + s_m = n$.
Suppose on a shelf of size $k$ there are cubes of colors $c_1, c_2, \ldots, c_k$, \textbf{in this... | Let's try to come up with a condition equivalent to "A set of cubes $a_1, \ldots, a_n$ can be distributed on a shelf of size $n$ such that the colorfulness of the shelf is $\geq d$" in such a way that this condition can be conveniently combined for $m$ shelves. Let's find the necessary condition (the condition that mus... | [
"constructive algorithms",
"data structures",
"greedy"
] | 2,600 | #include <bits/stdc++.h>
#define pb push_back
#define all(x) x.begin(), (x).end()
#define rall(x) x.rbegin(), (x).rend()
using namespace std;
void solve() {
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> s(m), d(m);
for (int i = 0; i < m; i++) {... |
1893 | E | Cacti Symphony | You are given an undirected connected graph in which any two distinct simple cycles \textbf{do not have} common vertices. Since the graph can be very large, it is given to you in a compressed form: for each edge, you are also given a number $d$, which indicates that there are $d$ additional vertices on this edge.
You ... | First observation: for each edge, the vertices connected by it have different weights, otherwise the XOR of the weights of the adjacent vertices of this edge is equal to $0$. Second observation: for each edge, one of its adjacent vertices has a weight equal to the weight of the edge, since $1 \oplus 2 \oplus 3 = 0$. Fr... | [
"combinatorics",
"dfs and similar",
"dp",
"graphs"
] | 3,500 | #include <bits/stdc++.h>
typedef long long ll;
#define pb push_back
using namespace std;
const int M = 998244353;
const int N = 500500;
vector<pair<int, int>> g[N];
set<int> bridgesV[N];
bitset<N> used;
int h[N], d[N];
ll bridges = 0;
ll solo = 0;
int binpow(ll a, ll x) {
ll ans = 1;
while (x) {
if (x %... |
1894 | A | Secret Sport | Let's consider a game in which two players, A and B, participate. This game is characterized by two positive integers, $X$ and $Y$.
The game consists of sets, and each set consists of plays. In each play, \textbf{exactly one} of the players, either A or B, wins. A set ends \textbf{exactly} when one of the players reac... | The winner will be the player who wins the last play. This is true because the winner will be the player who wins the last set, because, if this were not the case, the last set would not be played. And in a set, the player who wins the last play wins, because if this were not the case, the last play would not be played... | [
"implementation",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
string s;
cin >> s;
cout << s.back() << '\n';
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
} |
1894 | B | Two Out of Three | You are given an array $a_1, a_2, \ldots, a_n$. You need to find an array $b_1, b_2, \ldots, b_n$ consisting of numbers $1$, $2$, $3$ such that \textbf{exactly two} out of the following three conditions are satisfied:
- There exist indices $1 \leq i, j \leq n$ such that $a_i = a_j$, $b_i = 1$, $b_j = 2$.
- There exist... | By symmetry, it doesn't matter which two conditions are satisfied. Let's assume it's the conditions $(1, 2)$ and $(1, 3)$. Then the elements with $b_i = 2$ and the elements with $b_i = 3$ should not intersect. Therefore, it is sufficient to assign $b_i = 2$ and $b_i = 3$ to only one element that is common with the elem... | [
"constructive algorithms"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
const int N = 100;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> b(n, 1);
vector<vector<int>> inds(N + 1);
for (int i = 0; i < n; i++) {
inds[a[i]].push_back(i);
}
int k = 2;
for ... |
1895 | A | Treasure Chest | Monocarp has found a treasure map. The map represents the treasure location as an OX axis. Monocarp is at $0$, the treasure chest is at $x$, the key to the chest is at $y$.
Obviously, Monocarp wants to open the chest. He can perform the following actions:
- go $1$ to the left or $1$ to the right (spending $1$ second)... | Let's consider two cases: If $y < x$, then the answer is $x$, because we need to reach the chest and we can take the key on the way. If $y > x$, then the optimal option would be to bring the chest directly to the key. However, this is not always possible due to the value of $k$. If $y - x \le k$, then we can do it and ... | [
"math"
] | 800 | for _ in range(int(input())):
x, y, k = map(int, input().split())
if y < x:
print(x)
else:
print(y + max(0, y - x - k)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.