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
2093
E
Min Max MEX
You are given an array $a$ of length $n$ and a number $k$. A subarray is defined as a sequence of one or more consecutive elements of the array. You need to split the array $a$ into $k$ non-overlapping subarrays $b_1, b_2, \dots, b_k$ such that the union of these subarrays equals the entire array. Additionally, you ne...
To solve the problem, we use binary search on the answer. To do this, we need to learn how to check for a given $x$ whether there exists a partition that allows achieving an answer of at least $x$. To do this, we will collect the segments one by one, that is, first we will find the minimal valid first segment, then the...
[ "binary search", "brute force", "greedy" ]
1,500
#include <bits/stdc++.h> using namespace std; vector<int> nums(2e5 + 5, 0); bool check(vector<int>& v, int k, int m) { int cnt = 0; int cur_mex = 0; for (int i = 0; i < v.size(); i++) { if (v[i] <= v.size() + 1) { nums[v[i]] = 1; } while (nums[cur_mex]) { c...
2093
F
Hackers and Neural Networks
Hackers are once again trying to create entertaining phrases using the output of neural networks. This time, they want to obtain an array of strings $a$ of length $n$. Initially, they have an array $c$ of length $n$, filled with blanks, which are denoted by the symbol $*$. Thus, if $n=4$, then initially $c=[*,*,*,*]$....
Let's call the operation of the first type a miss if after it $c_i \neq a_i$. Let $x = \max_{i = 1 \dots m}( \sum_{j=1}^{n} b_{i,j} = a_j)$. Notice that in any case we will have at least $n - x$ misses. Why? Since the positions are chosen randomly, and we need to guarantee obtaining the array $a$, we must assume the wo...
[ "bitmasks", "brute force", "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<string> a(n); for (auto &i: a) { cin >> i; } vector<vector<string>> b(m, vector<string>(n)); for (auto &ar: b) { for (auto &s: ar) { cin >> s; } } vect...
2093
G
Shorten the Array
The beauty of an array $b$ of length $m$ is defined as $\max(b_i \oplus b_j)$ among all possible pairs $1 \le i \le j \le m$, where $x \oplus y$ is the bitwise XOR of numbers $x$ and $y$. We denote the beauty value of the array $b$ as $f(b)$. An array $b$ is called beautiful if $f(b) \ge k$. Recently, Kostya bought a...
First, note that in the optimal segment $[l, r]$, the maximum value of $a_i \oplus a_j$ must be achieved precisely when $i = l$ and $j = r$. Otherwise, we can shift at least one of the boundaries, thereby reducing the length of the found segment. Our task then becomes to find the nearest pair of indices $i$ and $j$ suc...
[ "binary search", "bitmasks", "data structures", "dfs and similar", "greedy", "strings", "trees", "two pointers" ]
1,900
#include <bits/stdc++.h> using namespace std; const int LOG_X = 29; struct node { int children[2] { -1, -1 }; int last = -1; }; int find(const vector<node>& trie, int value, int border) { int res = -1; int current = 0; bool ok = true; for (int position = LOG_X; ok && position >= 0; posit...
2094
A
Trippi Troppi
Trippi Troppi resides in a strange world. The ancient name of each country consists of three strings. The first letter of each string is concatenated to form the country's modern name. Given the country's ancient name, please output the modern name.
This can be solved by printing the zero-th index of each string in sequence. For example, suppose your strings are $a$, $b$, and $c$. Then in C++, you can use cout << a[0] << b[0] << c[0] << '\n';, and similarly, in Python you can use print(a[0] + b[0] + c[0]). See your preferred language's syntax for how to obtain a g...
[ "strings" ]
800
t = int(input()) for _ in range(t): inp = input() for w in inp.split(): print(w[0],end="") print()
2094
B
Bobritto Bandito
In Bobritto Bandito's home town of residence, there are an infinite number of houses on an infinite number line, with houses at $\ldots, -2, -1, 0, 1, 2, \ldots$. On day $0$, he started a plague by giving an infection to the unfortunate residents of house $0$. Each succeeding day, the plague spreads to \textbf{exactly ...
What is the condition for $l'$ and $r'$ to be valid? We must have $r' - l' = m$ and $l\leq l' \leq 0 \leq r'\leq r$. The problem reduces to finding $l'$ and $r'$ such that $r' - l' = m$ and $l\leq l' \leq 0 \leq r'\leq r$. There are several different approaches; two are outlined below. One approach which runs in $O(1)$...
[ "brute force", "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { int n, m, l, r; cin >> n >> m >> l >> r; int diff = n - m; l = abs(l); if (l >= diff) { l -= diff; diff = 0; } else { diff -= l; l = 0; } cout << -l << " " << r - diff << '...
2094
C
Brr Brrr Patapim
Brr Brrr Patapim is trying to learn of Tiramisù's secret passcode, which is a permutation$^{\text{∗}}$ of $2\cdot n$ elements. To help Patapim guess, Tiramisù gave him an $n\times n$ grid $G$, in which $G_{i,j}$ (or the element in the $i$-th row and $j$-th column of the grid) contains $p_{i+j}$, or the $(i+j)$-th eleme...
How can we find $p_i$ for $2\leq i\leq n$? How can we find $p_i$ for $n+1\leq i\leq 2n$? For $2\leq i\leq n$, we can find $p_i$ by checking $G_{1, i-1}$. For $n+1\leq i\leq 2n$, we can find $p_i$ by checking $G_{n, i-n}$. Observe that for all $2\leq i\leq n$, we can find $p_i$ by checking $G_{1, i-1}$. Then for all $n+...
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { int n; cin >> n; vector<int> ans(2*n+1, 0); vector<bool> used(2*n+1, false); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int x; cin >> x; ans[i + j] = x; used...
2094
D
Tung Tung Sahur
You have two drums in front of you: a left drum and a right drum. A hit on the left can be recorded as "L", and a hit on the right as "R". The strange forces that rule this world are fickle: sometimes, a blow sounds once, and sometimes it sounds twice. Therefore, a hit on the left drum could have sounded as either "L"...
What would happen if $s_1$ consists of only $L$? In this case, the answer is yes if and only if $|s_1| \leq |s_2| \leq 2|s_1|$. Now try to generalize this. First, let us consider a simpler case of the problem: suppose that there is only $L$ in both $s_1$ and $s_2$. Then it is clear that the answer is yes if and only if...
[ "greedy", "strings", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { string a, b; cin >> a >> b; int n = a.size(); int m = b.size(); if (m < n || m > 2 * n || a[0] != b[0]) { cout << "NO\n"; return; } vector<int> aa, bb; int cnt = 1; for (int i = 1; i < n; ...
2094
E
Boneca Ambalabu
Boneca Ambalabu gives you a sequence of $n$ integers $a_1,a_2,\ldots,a_n$. Output the maximum value of $(a_k\oplus a_1)+(a_k\oplus a_2)+\ldots+(a_k\oplus a_n)$ among all $1 \leq k \leq n$. Note that $\oplus$ denotes the bitwise XOR operation.
Consider each bit independently. Suppose we fix $k$. How can we compute the desired sum quickly? Note that this may require preprocessing. Here, it suffices to consider each bit independently, because addition is both commutative and associative. For $0\leq i < 30$, let $cnt_i$ denote the number of elements of $a$ whic...
[ "bitmasks" ]
1,200
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { int n; cin >> n; int arr[n+1]; vector<int> cnt(30, 0); for (int i = 1; i <= n; i++) { cin >> arr[i]; for (int j = 0; j < 30; j++) { cnt[j] += ((arr[i] >> j) & 1); } } int ans =...
2094
F
Trulimero Trulicina
Trulicina gives you integers $n$, $m$, and $k$. It is guaranteed that $k\geq 2$ and $n\cdot m\equiv 0 \pmod{k}$. Output a $n$ by $m$ grid of integers such that each of the following criteria hold: - Each integer in the grid is between $1$ and $k$, inclusive. - Each integer from $1$ to $k$ appears an equal number of t...
What would happen if we tried outputting the numbers $1, \dots, k, 1, \dots, k, \dots$ in the natural reading order? For example, for $n=3$, $m=4$, and $k=6$, we would output the following: In which cases does this fail? This fails if and only if $m$ is a multiple of $k$, because we see that horizontally adjacent eleme...
[ "constructive algorithms" ]
1,600
import sys input = sys.stdin.readline for _ in range(int(input())): n,m,k = map(int,input().split()) LAST = [-1 for _ in range(m)] for i in range(n): shift = False CUR = [0 for _ in range(m)] for j in range(m): elm = ((i * m + j) % k) + 1 if elm == LAST[j]: ...
2094
G
Chimpanzini Bananini
Chimpanzini Bananini stands on the brink of a momentous battle—one destined to bring finality. For an arbitrary array $b$ of length $m$, let's denote the rizziness of the array to be $\sum_{i=1}^mb_i\cdot i=b_1\cdot 1+b_2\cdot 2+b_3\cdot 3+\ldots + b_m\cdot m$. Chimpanzini Bananini gifts you an empty array. There are...
Note that reversing an array then pushing an element to the back is similar to simply pushing an element to the front. Thus, we would like to push elements to both ends of the array. What data structure supports this? A deque is the most natural choice to use. Most languages, including C++, Java, and Python, include de...
[ "data structures", "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { int norm = 0, rev = 0; int q; cin >> q; int tot = 0; int n = 0; deque<int> qNorm, qRev; int p = 0; while (q--) { int s; cin >> s; if (s == 1) { int last = qNorm.back(); ...
2094
H
La Vaca Saturno Saturnita
Saturnita's mood depends on an array $a$ of length $n$, which only he knows the meaning of, and a function $f(k, a, l, r)$, which only he knows how to compute. Shown below is the pseudocode for his function $f(k, a, l, r)$. \begin{verbatim} function f(k, a, l, r): ans := 0 for i from l to r (inclusive): while k is div...
What must the value of $a[i]$ be in order for $k$ to change? $a[i]$ must be a divisor of $k$. Can we use this to bound the number of times $k$ changes? For each divisor $d$ of $k$, $k$ can only change once, because after the first iteration with $a[i] = d$, $k$ is no longer divisible by $d$. Thus, the number of times $...
[ "binary search", "brute force", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { map<int, vector<int>> pos; map<int, int> ptr; int n, q; cin >> n >> q; int arr[n+1]; for (int i = 1; i <= n; i++) { cin >> arr[i]; pos[arr[i]].push_back(i); ptr[arr[i]] = 0; } vector<t...
2096
A
Wonderful Sticks
You are the proud owner of $n$ sticks. Each stick has an integer length from $1$ to $n$. The lengths of the sticks are \textbf{distinct}. You want to arrange the sticks in a row. There is a string $s$ of length $n - 1$ that describes the requirements of the arrangement. Specifically, for each $i$ from $1$ to $n - 1$:...
Create your own test cases and solve them! What can you observe? What is the length of the $n$-th stick? If $s_{n - 1} = \texttt{<}$, then $a_n = 1$, because the $n$-th stick must be shorter than all the other sticks. If $s_{n - 1} = \texttt{>}$, then $a_n = n$, because the $n$-th stick must be longer than all the othe...
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; void test() { int n; cin >> n; string s; cin >> s; int l = 1; int r = n; vector<int> a(n); for (int i = n - 2; i >= 0; i--) { if (s[i] == '<') { a[i + 1] = l; l++; } if (s[i] == '>') { ...
2096
B
Wonderful Gloves
You are the proud owner of many colorful gloves, and you keep them in a drawer. Each glove is in one of $n$ colors numbered $1$ to $n$. Specifically, for each $i$ from $1$ to $n$, you have $l_i$ left gloves and $r_i$ right gloves with color $i$. Unfortunately, it's late at night, so \textbf{you can't see any of your g...
Let's look at the third test case in the example. We have $k = 2$, and the answer is $x = 303$. If we take out $302$ gloves, then it's possible that we only have matching pairs of $1$ color. How can we generalize this fact for any $k$ and $x$? If we take out $(x - 1)$ gloves or fewer, then it's possible that we only ha...
[ "greedy", "math", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; void test() { int n, k; cin >> n >> k; int m = k - 1; vector<int> l(n); for (int i = 0; i < n; i++) { cin >> l[i]; } vector<int> r(n); for (int i = 0; i < n; i++) { cin >> r[i]; } vector<int> a(n), b(n); long lo...
2096
C
Wonderful City
You are the proud leader of a city in Ancient Berland. There are $n^2$ buildings arranged in a grid of $n$ rows and $n$ columns. The height of the building in row $i$ and column $j$ is $h_{i, j}$. The city is beautiful if no two adjacent by side buildings have the same height. In other words, it must satisfy the follo...
We are given an $n \times n$ matrix of positive integers. There are two types of operations we can perform: When we hire worker $i$ from company A, let's call it row operation $i$. When we hire worker $j$ from company B, let's call it column operation $j$. Each row and column operation can be performed at most once. Af...
[ "dp", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; const long long INF = 1e18; long long solveHor(int n, vector<vector<int>>& h, vector<int>& a) { vector<vector<long long>> dp(n, vector<long long>(2, INF)); dp[0][0] = 0; dp[0][1] = a[0]; for (int i = 1; i < n; i++) { for (int x = 0; x < 2; x++) { ...
2096
D
Wonderful Lightbulbs
You are the proud owner of an infinitely large grid of lightbulbs, represented by a Cartesian coordinate system. Initially, all of the lightbulbs are turned off, except for one lightbulb, where you buried your proudest treasure. In order to hide your treasure's position, you perform the following operation an arbitrar...
What can we say about the number of lightbulbs that are turned on for any valid configuration in the input? Can the number of lightbulbs that are turned on be even? The number of lightbulbs that are turned on is always odd. This is because we start with exactly one lightbulb turned on. Every operation changes the state...
[ "combinatorics", "constructive algorithms", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; void test() { int n; cin >> n; map<int, int> cntVer, cntDiag; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; cntVer[x]++; cntDiag[x + y]++; } int s; for (auto [c, cnt]: cntVer) { if (cnt % 2 == 1...
2096
E
Wonderful Teddy Bears
You are the proud owner of $n$ teddy bears, which are arranged in a row on a shelf. Each teddy bear is colored either black or pink. An arrangement of teddy bears is beautiful if all the black teddy bears are to the left of all the pink teddy bears. In other words, there \textbf{does not} exist a pair of indices $(i, ...
First, we'll treat all the black teddy bears as $0$ and all the pink teddy bears as $1$. So we are given a binary array of length $n$. In one operation, we can choose three consecutive elements and sort them in ascending order. Now we need to find the minimum number of operations required to sort the array. There are f...
[ "greedy", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; void test() { int n; cin >> n; string s; cin >> s; long long x = 0; int a = 0; int b = 0; for (int i = n - 1; i >= 0; i--) { if (s[i] == 'B') { a++; if ((i + 1) % 2 == 0) { b++; }...
2096
F
Wonderful Impostors
You are a proud live streamer known as Gigi Murin. Today, you will play a game with $n$ viewers numbered $1$ to $n$. In the game, each player is either a crewmate or an impostor. You don't know the role of each viewer. There are $m$ statements numbered $1$ to $m$, which are either \textbf{true or false}. For each $i$...
Let's call a set of statements satisfiable if it's possible that all of them are true. How do we check if a set of statements is satisfiable? For each statement of the form $0\,a_l\,a_r$, assign all viewers from $a_l$ to $a_r$ as crewmates. Then, assign the rest of the viewers as impostors. Now check if all statements ...
[ "data structures", "implementation", "two pointers" ]
3,100
null
2096
G
Wonderful Guessing Game
\textbf{This is an interactive problem.} You are a proud teacher at the Millennium Science School. Today, a student named Alice challenges you to a guessing game. Alice is thinking of an integer from $1$ to $n$, and you must guess it by asking her some queries. To make things harder, she says you must \textbf{ask al...
First, try solving it if Alice doesn't ignore any queries. We can represent the queries using a table. Let's look at the second test case in the example: Each row is a query. Column $x$ contains Alice's responses if her number was $x$. Let's treat $\texttt{L}$ as $-1$, $\texttt{R}$ as $1$, and $\texttt{N}$ as $0$. Then...
[ "bitmasks", "constructive algorithms", "interactive" ]
3,200
null
2096
H
Wonderful XOR Problem
You are the proud... never mind, just solve this problem. There are $n$ intervals $[l_1, r_1], [l_2, r_2], \ldots [l_n, r_n]$. For each $x$ from $0$ to $2^m - 1$, find the number, modulo $998\,244\,353$, of sequences $a_1, a_2, \ldots a_n$ such that: - $l_i \leq a_i \leq r_i$ for all $i$ from $1$ to $n$; - $a_1 \oplu...
Is this FFT? Let's consider the XOR convolution. Given two polynomials $A(x)$ and $B(x)$ with degree at most $(2^{m} - 1)$, the XOR convolution $C(x) = A(x) \star B(x)$ is defined as follows: $\displaystyle [x^k]C(x) = \sum_{0 \leq i < 2^m \\ 0 \leq j < 2^m \\ i \oplus j = k} [x^i]A(x) \cdot [x^j]B(x)$ To efficiently c...
[ "bitmasks", "combinatorics", "dp", "fft", "math" ]
3,200
null
2097
A
Sports Betting
The boarding process for various flights can occur in different ways: either by \textbf{bus} or through a \textbf{telescopic jet bridge}. Every day, exactly one flight is made from St. Petersburg to Minsk, and Vadim decided to demonstrate to the students that he always knows in advance how the boarding will take place....
Let's sort the array $a$ in non-decreasing order: $a_1 \le a_2 \le \ldots \le a_n$. Suppose Vadim argues with the students in turn. We can formalize the problem as follows: since there are only two possible seating arrangements each day, we can encode them with the digits $0$ and $1$. Each of Vadim's predictions can be...
[ "2-sat", "brute force", "math", "sortings" ]
1,400
null
2097
B
Baggage Claim
Every airport has a baggage claim area, and Balbesovo Airport is no exception. At some point, one of the administrators at Sheremetyevo came up with an unusual idea: to change the traditional shape of the baggage claim conveyor from a carousel to a more complex form. Suppose that the baggage claim area is represented ...
If any pair of adjacent cells $p_{2i-1}$ and $p_{2i+1}$ is at a distance other than $2$, then the answer is $0$. Otherwise, for each such pair of cells, there are two possible cases: Cells $p_{2i-1}$ and $p_{2i+1}$ are in the same row or column. Then cell $p_{2i}$ must be located between them. In the other case, there ...
[ "combinatorics", "dfs and similar", "dp", "dsu", "graphs", "implementation", "math", "trees" ]
2,300
null
2097
C
Bermuda Triangle
The Bermuda Triangle — a mysterious area in the Atlantic Ocean where, according to rumors, ships and airplanes disappear without a trace. Some blame magnetic anomalies, others — portals to other worlds, but the truth remains hidden in a fog of mysteries. A regular passenger flight 814 was traveling from Miami to Nassa...
We will use the idea of reflections. Instead of saying that the plane is reflected with respect to a side, we will say that it actually flew further but ended up in the triangle that results from reflecting the original triangle with respect to that side. All such triangles form a pattern of the following kind. The ver...
[ "chinese remainder theorem", "geometry", "implementation", "math", "number theory" ]
2,400
null
2097
D
Homework
Some teachers work at the educational center "Sirius" while simultaneously studying at the university. In this case, the trip does not exempt them from completing their homework, so they do their homework right on the plane. Artem is one of those teachers, and he was assigned the following homework at the university. ...
The problem itself is trivial, but solving it requires not skipping lectures on linear algebra. Suspecting that not all participants are familiar with the basics of linear algebra, we will try to explain each step in detail. Part 1. Matrices. Let $n = k \cdot m$, where $m$ is an odd number, and $k$ is a power of two. A...
[ "bitmasks", "math", "matrices" ]
2,800
null
2097
E
Clearing the Snowdrift
Boy Vasya loves to travel very much. In particular, flying in airplanes brings him extraordinary pleasure. He was about to fly to another city, but the runway was heavily covered with snow and needed to be cleared. The runway can be represented as $n$ consecutive sections numbered from $1$ to $n$. The snowstorm was qu...
We will assign to each operation the maximum $a_i$ on the segment of that operation. Consider some order of operations that zeroes out the entire array. If there are two adjacent operations in which the maximum on the segment of the earlier operation is smaller, then we can swap these two operations without changing an...
[ "data structures", "dfs and similar", "dp", "greedy" ]
3,100
null
2097
F
Lost Luggage
As is known, the airline "Trouble" often loses luggage, and concerned journalists decided to calculate the maximum number of luggage pieces that may not return to travelers. The airline "Trouble" operates flights between $n$ airports, numbered from $1$ to $n$. The journalists' experiment will last for $m$ days. It is ...
It is clear that the problem can be solved using flows. We will introduce a dummy source $s$ and $(m+1) n$ vertices $(i,j)$ ($0 \le i \le m$, $1 \le j \le n$), and the following edges will be added to the network: For all $j$ ($1 \le j \le n$), edges from $s$ to $(0, j)$ with capacity $s_j$. For all pairs $i$, $j$ ($1 ...
[ "dp", "flows" ]
3,500
null
2098
A
Vadim's Collection
We call a phone number a beautiful if it is a string of $10$ digits, where the $i$-th digit from the left is at least $10 - i$. That is, the first digit must be at least $9$, the second at least $8$, $\ldots$, with the last digit being at least $0$. For example, 9988776655 is a beautiful phone number, while 9099999999...
Our goal is to obtain the minimally possible string that satisfies the conditions of beauty. Therefore, we need to arrange the digits in order from the first to the last, each time choosing the minimally possible suitable digit. More formally: For the $i$-th position, we need to place the smallest available digit that ...
[ "brute force", "greedy" ]
800
null
2098
B
Sasha and the Apartment Purchase
Sasha wants to buy an apartment on a street where the houses are numbered from $1$ to $10^9$ from left to right. There are $n$ bars on this street, located in houses with numbers $a_1, a_2, \ldots, a_n$. Note that there might be multiple bars in the same house, and in this case, these bars are considered distinct. Sa...
Note that for a fixed position, the optimal point is the median (or for an even number of elements, any point between the two medians). Proof: Observe that if we move the point between $x$ and $x + 1$, the answer changes by the difference in the number of elements to the left and right between $x$ and $x + 1$. Therefor...
[ "math", "sortings" ]
1,400
null
2101
A
Mex in the Grid
You are given $n^2$ cards with values from $0$ to $n^2-1$. You are to arrange them in a $n$ by $n$ grid such that there is \textbf{exactly} one card in each cell. The MEX (minimum excluded value) of a subgrid$^{\text{∗}}$ is defined as the smallest non-negative integer that does not appear in the subgrid. Your task i...
What is the MEX, if $0$ is not there? When is the MEX equal to $k$? If we want a subgrid to be included in as many other subgrids as possible, what shape should it have? What about its place? The first fact to notice is that if the subgrid does not contain $0$, then the MEX is $0$ and we can ignore such subgrids. If th...
[ "constructive algorithms", "implementation" ]
1,300
def magical_spiral(n): arr = [[-1] * n for _ in range(n)] if n % 2 == 0: x, y = n // 2 - 1, n // 2 - 1 else: x, y = n // 2, n // 2 arr[x][y] = 0 value = step = 1 dir = [(0, 1), (1, 0), (0, -1), (-1, 0)] while value < n * n: for d in range(4): ...
2101
B
Quartet Swapping
You are given a permutation $a$ of length $n$$^{\text{∗}}$. You are allowed to do the following operation any number of times (possibly zero): - Choose an index $1\le i\le n - 3$. Then, swap $a_i$ with $a_{i + 2}$, and $a_{i + 1}$ with $a_{i + 3}$ simultaneously. In other words, permutation $a$ will be transformed fro...
Is it possible for an element to change its index parity after some operations? What else is not effected by the operation? How to combine the above two properties under the time limit? The first observation is that the parity of the position of the elements doesn't change with the operations. Thus, if an element is at...
[ "brute force", "data structures", "divide and conquer", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> #define pb push_back #define int long long #define F first #define S second #define sz(a) (int)a.size() #define pii pair<int,int> #define rep(i , a , b) for(int i = (a) ; i <= (b) ; i++) #define per(i , a , b) for(int i = (a) ; i >= (b) ; i--) #define all(a) a.begin(),a.end() using namespa...
2101
C
23 Kingdom
The distance of a value $x$ in an array $c$, denoted as $d_x(c)$, is defined as the largest gap between any two occurrences of $x$ in $c$. Formally, $d_x(c) = \max(j - i)$ over all pairs $i < j$ where $c_i = c_j = x$. If $x$ appears only once or not at all in $c$, then $d_x(c) = 0$. The beauty of an array is the sum ...
Does it matter if there are $2$ occurance of a number or $200$? What greedy approaches can you think of? Are they fast enough? The first observation is that we only care about the first and last occurrences of each number in the final array, as anything in between doesn't change the maximum distance. Instead of countin...
[ "binary search", "brute force", "data structures", "greedy", "ternary search", "two pointers" ]
2,200
#include <bits/stdc++.h> #define int long long // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") // #pragma GCC optimize("O3") // #pragma GCC optimize("unroll-loops") #define F first #define S second #define mp make_pair #define pb push_back #define all(x) x.begin(), x.end() #define kill(x) cout << x << "\n", ex...
2101
D
Mani and Segments
An array $b$ of length $|b|$ is cute if the sum of the length of its Longest Increasing Subsequence (LIS) and the length of its Longest Decreasing Subsequence (LDS)$^{\text{∗}}$ is \textbf{exactly} one more than the length of the array. More formally, the array $b$ is cute if $\operatorname{LIS}(b) + \operatorname{LDS}...
What are some characteristics of a cute subarray? Is cuteness a monotone property? How to find the maximal cute subarray for a fixed index $i$? The first observation is that a subarray is cute, iff there is an index $i$, such that it is the one and only share of the LIS and LDS, and all other elements belong to either ...
[ "data structures", "implementation", "sortings", "two pointers" ]
2,500
#include <bits/stdc++.h> #define pb push_back #define int long long #define F first #define S second #define sz(a) (int)a.size() #define pii pair<int,int> #define rep(i , a , b) for(int i = (a) ; i <= (b) ; i++) #define per(i , a , b) for(int i = (a) ; i >= (b) ; i--) #define all(a) a.begin(),a.end() using names...
2101
E
Kia Bakes a Cake
You are given a binary string $s$ of length $n$ and a tree $T$ with $n$ vertices. Let $k$ be the number of 1s in $s$. We will construct a complete undirected weighted graph with $k$ vertices as follows: - For each $1\le i\le n$ with $s_i = \mathtt{1}$, create a vertex labeled $i$. - For any two vertices labeled $u$ an...
Can we see any node twice in our walk? What is the upper bound on the length of the path? How do we approach this using dynamic programming? How to optimize the DP? The length of each two nodes in a tree is always less than the number of nodes, and therefore the maximum weight that we can see in our constructed graph h...
[ "data structures", "dp", "greedy", "trees" ]
3,100
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<long long, long long>; using ull = unsigned long long; #define X first #define Y second #define SZ(x) int(x.size()) #define all(x) x...
2101
F
Shoo Shatters the Sunshine
You are given a tree with $n$ vertices, where each vertex can be colored red, blue, or white. The coolness of a coloring is defined as the maximum distance$^{\text{∗}}$ between a red and a blue vertex. Formally, if we denote the color of the $i$-th vertex as $c_i$, the coolness of a coloring is $\max d(u, v)$ over all...
What are some properties of such colored trees? Is the farthest blue and red node unique? Should we look for an $O(n^2)$ solution or optimizes a slower one? Note: For the purpose of this editorial, the diameter of a colored tree is defined as a simple path with maximum coolness which has a blue and red node on each sid...
[ "combinatorics", "dp", "trees" ]
3,300
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<long long, long long>; using ull = unsigned long long; #define X first #define Y second #define SZ(x) int(x.size()) #define all(x) x...
2102
A
Dinner Time
Given four integers $n$, $m$, $p$, and $q$, determine whether there exists an integer array $a_1, a_2, \ldots, a_n$ (elements may be negative) satisfying the following conditions: - The sum of all elements in the array is equal to $m$: $$a_1 + a_2 + \ldots + a_n = m$$ - The sum of every $p$ consecutive elements is equ...
If you have the first $p$ elements, what happens to the rest? What happens if $n\%p\neq0$? How can the fact that we can also use negative numbers be useful? The first thing to realize is that if the first $p$ elements of the array are determined, the rest will be unique ($a_i = a_{i-p}$ to hold the sum). If $p$ divides...
[ "constructive algorithms", "math" ]
900
t = int(input()) for _ in range(t): n, m, p, q = map(int, input().split()) if n % p == 0 and (n // p) * q != m: print("NO") else: print("YES")
2102
B
The Picky Cat
You are given an array of integers $a_1, a_2, \ldots, a_n$. You are allowed to do the following operation any number of times (possibly zero): - Choose an index $i$ ($1\le i\le n$). Multiply $a_i$ by $-1$ (i.e., update $a_i := -a_i$). Your task is to determine whether it is possible to make the element at index $1$ b...
Does the initial sign and order of elements matter? If an element is before the median in the sorted array, can you shift it forward? What if it is initially after the median? Before starting, we take the absolute value of all elements since their signs do not matter. Then, if the first element of the array is equal to...
[ "implementation", "sortings" ]
900
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) pairs = [(abs(a[i]), i) for i in range(n)] pairs.sort() ans = [0] * n for i in range(n // 2 + 1): _, index = pairs[i] ans[index] = 1 if ans[0]: print("YES") ...
2103
A
Common Multiple
You are given an array of integers $a_1, a_2, \ldots, a_n$. An array $x_1, x_2, \ldots, x_m$ is beautiful if there exists an array $y_1, y_2, \ldots, y_m$ such that the elements of $y$ are distinct (in other words, $y_i\neq y_j$ for all $1 \le i < j \le m$), and the product of $x_i$ and $y_i$ is the same for all $1 \le...
We need to solve the same problem $t$ times. We will make use of loops to do so. From now we will focus on solving a problem for one test case, but remember that all of the following will be in a loop. So the array $x$ is beautiful if there exists an array of distinct elements $y$ such that $x_i \cdot y_i$ is the same ...
[ "brute force", "greedy", "implementation", "math" ]
800
t = int(input()) for i in range(t): n = int(input()) a = input().split(" ") count = 0 for i in range(0, n): add = 1 for j in range(0, i): if a[i]==a[j]: add = 0 count += add print(count)
2103
B
Binary Typewriter
You are given a binary string $s$ of length $n$ and a typewriter with two buttons: 0 and 1. Initially, your finger is on the button 0. You can do the following two operations: - Press the button your finger is currently on. This will type out the character that is on the button. - Move your finger to the other button....
Given the string $s$, how do we calculate the answer? We know that we need to type a character (apply operation $1$ exactly $n$ times). How many switches do we do? If the string $s$ starts with a 1, we need to do a switch immediately. From that point on, we only switch if the current number in the string changes. We ca...
[ "greedy", "math" ]
1,100
for _ in range(int(input())): n = int(input()) a = input().strip() cnt = 0 for i in range(n-1): if a[i] != a[i+1]: cnt += 1 if cnt == 0: print(n + int(a[0] == "1")) elif cnt == 1: print(n + 1) else: print(n+cnt-1 - int(a[0] == "0" and cnt > 2))
2103
C
Median Splits
The median of an array $b_1, b_2, \ldots b_m$, written as $\operatorname{med}(b_1, b_2, \ldots, b_m)$, is the $\left\lceil \frac{m}{2} \right\rceil$-th$^{\text{∗}}$ smallest element of array $b$. You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $k$. You need to determine whether there exists a...
We split our array into $3$ subarrays, take their medians, and the final median needs to be $\le k$. That means that the median of at least $2$ of those subarrays needs to be $\le k$. For a given array $x$ of length $m$, what is the condition that $\operatorname{med}(x_1, x_2, \ldots, x_m) \le k$? There need to be at l...
[ "binary search", "greedy", "implementation", "sortings" ]
1,600
def check_prefix_and_middle(n, arr): suf = [0] * (n + 1) minsuf = [0] * (n + 1) suf[n] = minsuf[n] = arr[n - 1] for i in range(n - 2, -1, -1): suf[i + 1] = suf[i + 2] + arr[i] minsuf[i + 1] = min(minsuf[i + 2], suf[i + 1]) s = 0 for i in range(n - 2): s += arr[i] ...
2103
D
Local Construction
An element $b_i$ ($1\le i\le m$) in an array $b_1, b_2, \ldots, b_m$ is a local minimum if at least one of the following holds: - $2\le i\le m - 1$ and $b_i < b_{i - 1}$ and $b_i < b_{i + 1}$, or - $i = 1$ and $b_1 < b_2$, or - $i = m$ and $b_m < b_{m - 1}$. Similarly, an element $b_i$ ($1\le i\le m$) in an array $b_...
Try to prove the claim that $a_i \le \lceil \log_2 n\rceil$. It also shall help you understand when the construction is possible, which is often a good way to think about constructive problems. We can notice that among any two consecutive elements $p_i$ and $p_{i+1}$, one of them has to be deleted. That means that afte...
[ "constructive algorithms", "dfs and similar", "implementation", "two pointers" ]
2,000
#include <algorithm> #include <bitset> #include <cassert> #include <chrono> #include <cmath> #include <deque> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <string> #include <vector> typedef long long ll; typedef long double ld; using namespace std; i...
2103
E
Keep the Sum
You are given an integer $k$ and an array $a$ of length $n$, where each element satisfies $0 \le a_i \le k$ for all $1 \le i \le n$. You can perform the following operation on the array: - Choose two distinct indices $i$ and $j$ ($1 \le i,j \le n$ and $i \neq j$) such that $a_i + a_j = k$. - Select an integer $x$ sati...
When is the solution trivially -1? When it is impossible to do any operation and array is not sorted in the beginning. Is that enough though? It is enough. If we have even a single pair of values that sums up to $k$, we can make the array non-decreasing. From now assume there is only one such pair as we can ignore othe...
[ "constructive algorithms", "implementation", "two pointers" ]
2,600
#include<bits/stdc++.h> #define ll long long using namespace std; const int maxn=2e5+5; int n,k,arr[maxn],A,B,p[maxn]; map<int,int> pos; vector<tuple<int,int,int>> V; /// All operations void dooperation(int a,int b,int x){ arr[a]-=x; arr[b]+=x; V.push_back(make_tuple(a,b,x)); } void setvalue(int pos,int b,int ...
2103
F
Maximize Nor
The bitwise nor$^{\text{∗}}$ of an array of $k$-bit integers $b_1, b_2, \ldots, b_m$ can be computed by calculating the bitwise nor cumulatively from left to right. More formally, $\operatorname{nor}(b_1, b_2, \ldots, b_m) = \operatorname{nor}(\operatorname{nor}(b_1, b_2, \ldots, b_{m - 1}), b_m)$ for $m\ge 2$, and $\o...
If problem had queries of form "What is nor of some interval [$l$, $r$]", how would you answer them? You can look at all the bits separately and answer for each. For each bit, we only care about the position of the last $1$ on it before $r$. Let that position be $x$. If $x>l$, then if $x$ and $r$ are of the same parity...
[ "bitmasks", "data structures", "dp", "implementation", "sortings" ]
2,600
#include<bits/stdc++.h> #define ll long long using namespace std; const int maxn=2e5+5; int N,M,arr[maxn],pref[maxn][25],logg,st[4*maxn],stk; int nor(int a,int b){ return M^(a|b); } int getlog(int x){ int ans=-1; while(x){ ans+=1; x/=2; } return ans; } int internor(int l,int r){ if(l<=0 or...
2104
A
Three Decks
Monocarp placed three decks of cards in a row on the table. The first deck consists of $a$ cards, the second deck consists of $b$ cards, and the third deck consists of $c$ cards, with the condition $a < b < c$. Monocarp wants to take some number of cards (at least one, but no more than $c$) from the \textbf{third} dec...
Let us assume that we have managed to make the number of cards equal. Then each deck contains $x$ cards. Since the total number of cards from the hasn't changed, there were $3x$ cards in total. This means that if $a + b + c$ is not divisible by $3$, the answer is definitely "NO". Otherwise, we know that $3x = a + b + c...
[ "math" ]
800
for _ in range(int(input())): a, b, c = map(int, input().split()) if (a + b + c) % 3 != 0: print("NO") continue x = (a + b + c) // 3 print("YES" if b <= x else "NO")
2104
B
Move to the End
You are given an array $a$ consisting of $n$ integers. For every integer $k$ from $1$ to $n$, you have to do the following: - choose an arbitrary element of $a$ and move it to the right end of the array (you can choose the last element, then the array won't change); - print the sum of $k$ last elements of $a$; - move...
If we move an element to the end of the array, then each element (except the one we selected) will either remain in its place or move $1$ position to the left. This means that if we are interested in the sum of the last $k$ elements after we have shifted some element to the end, it will necessarily include the last $(k...
[ "brute force", "data structures", "dp", "greedy", "implementation" ]
1,000
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int n; cin >> n; vector<int> a(n); for(int j = 0; j < n; j++) cin >> a[j]; vector<int> pmax(n + 1); vector<long long> psum(n + 1); for(int j...
2104
C
Card Game
Alice and Bob are playing a game. They have $n$ cards numbered from $1$ to $n$. At the beginning of the game, some of these cards are given to Alice, and the rest are given to Bob. Card with number $i$ beats card with number $j$ if and only if $i > j$, \textbf{with one exception}: card $1$ beats card $n$. The game co...
There are many ways to solve this problem. I will describe one of the ways that doesn't use too much casework. The key observation we need is that, if a player has a strategy that allows him/her to take the cards on turn $i$, then he/she has a strategy to take the cards on turn $i+1$. There are two ways to prove it, ch...
[ "brute force", "constructive algorithms", "games", "greedy", "math" ]
1,100
def beats(n, x, y): if x == 0: return y == n - 1 if x == n - 1: return y != 0 return x > y for _ in range(int(input())): n = int(input()) owner = input() good = False for i in range(n): if owner[i] != 'A': continue good_move = True for j ...
2104
D
Array and GCD
You are given an integer array $a$ of size $n$. You can perform the following operations any number of times (possibly, zero): - pay one coin and increase any element of the array by $1$ (you must have at least $1$ coin to perform this operation); - gain one coin and decrease any element of the array by $1$. Let's s...
First, let's understand that operations from the statement impose only one restriction: the sum of the resulting array must not be greater than the sum of the original one. Now let's consider an ideal array. If there is an element that contains at least two distinct prime factors (or its factorization includes some pri...
[ "binary search", "greedy", "math", "number theory" ]
1,400
#include <bits/stdc++.h> using namespace std; const int N = 6e6; int main() { ios::sync_with_stdio(false); cin.tie(0); vector<int> p, ip(N, 1); for (int i = 2; i < N; ++i) { if (!ip[i]) continue; p.push_back(i); for (int j = i; j < N; j += i) { ip[j] = 0; } } int t; cin >> t; w...
2104
E
Unpleasant Strings
Let's call a letter allowed if it is a lowercase letter and is one of the first $k$ letters of the Latin alphabet. You are given a string $s$ of length $n$, consisting only of allowed letters. Let's call a string $t$ pleasant if $t$ is a subsequence of $s$. You are given $q$ strings $t_1, t_2, \dots, t_q$. All of th...
For a start, let's think about how to check, is $t$ a subsequence of $s$. There is a greedy solution to that: let's match $t_0$ with the leftmost character in $s$ that is equal to it. Then match $t_1$ with the next leftmost character in $s$ that goes after the first one, and so on. If we matched all characters in $t$, ...
[ "binary search", "dp", "greedy", "strings" ]
1,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pa...
2104
F
Numbers and Strings
For each integer $x$ from $1$ to $n$, we will form the string $S(x)$ according to the following rules: - compute $(x+1)$; - write $x$ and $x+1$ next to each other in the decimal system without separators and leading zeros; - in the resulting string, sort all digits in non-decreasing order. For example, the string $S(...
Consider how the decimal representation of $(x+1)$ depends on $x$. Usually, all digits of $(x+1)$ remain the same, except for the last digit, which is increased by $1$. It does not actually work if the last digit of $x$ is $9$, but we can get a more general rule that handles that case: all $9$'s at the end of the numbe...
[ "binary search", "brute force", "dfs and similar", "dp", "implementation", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; const long long A = (long long)(1e18); string S(long long x) { string s = to_string(x) + to_string(x + 1); sort(s.begin(), s.end()); return s; } vector<long long> aux2; vector<pair<string, long long>> aux; long long get_num(string cur) { int first_n...
2104
G
Modulo 3
Surely, you have seen problems which require you to output the answer modulo $10^9+7$, $10^9+9$, or $998244353$. But have you ever seen a problem where you have to print the answer modulo $3$? You are given a functional graph consisting of $n$ vertices, numbered from $1$ to $n$. It is a directed graph, in which each v...
First, let's find out how to solve the following problem: you are given a directed graph where all vertices have color $1$. You can choose a vertex and a color from $1$ to $k$, then color it and all vertices reachable from it with that color. How many different colorings are there? Clearly, if a pair of vertices is in ...
[ "data structures", "divide and conquer", "dsu", "graphs", "trees" ]
2,700
#include <bits/stdc++.h> using namespace std; using pt = pair<int, int>; const int N = 200007; int n, q; int k[N]; vector<pt> t[4 * N]; int p[N], e[N], rk[N]; int *pos[3 * N]; int val[3 * N]; int csz; int ans[N]; void upd(int v, int l, int r, int L, int R, pt val) { if (L >= R) return; if (l == L && r == ...
2106
A
Dr. TC
In order to test his patients' intelligence, Dr. TC created the following test. First, he creates a binary string$^{\text{∗}}$ $s$ having $n$ characters. Then, he creates $n$ binary strings $a_1, a_2, \ldots, a_n$. It is known that $a_i$ is created by first copying $s$, then flipping the $i$'th character ($1$ becomes ...
Every character of $a$ is flipped in exactly one string. Therefore, if $a_i = 1$, we need to add $n-1$ to the answer (since the $i$-$th$ character will stay $1$ for $n-1$ strings), and if $a_i = 0$ we need to add $1$ (since the $i$-$th$ character will be $1$ in exactly one string).
[ "brute force", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; int ans = 0; for (auto x: s) { if (x == '0') ans++; else ans += n - 1; } cout << ans << '\n'; } int main() { int t; cin >> t; while (t--) solve(); return 0; }
2106
B
St. Chroma
Given a permutation$^{\text{∗}}$ $p$ of length $n$ that contains every integer from $0$ to $n-1$ and a strip of $n$ cells, St. Chroma will paint the $i$-th cell of the strip in the color $\operatorname{MEX}(p_1, p_2, ..., p_i)$$^{\text{†}}$. For example, suppose $p = [1, 0, 3, 2]$. Then, St. Chroma will paint the cell...
If $x = n$ then we can output any permutation, since in order for the $\operatorname{MEX}$ to be equal to $n$, every value $0, 1, ..., n-1$ must appear. Otherwise, we want to build a permutation $p$ such that two main conditions hold. Firstly, we want $x$ to appear on the final strip as soon as possible. In other words...
[ "constructive algorithms", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; void solve() { int n, x; cin >> n >> x; for (int i = 0; i < x; i++) cout << i << " "; for (int i = x+1; i < n; i++) cout << i << " "; if (x < n) cout << x; cout << '\n'; } int main() { int t; cin >> t; while (t--) solve(); return 0; }
2106
C
Cherry Bomb
Two integer arrays $a$ and $b$ of size $n$ are \textbf{complementary} if there exists an integer $x$ such that $a_i + b_i = x$ over all $1 \le i \le n$. For example, the arrays $a = [2, 1, 4]$ and $b = [3, 4, 1]$ are complementary, since $a_i + b_i = 5$ over all $1 \le i \le 3$. However, the arrays $a = [1, 3]$ and $b ...
Suppose that the two arrays $a$ and $b$ of size $n$ are called $s$-complementary if and only if $a_i + b_i = s$ for all $1 \le i \le n$. Observation 1: If we know every element of $a$, and we know $s$, we can uniquely determine the elements of $b$. We split the problem into two cases. The first case is if there exists ...
[ "greedy", "math", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; int a[n], b[n]; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; int s = -1; for (int i = 0; i < n; i++) { if (b[i] != -1) { if (s == -1) s = a[i] + b[i]; ...
2106
D
Flower Boy
Flower boy has a garden of $n$ flowers that can be represented as an integer sequence $a_1, a_2, \dots, a_n$, where $a_i$ is the beauty of the $i$-th flower from the left. Igor wants to collect exactly $m$ flowers. To do so, he will walk the garden \textbf{from left to right} and choose whether to collect the flower a...
There is a greedy strategy. Every time you see some flower in $a$, if its beauty is not less than the beauty of next flower you must pick from $b$, you will pick it. The answer is $0$ if we run the greedy without inserting a new flower in $a$ and still collecting all $m$ needed flowers. Now, consider what inserting a n...
[ "binary search", "dp", "greedy", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 5; int main(){ int T; cin >> T; while(T--){ int N, M; cin >> N >> M; vector<int> a(N), b(M); for(int i = 0; i < N; i++) cin >> a[i]; for(int i = 0; i < M; i++) cin >> b[i]; vector<int> backwards_match(M...
2106
E
Wolf
Wolf has found $n$ sheep with tastiness values $p_1, p_2, ..., p_n$ where $p$ is a permutation$^{\text{∗}}$. Wolf wants to perform binary search on $p$ to find the sheep with tastiness of $k$, but $p$ may not necessarily be sorted. The success of binary search on the range $[l, r]$ for $k$ is represented as $f(l, r, k)...
Consider some permutation $p_1, p_2, ..., p_n$. Before answering queries, precompute the index of integer $i$ $(1 \le i \le n)$, suppose it is represented as $idx_i$. Let's see how to answer some query $l, r, x$. Obviously, if $idx_x$ does not belong in the range $[l, r]$, the answer is $-1$. Otherwise, we want to some...
[ "binary search", "greedy", "math" ]
1,800
#include <bits/stdc++.h> using namespace std; #define int long long void solve() { int n, q; cin >> n >> q; int arr[n+1]; vector<int> idx(n+1, 0); for (int i = 1; i <= n; i++) { cin >> arr[i]; idx[arr[i]] = i; } while (q--) { int l, r, k; cin >> l >> r >> k; if ...
2106
F
Goblin
Dr. TC has a new patient called Goblin. He wants to test Goblin's intelligence, but he has gotten bored of his standard test. So, he decided to make it a bit harder. First, he creates a binary string$^{\text{∗}}$ $s$ having $n$ characters. Then, he creates $n$ binary strings $a_1, a_2, \ldots, a_n$. It is known that $...
Each column can be broken down to $3$ components: If $a_i = 0$, the top-most component will contain $i-1$ zeros, the second component a single one, and the third component $n-i$ zeros. If $a_i = 1$, the top-most component will contain $i-1$ ones, the second component a single zero, and the third component $n-i$ ones. T...
[ "dfs and similar", "dp", "dsu", "greedy", "math" ]
1,900
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2106
G1
Baudelaire (easy version)
\textbf{This is the easy version of the problem. The only difference between the two versions is that in this version, it is guaranteed that every node is adjacent to node $1$.} This problem is interactive. Baudelaire is very rich, so he bought a tree of size $n$ that is rooted at some arbitrary node. Additionally, e...
For some node $u$, let $v_u$ be its value and $s_u$ be the sum of the values of all nodes on the simple path from the root of the tree to node $u$ ($s_u$ will also be referenced as "the sum of node $u$" for the purposes of this solution). Also, let $p_u$ be the parent of node $u$ (if $u$ is not the root). Suppose that ...
[ "binary search", "constructive algorithms", "divide and conquer", "greedy", "interactive", "trees" ]
2,200
#include <bits/stdc++.h> using i64 = long long; void solve() { int n; std::cin >> n; std::vector<int> a(n+1), son(n-1); for (int i = 1; i < n; ++i) { int u, v; std::cin >> u >> v; son[i-1] = i + 1; } int Q = 0; auto ask = [&](int op, const std::vector<int> &v) { ...
2106
G2
Baudelaire (hard version)
\textbf{This is the Hard Version of the problem. The only difference between the two versions is that in the Hard Version the tree may be of any shape.} This problem is interactive. Baudelaire is very rich, so he bought a tree of size $n$, rooted at some arbitrary node. Additionally, every node has a value of $1$ or ...
Read the solution to the Easy Version first. Obviously, if we know the parent of some node, we know which nodes are under that node's subtree, so we never have to consider them as candidates for the root of the tree. Let's use this to choose nodes in a way such that each time we eliminate as many candidates as possible...
[ "binary search", "dfs and similar", "divide and conquer", "implementation", "interactive", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; #define int long long vector<vector<int>> tree, cd; vector<int> sub, val; vector<bool> del; int n, cdRoot = -1; int ask(vector<int> a) { int k = a.size(); cout << "? 1 " << k << " "; for (auto x: a) { cout << x << " "; } cout << endl; int...
2107
A
LRC and VIP
You have an array $a$ of size $n$ — $a_1, a_2, \ldots a_n$. You need to divide the $n$ elements into $2$ sequences $B$ and $C$, satisfying the following conditions: - Each element belongs to exactly one sequence. - Both sequences $B$ and $C$ contain at least one element. - $\gcd$ $(B_1, B_2, \ldots, B_{|B|}) \ne \gcd...
When all the elements of the array are equal, the solution is trivially impossible since the $\gcd$ of any subset will always be equal to $a_1$. That is infact the only $\texttt{No}$ case. We show a construction otherwise. Let $\operatorname{mx} = \max(a)$. Put all the elements equal to $\operatorname{mx}$ in one set, ...
[ "greedy", "number theory" ]
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 (int i = 0; i < n; i++){ cin >> a[i]; } int mn = *min_element(a.begin(), a.end()); int mx = *max_element(a.begin(), a....
2107
B
Apples in Boxes
Tom and Jerry found some apples in the basement. They decided to play a game to get some apples. There are $n$ boxes, and the $i$-th box has $a_i$ apples inside. Tom and Jerry take turns picking up apples. Tom goes first. On their turn, they have to do the following: - Choose a box $i$ ($1 \le i \le n$) with a positi...
Suppose $\max(a) - \min(a) \le k$ holds, and there is at least one $a_i \ge 1$. Then, infact it is possible to take one apple while still keeping the condition of $\max(a) - \min(a) \le k$. We will subtract from the maximum element. Then $\min(a)$ does not change except when $a_1 = a_2 = \ldots = a_n$. In that special ...
[ "games", "greedy", "math" ]
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); for (auto &x : a) cin >> x; long long sum = accumulate(a.begin(), a.end(), 0LL); sort(a.begin(), a.end()); ...
2107
C
Maximum Subarray Sum
You are given an array $a_1,a_2,\ldots,a_n$ of length $n$ and a positive integer $k$, but some parts of the array $a$ are missing. Your task is to fill the missing part so that the \textbf{maximum subarray sum}$^{\text{∗}}$ of $a$ is exactly $k$, or report that no solution exists. Formally, you are given a binary stri...
We assume that there is at least one $s_i = 0$ (unfilled position). In the other case that all $s_i = 1$, we can easily check if the maximum subarray sum is $k$ or not. Let us first figure out when the answer is impossible. Replace all $a_i = -\texttt{INF}$ such that $s_i = 0$. If the maximum subarray sum is still $> k...
[ "binary search", "constructive algorithms", "dp", "implementation", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--){ int n; long long k; cin >> n >> k; string s; cin >> s; vector <long long> a(n); for (auto &x : a) cin >> x; int pos = -1; for (int i = 0; i < n; i++...
2107
D
Apple Tree Traversing
There is an apple tree with $n$ nodes, initially with one apple at each node. You have a paper with you, initially with nothing written on it. You are traversing on the apple tree, by doing the following action as long as there is at least one apple left: - Choose an \textbf{apple path} $(u,v)$. A path $(u,v)$ is cal...
Note that the problem has a simple $O(n^2)$ solution by greedily finding the largest diameter in the current forest (set of disjoint trees) at every step, tiebreaking by the lexicographic order of the endpoints, then removing the diameter and continuing this process while at least $1$ node remains. Property $1$: $2$ di...
[ "brute force", "dfs and similar", "greedy", "implementation", "trees" ]
2,100
#include<bits/stdc++.h> #ifdef DEBUG_LOCAL #include <mydebug/debug.h> #endif using ll = long long; const int N = 5e5+5; using namespace std; using pi = pair<int,int>; using ti = tuple<int,int,int,int>; int T,n,u,v,del[N],fa[N],ct; vector<int> g[N]; set<pi> t[N]; void dfs(int u,int f){ t[u].emplace(0,u),fa[u] = f; ...
2107
E
Ain and Apple Tree
If I was also hit by an apple falling from an apple tree, could I become as good at physics as Newton? To be better at physics, Ain wants to build an apple tree so that she can get hit by apples on it. Her apple tree has $n$ nodes and is rooted at $1$. She defines the weight of an apple tree as $\sum \limits_{i=1}^n \...
Let $C(n, k)$ denote $\frac{n!}{k! \cdot (n - k)!}$. We first start from the maximum possible value of $k$, and the tree that achieves it, i.e. a straight line path rooted at $1$. It is not too hard to see that this tree has the largest weight, and the weight of this tree is $C(n, 3)$. Thus, for $k > C(n, 3) + 1$, we a...
[ "binary search", "constructive algorithms", "greedy", "math", "trees" ]
2,600
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--){ int n; cin >> n; long long k; cin >> k; long long mx = 1LL * n * (n - 1) * (n - 2) / 6; if (k > mx + 1){ cout << "No\n"; continue; } cout << ...
2107
F1
Cycling (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $1\le n\le 5\cdot 10^3$ and you don't need to output the answer for each prefix. You can hack only if you solved all versions of this problem.} Leo works as a programmer in the city center, and his lover teach...
Let us try to figure out the optimal strategy. We want to use small values for the "overtake" operation, and we will use "swap" operations to make the overtakes less costly. Suppose $p =$ first position of minima element. We should over take cyclists $1, 2, \ldots, p$ for the cost of $a_p$, swapping $p$ till first. Thi...
[ "binary search", "brute force", "dp", "greedy" ]
2,300
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--){ int n; cin >> n; vector <int> a(n + 1); for (int i = 1; i <= n; i++){ cin >> a[i]; } vector <long long> dp(n + 1, 1e18); dp[n] = 0; ...
2107
F2
Cycling (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $1\le n\le 10^6$ and you need to output the answer for each prefix. You can hack only if you solved all versions of this problem.} Leo works as a programmer in the city center, and his lover teaches at a high ...
Read the editorial for F1 first. We considered the positions that we would take $p$ to, which we assumed was $q$ and iterated $q = p, p + 1, \ldots, n$, finding the cost for each. Property : Optimal $q$ is only $q = p$ or $q = n$. Suppose $q \ne p$, i.e. we use $a_p$ for overtaking $p + 1$, and we used $a_i$ for overta...
[ "binary search", "brute force", "data structures", "dp", "greedy" ]
2,800
#include <bits/stdc++.h> using namespace std; #define int long long #define INF (int)1e18 #define inf 1e18 #define ld long double mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count()); struct chtDynamicMin { struct line { int m, b; ld x; int om, ob; int val; bool isQuery; line(int _m ...
2108
A
Permutation Warm-Up
For a permutation $p$ of length $n$$^{\text{∗}}$, we define the function: $$ f(p) = \sum_{i=1}^{n} \lvert p_i - i \rvert $$ You are given a number $n$. You need to compute how many \textbf{distinct} values the function $f(p)$ can take when considering \textbf{all possible} permutations of the numbers from $1$ to $n$....
Let's start with $p = [1, 2, 3, \dots , n]$. For this $p$, $f(p) = 0$. Let's move $n$ to the beginning one position at a time. It's easy to see that we increase the answer by $2$ at each step. Now, let's move $n - 1$ to position $2$, then $n - 2$ to position $3$, and so on, until we reach $p = [n, n - 1, \dots , 2, 1...
[ "combinatorics", "greedy", "math" ]
800
#include <iostream> #include <vector> using namespace std; typedef long long int ll; #define SPEEDY std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0); #define forn(i, n) for (ll i = 0; i < ll(n); ++i) void solution(){ ll n;cin>>n; ll k=n/2; if (n%2){cout<<k*(k+1)+1;return;} cout<<k*k...
2108
B
SUMdamental Decomposition
On a recent birthday, your best friend Maurice gave you a pair of numbers $n$ and $x$, and asked you to construct an array of \textbf{positive} numbers $a$ of length $n$ such that $a_1 \oplus a_2 \oplus \cdots \oplus a_n = x$ $^{\text{∗}}$. This task seemed too simple to you, and therefore you decided to give Maurice ...
Let $x > 1$, and let $c$ denote the number of 1-bits in its binary representation. Clearly, when $n \le c$, it is optimal to simply distribute distinct powers of two across the elements of the array, resulting in the minimum achievable sum of $x$. If, however, $n > c$, then it is obviously beneficial to add only ones t...
[ "bitmasks", "constructive algorithms", "greedy", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; typedef long long int ll; void solution(){ int n,x;cin>>n>>x; int bits=__builtin_popcountll(x); if (n<=bits){cout<<x;return;} if ((n-bits)%2==0)cout<<x+n-bits; else{ if (x>1){cout<<x+n-bits+1;return;} if (x==1){cout<<n+3;return;} ...
2108
C
Neo's Escape
Neo wants to escape from the Matrix. In front of him are $n$ buttons arranged in a row. Each button has a weight given by an integer: $a_1, a_2, \ldots, a_n$. Neo is immobilized, but he can create and move clones. This means he can perform an unlimited number of actions of the following two types in any order: - Crea...
Note that consecutive buttons with the same weight do not affect the result, so we will keep only one of them in such sequences. In the resulting array, we find peaks (local maxima - elements that are strictly greater than both of their neighbors). The number of such peaks is the answer, because: - Each peak is separat...
[ "binary search", "brute force", "data structures", "dp", "dsu", "graphs", "greedy", "implementation" ]
1,500
#include <iostream> #include <vector> using namespace std; int main() { int tt = 1; cin >> tt; while(tt--){ int n; cin >> n; vector<int> a; a.push_back(-1e9); for (int i = 0; i < n; i++){ int x; cin >> x; if (a.back() == x); else a.push...
2108
D
Needle in a Numstack
This is an interactive problem. You found the numbers $k$ and $n$ in the attic, but lost two arrays $A$ and $B$. You remember that: - $|A| + |B| = n$, the total length of the arrays is $n$. - $|A| \geq k$ and $|B| \geq k$, the length of each array is at least $k$. - The arrays consist only of numbers from $1$ to $k$...
Let $k = 4$ and the following array is guessed: [ 2 4 3 1 2 4 3 1 2 1 3 2 4 1 3 2 4 1 ] For clarity, let's divide it into groups of $k$ elements: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 ] By statement, the lengths of the left and right sides are at least $k$. Let's request the left $k$ and right $k$ eleme...
[ "binary search", "brute force", "implementation", "interactive" ]
2,200
#include <cstdio> #include <cstdlib> #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)) #define MAX(X, Y) (((X) > (Y)) ? (X) : (Y)) typedef long long l; l a[55], b[55], ui[55]; l ask(l v) { printf("? %lld\n", v + 1); fflush(stdout); l t; scanf("%lld", &t); return t; } void noans() { printf("! -1\n"); ...
2108
E
Spruce Dispute
It's already a hot April outside, and Polycarp decided that this is the perfect time to finally take down the spruce tree he set up several years ago. As he spent several hours walking around it, gathering his strength, he noticed something curious: the spruce is actually a tree$^{\text{∗}}$ — and not just any tree, bu...
Let's assume we have already removed one of the edges from the original tree. Then, we are left with a tree containing an even number of vertices, namely $n - 1$. Note that the maximum possible sum of distances between same-colored balls in this tree will be achieved if, for every edge, all vertices in its smaller subt...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy", "implementation", "shortest paths", "trees" ]
2,600
#include <cstdio> #include <vector> #define S 200005 using namespace std; typedef long long l; l coloring[S], centroid, best, best_dist, n, color; vector<vector<l>> g; l search_centroid(l u, l from) { l sum = 0; bool f = true; for (l v : g[u]) if (v != from) { l t = search_centroid(v, u); if (t > n / ...
2108
F
Fallen Towers
Pizano built an array $a$ of $n$ towers, each consisting of $a_i \ge 0$ blocks. Pizano can knock down a tower so that the next $a_i$ towers grow by $1$. In other words, he can take the element $a_i$, increase the next $a_i$ elements by one, and then set $a_i$ to $0$. The blocks that fall outside the array of towers di...
It can be shown that for any array $A$ obtained after collapsing all $n$ towers, we can also obtain any other array $B$ whose elements do not exceed the elements of $A$. A strict formal proof is provided in the spoiler below; here is a brief explanation. Suppose $k$ blocks fell onto the $i$-th tower over the entire pro...
[ "binary search", "greedy" ]
2,900
#include <cstdio> #include <algorithm> #include <cstring> #define S 100005 typedef long long l; l a[S], d[S], n; bool check(l ans) { memset(d, 0, sizeof(l) * n); l acc = 0; for (l i = 0; i < n; ++i) { acc -= d[i]; l need = std::max(0LL, i - (n - ans)); if (acc < ne...
2109
A
It's Time To Duel
Something you may not know about Mouf is that he is a big fan of the Yu-Gi-Oh! card game. He loves to duel with anyone he meets. To gather all fans who love to play as well, he decided to organize a big Yu-Gi-Oh! tournament and invited $n$ players. Mouf arranged the $n$ players in a line, numbered from $1$ to $n$. The...
What can you say when every player has reported a win? A report array can be genuine only if it meets both of these conditions: There must be at least one player who reported $0$ - there are $n - 1$ duels and $n$ players. There cannot be two adjacent players who both reported $0$ - one of them must have won the duel be...
[ "implementation" ]
800
#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]; } if (accumulate(a.begin(), a.end(), 0) == n) { cout << "YES" << "\n"; return; } for (int i = 0; i < n - 1; i++) if (!a[i]...
2109
B
Slice to Survive
Duelists Mouf and Fouad enter the arena, which is an $n \times m$ grid! Fouad's monster starts at cell $(a, b)$, where rows are numbered $1$ to $n$ and columns $1$ to $m$. Mouf and Fouad will keep duelling until the grid consists of only one cell. In each turn: - Mouf first cuts the grid along a row or column line ...
What changes if the turn order is reversed - starting with Fouad's move before Mouf's cut? Can the row and column dimensions be treated independently, or do they interact? How might that influence your approach? We restructure the game by grouping each move (Fouad's move) with the following cut (Mouf's cut). After Mouf...
[ "bitmasks", "greedy", "math" ]
1,200
#include<bits/stdc++.h> using namespace std; void solve() { int n, m, a, b; cin >> n >> m >> a >> b; vector<pair<int, int>> rec({ make_pair(a, m), make_pair(n - a + 1, m), make_pair(n, b), make_pair(n, m - b + 1)}); int ans = n + m; for (auto [n1, m1] : rec) { int res = 0; ...
2109
C1
Hacking Numbers (Easy Version)
\textbf{This is the easy version of the problem. In this version, you can send at most $\mathbf{7}$ commands. You can make hacks only if all versions of the problem are solved.} This is an interactive problem. Welcome, Duelists! In this interactive challenge, there is an unknown integer $x$ ($1 \le x \le 10^9$). You ...
Figure out a way to make $x$ equal $1$, then the final command will be $\texttt{"add n-1"}$. What range of values can $x$ take after the first application of the $\texttt{"digit"}$ command? What about the second application of the $\texttt{"digit"}$ command? Avoid overusing the $\texttt{"digit"}$ command - after the se...
[ "bitmasks", "constructive algorithms", "interactive", "math", "number theory" ]
1,500
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; cout << "digit" << endl; int x; cin >> x; cout << "digit" << endl; cin >> x; for (int i = 8; i >= 1; i /= 2) { cout << "add " << -i << endl; cin >> x; } cout << "add " << n - 1 << e...
2109
C2
Hacking Numbers (Medium Version)
\textbf{This is the medium version of the problem. In this version, you can send at most $\mathbf{4}$ commands. You can make hacks only if all versions of the problem are solved.} This is an interactive problem. Welcome, Duelists! In this interactive challenge, there is an unknown integer $x$ ($1 \le x \le 10^9$). Yo...
The first command is not $\texttt{"digit"}$. The first command is $\texttt{"mul"}$. Combining the $\texttt{"mul"}$ and $\texttt{"digit"}$ commands is powerful! Consider a number that links these two commands. Recall that well-known fact from high school: a number is divisible by $9$ if and only if the sum of its digits...
[ "constructive algorithms", "interactive", "math", "number theory" ]
1,700
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; cout << "mul " << 9 << endl; int x; cin >> x; cout << "digit" << endl; cin >> x; cout << "digit" << endl; cin >> x; cout << "add " << n - 9 << endl; cin >> x; cout << "!" << endl; cin ...
2109
C3
Hacking Numbers (Hard Version)
\textbf{This is the hard version of the problem. In this version, the limit of commands you can send is described in the statement. You can make hacks only if all versions of the problem are solved.} This is an interactive problem. Welcome, Duelists! In this interactive challenge, there is an unknown integer $x$ ($1 ...
While $9$ connects the $\texttt{"mul"}$ and $\texttt{"digit"}$ commands, there may be other numbers that do so as well. Another valid solution for the medium version is as follows: $\texttt{"digit"}$. $\texttt{"mul 99"}$. $\texttt{"digit"}$. $\texttt{"add n-18"}$. But what's the reasoning behind this sequence? $S[(10^d...
[ "constructive algorithms", "interactive", "math", "number theory" ]
2,600
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; cout << "mul 999999999" << endl; int x; cin >> x; cout << "digit" << endl; cin >> x; if (n != 81) { cout << "add " << n - 81 << endl; cin >> x; } cout << "!" << endl; cin >> x; ...
2109
D
D/D/D
Of course, a problem with the letter D is sponsored by Declan Akaba. You are given a simple, connected, undirected graph with $n$ vertices and $m$ edges. The graph contains no self-loops or multiple edges. You are also given a multiset $A$ consisting of $\ell$ elements: $$ A = \{A_1, A_2, \ldots, A_\ell\} $$ Starting...
Suppose you've reached vertex $i$, what is the shortest possible sequence of moves that brings you back to $i$? At any vertex $j$ adjacent to $i$, you may take back-and-forth move $[i \to j \to i].$ Let us temporarily set aside the multiset $A$. Starting from vertex $1$, define ${}$ $\mathrm{dist}[i][p] = \min \{ \, \t...
[ "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,900
#include<bits/stdc++.h> using namespace std; void solve() { int n, m, l; cin >> n >> m >> l; int const inf = 2e9 + 1; int sum = 0, min_odd = inf; vector<int> a(l); for (int i = 0; i < l; ++i) { cin >> a[i]; sum += a[i]; if (a[i] % 2) { min_odd = min(min_odd...
2109
E
Binary String Wowee
Mouf is bored with themes, so he decided not to use any themes for this problem. You are given a binary$^{\text{∗}}$ string $s$ of length $n$. You are to perform the following operation exactly $k$ times: - select an index $i$ ($1 \le i \le n$) such that $s_i = \mathtt{0}$; - then flip$^{\text{†}}$ each $s_j$ for all...
The state of $s_i$ depend entirely on how many operations have been performed on the suffix $s_i, s_{i+1}, \ldots, s_n$. Let $dp[i][j]$ denote the number of ways to perform exactly $j$ moves on the suffix $s_i, s_{i+1}, \ldots, s_n$. Some useful insight is to see that if you operate on an element, then every element af...
[ "combinatorics", "dp", "strings" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2109
F
Penguin Steps
Mouf, the clever master of Darkness, and Fouad, the brave champion of Light, have entered the Grid Realm once more. This time, they have found the exit, but it is guarded by fierce monsters! They must fight with their bare hands instead of summoning monsters! Mouf and Fouad are standing on an $n \times n$ grid. Each c...
Suppose you need $\mathrm{dis}_F \ge x$. To achieve this, construct a "cage" - a contiguous path of cells all with values at least $x$ - that separates Fouad from the exit, while ensuring that $\mathrm{dis}_M$ remains unchanged. Try to find a path for Mouf that impacts the building of the "cage" as little as possible. ...
[ "binary search", "dfs and similar", "flows", "graphs", "shortest paths" ]
3,000
#include<bits/stdc++.h> using namespace std; using i64 = long long; constexpr int inf = 1e9; array<int, 8> dx{0, 0, 1, -1, 1, 1, -1, -1}; array<int, 8> dy{1, -1, 0, 0, -1, 1, -1, 1}; void solve() { int n, r, k; cin >> n >> r >> k; --r; vector a(n, vector<int>(n)); for (int i = 0; i < n; ++i...
2110
A
Fashionable Array
In 2077, everything became fashionable among robots, even arrays... We will call an array of integers $a$ fashionable if $\min(a) + \max(a)$ is divisible by $2$ without a remainder, where $\min(a)$ — the value of the minimum element of the array $a$, and $\max(a)$ — the value of the maximum element of the array $a$. ...
Sort the array $a$. Notice that now, after any removals, the minimum element is the leftmost of the remaining elements, and the maximum is the rightmost of the remaining elements. Check if it is fashionable. If yes, then the answer is $0$. Otherwise, $a_1 + a_n$ is not divisible by $2$. Thus, we need to remove the mini...
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> x(n); for (int i = 0; i < n; ++i) { cin >> x[i]; } sort(x.begin(), x.end()); if (x[0] % 2 == x[n - 1] % 2) { cout << 0 << endl; return; } int left = n, right = n; f...
2110
B
Down with Brackets
In 2077, robots decided to get rid of balanced bracket sequences once and for all! A bracket sequence is called balanced if it can be constructed by the following formal grammar. - The empty sequence $\varnothing$ is balanced. - If the bracket sequence $A$ is balanced, then $\mathtt{(}A\mathtt{)}$ is also balanced. -...
Let's recall the algorithm for checking the correctness of a bracket sequence. To do this, we check that the balance $bal$ at each prefix is non-negative, and that the balance $bal$ of the entire sequence is equal to $0$. To break a correct bracket sequence, we need to violate at least one of the conditions. Note that ...
[ "strings" ]
900
#include "bits/stdc++.h" #define int long long #define all(v) (v).begin(), (v).end() #define pb push_back #define em emplace_back #define mp make_pair #define F first #define S second using namespace std; template<class C> using vec = vector<C>; using vi = vector<int>; using vpi = vector<pair<int, int>>; using pii = p...
2110
C
Racing
In 2077, a sport called hobby-droning is gaining popularity among robots. You already have a drone, and you want to win. For this, your drone needs to fly through a course with $n$ obstacles. The $i$-th obstacle is defined by two numbers $l_i, r_i$. Let the height of your drone at the $i$-th obstacle be $h_i$. Then t...
Let's maintain the bounds $L, R$ - the segment of heights in which $h_i$ can currently be. Initially, $L = R = 0$. Now, we will iterate from $i = 1$ to $n$. We could have risen by $1$, so $R$ increases by $1$. We also cannot rise above $r_i$ or drop below $l_i$, so if $R > r_i$, then $R = r_i$, and if $L < l_i$, then $...
[ "constructive algorithms", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> d(n); for (auto &x : d) { cin >> x; } vector<int> l(n), r(n); for (int i = 0; i < n; ++i) { cin >> l[i] >> r[i]; } int left = 0; vector<int> last; for (int i = 0; i < n...
2110
D
Fewer Batteries
In 2077, when robots took over the world, they decided to compete in the following game. There are $n$ checkpoints, and the $i$-th checkpoint contains $b_i$ batteries. Initially, the Robot starts at the $1$-st checkpoint with no batteries and must reach the $n$-th checkpoint. There are a total of $m$ one-way passages...
We will build a directed graph: vertices are points, and edges are passages. We will perform a binary search on the answer. Suppose we are currently checking that $ans \leq mid$. Then we will perform the following dynamic programming: $dp_v$ - the maximum number of batteries that the robot can have when it is at vertex...
[ "binary search", "dfs and similar", "dp", "graphs", "greedy", "hashing" ]
1,700
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 11; struct edge { int t, w; edge(int t, int w) : t(t), w(w) {} }; void solve() { int n, m; cin >> n >> m; vector<int> b(n); for (auto &x : b) { cin >> x; } vector<vector<edge>> graph(n); for (int i = 0; i...
2110
E
Melody
In 2077, the robots that took over the world realized that human music wasn't that great, so they started composing their own. To write music, the robots have a special musical instrument capable of producing $n$ different sounds. Each sound is characterized by its volume and pitch. A sequence of sounds is called musi...
Let's construct a bipartite graph, where all possible volumes of sounds are on the left and pitches are on the right. Then a pair of vertices $p,v$ will be connected by an edge if the musical instrument can produce the sound $(p,v)$. Notice that each path in such a graph represents $beautiful$ music. This is because an...
[ "dfs and similar", "graphs", "implementation" ]
2,300
#include <bits/stdc++.h> using namespace std; vector<set<int>> graph; vector<int> ans; void dfs(int v) { while (!graph[v].empty()) { int u = *graph[v].begin(); graph[u].erase(v); graph[v].erase(u); dfs(u); } ans.push_back(v); } signed main() { int t; cin >> t; ...
2110
F
Faculty
In 2077, after the world was enslaved by robots, the robots decided to implement an educational reform, and now the operation of taking the modulus is only taught in the faculty of "Ancient World History". Here is one of the entrance tasks for this faculty: We define the beauty of an array of positive integers $b$ as ...
To solve the problem, several facts need to be noted. Fact I. $f(x, y) \leq \max(x, y)$. If $x = y$, then $f(x, y) = 0$. Otherwise, let $x < y$. Then $x \mod y = x$. Thus, $f(x, y) = x + y - \lfloor{\frac{y}{x}}\rfloor \cdot x \leq y$, since $\lfloor{\frac{y}{x}}\rfloor \geq 1$. Fact II. We can only consider pairs with...
[ "brute force", "greedy", "math", "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; int f(int x, int y) { return (x % y) + (y % x); } void Solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int ans = 0; int mx = a[0]; for (int i = 0; i < n; ++i) { ans = max(ans, f...
2111
A
Energy Crystals
There are three energy crystals numbered $1$, $2$, and $3$; let's denote the energy level of the $i$-th crystal as $a_i$. Initially, all of them are discharged, meaning their energy levels are equal to $0$. Each crystal needs to be charged to level $x$ \textbf{(exactly $x$, not greater)}. In one action, you can increa...
Let's relax the requirement that all crystals must be charged exactly to level $x$ and allow the energy level to rise above it, i.e., $a_{i} \ge x$ in the end. We will try to come up with a greedy algorithm to charge the crystals. The simplest idea is to take the crystal with the minimum energy level and charge it as m...
[ "greedy", "implementation", "math" ]
800
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int x; cin >> x; int ans = 0; int a1 = 0, a2 = 0, a3 = 0; while(min({a1, a2, a3}) < x){ if (a1 <= a2 && a1 <= a3){ a1 = min(a2, a3) * 2 + 1; } else if (a2 <= a1 && a2 <= a3){ a2 = min(a1, a3) * 2 + 1; } else{ ...
2111
B
Fibonacci Cubes
There are $n$ Fibonacci cubes, where the side of the $i$-th cube is equal to $f_{i}$, where $f_{i}$ is the $i$-th Fibonacci number. In this problem, the Fibonacci numbers are defined as follows: - $f_{1} = 1$ - $f_{2} = 2$ - $f_{i} = f_{i - 1} + f_{i - 2}$ for $i > 2$ There are also $m$ empty boxes, where the $i$-th...
Notice the following: if we can fit the two largest cubes from the set into the box, then we can also fit all the smaller cubes into it. To fit the two largest cubes, it is sufficient that all sides of the box are at least $f_{n}$, and the larger of the sides of the box is at least $f_{n + 1}$. The first condition is q...
[ "brute force", "dp", "implementation", "math" ]
1,100
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int n, m; cin >> n >> m; vector<vector<int>> a(m); for (int i = 0; i < m; i++){ for (int j = 0; j < 3; j++){ int x; cin >> x; a[i].emplace_back(x); } sort(a[i].begin(), a[i].end()); } vector<int> fib(n + 5); fi...
2111
C
Equal Values
You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ integers. In one operation, you are allowed to perform one of the following actions: - Choose a position $i$ ($1 < i \le n$) and make all elements to the left of $i$ equal to $a_i$. That is, assign the value $a_i$ to all $a_j$ ($1 \le j < i$). The cost ...
The first minor observation is that the cost of both operations is the value of the element times the number of the elements affected by the operation. Let's also expand the scope of both operations so that we can apply the first operation to the first element (with cost $0$, since $0$ elements are affected) and the se...
[ "brute force", "greedy", "two pointers" ]
1,100
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) i = 0 ans = 10**18 while i < n: j = i while j < n and a[j] == a[i]: j += 1 ans = min(ans, (i + n - j) * a[i]) i = j print(ans)
2111
D
Creating a Schedule
A new semester is about to begin, and it is necessary to create a schedule for the first day. There are a total of $n$ groups and $m$ classrooms in the faculty. It is also known that each group has exactly $6$ classes on the first day, and the $k$-th class of each group takes place at the same time. Each class must be ...
Let $f_{i,j}$ be the floor where the $i$-th group has its $j$-th class. Then, the number of moves between floors can be expressed as follows: $\sum\limits_{j=1}^{5} \sum\limits_{i=1}^{n} |f_{i,j} - f_{i,j+1}|$ Using the fact that $|x-y| = \max(x,y) - \min(x,y)|$, we can rewrite it as follows: $\sum\limits_{j=1}^{5} \su...
[ "constructive algorithms", "data structures", "greedy", "implementation", "sortings" ]
1,400
#include<bits/stdc++.h> using namespace std; void solve(){ int n, m; cin >> n >> m; vector<int> a(m); for (int i = 0; i < m; i++){ cin >> a[i]; } sort(a.begin(), a.end()); vector<vector<int>> ans(n, vector<int> (6)); for (int i = 0; i < n; i += 2){ if (i + 1 == n){ for (int j = 0; j < 6; j++){ ...
2111
E
Changing the String
Given a string $s$ that consists only of the first three letters of the Latin alphabet, meaning each character of the string is either a, b, or c. Also given are $q$ operations that need to be performed on the string. In each operation, two letters $x$ and $y$ from the set of the first three letters of the Latin alpha...
First, let's try to understand what operations and sequences of operations make sense to perform. Each letter can be transformed at most two times: if we change it more than twice, then at two moments in time it will be the same, and all operations between them can be omitted. Clearly, there is no point in transforming...
[ "binary search", "data structures", "greedy", "implementation", "sortings", "strings" ]
1,900
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int n, q; cin >> n >> q; string s; cin >> s; vector<vector<set<int>>> st(3, vector<set<int>> (3)); for (int i = 0; i < q; i++){ char x, y; cin >> x >> y; st[x - 'a'][y - 'a'].insert(i); } for (int i = 0; i < n; i++){ i...
2111
F
Puzzle
You have been gifted a puzzle, where each piece of this puzzle is a square with a side length of one. You can glue any picture onto this puzzle, cut it, and obtain an almost ordinary jigsaw puzzle. Your friend is an avid mathematician, so he suggested you consider the following problem. Is it possible to arrange the p...
If a figure consists of a single piece, then its perimeter-to-area ratio is $4$ to $1$. In fact, this is the maximum ratio that can be achieved. That is, if $\frac{p}{s} > 4$, the answer is $-1$. Now we need to understand what other ratios can exist: Suppose we have placed one piece; let's add one neighboring piece to ...
[ "brute force", "constructive algorithms", "greedy", "math" ]
2,400
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int p, s; cin >> p >> s; if (p > 4 * s){ cout << "-1\n"; return; } if (p > 2 * s){ for (int i = 1; i <= 50000; i++){ if (p * i == (2 + 2 * i) * s){ cout << i << '\n'; for (int j = 0; j < i; j++){ cout << "0 "...
2111
G
Divisible Subarrays
\textbf{Technically, this is an interactive problem.} An array $a$ of $m$ numbers is called divisible if at least one of the following conditions holds: - There exists an index $i$ ($1 \le i < m$) and an integer $x$ such that for all indices $j$ ($j \le i$), it holds that $a_{j} \le x$ and for all indices $k$ ($k > i...
Solution 1: Note that you are asked to solve the problem "online". This means there is some simple "offline" solution that is being cut off. In other words, the problem can be solved more easily if you could answer the queries in an arbitrary order. Let's iterate over $x$ in an increasing order. Maintain the following ...
[ "binary search", "bitmasks", "brute force", "data structures", "interactive" ]
2,900
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) const int INF = 1e9; const int LOGN = 18; struct solver{ int n; vector<int> p; solver(const vector<int> &p) : p(p){ n = p.size(); build(); } vector<int> nxtmn, nxtmx; vector<v...
2113
A
Shashliks
You are the owner of a popular shashlik restaurant, and your grill is the heart of your kitchen. However, the grill has a peculiarity: after cooking each shashlik, its temperature drops. You need to cook as many portions of shashlik as possible, and you have an unlimited number of portions of two types available for c...
Notice that it is beneficial for us to cook the portion of barbecue that we can prepare and, at the same time, after cooking it, the temperature drops by the smallest amount. Indeed, the higher the current temperature of the grill, the more portions of barbecue we can prepare. Therefore, the complete solution is as fol...
[ "greedy", "math" ]
800
#include <iostream> using namespace std; void solve() { int t, a, b, x, y; cin >> t >> a >> b >> x >> y; auto solve = [&](int t, int a, int b, int x, int y) { int cur = 0; cur += max((t - a + x) / x, 0); t -= max((t - a + x) / x, 0) * x; cur += max((t - b + y) / y, 0); ...
2113
B
Good Start
The roof is a rectangle of size $w \times h$ with the bottom left corner at the point $(0, 0)$ on the plane. Your team needs to completely cover this roof with identical roofing sheets of size $a \times b$, with the following conditions: - The sheets cannot be rotated (not even by $90^\circ$). - The sheets must not ov...
Let $x_1 \neq x_2, y_1 \neq y_2$. We will show that the necessary and sufficient condition to tile the roof is $(x_2 - x_1)~\text{mod}~a = 0$ or $(y_2 - y_1)~\text{mod}~b = 0$. If this condition is satisfied, then we can tile the roof either "by columns" or "by rows". On the other hand, suppose there is some tiling, th...
[ "constructive algorithms", "math" ]
1,200
def solve(): w, h, a, b = map(int, input().split()) x1, y1, x2, y2 = map(int, input().split()) if x1 == x2: if abs(y1 - y2) % b == 0: return "Yes" else: return "No" if y1 == y2: if abs(x1 - x2) % a == 0: return "Yes" else: ...
2113
C
Smilo and Minecraft
The boy Smilo is playing Minecraft! To prepare for the battle with the dragon, he needs a lot of golden apples, and for that, he requires a lot of gold. Therefore, Smilo goes to the mine. The mine is a rectangular grid of size $n \times m$, where each cell can be either gold ore, stone, or an empty cell. Smilo can blo...
Let us consider the first explosion. Note that all the gold ore that was inside this square will be lost. However, observe that all the remaining gold ore in the mine will be obtained for sure. Indeed, we make explosions first in all the cells on the border of the square with side $3$ and center at the point of the fir...
[ "brute force", "constructive algorithms", "greedy" ]
1,700
#include <algorithm> #include <iostream> #include <vector> #include <string> #include <map> #include <set> #include <unordered_map> #include <random> #include <chrono> #include <cassert> #include <numeric> #include <bitset> #include <iomanip> #include <queue> #include <unordered_set> #include <fstream> #include <random...
2113
D
Cheater
You are playing a new card game in a casino with the following rules: - The game uses a deck of $2n$ cards with different values. - The deck is evenly split between the player and the dealer: each receives $n$ cards. - Over $n$ rounds, the player and the dealer simultaneously play one top card from their hand. The car...
Let us consider all prefix minimums, and let their positions be $k_{1}, k_{2}, \ldots, k_{s}$. Note that if at some round the card $a_{k_{j}}$ wins ($a_{k_{j}} > b_{t}$), then the cards $a_{k_{j} + 1}, a_{k_{j} + 2}, \ldots, a_{k_{j + 1}}$ will also win, since all of them have a nominal value greater than $a_{k_{j}}$. ...
[ "binary search", "constructive algorithms", "greedy", "implementation" ]
2,200
#include <bits/stdc++.h> using namespace std; #define sz(x) (int) ((x).size()) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const char en = '\n'; const int INF = 1e9 + 7; const ll IN...
2113
E
From Kazan with Love
Marat is a native of Kazan. Kazan can be represented as an undirected tree consisting of $n$ vertices. In his youth, Marat often got into street fights, and now he has $m$ enemies, numbered from $1$ to $m$, living in Kazan along with him. Every day, all the people living in the city go to work. Marat knows that the $i...
Lemma: If the answer $\neq$ -1, then it does not exceed $2 \times N + 1$. Proof: Let the optimal path be $s_1 = x, s_2, s_3, \cdots, s_k = y$. Then, at time $N+1$, all the enemies have already reached work, and we can go from $s_{N+1}$ to $s_{k}$ in $\leq N$ moves $\Rightarrow k \leq 2 \times N + 1$. Let us call a mome...
[ "dfs and similar", "graphs", "implementation", "trees" ]
2,800
//#pragma GCC optimize("Ofast") #include "bits/stdc++.h" #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep1(i, n) for (int i = 1; i < (n); ++i) #define rep1n(i, n) for (int i = 1; i <= (n); ++i) #define repr(i, n) for (int i = (n) - 1; i >= 0; --i) //#define pb push_back #define eb emplace_back #define all(...
2113
F
Two Arrays
You are given two arrays $a$ and $b$ of length $n$. You can perform the following operation an unlimited number of times: - Choose an integer $i$ from $1$ to $n$ and swap $a_i$ and $b_i$. Let $f(c)$ be the number of distinct numbers in array $c$. Find the maximum value of $f(a) + f(b)$. Also, output the arrays $a$ an...
This problem has many different solutions. Feel free to share your ideas in the comments. Let us consider an arbitrary number $x$: If it does not appear in arrays $a$ and $b$, then it does not affect the answer in any way. If it appears exactly once, then no matter how we perform the operations, it always contributes $...
[ "constructive algorithms", "dfs and similar", "graphs", "math" ]
2,500
#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]; } vector<int> b(n); for (int i = 0; i < n; i++) { cin >> b[i]; } vector<int> want(n); auto make = [&] (int i, int x, int ...
2114
A
Square Year
One can notice the following remarkable mathematical fact: the number $2025$ can be represented as $(20+25)^2$. You are given a year represented by a string $s$, consisting of exactly $4$ characters. Thus, leading zeros are allowed in the year representation. For example, "0001", "0185", "1375" are valid year represen...
To solve this problem it was enough to check whether number $s$ is the square of some integer $x$. If yes, then the answer to the set of input data could be a pair of numbers $a=0$, $b=x$, or any other existing partition of number $x$ into a pair of non-negative summands. Otherwise, the answer to the problem is - $-1$.
[ "binary search", "brute force", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int sq = ceil(sqrt(n)); if (sq * sq == n) { cout << 0 << ' ' << sq << "\n"; } else { cout << "-1\n"; } } int main() { int t; cin >> t; while (t--) solve(); }
2114
B
Not Quite a Palindromic String
Vlad found a binary string$^{\text{∗}}$ $s$ of even length $n$. He considers a pair of indices ($i, n - i + 1$), where $1 \le i < n - i + 1$, to be good if $s_i = s_{n - i + 1}$ holds true. For example, in the string '010001' there is only $1$ good pair, since $s_1 \ne s_6$, $s_2 \ne s_5$, and $s_3=s_4$. In the string...
To begin, let's solve a simpler problem: we will find the minimum and maximum possible number of good pairs. To achieve the minimum number of pairs, we will place all zeros at the beginning of the string and all ones at the end. Then, if the number of zeros is $c_0$ and the number of ones is $c_1$, the number of good p...
[ "greedy", "math" ]
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 int inf = 1e9; con...
2114
C
Need More Arrays
Given an array $a$ and $n$ integers. It is sorted in non-decreasing order, that is, $a_i \le a_{i + 1}$ for all $1 \le i < n$. You can remove any number of elements from the array (including the option of not removing any at all) without changing the order of the remaining elements. After the removals, the following w...
We will be selecting elements from left to right, skipping some of them. If a new element is supposed to go into the same array as the last one we took, then skipping it will not make things worse. This is true because if we took an element equal to $x$, then skipping an element equal to $x + 1$ will allow an element e...
[ "dp", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve(int tc){ int n; cin >> n; int last = -1, ans = 0; for(int i = 0; i < n; ++i){ int a; cin >> a; if(a - last > 1){ ans++; last = a; } } cout << ans; } bool multi = true; signed main...
2114
D
Come a Little Closer
The game field is a matrix of size $10^9 \times 10^9$, with a cell at the intersection of the $a$-th row and the $b$-th column denoted as ($a, b$). There are $n$ monsters on the game field, with the $i$-th monster located in the cell ($x_i, y_i$), while the other cells are empty. No more than one monster can occupy a ...
The minimum rectangle that we can choose must have sides of length $\max_i(x_i) - \min_i(x_i) + 1$ and $\max_i(y_i) - \min_i(y_i) + 1$, meaning that the maximum and minimum values along both axes are important. Let's consider the movement of a certain monster; we will not choose a new position but will simply examine t...
[ "brute force", "greedy", "implementation", "math" ]
1,400
#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 int inf = 1e9; con...