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
1916
A
2023
In a sequence $a$, whose product was equal to $2023$, $k$ numbers were removed, leaving a sequence $b$ of length $n$. Given the resulting sequence $b$, find any suitable sequence $a$ and output which $k$ elements were removed from it, or state that such a sequence could not have existed. Notice that you are not guaran...
Let the product of the numbers in our array be $x$. If $2023$ is not divisible by $x$, then the answer is NO, otherwise the answer is YES. One of the ways to construct the removed numbers is as follows-$1$ number $\frac{2023}{x}$ and $k - 1$ numbers $1$.
[ "constructive algorithms", "implementation", "math", "number theory" ]
800
null
1916
B
Two Divisors
A certain number $1 \le x \le 10^9$ is chosen. You are given two integers $a$ and $b$, which are the two largest divisors of the number $x$. At the same time, the condition $1 \le a < b < x$ is satisfied. For the given numbers $a$, $b$, you need to find the value of $x$. $^{\dagger}$ The number $y$ is a divisor of th...
First case: $b \mod a = 0$. In this case, $b = a \cdot p$, where $p$ is the smallest prime factor of $x$. Then $x = b \cdot p = b \cdot \frac{b}{a}$. Second case: $b \mod a \neq 0$. In this case, $b = \frac{x}{p}, a = \frac{x}{q}$, where $p, q$ are the two smallest prime factors of $x$. Then $\gcd(a, b) = \frac{x}{p \c...
[ "constructive algorithms", "math", "number theory" ]
1,000
null
1916
C
Training Before the Olympiad
Masha and Olya have an important team olympiad coming up soon. In honor of this, Masha, for warm-up, suggested playing a game with Olya: There is an array $a$ of size $n$. Masha goes first, and the players take turns. Each move is described by the following sequence of actions: $\bullet$ If the size of the array is $...
Note that our operation replaces two numbers with their sum if they are of the same parity, and with their sum $-1$ otherwise. Therefore, the second player needs to perform as many operations as possible where an even and an odd number are used. Also, note that on any move of the second player, there will be at least o...
[ "constructive algorithms", "games", "greedy", "implementation", "math" ]
1,200
null
1916
D
Mathematical Problem
The mathematicians of the 31st lyceum were given the following task: You are given an \textbf{odd} number $n$, and you need to find $n$ different numbers that are squares of integers. But it's not that simple. Each number should have a length of $n$ (and should not have leading zeros), and the multiset of digits of al...
$1.$ For $n = 1$ the answer is $1$. $2.$ For $n = 3$ the answers are $169, 961, 196$. $3.$ How to obtain the answer for $n + 2$: multiply each number for the answer of length $n$ by $100$ (the square of the number $10$), then each number will also remain a square. And we still have 2 numbers left, let's compose them as...
[ "brute force", "constructive algorithms", "geometry", "math" ]
1,700
null
1916
E
Happy Life in University
Egor and his friend Arseniy are finishing school this year and will soon enter university. And since they are very responsible guys, they have started preparing for admission already. First of all, they decided to take care of where they will live for the long four years of study, and after visiting the university's w...
Let's initiate a tree traversal from the first vertex, in which for each color on the path from the root to the current vertex, we will maintain the nearest vertex with that color, or note that it does not exist. This can be maintained using an array that is recalculated in $O(1)$. Now, for each vertex, let's remember ...
[ "data structures", "dfs and similar", "greedy", "trees" ]
2,300
null
1916
F
Group Division
In the $31$st lyceum, there were two groups of olympiad participants: computer science and mathematics. The number of computer scientists was $n_1$, and the number of mathematicians was $n_2$. It is not known for certain who belonged to which group, but it is known that there were friendly connections between some pair...
We will generate the first set by adding one vertex at a time. Initially, we will include any vertex. Then, to add a vertex from the second set, it must not be a cut vertex and must be connected to some vertex in the first set. Statement: such a vertex always exists. Proof: No cut vertex $\Rightarrow$ such a vertex exi...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
2,900
null
1916
G
Optimizations From Chelsu
You are given a tree with $n$ vertices, whose vertices are numbered from $1$ to $n$. Each edge is labeled with some integer $w_i$. Define $len(u, v)$ as the number of edges in the simple path between vertices $u$ and $v$, and $gcd(u, v)$ as the Greatest Common Divisor of all numbers written on the edges of the simple ...
Let's perform centroid decomposition and maintain the current found answer $ans$. On vertical paths, simply find the value of the function, and we will immediately update the answer, We need to learn how to update the answer for a pair of vertical paths, combining pairs $(g_1, len_1)$ and $(g_2, len_2)$. Let's make sev...
[ "divide and conquer", "dp", "number theory", "trees" ]
3,500
null
1916
H2
Matrix Rank (Hard Version)
\textbf{This is the hard version of the problem. The only differences between the two versions of this problem are the constraints on $k$. You can make hacks only if all versions of the problem are solved.} You are given integers $n$, $p$ and $k$. $p$ is guaranteed to be a prime number. For each $r$ from $0$ to $k$, ...
Let $dp_{m,k}$ denote the number of $m \times n$ matrices whose rank is $k$. The recurrence for $dp_{m,k} = dp_{m-1,k} \cdot p^k + dp_{m-1,k-1} \cdot (p^n-p^{k-1})$ with the base case of $dp_{0,0}=1$. Consider enumerating $m \times n$ matrices $A$ such that $\text{rank}(A)=k$ based on a $(m-1) \times n$ matrix $B$ and ...
[ "combinatorics", "dp", "math", "matrices", "string suffix structures" ]
2,700
null
1917
A
Least Product
You are given an array of integers $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times (possibly zero): - Choose any element $a_i$ from the array and change its value to any integer between $0$ and $a_i$ (inclusive). More formally, if $a_i < 0$, replace $a_i$ with any integer in $[a_i, ...
What is the minimum product that we can get, when one of the given numbers is equal to $0$. How is the absolute value of the integer changed, when we apply the given operation on that integer? We can always make the product as small as possible with at most $1$ operation. First, let's find the minimum product we can ge...
[ "constructive algorithms", "math" ]
800
#include <iostream> #include <string> #include <vector> using namespace std; const int N = 105; int t, n; int a[N]; int main() { cin >> t; while (t--) { cin >> n; int c_neg = 0; int c_zero = 0; int c_pos = 0; for (int i = 1; i <= n; i++) { ...
1917
B
Erase First or Second Letter
You are given a string $s$ of length $n$. Let's define two operations you can apply on the string: - remove the first character of the string; - remove the second character of the string. Your task is to find the number of distinct \textbf{non-empty} strings that can be generated by applying the given operations on t...
Do we need to use the first operation after the second operation? Try to fix the number of the applied first operation. How many different strings can be obtained? When can two reached strings be the same? Try to consider the first occurrence for each letter. Let's first see, that applying the second operation and then...
[ "brute force", "combinatorics", "data structures", "dp", "strings" ]
1,100
#include <iostream> #include <vector> #include <string> using namespace std; int n, t; int main() { cin >> t; while (t--) { cin >> n; string s; cin >> s; vector<long long> ans(n, 0); vector<int> nxt(26, n); ans[n - 1] = 1; nxt[s[n - 1] ...
1917
C
Watering an Array
You have an array of integers $a_1, a_2, \ldots, a_n$ of length $n$. On the $i$-th of the next $d$ days you are going to do exactly one of the following two actions: - Add $1$ to each of the first $b_i$ elements of the array $a$ (i.e., set $a_j := a_j + 1$ for each $1 \le j \le b_i$). - Count the elements which are eq...
Assume that you are starting with array $a=[0, 0, \ldots, 0]$. Can your score increase by more than $1$ in this case? Note that array $a$ is non-increasing after each operation and $[1, 2, \ldots, n]$ is strictly increasing. Try fixing the first day you make reset operation on. Can your score increase by more than $n$ ...
[ "brute force", "greedy", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve() { int n, k, s; cin >> n >> k >> s; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector<int> b(k); for (int i = 0; i < k; i++) cin >> b[i]; int ans = 0; for (int i = 0; i < s && i <= 2 * n; i++) { ...
1917
D
Yet Another Inversions Problem
You are given a permutation $p_0, p_1, \ldots, p_{n-1}$ of odd integers from $1$ to $2n-1$ and a permutation $q_0, q_1, \ldots, q_{k-1}$ of integers from $0$ to $k-1$. An array $a_0, a_1, \ldots, a_{nk-1}$ of length $nk$ is defined as follows: \begin{center} $a_{i \cdot k+j}=p_i \cdot 2^{q_j}$ for all $0 \le i < n$ a...
How to count the number of inversions in the permutation of length $n$ in $\mathcal{O}(n \log n)$? Consider two arrays $x_1, x_2, \ldots, x_k$ and $\alpha x_1, \alpha x_2, \ldots, \alpha x_k$ for some positive $\alpha$. How does the number of inversions in one of them correspond to the number of inversions in the other...
[ "combinatorics", "data structures", "dp", "implementation", "math", "number theory" ]
2,300
const int MOD = 998'244'353; #include <bits/stdc++.h> using namespace std; void add(int pos, long long val, vector<long long>& fenw) { while (pos < fenw.size()) { fenw[pos] += val; fenw[pos] = (fenw[pos] % MOD + MOD) % MOD; pos |= (pos + 1); } } long long get(int pos, vector<...
1917
E
Construct Matrix
You are given an \textbf{even} integer $n$ and an integer $k$. Your task is to construct a matrix of size $n \times n$ consisting of numbers $0$ and $1$ in such a way that the following conditions are true, or report that it is impossible: - the sum of all the numbers in the matrix is exactly $k$; - the bitwise $XOR$ ...
Does solution exist when $k$ is odd? What can you understand when $k = 2$ or $k = n^2 - 2$? How can we easily fill the matrix with $1$s, such that all problem conditions are satisfied when $k$ is divisible by $4$? How will you solve the problem when $k = 6$? Try to merge ideas of Hint $3$ and Hint $4$ together. First, ...
[ "constructive algorithms", "math" ]
2,500
/////////////////////////////// _LeMur_ #define _CRT_SECURE_NO_WARNINGS #include <unordered_map> #include <unordered_set> #include <algorithm> #include <iostream> #include <cstring> #include <cassert> #include <complex> #include <chrono> #include <random> #include <bitset> #include <cstdio> #include <vector> #includ...
1917
F
Construct Tree
You are given an array of integers $l_1, l_2, \dots, l_n$ and an integer $d$. Is it possible to construct a tree satisfying the following three conditions? - The tree contains $n + 1$ nodes. - The length of the $i$-th edge is equal to $l_i$. - The (weighted) diameter of the tree is equal to $d$.
If a solution exists, then we can always construct a tree containing a diameter and edges incident to the vertex $v$ ($v$ is from diameter). Try to consider the maximum of the given lengths. What can we say when there exist two lengths with a sum greater than $d$? If a solution exists, then there should be a subset of ...
[ "bitmasks", "constructive algorithms", "dp", "trees" ]
2,500
/////////////////////////////// _LeMur_ #define _CRT_SECURE_NO_WARNINGS #include <unordered_map> #include <unordered_set> #include <algorithm> #include <iostream> #include <cstring> #include <cassert> #include <complex> #include <chrono> #include <random> #include <bitset> #include <cstdio> #include <vector> #includ...
1918
A
Brick Wall
A brick is a strip of size $1 \times k$, placed horizontally or vertically, where $k$ can be an arbitrary number that is at least $2$ ($k \ge 2$). A brick wall of size $n \times m$ is such a way to place several bricks inside a rectangle $n \times m$, that all bricks lie either horizontally or vertically in the cells,...
The stability of the wall is the number of horizontal bricks minus the number of vertical bricks. Since a horizontal brick has a length of at least $2$, no more than $\lfloor\frac{m}{2}\rfloor$ horizontal bricks can be placed in one row. Therefore, the answer does not exceed $n \cdot \lfloor\frac{m}{2}\rfloor$. On the ...
[ "constructive algorithms", "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int64_t n,m; cin >> n >> m; cout << n*(m/2) << '\n'; } return 0; }
1918
B
Minimize Inversions
You are given two permutations $a$ and $b$ of length $n$. A permutation is an array of $n$ elements from $1$ to $n$ where all elements are distinct. For example, an array [$2,1,3$] is a permutation, but [$0,1$] and [$1,3,1$] aren't. You can (as many times as you want) choose two indices $i$ and $j$, then swap $a_i$ wi...
Notice that by performing operations of the form: swap $a_i$ with $a_j$ and $b_i$ with $b_j$ simultaneously, we can rearrange the array $a$ how we want, but the same $a_i$ will correspond to the same $b_i$ (because we are changing both $a_i$ and $b_i$ at the same time). Let's sort the array $a$ using these operations. ...
[ "constructive algorithms", "data structures", "greedy", "implementation", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int n; cin >> n; pair<int,int> ab[n]; for(int i = 0;i < n;++i) { cin >> ab[i].first; } for(...
1918
C
XOR-distance
You are given integers $a$, $b$, $r$. Find the smallest value of $|({a \oplus x}) - ({b \oplus x})|$ among all $0 \leq x \leq r$. $\oplus$ is the operation of bitwise XOR, and $|y|$ is absolute value of $y$.
Let's consider the bitwise representation of numbers $a$, $b$, $x$. Let's look at any $2$ bits at the same position in $a$ and $b$, if they are the same, then regardless of what is in $x$ on this position, the number $|({a \oplus x}) - ({b \oplus x})|$ will have a $0$ at this position. Therefore, it is advantageous to ...
[ "bitmasks", "greedy", "implementation", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; const int maxb = 60; bool get_bit(int64_t a,int i) { return a&(1ll<<i); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int64_t a,b,r; cin >> a >> b >> r; int64_t x = 0; ...
1918
D
Blocking Elements
You are given an array of numbers $a_1, a_2, \ldots, a_n$. Your task is to block some elements of the array in order to minimize its cost. Suppose you block the elements with indices $1 \leq b_1 < b_2 < \ldots < b_m \leq n$. Then the cost of the array is calculated as the maximum of: - the sum of the blocked elements,...
Let's do a binary search. Suppose we know that the minimum possible cost is at least $l$ and not greater than $r$. Let's choose $m = (l+r)/2$. We need to learn how to check if the answer is less than or equal to $m$. We will calculate $dp_i$-the minimum sum of blocked elements in the prefix up to $i$ if position $i$ is...
[ "binary search", "data structures", "dp", "implementation", "two pointers" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int n; cin >> n; int64_t a[n+1]; for(int i = 0;i < n;++i) { cin >> a[i]; } int64_t l = 0,r ...
1918
E
ace5 and Task Order
This is an interactive problem! In the new round, there were $n$ tasks with difficulties from $1$ to $n$. The coordinator, who decided to have the first round with tasks in unsorted order of difficulty, rearranged the tasks, resulting in a permutation of difficulties from $1$ to $n$. After that, the coordinator challe...
Randomized solution: We will use the quicksort algorithm. We will choose a random element from the array, let its index be $i$, and we will perform $?$ $i$ until we get the answer $=$ (i.e., $x = a_i$). Now we will ask about all the other elements, thereby finding out whether they are greater than or less than $a_i$ (d...
[ "constructive algorithms", "divide and conquer", "implementation", "interactive", "probabilities", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; char query(int pos) { cout << "? " << pos << endl; char ans; cin >> ans; return ans; } void dnq(int l,int r,vector<int> pos,vector<int> & res,int pos1,int posn) { int m = (l+r)/2; vector<int> lh; vector<int> rh; for(int i = 0;i < pos.size(...
1918
F
Caterpillar on a Tree
The caterpillar decided to visit every node of the tree. Initially, it is sitting at the root. The tree is represented as a rooted tree with the root at the node $1$. Each crawl to a neighboring node takes $1$ minute for the caterpillar. And there is a trampoline under the tree. If the caterpillar detaches from the t...
First, it can be noticed that it is enough to visit all the leaves of the tree. After all, if the caterpillar skips some internal node, then it will not be able to reach the subtree of this node and visit the leaves in it. Therefore, it makes no sense to teleport to the root from a non-leaf (otherwise it would be more ...
[ "dfs and similar", "graphs", "greedy", "implementation", "sortings", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; const int maxn = 200005; int d[maxn]; int h[maxn]; int p[maxn]; vector<int> leaf_jump_gains; vector<vector<int> > children; bool comp_by_depth(int u,int v) { return d[u] < d[v]; } void sort_subtrees_by_depth(int v) { d[v] = 0; if(v == 1) h[v] = 0; ...
1918
G
Permutation of Given
You were given only one number, $n$. It didn't seem interesting to you, so you wondered if it's possible to come up with an array of length $n$ consisting of non-zero integers, such that if each element of the array is replaced by the sum of its neighbors (the elements on the ends are replaced by their only neighbors),...
At first, you can manually find answers for small values of $n$. For $n = 2, 4, 6$, the answer will be "YES" and the arrays will be $[-1, 1]$, $[-1, -2, 2, 1]$, $[-1, -2, 2, 1, -1, 1]$. It is not difficult to prove by case analysis that the answer is "NO" for $3$ and $5$. It can be assumed that for all odd $n$, the ans...
[ "constructive algorithms", "math" ]
2,700
//#pragma GCC optimize("Ofast") //#pragma GCC target("avx,avx2,sse,sse2,sse3,ssse3,sse4,abm,popcnt,mmx") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double db; typedef long double ldb; typedef complex<double> cd; constexpr ll INF64 = 9'000'000'000'000'000'000, INF32 = 2'000'000'000...
1919
A
Wallet Exchange
Alice and Bob are bored, so they decide to play a game with their wallets. Alice has $a$ coins in her wallet, while Bob has $b$ coins in his wallet. Both players take turns playing, with Alice making the first move. In each turn, the player will perform the following steps \textbf{in order}: - Choose to exchange wall...
When does the game end? Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choice...
[ "games", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if ((a + b) % 2 == 0) { cout << "Bob\n"; } else { cout << "Alice\n"; } } }
1919
B
Plus-Minus Split
You are given a string $s$ of length $n$ consisting of characters "+" and "-". $s$ represents an array $a$ of length $n$ defined by $a_i=1$ if $s_i=$ "+" and $a_i=-1$ if $s_i=$ "-". You will do the following process to calculate your penalty: - Split $a$ into non-empty arrays $b_1,b_2,\ldots,b_k$ such that $b_1+b_2+\...
Try to find a lower bound. The answer is $|a_1 + a_2 + \ldots + a_n|$. Intuitively, whenever we have a subarray with a sum equal to $0$, it will be helpful for us as its penalty will become $0$. Hence, we can split $a$ into subarrays with a sum equal to $0$ and group up the remaining elements into individual subarrays ...
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; int t; int n; string s; int main() { cin >> t; while (t--) { cin >> n; cin >> s; int sm = 0; for (int i = 0; i < n; i++) { sm += s[i] == '+' ? 1 : -1; } cout << abs(sm) << '\n'; } }
1919
C
Grouping Increases
You are given an array $a$ of size $n$. You will do the following process to calculate your penalty: - Split array $a$ into two (possibly empty) subsequences$^\dagger$ $s$ and $t$ such that every element of $a$ is either in $s$ or $t^\ddagger$. - For an array $b$ of size $m$, define the penalty $p(b)$ of an array $b$ ...
Consider a greedy approach. Consider the following approach. We start with empty arrays $b$ and $c$, then insert elements of the array $a$ one by one to the back of $b$ or $c$. Our penalty function only depends on adjacent elements, so at any point in time, we only care about the value of the last element of arrays $b$...
[ "data structures", "dp", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; const int INF = 1000000005; const int MAXN = 200005; int t; int n; int a[MAXN]; int mn[MAXN * 4], lz[MAXN * 4]; void init(int u = 1, int lo = 1, int hi = n) { mn[u] = lz[u] = 0; if (lo != hi) { int mid = lo + hi >> 1; init(u << 1, lo, mid); ...
1919
D
01 Tree
There is an edge-weighted complete binary tree with $n$ leaves. A complete binary tree is defined as a tree where every non-leaf vertex has exactly 2 children. For each non-leaf vertex, we label one of its children as the left child and the other as the right child. The binary tree has a very strange property. For eve...
What does the distance of two leaves that share the same parent look like? What happens if we delete two leaves that share the same parent? Consider two leaves that share the same parent. They will be adjacent to each other in the dfs order, so their distances will be adjacent in array $a$. Furthermore, their distances...
[ "constructive algorithms", "data structures", "dsu", "greedy", "sortings", "trees" ]
2,100
#include<bits/stdc++.h> using namespace std; const int MAXN = 200005; int n; int a[MAXN]; int prv[MAXN],nxt[MAXN]; bool in[MAXN]; bool good(int i) { if (i < 1 || i > n) { return 0; } return a[prv[i]] == a[i] - 1 || a[nxt[i]] == a[i] - 1; } int main(){ ios::sync_with_stdio(0), cin.tie(0); ...
1919
E
Counting Prefixes
There is a hidden array $a$ of size $n$ consisting of only $1$ and $-1$. Let $p$ be the prefix sums of array $a$. More formally, $p$ is an array of length $n$ defined as $p_i = a_1 + a_2 + \ldots + a_i$. Afterwards, array $p$ is sorted in non-decreasing order. For example, if $a = [1, -1, -1, 1, 1]$, then $p = [1, 0, -...
Try solving the problem if the sum of elements of array $a$ is equal to $s$. If we can do this in $O(n)$ time, we can iterate through all possible values of $p_1 \le s \le p_n$ and sum up the number of ways for each possible sum. Consider starting with array $a = [1, 1, \ldots, 1, -1, -1, \ldots, -1]$ where there are $...
[ "combinatorics", "constructive algorithms", "dp", "implementation", "math" ]
2,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 1000000005; const int MAXN = 200005; const int MOD = 998244353; ll fact[MAXN * 2], ifact[MAXN * 2]; int t; int n; int f[MAXN * 2], d[MAXN * 2]; inline ll ncr(int n, int r) { if (r < 0 || n < r) { return 0; } retu...
1919
F1
Wine Factory (Easy Version)
\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $c_i$ and $z$. You can make hacks only if both versions of the problem are solved.} There are three arrays $a$, $b$ and $c$. $a$ and $b$ have length $n$ and $c$ has length $n-1$. Let $W(a,b,c)$ denote the...
When $c_i$ and $z$ equals $10^{18}$, it means that all the remaining water will always flow into the next water tower. Hence, the answer will be the sum of $a_i$ minus the amount of water remaining at tower $n$ after the process. From hint 1, our new task now is to determine the amount of water remaining at tower $n$ a...
[ "data structures", "greedy" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll LINF = 1000000000000000005; const int MAXN = 500005; int n, q; int a[MAXN], b[MAXN]; ll c[MAXN]; ll v[MAXN], sv[MAXN]; ll mx[MAXN * 4], lz[MAXN * 4]; void init(int u = 1, int lo = 1, int hi = n) { lz[u] = 0; if (lo == hi) { ...
1919
F2
Wine Factory (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $c_i$ and $z$. You can make hacks only if both versions of the problem are solved.} There are three arrays $a$, $b$ and $c$. $a$ and $b$ have length $n$ and $c$ has length $n-1$. Let $W(a,b,c)$ denote the...
Try modelling this problem into a maximum flow problem. Try using minimum cut to find the maximum flow. Speed up finding the minimum cut using a segment tree. Consider a flow graph with $n + 2$ vertices. Let the source vertex be $s = n + 1$ and the sink vertex be $t = n + 2$. For each $i$ from $1$ to $n$, add edge $s\r...
[ "data structures", "dp", "flows", "greedy", "matrices" ]
2,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll LINF = 1000000000000000005ll; const int MAXN = 500005; int n, q; int a[MAXN], b[MAXN]; ll c[MAXN]; ll st[MAXN * 4][2][2]; void merge(int u, int lo, int hi) { int mid = lo + hi >> 1, lc = u << 1, rc = u << 1 ^ 1; for (int l = 0; l <...
1919
G
Tree LGM
In TreeWorld, there is a popular two-player game played on a tree with $n$ vertices labelled from $1$ to $n$. In this game, the tournament leaders first choose a vertex to be the root of the tree and choose another vertex (possibly the same vertex as the root) to place a coin on. Then, each player will take turns movin...
Think about how you would construct matrix $s$ if you were given the tree. If $s_{i, i} = \mathtt{0}$, what should the value of $s_{j, i}$ be for all $1\le j\le n$? For some $i$ where $s_{i, i} = \mathtt{1}$, let $Z$ be a set containing all the vertices $j$ where $s_{j, i} = \mathtt{0}$. More formally, $Z = \{j\ |\ 1\l...
[ "constructive algorithms", "divide and conquer", "games", "trees" ]
3,500
#include <bits/stdc++.h> using namespace std; const int MAXN = 5005; mt19937_64 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); int n; unsigned long long r[MAXN], hsh[MAXN], totr; string s[MAXN]; vector<pair<int, int>> ans; bool done[MAXN]; bool solve(vector<int> grp) { int pr = -1, pl...
1919
H
Tree Diameter
There is a hidden tree with $n$ vertices. The $n-1$ edges of the tree are numbered from $1$ to $n-1$. You can ask the following queries of two types: - Give the grader an array $a$ with $n - 1$ \textbf{positive} integers. For each edge from $1$ to $n - 1$, the weight of edge $i$ is set to $a_i$. Then, the grader will ...
Full solution: dario2994 The original problem allowed $5n$ type 1 queries and $n$ type 2 queries and was used as the last problem of a Div. 2 round. When we opened the round for testing, dario2994 solved the problem using $2n$ type 1 queries, and a few days later, he managed to improve his solution to use only $n$ type...
[ "interactive", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 1000000000; const int MAXN = 1000; int n; int lvl[MAXN + 5]; int pe[MAXN + 5]; vector<int> ch[MAXN + 5]; ll query(vector<int> a) { cout << "? 1"; for (int i = 1; i < n; i++) { cout << ' ' << a[i]; } cout << e...
1920
A
Satisfying Constraints
Alex is solving a problem. He has $n$ constraints on what the integer $k$ can be. There are three types of constraints: - $k$ must be \textbf{greater than or equal to} some integer $x$; - $k$ must be \textbf{less than or equal to} some integer $x$; - $k$ must be \textbf{not equal to} some integer $x$. Help Alex find ...
Suppose there are no $\neq$ constraints. How would you solve the problem? How would you then factor in the $\neq$ constraints into your solution? Let's first only consider the $\geq$ and $\leq$ constraints. The integers satisfying those two constraints will be some contiguous interval $[l, r]$. To find $[l,r]$, for eac...
[ "brute force", "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; int l = 1; int r = 1e9; int s = 0; vector<int> neq; for (int i = 0; i < n; i++){ int a, x; cin >> a >> x; if (a == 1) l = max(l, x); if (a == 2) r = ...
1920
B
Summation Game
Alice and Bob are playing a game. They have an array $a_1, a_2,\ldots,a_n$. The game consists of two steps: - First, Alice will remove \textbf{at most} $k$ elements from the array. - Second, Bob will multiply \textbf{at most} $x$ elements of the array by $-1$. Alice wants to maximize the sum of elements of the array ...
What is the optimal strategy for Bob? It is optimal for Bob to negate the $x$ largest elements of the array. So what should Alice do? It is optimal for Bob to negate the $x$ largest elements of the array. So in order to minimize the damage Bob will do, Alice should always remove some number of largest elements. To solv...
[ "games", "greedy", "math", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve(){ int n, k, x; cin >> n >> k >> x; int A[n + 1] = {}; for (int i = 1; i <= n; i++) cin >> A[i]; sort(A + 1, A + n + 1, greater<int>()); for (int i = 1; i <= n; i++) A[i] += A[i - 1]; int ans = -1e9; ...
1920
C
Partitioning the Array
Allen has an array $a_1, a_2,\ldots,a_n$. For every positive integer $k$ that is a divisor of $n$, Allen does the following: - He partitions the array into $\frac{n}{k}$ disjoint subarrays of length $k$. In other words, he partitions the array into the following subarrays: $$[a_1,a_2,\ldots,a_k],[a_{k+1}, a_{k+2},\ldo...
Try to solve the problem for just two integers $x$ and $y$. Under what $m$ are they equal (modulo $m$)? How can we use the previous hint and gcd to solve the problem? For some $x$ and $y$, let's try to find all $m$ such that $x \bmod m \equiv y \bmod m$. We can rearrange the equation into $(x-y) \equiv 0 \pmod m$. Thus...
[ "brute force", "math", "number theory" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; int A[n]; for (int &i : A) cin >> i; int ans = 0; for (int k = 1; k <= n; k++){ if (n % k == 0){ int g = 0; for (int i = 0; i + k < n; i++) g = __gcd(g, a...
1920
D
Array Repetition
Jayden has an array $a$ which is initially empty. There are $n$ operations of two types he must perform in the given order. - Jayden appends an integer $x$ ($1 \leq x \leq n$) to the end of array $a$. - Jayden appends $x$ copies of array $a$ to the end of array $a$. In other words, array $a$ becomes $[a,\underbrace{a,...
For some query try to trace your way back to where the $k$-th number was added. Here's an example of tracing back: $\underbrace{[l_1, l_2,...l_{x}]}_{\text{length } x} \underbrace{[l_1, l_2,...l_{x}]}_{\text{length } x} \underbrace{[l_1, l_2,...l_{x}]}_{\text{length } x} ... \underbrace{[l_1, \textbf{l_2},...l_{x}]}_{\...
[ "binary search", "brute force", "dsu", "implementation", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ int n, q; cin >> n >> q; ll dp[n + 1] = {}; int lstAdd[n + 1] = {}; for (int i = 1; i <= n; i++){ int a, v; cin >> a >> v; if (a == 1){ lstAdd[i] = v; dp[i] = dp[i ...
1920
E
Counting Binary Strings
Patrick calls a substring$^\dagger$ of a binary string$^\ddagger$ good if this substring contains exactly one 1. Help Patrick count the number of binary strings $s$ such that $s$ contains exactly $n$ good substrings and has no good substring of length strictly greater than $k$. Note that substrings are differentiated ...
How do you count the number of good substrings in a string? We can count the number of good substrings in a string with the counting contribution technique. Now try to solve this problem with dynamic programming. $\frac{n}{1} + \frac{n}{2} + \cdots + \frac{n}{n} = O(n\log n)$ Let's first solve the problem where we are ...
[ "combinatorics", "dp", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; const int md = 998244353; void solve(){ int n, k; cin >> n >> k; int dp[n + 1][k + 1] = {}; int ans = 0; fill(dp[0] + 1, dp[0] + k + 1, 1); for (int sum = 1; sum <= n; sum++){ for (int cur = 1; cur <= k; cur++){ for ...
1920
F1
Smooth Sailing (Easy Version)
\textbf{The only difference between the two versions of this problem is the constraint on $q$. You can make hacks only if both versions of the problem are solved.} Thomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with $n$ rows and $m$ columns. The rows are n...
Use the fact that a good some path $p$ fully encircles the island if it is impossible to go from an island cell to a cell on the border by only travelling to adjacent or diagonal cells without touching a cell on path $p$. Binary search! For each non-island cell $(i, j)$, let $d_{i,j}$ be the minimum Manhattan distance ...
[ "binary search", "brute force", "data structures", "dfs and similar", "dsu", "graphs", "shortest paths" ]
2,500
#include <bits/stdc++.h> using namespace std; const int mx = 3e5 + 5; const int diAdj[4] = {-1, 0, 1, 0}, djAdj[4] = {0, -1, 0, 1}; const int diDiag[8] = {0, 0, -1, 1, -1, -1, 1, 1}, djDiag[8] = {-1, 1, 0, 0, -1, 1, 1, -1}; int n, m, q, islandi, islandj; string A[mx]; vector<int> dist[mx]; vector<bool> reachable[mx],...
1920
F2
Smooth Sailing (Hard Version)
\textbf{The only difference between the two versions of this problem is the constraint on $q$. You can make hacks only if both versions of the problem are solved.} Thomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with $n$ rows and $m$ columns. The rows are n...
How do we check if a point is inside a polygon using a ray? If u draw line from island cell extending all the way right, an optimal round trip will cross this line an odd number of times. What can your state be? How can we simplify this problem down into finding the path that maximizes the minimum node? How can we solv...
[ "binary search", "data structures", "dsu", "geometry", "graphs", "trees" ]
3,000
#include <bits/stdc++.h> using namespace std; const int mx = 3e5 + 5, di[4] = {-1, 0, 1, 0}, dj[4] = {0, -1, 0, 1}; int n, m, q, id, linei, linej, par[mx * 4], dep[mx], up[mx * 4][21], val[mx * 4]; string A[mx]; queue<pair<int, int>> bfsQ; vector<int> dist[mx], adj[mx * 4]; vector<array<int, 3>> edges; int enc(in...
1921
A
Square
A square of positive (strictly greater than $0$) area is located on the coordinate plane, with sides parallel to the coordinate axes. You are given the coordinates of its corners, in random order. Your task is to find the area of the square.
There are many ways to solve this problem, the simplest way is as follows. Let's find the minimum and maximum coordinate $x$ among all the corners of the square. The difference of these coordinates will give us the length of the square side $d = x_{max} - x_{min}$. After that, we can calculate the area of the square as...
[ "greedy", "math" ]
800
t = int(input()) for _ in range(t): a = [[int(x) for x in input().split()] for i in range(4)] x = [p[0] for p in a] dx = max(x) - min(x) print(dx * dx)
1921
B
Arranging Cats
In order to test the hypothesis about the cats, the scientists must arrange the cats in the boxes in a specific way. Of course, they would like to test the hypothesis and publish a sensational article as quickly as possible, because they are too engrossed in the next hypothesis about the phone's battery charge. Scient...
Denote the amount of indices $i$ such that $s_i = 0$ and $f_i = 1$ as $add\_amnt$. Since it is impossible to change 0 to 1 at two different positions in one turn, the answer is not less than $add\_amnt$. Analogously, if $rmv\_amnt$ is amount of indices such that $s_i = 1$ and $f_i = 0$, the answer is not less than $rmv...
[ "greedy", "implementation" ]
800
t = int(input()) for _ in range(t): n = int(input()) start = [int(x) for x in input()] finish = [int(x) for x in input()] pairs = list(zip(start, finish)) add_amnt = sum(int(a < b) for a, b in pairs) rmv_amnt = sum(int(a > b) for a, b in pairs) print(max(add_amnt, rmv_amnt))
1921
C
Sending Messages
Stepan is a very busy person. Today he needs to send $n$ messages at moments $m_1, m_2, \dots m_n$ ($m_i < m_{i + 1}$). Unfortunately, by the moment $0$, his phone only has $f$ units of charge left. At the moment $0$, the phone is turned on. The phone loses $a$ units of charge for each unit of time it is on. Also, at ...
The most challenging part of this problem was probably carefully understanding the problem statement. The problem can be reduced to the following. There are $n$ time intervals: from 0 to $m_1$, from $m_1$ to $m_2$, ..., from $m_{n-1}$ to $m_n$. For each interval, we need to find a way to spend as little charge of the p...
[ "greedy", "math" ]
900
t = int(input()) for _ in range(t): n, f, a, b = map(int, input().split()) m = [0] + [int(x) for x in input().split()] for i in range(1, n + 1): f -= min(a * (m[i] - m[i - 1]), b) print('YES' if f > 0 else 'NO')
1921
D
Very Different Array
Petya has an array $a_i$ of $n$ integers. His brother Vasya became envious and decided to make his own array of $n$ integers. To do this, he found $m$ integers $b_i$ ($m\ge n$), and now he wants to choose some $n$ integers of them and arrange them in a certain order to obtain an array $c_i$ of length $n$. To avoid be...
Let's sort the array $a$ in ascending order, and the array $b$ in descending order. Notice that small elements of array $a$ need to be matched with large elements of array $b$ and vice versa. Thus, for some $k$, we need to take a prefix of array $b$ of length $k$ and a suffix of length $n-k$, and form array $c$ from th...
[ "data structures", "greedy", "sortings", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; struct test { void solve() { int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector<int> b(m); for (int i = 0; i < m; i++) cin >> b[i]; sort(a.begin(), a.end()); sort(b.r...
1921
E
Eat the Chip
Alice and Bob are playing a game on a checkered board. The board has $h$ rows, numbered from top to bottom, and $w$ columns, numbered from left to right. Both players have a chip each. Initially, Alice's chip is located at the cell with coordinates $(x_a, y_a)$ (row $x_a$, column $y_a$), and Bob's chip is located at $(...
First, let's note that the difference $x_b - x_a$ decreases exactly by one each (both Alice's and Bob's) turn. In the end, if one of the players was able to win, $x_b - x_a = 0$. In particular, that means that if $x_a - x_b$ is initially odd then only Alice has a chance of winning the match and vice versa. Suppose that...
[ "brute force", "games", "greedy", "math" ]
1,600
def solve(): h, w, xA, yA, xB, yB = map(int, input().split()) if (xA - xB) % 2 == 0: winner = "Bob" if xA >= xB: win = False elif yA == yB: win = True else: if yA < yB: n_turns = yB - 1 else: n_turns...
1921
F
Sum of Progression
You are given an array $a$ of $n$ numbers. There are also $q$ queries of the form $s, d, k$. For each query $q$, find the sum of elements $a_s + a_{s+d} \cdot 2 + \dots + a_{s + d \cdot (k - 1)} \cdot k$. In other words, for each query, it is necessary to find the sum of $k$ elements of the array with indices starting...
The key idea is that we know how to calculate the sum $(i - l + 1) \cdot a_i$ for $l \le i \le r$ fast - we need to calculate all prefix sums $i \cdot a_i$ and $a_i$ for $1 \le i \le k$, then take the difference between the $r$-th and $(l-1)$-th of $i \cdot a_i$ and subtract the difference between the $r$-th and $(l-1)...
[ "brute force", "data structures", "dp", "implementation", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; long long precalc[322][200322]; long long precalci[322][200322]; void solve() { int n, q; cin >> n >> q; vector<long long> a(n); int pivot = 1; while (pivot * pivot < n) { pivot++; } for (int i = 0; i < n; i++) { cin >> a[i]; ...
1921
G
Mischievous Shooter
Once the mischievous and wayward shooter named Shel found himself on a rectangular field of size $n \times m$, divided into unit squares. Each cell either contains a target or not. Shel only had a lucky shotgun with him, with which he can shoot in one of the four directions: right-down, left-down, left-up, or right-up...
First of all, notice that we can consider only the case where the triangle of affected cells is oriented left-up. To solve the remaining cases, we can solve the problem for four different board orientations and choose the maximum result from the obtained results. We will store several arrays with prefix sums: for the s...
[ "brute force", "data structures", "divide and conquer", "dp", "implementation" ]
2,200
//ciao_chill #include<bits/stdc++.h> using namespace std; #define int long long int n, m, k; vector<vector<int>> a; bool prov(int i, int j) { return 0 <= i && i < n && 0 <= j && j < m; } int ans() { int cnt = 0; int dp[n][m]; int pref[n][m]; int pref_up[n][m]; for (int i = 0; i < n; i++) { ...
1922
A
Tricky Template
You are given an integer $n$ and three strings $a, b, c$, each consisting of $n$ lowercase Latin letters. Let a template be a string $t$ consisting of $n$ lowercase and/or uppercase Latin letters. The string $s$ matches the template $t$ if the following conditions hold for all $i$ from $1$ to $n$: - if the $i$-th let...
In order for a string not to match the pattern, there must be at least one position $i$ from $1$ to $n$ where the condition doesn't hold. Let's iterate over this position and check if it is possible to pick a letter in the pattern such that $a_i$ and $b_i$ match, while $c_i$ doesn't match. If $a_i$ or $b_i$ equal $c_i$...
[ "constructive algorithms", "implementation", "strings" ]
800
for _ in range(int(input())): n = int(input()) a = input() b = input() c = input() print("YES" if any([a[i] != c[i] and b[i] != c[i] for i in range(n)]) else "NO")
1922
B
Forming Triangles
You have $n$ sticks, numbered from $1$ to $n$. The length of the $i$-th stick is $2^{a_i}$. You want to choose \textbf{exactly} $3$ sticks out of the given $n$ sticks, and form a \textbf{non-degenerate} triangle out of them, using the sticks as the sides of the triangle. A triangle is called non-degenerate if its area...
At first, let's figure out which sticks can be used to make a triangle. Let's denote the length of the longest stick as $2^{s_0}$, the shortest stick as $2^{s_2}$ and the middle stick as $2^{s_1}$ (in other words, $s$ is an array of length $3$, consisting of three sticks for a triangle, sorted in non-ascending order). ...
[ "combinatorics", "constructive algorithms", "math", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int t; int main() { cin >> t; for (int tc = 0; tc < t; ++tc) { int n; cin >> n; map<int, int> numOfLens; for (int i = 0; i < n; ++i){ int x; cin >> x; ++numOfLens[x]; } ...
1922
C
Closest Cities
There are $n$ cities located on the number line, the $i$-th city is in the point $a_i$. The coordinates of the cities are given in ascending order, so $a_1 < a_2 < \dots < a_n$. The distance between two cities $x$ and $y$ is equal to $|a_x - a_y|$. For each city $i$, let's define the \textbf{closest} city $j$ as the ...
Important observation: the answer will not change if you are allowed to move only to adjacent cities. It is true because if you move to a non-adjacent city, you can split the path to that city into parts without increasing its cost. So, the shortest way from $x$ to $y$ (consider the case $x < y$) is to move from city $...
[ "greedy", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; const int N = 200'000; const int INF = 1'000'000'009; int t; char type(const vector <int>& a, int id) { int distL = (id == 0? INF : a[id] - a[id - 1]); int distR = (id + 1 == a.size()? INF : a[id + 1] - a[id]); if(distL < distR) return 'L'; if(distL > ...
1922
D
Berserk Monsters
Monocarp is playing a computer game (yet again). Guess what is he doing? That's right, killing monsters. There are $n$ monsters in a row, numbered from $1$ to $n$. The $i$-th monster has two parameters: attack value equal to $a_i$ and defense value equal to $d_i$. In order to kill these monsters, Monocarp put a berser...
It is important to note that if during the $j$-th round the $i$-th monster did not die and none of its alive neighbors died, then there is no point in checking this monster in the $(j+1)$-th round. Therefore, we can solve the problem as follows: let's maintain a list of candidates (those who can die) for the current ro...
[ "brute force", "data structures", "dsu", "implementation", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n + 2), d(n + 2, INT_MAX); for (int i = 1; i <= n; ++i) cin >> a[i]; for (int i = 1; i <= n; ++i) cin >> d[i]; set<int> lf...
1922
E
Increasing Subsequences
Let's recall that an increasing subsequence of the array $a$ is a sequence that can be obtained from it by removing some elements without changing the order of the remaining elements, and the remaining elements are strictly increasing (i. e $a_{b_1} < a_{b_2} < \dots < a_{b_k}$ and $b_1 < b_2 < \dots < b_k$). Note that...
Let's consider one of the solutions for constructing the required array. Let array $a$ have $x$ increasing subsequences. If we add a new minimum to the end of the array, the number of increasing subsequences in the new array equals $x+1$ (since the new element does not form increasing subsequences with other elements, ...
[ "bitmasks", "constructive algorithms", "divide and conquer", "greedy", "math" ]
1,800
#include <bits/stdc++.h> using namespace std; vector<int> f(long long x) { vector<int> res; if (x == 2) { res.push_back(0); } else if (x & 1) { res = f(x - 1); res.push_back(*min_element(res.begin(), res.end()) - 1); } else { res = f(x / 2); res.push_back(*max_element(res.begin(), res.end...
1922
F
Replace on Segment
You are given an array $a_1, a_2, \dots, a_n$, where each element is an integer from $1$ to $x$. You can perform the following operation with it any number of times: - choose three integers $l$, $r$ and $k$ such that $1 \le l \le r \le n$, $1 \le k \le x$ and \textbf{each} element $a_i$ such that $l \le i \le r$ is d...
First of all, we claim the following: if you apply an operation on a segment, you may treat the resulting segment as one element (i. e. we can "merge" the elements affected by an operation into one). This is quite intuitive, but the formal proof is kinda long, so if you're not interested in it, feel free to skip the ne...
[ "dp", "graph matchings" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 111; int n, k; int a[N]; int nxtx[N][N], prvx[N][N]; int nxtnx[N][N], prvnx[N][N]; int dp1[N][N][N], dp2[N][N][N]; int calc2(int, int, int); int calc1(int l, int r, int x) { l = nxtnx[l][x], r = prvnx[r][x]; if (l > r) return 0; if (dp1[l][r][x...
1923
A
Moving Chips
There is a ribbon divided into $n$ cells, numbered from $1$ to $n$ from left to right. Each cell either contains a chip or is free. You can perform the following operation any number of times (possibly zero): choose a chip and move it to the \textbf{closest free cell to the left}. You can choose any chip that you want...
Denote the position of the leftmost chip as $l$, the position of the rightmost chip as $r$, and the number of chips as $c$. Having all chips in one block without free spaces means that we need to reach the situation when $r - l = c - 1$. Since $r - l \ge c - 1$ is always met (the situation when $r-l = c-1$ is when the ...
[ "greedy", "implementation" ]
800
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) l, r = a.index(1), n - a[::-1].index(1) - 1 c = a.count(1) print(r - l - c + 1)
1923
B
Monsters Attack!
You are playing a computer game. The current level of this game can be modeled as a straight line. Your character is in point $0$ of this line. There are $n$ monsters trying to kill your character; the $i$-th monster has health equal to $a_i$ and is initially in the point $x_i$. Every second, the following happens: -...
Let's look at monsters at distance of $1$ (i. e. in positions $1$ and $-1$). We must kill them in the $1$-st second, so their total hp (let denote it as $s_1$) should not exceed $k$. If this condition is not met, the answer is NO. Otherwise, we can say that there are $k-s_1$ bullets left unused during the first second ...
[ "dp", "greedy", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n), x(n); for (auto& it : a) cin >> it; for (auto& it : x) cin >> it; vector<long long> s(n + 1); for (int i = 0; i < n; ++i) s[abs(x[i])] += a[i]; b...
1923
C
Find B
An array $a$ of length $m$ is considered good if there exists an integer array $b$ of length $m$ such that the following conditions hold: - $\sum\limits_{i=1}^{m} a_i = \sum\limits_{i=1}^{m} b_i$; - $a_i \neq b_i$ for every index $i$ from $1$ to $m$; - $b_i > 0$ for every index $i$ from $1$ to $m$. You are given an a...
At first, let's precalculate the array of prefix sum and the number of elements equal to one on prefix (let's denote them as $sum[]$ and $cnt1[]$). More formally, $sum_i = \sum_{k=1}^{i} c_i$ and $cnt1_i = \sum_{k=1}^{i} (is\_1(c_i))$, where the function $is\_1(x)$ returns $1$ if $x$ equals $1$ and $0$ otherwise . For ...
[ "constructive algorithms", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; const int N = 300043; int t; int n, m; int a[N]; long long sum[N]; int cnt1[N]; int main() { ios_base::sync_with_stdio(false); cin >> t; for (int tc = 0; tc < t; ++tc) { cin >> n >> m; memset(sum, 0, sizeof(sum[0]) * (n + 5)); ...
1923
D
Slimes
There are $n$ slimes placed in a line. The slimes are numbered from $1$ to $n$ in order from left to right. The size of the $i$-th slime is $a_i$. Every second, the following happens: \textbf{exactly one} slime eats one of its neighbors and increases its size by the eaten neighbor's size. A slime can eat its neighbor ...
Let's solve the problem independently for each slime (denote it as $i$). After any number of seconds, the size of each slime is equal to the sum of some subarray. In order to eat the $i$-th slime, the "eater" should be its neighbor. So the eater size is equal to the sum of subarray $[j, i-1]$ for some $j < i$ or $[i + ...
[ "binary search", "constructive algorithms", "data structures", "greedy", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto& x : a) cin >> x; vector<int> ans(n, n); for (int z = 0; z < 2; ++z) { vector<long long> s(n + 1); for (int i = 0; i < n; ++i) s[i + 1] = s...
1923
E
Count Paths
You are given a tree, consisting of $n$ vertices, numbered from $1$ to $n$. Every vertex is colored in some color, denoted by an integer from $1$ to $n$. A simple path of the tree is called beautiful if: - it consists of at least $2$ vertices; - the first and the last vertices of the path have the same color; - no ot...
Let's consider what the paths passing through some vertex $v$ look like. First, root the tree arbitrarily. Let $u_1, u_2, \dots, u_k$ be the children of $v$. Then, for some color $x$, there are $\mathit{cnt}[u_1][x], \mathit{cnt}[u_2][x], \dots, \mathit{cnt}[u_k][x]$ top-level vertices in their subtrees. Top-level here...
[ "data structures", "dfs and similar", "dp", "dsu", "graphs", "trees" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n; vector<int> a; vector<vector<int>> g; long long ans; vector<map<int, int>> cnt; void dfs(int v, int p = -1){ int bst = -1; for (int u : g[v]) if (u != p){ dfs(u, v); if (bst == -1 |...
1923
F
Shrink-Reverse
You are given a binary string $s$ of length $n$ (a string consisting of $n$ characters, and each character is either 0 or 1). Let's look at $s$ as at a binary representation of some integer, and name that integer as the value of string $s$. For example, the value of 000 is $0$, the value of 01101 is $13$, "100000" is ...
In order to solve a task, let's observe and prove several facts: Fact 0: Suppose, you have two strings $s_1$ and $s_2$ without leading zeroes. Value of $s_1$ is lower than value of $s_2$ if either $|s_1| < |s_2|$ or $|s_1| = |s_2|$ and $s_1 < s_2$ lexicographically. Fact 1: There is a strategy, where you, firstly, perf...
[ "binary search", "brute force", "greedy", "hashing", "implementation", "string suffix structures", "strings" ]
2,800
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); const int MOD = int(1e9) + 7; int add(int a, int b) { a += ...
1924
A
Did We Get Everything Covered?
You are given two integers $n$ and $k$ along with a string $s$. Your task is to check whether all possible strings of length $n$ that can be formed using the first $k$ lowercase English alphabets occur as a subsequence of $s$. If the answer is NO, you also need to print a string of length $n$ that can be formed using ...
Try to build the counter-case greedily. While building the counter-case, it is always optimal to choose the first character as the one whose first index of occurrence in the given string is the highest. We will try to construct a counter-case. If we can't the answer is YES otherwise NO. We will greedily construct the c...
[ "constructive algorithms", "dp", "greedy", "shortest paths", "strings" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); int t; cin>>t; while(t--) { int n, k, m; cin>>n>>k>>m; string s; cin>>s; string res=""; bool found[k]; ...
1924
B
Space Harbour
There are $n$ points numbered $1$ to $n$ on a straight line. Initially, there are $m$ harbours. The $i$-th harbour is at point $X_i$ and has a value $V_i$. \textbf{It is guaranteed that there are harbours at the points $1$ and $n$.} There is exactly one ship on each of the $n$ points. The cost of moving a ship from its...
Segment Tree with Lazy Propogation We can maintain a segment tree of size $n$ which initially stores the cost of all the ships. Now there are 2 types of updates when we add an harbour: The ships to the left of the new harbour have their cost decreased by a fixed amount. The ships to the right of the harbour have their ...
[ "data structures", "implementation", "math", "sortings" ]
2,100
#include <bits/stdc++.h> #define int long long #define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); using namespace std; const long long N=300005; struct ap { int base, dif; }; ap add(ap a, ap b) { ap res; res.base = a.base + b.base; res.dif = a.dif + b.dif;...
1924
C
Fractal Origami
You have a square piece of paper with a side length equal to $1$ unit. In one operation, you fold each corner of the square to the center of the paper, thus forming another square with a side length equal to $\dfrac{1}{\sqrt{2}}$ units. By taking this square as a new square, you do the operation again and repeat this p...
You need more math and less paper :) The length of mountain crease lines and valley crease lines created in each operation is the same, except for the first operation. Let there be an upside of the paper and a downside of the paper, initially the upside of the paper is facing up. With a little imagination, we can see t...
[ "geometry", "math", "matrices" ]
2,400
// library link: https://github.com/manan-grover/My-CP-Library/blob/main/library.cpp #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define asc(i,a,n) for(I i=a;i<n;i++) #define dsc(i,a,n) for(I i=n-1;i>=a;i--) #def...
1924
D
Balanced Subsequences
A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not. A subsequence is a sequence that can be derived from the given sequence by deleting ze...
Consider a function $f(n, m, k)$ which returns the number of permutations such that length of longest regular bracket subsequence is at most $2 \cdot k$ where $n$ is the number of '(' and $m$ is the number of ')'. Answer to the problem is $f(n, m, k) - f(n, m, k-1)$ Now to compute $f(n, m, k)$, we can consider the foll...
[ "combinatorics", "dp", "math" ]
2,700
#include <bits/stdc++.h> #define int long long using namespace std; const long long N=4005, mod=1000000007; int power(int a, int b, int p) { if(a==0) return 0; int res=1; a%=p; while(b>0) { if(b&1) res=(1ll*res*a)%p; b>>=1; a=(1ll*a*a)%p;...
1924
E
Paper Cutting Again
There is a rectangular sheet of paper with initial height $n$ and width $m$. Let the current height and width be $h$ and $w$ respectively. We introduce a $xy$-coordinate system so that the four corners of the sheet are $(0, 0), (w, 0), (0, h)$, and $(w, h)$. The sheet can then be cut along the lines $x = 1,2,\ldots,w-1...
Can you solve it for $k=2$? Using linearity of expectation, we can say that expected number of cuts is same as sum of probability of each line being cut and for $k=2$, we need to cut the paper until we achieve a $1 \times 1$ piece of paper. Probability of each horizontal line being cut is $\dfrac {1}{count \thinspace o...
[ "combinatorics", "probabilities" ]
3,100
#include <bits/stdc++.h> #define int long long using namespace std; const long long N=2000005, mod=1000000007; int power(int a, int b, int p) { if(a==0) return 0; int res=1; a%=p; while(b>0) { if(b&1) res=(1ll*res*a)%p; b>>=1; a=(1ll*a*a)%...
1924
F
Anti-Proxy Attendance
This is an interactive problem! Mr. 1048576 is one of those faculty who hates wasting his time in taking class attendance. Instead of taking attendance the old-fashioned way, he decided to try out something new today. There are $n$ students in his class, having roll numbers $1$ to $n$. He knows that \textbf{exactly $...
$\sqrt[4]{1.5}=1.1069$ Try to do a $3\rightarrow 2$ reduction in $4$ queries. Try to do a $3\rightarrow 2$ reduction in such a way that if the middle part is eliminated $3$ queries are used otherwise $4$ queries are used. Instead of dividing the search space into $3$ equal parts, divide it into parts having size $36\%$...
[ "constructive algorithms", "dp", "interactive", "ternary search" ]
3,500
#include <bits/stdc++.h> using namespace std; void assemble(vector<int> &x,vector<int> &x1,vector<int> &x2,vector<int> &x3,string mask) { x.clear(); if(mask[0]=='1') { for(int i=0;i<x1.size();i++) x.push_back(x1[i]); } if(mask[1]=='1') { for(int i=0;i<x2.size();i++) ...
1925
A
We Got Everything Covered!
You are given two positive integers $n$ and $k$. Your task is to find a string $s$ such that all possible strings of length $n$ that can be formed using the first $k$ lowercase English alphabets occur as a subsequence of $s$. If there are multiple answers, print the one with the smallest length. If there are still mu...
The smallest length for such a string is $n\cdot k$. The smallest length possible for such a string is $n\cdot k$. To have the string $\texttt{aaa}\ldots\texttt{a}$ as a subsequence, you need to have at least $n$ characters in the string as $\texttt{a}$. Similarly for all $k$ different characters. So, that gives a tota...
[ "constructive algorithms", "greedy", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while(tc--) { int n,k; cin >> n >> k; for(int i=0;i<n;i++) for(char c='a';c<'a'+k;c++) cout << c; cout << '\n'; } }
1925
B
A Balanced Problemset?
Jay managed to create a problem of difficulty $x$ and decided to make it the second problem for Codeforces Round #921. But Yash fears that this problem will make the contest highly unbalanced, and the coordinator will reject it. So, he decided to break it up into a problemset of $n$ sub-problems such that the difficul...
$GCD(a_1,a_2,a_3,\ldots,a_n) = GCD(a_1,a_1+a_2,a_1+a_2+a_3,\ldots,a_1+a_2+a_3+\ldots+a_n)$ The maximum GCD that can be achieved is always a divisor of $x$. Let the difficulties of the $n$ sub-problems be $a_1,a_2,a_3,\ldots,a_n$. By properties of GCD, $GCD(a_1,a_2,a_3,\ldots,a_n)$ $= GCD(a_1,a_1+a_2,a_1+a_2+a_3,\ldots,...
[ "brute force", "greedy", "math", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while(tc--) { int x,n; cin >> x >> n; int ans = 1; for(int i=1;i*i<=x;i++) { if(x%i==0) { if(n<=x/i) ans=max(ans,i); ...
1925
D
Good Trip
There are $n$ children in a class, $m$ pairs among them are friends. The $i$-th pair who are friends have a friendship value of $f_i$. The teacher has to go for $k$ excursions, and for each of the excursions she chooses a pair of children randomly, equiprobably and independently. If a pair of children who are friends ...
Since expected value is linear, we can consider the contribution of initial friendship values and the contribution of increase in friendship values by repeated excursions independently. Contribution of the initial friendship values will be $\dfrac{k\times \sum_{i=1}^{n}f_i}{\binom{n}{2}}$. Now we can assume that there ...
[ "combinatorics", "dp", "math", "probabilities" ]
1,900
#include <bits/stdc++.h> #define int long long #define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); #define mod 1000000007ll using namespace std; const long long N=200005, INF=2000000000000000000; int power(int a, int b, int p) { if(b==0) return 1; if(a==0) ret...
1926
A
Vlad and the Best of Five
Vladislav has a string of length $5$, whose characters are each either $A$ or $B$. Which letter appears most frequently: $A$ or $B$?
Since the string is of an odd length, we know that the number of $\texttt{A}$s can't be equal to the number of $\texttt{B}$s. So, there is always only one possible answer. Denote variables a_counter and b_counter - the count of $\texttt{A}$s and $\texttt{B}$s in the string respectively. Let's just iterate through all 5...
[ "implementation" ]
800
#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 a = 0, b = 0; for (char c : s) { if (c == 'A') {a++;} else {b++;} } cout << (a > b ? 'A' : 'B') << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(n...
1926
B
Vlad and Shapes
Vladislav has a binary square grid of $n \times n$ cells. A triangle or a square is drawn on the grid with symbols $1$. As he is too busy being cool, he asks you to tell him which shape is drawn on the grid. - A triangle is a shape consisting of $k$ ($k>1$) consecutive rows, where the $i$-th row has $2 \cdot i-1$ cons...
Let's draw some examples on paper and notice a pattern. What we notice is that in the case of a triangle there is a row with exactly one $\texttt{1}$, but not a square. So, this is what we need to check. Iterate through all rows, and check if there is a row with exactly one $\texttt{1}$. If it was the case for at least...
[ "geometry", "implementation" ]
800
#include <iostream> #include <algorithm> #include <vector> #include <array> #include <set> #include <map> #include <queue> #include <stack> #include <list> #include <chrono> #include <random> #include <cstdlib> #include <cmath> #include <ctime> #include <cstring> #include <iomanip> #include <bitset> #include <cassert>...
1926
C
Vlad and a Sum of Sum of Digits
{\textbf{Please note that the time limit for this problem is only 0.5 seconds per test.}} Vladislav wrote the integers from $1$ to $n$, inclusive, on the board. Then he replaced each integer with the sum of its digits. What is the sum of the numbers on the board now? For example, if $n=12$ then initially the numbers...
Let's denote $S(x)$ as the sum of digits of number $x$. Since $n \leq 2 \cdot 10^5$, for a single test case, we can brute force $S(1) + S(2) + S(3) + \dots + S(n)$ and output the answer. However, since the number of test cases is large, we can't compute this value for $n$ each time. This needs a standard idea of precom...
[ "dp", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; int res[MAX]; int S(int x) { int res = 0; while (x) { res += (x % 10); x /= 10; } return res; } void solve() { int x; cin >> x; cout << res[x] << '\n'; } int main() { res[0] = 0; for (int i = 1...
1926
D
Vlad and Division
Vladislav has $n$ non-negative integers, and he wants to divide \textbf{all} of them into several groups so that in any group, any pair of numbers does not have matching bit values among bits from $1$-st to $31$-st bit (i.e., considering the $31$ least significant bits of the binary representation). For an integer $k$...
We can notice that a group contains either one or two numbers. Now, we check how many numbers we can pair together. The condition that all bits in a pair differ is equivalent to the pair resulting in a number which has all bits set as $1$ when we XOR the $2$ numbers. So, we need to see the number of pairs for which the...
[ "bitmasks", "greedy" ]
1,300
#include "bits/stdc++.h" using namespace std; void solve() { int n; cin >> n; map<int, int> cnt; int ans = 0; for(int i = 0, x; i < n; ++i) { cin >> x; if(!cnt[x]) ++ans, ++cnt[((1 << 31) - 1) ^ x]; else --cnt[x]; } cout << ans << "\n"; } main() { int t = 1; ci...
1926
E
Vlad and an Odd Ordering
Vladislav has $n$ cards numbered $1, 2, \dots, n$. He wants to lay them down in a row as follows: - First, he lays down all the odd-numbered cards from smallest to largest. - Next, he lays down all cards that are twice an odd number from smallest to largest (i.e. $2$ multiplied by an odd number). - Next, he lays down ...
Idea. The problem is very recursive; after we lay all the odd cards down, we have the same problem as we started with, but every card is multiplied by $2$. Can you solve the problem from here? We present two different solutions, which are actually the same idea, but presented a little differently, so you can understand...
[ "binary search", "bitmasks", "data structures", "dp", "implementation", "math", "number theory" ]
1,500
#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; vector<int> v; while (n) { v.push_back((n + 1) / 2); n /= 2; } int tot = 0, pow2 = 1; for (int x : v) { if (tot < k && k <= tot + x) { cout << pow2 * (2 * (...
1926
F
Vlad and Avoiding X
Vladislav has a grid of size $7 \times 7$, where each cell is colored black or white. In one operation, he can choose any cell and change its color (black $\leftrightarrow$ white). Find the minimum number of operations required to ensure that there are no black cells with four diagonal neighbors also being black. \be...
Notice that we can split the grid into two parts, red and blue, in a chessboard coloring fashion as shown, and that Xs from one color only influence cells of that color. This means that we can solve the problem for the red and blue parts independently, and combine them at the end. Let's brute force the number of cells ...
[ "bitmasks", "brute force", "dfs and similar", "dp", "implementation" ]
2,200
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; vector<pair<int, int>> odd, even; bool valid(int gc[7][7], bool odd) { for (int r = 1; r < 6; r++) { for (int c = 1; c < 6; c++) { if (gc[r][c] && ((r + c) % 2 == odd)) { if (gc[r - 1][c - 1] && gc[r ...
1926
G
Vlad and Trouble at MIT
Vladislav has a son who really wanted to go to MIT. The college dormitory at MIT (Moldova Institute of Technology) can be represented as a tree with $n$ vertices, each vertex being a room with exactly one student. A tree is a connected undirected graph with $n$ vertices and $n-1$ edges. Tonight, there are three types ...
Let's think of the problem as trying to separate some rooms(with P and possibly some C) that will hear music and the other ones(with S and possibly some C) that will not hear music. Imagine red "water" from the P nodes and blue "water" flowing from the S nodes flowing freely until hitting a thick wall. We don't want th...
[ "dfs and similar", "dp", "flows", "graphs", "greedy", "implementation", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; #define int long long #define INF (int)1e18 int n; const int N = 1e5 + 69; int dp[N][3]; string s; vector <int> adj[N]; void dfs(int u){ // dp[u][0] = nothing open // dp[u][1] = P open // dp[u][2] = S open dp[u][0] = INF; if (s[u] != 'S') d...
1927
A
Make it White
You have a horizontal strip of $n$ cells. Each cell is either white or black. You can choose a \textbf{continuous} segment of cells once and paint them all white. After this action, all the black cells in this segment will become white, and the white ones will remain white. What is the minimum length of the segment t...
To repaint all the black cells in white, it is necessary to select a segment from $l$ to $r$ that contains all the black cells. Let's choose the entire strip as a segment ($l=1, r=n$). As long as the segment starts with a white cell, it can be left unpainted, i.e., $l$ can be increased by one. Otherwise, we cannot excl...
[ "greedy", "strings" ]
800
from collections import deque def solve(): n = int(input()) s = deque(input()) while len(s) > 0 and s[0] == 'W': s.popleft() while len(s) > 0 and s[-1] == 'W': s.pop() print(len(s)) for _ in range(int(input())): solve()
1927
B
Following the String
Polycarp lost the string $s$ of length $n$ consisting of lowercase Latin letters, but he still has its trace. The trace of the string $s$ is an array $a$ of $n$ integers, where $a_i$ is the number of such indices $j$ ($j < i$) that $s_i=s_j$. For example, the trace of the string abracadabra is the array [$0, 0, 0, 1, ...
To build the desired string, we will move from left to right and add characters. In order to add a character at each step with the required number of occurrences, we will keep track of the number of times each character is added.
[ "constructive algorithms", "greedy", "strings" ]
900
def solve(): n = int(input()) a = [int(x) for x in input().split()] cnt = [0] * 26 s = '' for i in range(n): for j in range(26): if cnt[j] == a[i]: cnt[j] += 1 s += chr(97 + j) break print(s) for _ in range(int(input())): ...
1927
C
Choose the Different Ones!
Given an array $a$ of $n$ integers, an array $b$ of $m$ integers, and an even number $k$. Your task is to determine whether it is possible to choose \textbf{exactly} $\frac{k}{2}$ elements from both arrays in such a way that among the chosen elements, every integer from $1$ to $k$ is included. For example: - If $a=[...
Notice that elements with a value greater than $k$ are not relevant to us. Let's divide the values into three categories: Occurring only in array $a$; occurring only in array $b$; occurring in both arrays. The answer will be NO if any of the following conditions are met: the number of values of the first type is greate...
[ "brute force", "greedy", "math" ]
1,000
def solve(): n, m, k = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] cnt = [0] * (k + 1) for e in a: if e <= k: cnt[e] |= 1 for e in b: if e <= k: cnt[e] |= 2 c = [0] * 4 for e in cnt: ...
1927
D
Find the Different Ones!
You are given an array $a$ of $n$ integers, and $q$ queries. Each query is represented by two integers $l$ and $r$ ($1 \le l \le r \le n$). Your task is to find, for each query, two indices $i$ and $j$ (or determine that they do not exist) such that: - $l \le i \le r$; - $l \le j \le r$; - $a_i \ne a_j$. In other wo...
Before processing the requests, let's calculate the position $p_i$ of the nearest element to the left that is not equal to it (we will consider $p_1 = -1$). To do this in linear time, we will traverse the array from left to right. For the $i$-th element ($1 < i \le n$), if $a_i \ne a_{i - 1}$, then $p_i=i-1$, otherwise...
[ "binary search", "brute force", "data structures", "dp", "dsu", "greedy", "two pointers" ]
1,300
def solve(): n = int(input()) a = [int(x) for x in input().split()] p = [-1] * n for i in range(1, n): p[i] = p[i - 1] if a[i] != a[i - 1]: p[i] = i - 1 for i in range(int(input())): l, r = map(int, input().split()) l -= 1 r -= 1 if p[r] < ...
1927
E
Klever Permutation
You are given two integers $n$ and $k$ ($k \le n$), where $k$ is even. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (as $2$ appears twice in the array) and $[0,1,2]$ is also not ...
To construct a permutation, let's make an important observation: $s_i$ cannot be equal to $s_{i + 1}$ (i.e., they differ by at least $1$). Since the array $s$ can only contain two different values, it always has the form $[x, x+1, x, x+1, \dots]$ or $[x, x-1, x, x-1, \dots]$. Let's construct a permutation of the first ...
[ "constructive algorithms", "math", "two pointers" ]
1,400
def solve(): n, k = map(int, input().split()) l, r = 1, n ans = [0] * n for i in range(k): for j in range(i, n, k): if i % 2 == 0: ans[j] = l l += 1 else: ans[j] = r r -= 1 print(*ans) for _ in ...
1927
F
Microcycle
Given an undirected weighted graph with $n$ vertices and $m$ edges. There is at most one edge between each pair of vertices in the graph, and the graph does not contain loops (edges from a vertex to itself). The graph is not necessarily connected. A cycle in the graph is called simple if it doesn't pass through the sa...
Let's use the disjoint sets union (DSU). We will add edges to the DSU in descending order of weight. At the same time, we will build a graph containing only the edges that, when added to the DSU, unite different sets. We will also remember the last edge that we did not add to the graph, as it will be the lightest edge ...
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy", "implementation", "sortings", "trees" ]
1,900
#include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(time(nullptr)); const ll inf = 1e18...
1927
G
Paint Charges
A horizontal grid strip of $n$ cells is given. In the $i$-th cell, there is a paint charge of size $a_i$. This charge can be: - either used to the left — then all cells to the left at a distance less than $a_i$ (from $\max(i - a_i + 1, 1)$ to $i$ inclusive) will be painted, - or used to the right — then all cells to t...
Let's use the method of dynamic programming. Let $dp[i][j][k]$ be the minimum number of operations required for the distance from $i$ to the farthest unpainted cell on the left to be $j$, and to the nearest unpainted cell on the right to be $k$ (including itself). We will update the values forward, that is, for all rea...
[ "data structures", "dp", "greedy", "math" ]
2,300
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; vector<vector<vector<int>>> d(n + 1, vector<vec...
1928
A
Rectangle Cutting
Bob has a rectangle of size $a \times b$. He tries to cut this rectangle into two rectangles with integer sides by making a cut parallel to one of the sides of the original rectangle. Then Bob tries to form some \textbf{other} rectangle from the two resulting rectangles, and he can rotate and move these two rectangles ...
Let $a \le b$. Let's consider several cases: If $a$ is even, then we can cut the rectangle into two rectangles of size $\frac{a}{2} \times b$ and combine them into a rectangle of size $\frac{a}{2} \times 2b$, which is definitely different from $a \times b$. If $a$ is even, then we can cut the rectangle into two rectang...
[ "geometry", "math" ]
800
#include <vector> #include <iostream> #include <numeric> #include <algorithm> #include <cassert> #include <map> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if (a > b) { swap(a, b); ...
1928
B
Equalize
Vasya has two hobbies — adding permutations$^{\dagger}$ to arrays and finding the most frequently occurring element. Recently, he found an array $a$ and decided to find out the maximum number of elements equal to the same number in the array $a$ that he can obtain after adding some permutation to the array $a$. More f...
Suppose we already know the permutation that needs to be added. Let's consider the elements that will become equal after the addition. Notice that among them there cannot be equal elements, because among the numbers we are adding, there are no duplicates. Thus, only a set of numbers among which there are no equal ones,...
[ "binary search", "greedy", "sortings", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); a.resize(unique(a.begin(), a.end()) - a.begin()); int pnt = 0, ans = 0; for (int i = 0; i < a.size(); i++) ...
1928
C
Physical Education Lesson
In a well-known school, a physical education lesson took place. As usual, everyone was lined up and asked to settle in "the first–$k$-th" position. As is known, settling in "the first–$k$-th" position occurs as follows: the first $k$ people have numbers $1, 2, 3, \ldots, k$, the next $k - 2$ people have numbers $k - 1...
All numbers repeat every $2k - 2$ positions. If the boy Vasya's number is calculated to be $x$, then it can be at positions of the form $(2k - 2) \cdot t + x$, or $(2k - 2) \cdot t + k + k - x$, for some non-negative $t$. This is true for all $x$, except for $x = 1$ and $x = k$ ~--- for these values, there is only one ...
[ "brute force", "math", "number theory" ]
1,600
#include <iostream> #include <unordered_set> using namespace std; unordered_set<int> solve(int a) { unordered_set<int> candidates; for (int i = 1; i * i <= a; i++) { if (a % i == 0) { if (i % 2 == 0) // segment len should be even candidates.insert(i); if ((a / i...
1928
D
Lonely Mountain Dungeons
Once, the people, elves, dwarves, and other inhabitants of Middle-earth gathered to reclaim the treasures stolen from them by Smaug. In the name of this great goal, they rallied around the powerful elf Timothy and began to plan the overthrow of the ruler of the Lonely Mountain. The army of Middle-earth inhabitants wil...
Let's learn how to solve the problem when $n = 1$. Suppose there is only one race and the number of its representatives is $c$. Notice that for a fixed $k$, it is advantageous for us to divide the representatives of the race almost evenly into squads. If $c$ is divisible by $k$, then it is advantageous for us to take e...
[ "brute force", "data structures", "greedy", "math", "ternary search" ]
1,900
#include <iostream> #include <vector> using namespace std; using ll = long long; ll pairs(ll n, ll k){ if (n == 0 || k == 0){ return 0; } ll x = n / k; ll l = n % k; ll r = k - l; ll L = (x + 1) * l, R = x * r; return R * L + (R - x) * R / 2 + L * (L - x - 1) / 2; } void solve(){...
1928
E
Modular Sequence
You are given two integers $x$ and $y$. A sequence $a$ of length $n$ is called modular if $a_1=x$, and for all $1 < i \le n$ the value of $a_{i}$ is either $a_{i-1} + y$ or $a_{i-1} \bmod y$. Here $x \bmod y$ denotes the remainder from dividing $x$ by $y$. Determine if there exists a modular sequence of length $n$ wit...
Let's see what the answer will look like: first, there will be a prefix of the form $x, x + y, \ldots, x + k\cdot y$, and then there will be some number of blocks of the form $x \bmod y, x \bmod y + y, \ldots, x \bmod y + k \cdot y$. We can subtract the number $x \bmod y$ from all the elements of the sequence, and then...
[ "brute force", "constructive algorithms", "dp", "graphs", "greedy", "math", "number theory" ]
2,300
#include <cassert> #include <initializer_list> #include <numeric> #include <vector> #include <iostream> #include <utility> #include <stack> #include <queue> #include <set> #include <map> #include <algorithm> #include <math.h> using namespace std; #define pii pair<int, int> #define mp make_pair #define fi first #defin...
1928
F
Digital Patterns
Anya is engaged in needlework. Today she decided to knit a scarf from semi-transparent threads. Each thread is characterized by a single integer — the transparency coefficient. The scarf is made according to the following scheme: horizontal threads with transparency coefficients $a_1, a_2, \ldots, a_n$ and vertical th...
Let's assume that $a_i = a_{i+1}$ for some $1 \le i < n$, then for any $1 \le j \le m$, the cells $(i, j)$ and $(i+1, j)$ will have the same transparency. A similar statement can be made if there is an index $j$: $b_j = b_{j+1}$. Then the positions $a_i = a_{i+1}$ divide the array $a$ into \textit{blocks}, in each of w...
[ "combinatorics", "data structures", "implementation", "math" ]
2,900
#include <bits/stdc++.h> using namespace std; using ll = long long; using pi = pair<int, int>; struct SegmentTree { int n; vector<ll> t; SegmentTree(int n) : n(n), t(2*n) { } void Add(int i, ll x) { for (i += n; i != 0; i >>= 1) t[i] += x; } ll Query(int l, int r) { ll ans =...
1929
A
Sasha and the Beautiful Array
Sasha decided to give his girlfriend an array $a_1, a_2, \ldots, a_n$. He found out that his girlfriend evaluates the beauty of the array as the sum of the values $(a_i - a_{i - 1})$ for all integers $i$ from $2$ to $n$. Help Sasha and tell him the maximum beauty of the array $a$ that he can obtain, if he can rearrang...
$a_2 - a_1 + a_3 - a_2 + \ldots + a_n - a_{n - 1} = a_n - a_1$. So we just need to maximize this value, which means the answer is the maximum number in the array minus the minimum.
[ "constructive algorithms", "greedy", "math", "sortings" ]
800
null
1929
B
Sasha and the Drawing
Even in kindergarten, Sasha liked a girl. Therefore, he wanted to give her a drawing and attract her attention. As a drawing, he decided to draw a square grid of size $n \times n$, in which some cells are colored. But coloring the cells is difficult, so he wants to color as few cells as possible. But at the same time,...
Let's notice that each cell intersects with no more than two diagonals, so the answer to the problem is at least $\frac{k + 1}{2}$. Claim: Let's look at the construction where we color all cells in the first row and leave only two side cells uncolored in the last row. Then each of these cells corresponds to exactly two...
[ "constructive algorithms", "greedy", "math" ]
800
null
1929
C
Sasha and the Casino
Sasha decided to give his girlfriend the best handbag, but unfortunately for Sasha, it is very expensive. Therefore, Sasha wants to earn it. After looking at earning tips on the internet, he decided to go to the casino. Sasha knows that the casino operates under the following rules. If Sasha places a bet of $y$ coins ...
Let's notice that the condition that we can achieve arbitrarily large values means that we need to guarantee at least a $+1$ to our coins. At the very first win. In this case, we can repeat this strategy indefinitely. Also, let's notice that if we have lost a total of $z$ before, then in the next round we need to bet $...
[ "binary search", "brute force", "constructive algorithms", "games", "greedy", "math" ]
1,400
null
1929
D
Sasha and a Walk in the City
Sasha wants to take a walk with his girlfriend in the city. The city consists of $n$ intersections, numbered from $1$ to $n$. Some of them are connected by roads, and from any intersection, there is exactly one simple path$^{\dagger}$ to any other intersection. In other words, the intersections and the roads between th...
Let $dpv$ be the number of non-empty sets of vertices in the subtree rooted at $v$ such that there are no pairs of vertices in the set where one vertex is the ancestor of the other. Then $dpv = (dp_{u_1} + 1) \cdot (dp_{u_2} + 1) \cdot \ldots \cdot (dp_{u_k} + 1)$, where $u_1, \ldots, u_k$ are the children of vertex $v...
[ "combinatorics", "dp", "math", "trees" ]
1,900
null
1929
E
Sasha and the Happy Tree Cutting
Sasha was given a tree$^{\dagger}$ with $n$ vertices as a prize for winning yet another competition. However, upon returning home after celebrating his victory, he noticed that some parts of the tree were missing. Sasha remembers that he colored some of the edges of this tree. He is certain that for any of the $k$ pair...
Let's consider each edge $i$ and mark the set of pairs $S_i$ that it covers. Then the claim is: we have a total of $O(k)$ different sets. This is because we are only interested in the edges that are present in the compressed tree on these $k$ pairs of vertices. And as it is known, the number of edges in the compressed ...
[ "bitmasks", "brute force", "dfs and similar", "dp", "graphs", "greedy", "math", "trees" ]
2,300
null
1929
F
Sasha and the Wedding Binary Search Tree
Having overcome all the difficulties and hardships, Sasha finally decided to marry his girlfriend. To do this, he needs to give her an engagement ring. However, his girlfriend does not like such romantic gestures, but she does like binary search trees$^{\dagger}$. So Sasha decided to give her such a tree. After spendi...
Let's list the numbers of vertices in the order of their values. Let it be $v1, \ldots, vn$. Then it must satisfy $value{vi} \leq value{v{i + 1}}$. Then we have some segments in this order for which we do not know the values. For each segment, we know the maximum and minimum value that the values in this segment can ta...
[ "brute force", "combinatorics", "data structures", "dfs and similar", "math", "trees" ]
2,300
null
1930
A
Maximise The Score
There are $2n$ positive integers written on a whiteboard. Being bored, you decided to play a one-player game with the numbers on the whiteboard. You start with a score of $0$. You will increase your score by performing the following move \textbf{exactly} $n$ times: - Choose two integers $x$ and $y$ that are written o...
Selecting the smallest two elements on the whiteboard is a good choice in the first move. Let $b$ denote the sorted array $a$. Assume that $b$ contains only distinct elements for convenience. We prove by induction on $n$ that the maximum final score is $b_1 + b_3 + \ldots + b_{2n-1}$. For the base case $n = 1$, the fin...
[ "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; vector<ll> a(2*n); ll ans=0; for(auto &it:a){ cin>>it; } sort(a.begin(),a.end()); for(ll i=0;i<2*n;i+=2){ ans+=a[i]; } cout<<ans<<"\n"; return; } ...
1930
B
Permutation Printing
You are given a positive integer $n$. Find a permutation$^\dagger$ $p$ of length $n$ such that there do \textbf{not} exist two \textbf{distinct} indices $i$ and $j$ ($1 \leq i, j < n$; $i \neq j$) such that $p_i$ divides $p_j$ and $p_{i+1}$ divides $p_{j+1}$. Refer to the Notes section for some examples. Under the c...
For integers $x$ ($\lfloor \frac{n}{2} \rfloor < x \leq n$), there does not exist integer $y$ ($y > x$) such that $y$ is divisible by $x$. Consider the permutation $p$ such that $p=[1, n, 2, n - 1, \ldots \lceil \frac{n+1}{2} \rceil]$. It is valid. Why? We have $\max(p_a, p_{a+1}) > \lfloor \frac{n}{2} \rfloor$ for all...
[ "brute force", "constructive algorithms", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; ll l=1,r=n; for(ll i=1;i<=n;i++){ if(i&1){ cout<<l<<" "; l++; } else{ cout<<r<<" "; r--; } } cout<<"\n"; return; ...
1930
C
Lexicographically Largest
Stack has an array $a$ of length $n$. He also has an empty set $S$. Note that $S$ is \textbf{not} a multiset. He will do the following three-step operation exactly $n$ times: - Select an index $i$ such that $1 \leq i \leq |a|$. - Insert$^\dagger$ $a_i + i$ into $S$. - Delete $a_i$ from $a$. Note that the indices of a...
and satyam343 Consider an array $c$ of length $n$ such that $c_i :=$ number of indices smaller than $i$ which were chosen before index $i$. So set $S$ will be a collection of $a_i + i - c_i$ over all $1 \leq i \leq n$. Now one might wonder what type of arrays $c$ is it possible to get. First, it is easy to see that we ...
[ "binary search", "constructive algorithms", "data structures", "greedy", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; set<ll> used,not_used; vector<ll> ans; for(ll i=1;i<=n;i++){ ll x; cin>>x; x+=i; if(!used.count(x)){ not_used.insert(x); } ll cur=*(--not_used.upper_bound(x));...
1930
D1
Sum over all Substrings (Easy Version)
\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $t$ and $n$. You can make hacks only if both versions of the problem are solved.} For a binary$^\dagger$ pattern $p$ and a binary string $q$, both of length $m$, $q$ is called $p$-good if for every $i$ ($...
To find $f(s)$, we can partition $s$ into multiple independent substrings of length atmost $3$ and find best answer for them separately. There always exists a string $g$ such that: $g$ is $s-good$ there are $f(s)$ number of $\mathtt{1}$s in $g$ $g$ is of the form $b_1 + b_2 + \ldots b_q$, where $b_i$ is either equal to...
[ "brute force", "dp", "greedy", "strings" ]
1,800
#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 #define pb push_back #define mp make_pair #define nline "\n" #define f first ...
1930
D2
Sum over all Substrings (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $t$ and $n$. You can make hacks only if both versions of the problem are solved.} For a binary$^\dagger$ pattern $p$ and a binary string $q$, both of length $m$, $q$ is called $p$-good if for every $i$ ($...
We can use the idea of D1 and dynamic programming to solve in $O(n)$. Suppose $dp[i][j]$ denotes $f(s[i,j])$ for all $1 \le i \le j \le n$. Performing the transition is quite easy. If $s_i = \mathtt{1}$, $dp[i][j]=1+dp[i+3][j]$, otherwise $dp[i][j]=dp[i+1][j]$. Note that $dp[i][j] = 0$ for if $i > j$. So if we fix $j$,...
[ "bitmasks", "divide and conquer", "dp", "dsu", "greedy", "implementation", "strings" ]
2,100
#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 #define pb push_back #define mp make_pair #define nline "\n" #define f first ...
1930
E
2..3...4.... Wonderful! Wonderful!
Stack has an array $a$ of length $n$ such that $a_i = i$ for all $i$ ($1 \leq i \leq n$). He will select a positive integer $k$ ($1 \leq k \leq \lfloor \frac{n-1}{2} \rfloor$) and do the following operation on $a$ any number (possibly $0$) of times. - Select a subsequence$^\dagger$ $s$ of length $2 \cdot k + 1$ from $...
Suppose you are given some array $b$ of length $m$ and a positive integer $k$. How to check whether we can get the array $b$ if we start with an array $a$ of length $n$ such that $a_i = i$ for all $i$ ($1 \leq i \leq n$)? First of all, array $b$ should be a subsequence of $a$. Now consider an increasing array $c$ (poss...
[ "combinatorics", "dp", "math" ]
2,400
#pragma GCC optimize("O3,unroll-loops") #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_ADD=1e18; #define pb push_back #define mp make_pair #define ...
1930
F
Maximize the Difference
For an array $b$ of $m$ non-negative integers, define $f(b)$ as the \textbf{maximum} value of $\max\limits_{i = 1}^{m} (b_i | x) - \min\limits_{i = 1}^{m} (b_i | x)$ over all possible non-negative integers $x$, where $|$ is bitwise OR operation. You are given integers $n$ and $q$. You start with an empty array $a$. Pr...
For an array $b$ consiting of $m$ non-negative integers, $f(b) = \max\limits_{p=1}^{m} ( \max\limits_{i = 1}^{m} (b_i | b_p) - \min\limits_{i = 1}^{m} (b_i | b_p))$. In other, we can get the maximum possible value by choosing $x=b_p$ for some $p$ ($1 \leq p \leq m$). $f(b)$ is the maximum value of $b_i \land$ ~ $b_j$ o...
[ "bitmasks", "brute force", "dfs and similar" ]
2,700
#pragma GCC optimize("O3,unroll-loops") #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 #define pb push_back #define mp make_pair #define nline "\n" ...
1930
G
Prefix Max Set Counting
Define a function $f$ such that for an array $b$, $f(b)$ returns the array of prefix maxima of $b$. In other words, $f(b)$ is an array containing only those elements $b_i$, for which $b_i=\max(b_1,b_2,\ldots,b_i)$, without changing their order. For example, $f([3,10,4,10,15,1])=[3,10,10,15]$. You are given a tree cons...
Consider some subsequence $S$ of $[1,2, \ldots n]$ such that there exists atleast one pre-order $a$ such that $F(a)=S$. Look for some non-trivial properties about $S$. Node $S_i$ will be visited before the node $S_{i+1}$. Assume $|S|=k$. First of all, we should $S_1=1$ and $S_k = n$. There cannot exists there distinct ...
[ "data structures", "dp", "trees" ]
3,100
#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 #define pb push_back #define mp make_pair #define nline "\n" #define f first ...
1930
H
Interactive Mex Tree
This is an interactive problem. Alice has a tree $T$ consisting of $n$ nodes, numbered from $1$ to $n$. Alice will show $T$ to Bob. After observing $T$, Bob needs to tell Alice two permutations $p_1$ and $p_2$ of $[1, 2, \ldots, n]$. Then, Alice will play $q$ rounds of the following game. - Alice will create an arra...
$\operatorname{MEX}$ of the path from $u$ to $v$ will be the minimum value over all the nodes of $T$ which do not lie on the path from $u$ to $v$. $p_1$ and $p_2$ are associated with the Euler tour $p_1$ is the permutation of $[1,2, \ldots n]$ sorted in increasing order on the basis on $tin$ time observed during Euler ...
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
3,300
#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_ADD=1e18; #define pb push_back #define mp make_pair #define nline "\n" ...