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
1950
A
Stair, Peak, or Neither?
You are given three digits $a$, $b$, and $c$. Determine whether they form a stair, a peak, or neither. - A stair satisfies the condition $a<b<c$. - A peak satisfies the condition $a<b>c$.
You just need to write two if-statements and check the two cases. Please note that some languages like C++ won't allow a chain of comparisons like a < b < c, and you should instead write it as a < b && b < c.
[ "implementation" ]
800
#include <iostream> void solve() { int a, b, c; std::cin >> a >> b >> c; if(a < b && b < c) std::cout << "STAIR"<< "\n"; else if(a < b && b > c) std::cout << "PEAK"<< "\n"; else std::cout << "NONE" << "\n"; } int main() { int tt; std::cin >> tt; while(tt--) solve(); }
1950
B
Upscaling
You are given an integer $n$. Output a $2n \times 2n$ checkerboard made of $2 \times 2$ squares alternating '$#$' and '$.$', with the top-left cell being '$#$'. \begin{center} {\small The picture above shows the answers for $n=1,2,3,4$.} \end{center}
You just need to implement what is written. One way is to go cell-by-cell in a regular $n \times n$ checkerboard, and construct the larger one one cell at a time by copying cell $(i,j)$ into cells $(2i,2j)$, $(2i+1, 2j)$, $(2i, 2j+1)$, $(2i+1, 2j+1)$. A faster solution is to notice that if we round down coordinates $(x...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; for (int i = 0; i < 2 * n; i++) { for (int j = 0; j < 2 * n; j++) { cout << (i / 2 + j / 2 & 1 ? '.' : '#'); } cout << '\n'; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1...
1950
C
Clock Conversion
Given the time in 24-hour format, output the equivalent time in 12-hour format. - 24-hour format divides the day into 24 hours from $00$ to $23$, each of which has 60 minutes from $00$ to $59$. - 12-hour format divides the day into two halves: the first half is $\mathrm{AM}$, and the second half is $\mathrm{PM}$. In e...
From 24-hour format to 12-hour format, the minutes are the same. For the hours: If $\texttt{hh}$ is $00$, then it should become $12 \; \mathrm{AM}$. If $\texttt{hh}$ is from $01$ to $11$, then it should become $\texttt{hh} \; \mathrm{AM}$. If $\texttt{hh}$ is $12$, then it should become $12 \; \mathrm{PM}$. If $\texttt...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int h, m; char c; cin >> h >> c >> m; string am = (h < 12 ? " AM" : " PM"); h = (h % 12 ? h % 12 : 12); cout << (h < 10 ? "0" : "") << h << c << (m < 10 ? "0" : "") << m << am << '\n'; } int main() { ios::sync_with_stdio(false); cin.t...
1950
D
Product of Binary Decimals
Let's call a number a binary decimal if it is a positive integer and all digits in its decimal notation are either $0$ or $1$. For example, $1\,010\,111$ is a binary decimal, while $10\,201$ and $787\,788$ are not. Given a number $n$, you are asked whether or not it is possible to represent $n$ as a product of some (n...
First, let's make precompute list of all binary decimals at most $10^5$. You can do it in many ways, for example iterating through all numbers up to $10^5$ and checking if each is a binary decimal. Let's call a number good if it can be represented as the product of binary decimals. For each test case, we will write a s...
[ "brute force", "dp", "implementation", "number theory" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX = 100'007; const int MOD = 1'000'000'007; vector<int> binary_decimals; bool ok(int n) { if (n == 1) {return true;} bool ans = false; for (int i : binary_decimals) { if (n % i == 0) { ans |= ok(n / i); } } return ans; } void solve() { int n; ...
1950
E
Nearly Shortest Repeating Substring
You are given a string $s$ of length $n$ consisting of lowercase Latin characters. Find the length of the shortest string $k$ such that several (possibly one) copies of $k$ can be concatenated together to form a string with the same length as $s$ and, at most, one different character. More formally, find the length of...
Let's call a string a period if it can be multiplied to the same length as $s$ What are the possibilities for the lengths of the period? Clearly, it must be a divisor of $n$. So the solution is to check all divisors of $n$ and see the smallest one that works. To check if length $l$ works, multiply the prefix of length ...
[ "brute force", "implementation", "number theory", "strings" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; for(int i = 1; i <= n; i++) { if(n%i == 0) { int satisfy = 2; for(int j = 0; j < i; j++) { for(int k = j+i; k < n; k+=i) ...
1950
F
0, 1, 2, Tree!
Find the minimum height of a rooted tree$^{\dagger}$ with $a+b+c$ vertices that satisfies the following conditions: - $a$ vertices have exactly $2$ children, - $b$ vertices have exactly $1$ child, and - $c$ vertices have exactly $0$ children. If no such tree exists, you should report it.\begin{center} {\small The tre...
Note that since the tree has $a+b+c$ vertices, all vertices have $0$, $1$, or $2$ children. Call a vertex a leaf if it has no children. The idea is to "grow" the tree from the root by adding one or two vertices at a time. Formally: Start with a root (which is initially a leaf). Repeatedly add $1$ or $2$ children to a l...
[ "bitmasks", "brute force", "greedy", "implementation", "trees" ]
1,700
#include <bits/stdc++.h> using namespace std; void solve() { int a, b, c; cin >> a >> b >> c; if (a + 1 != c) {cout << -1 << '\n'; return;} if (a + b + c == 1) {cout << 0 << '\n'; return;} int curr = 1, next = 0, res = 1; for (int i = 0; i < a + b; i++) { if (!curr) { swap(next, curr); res++...
1950
G
Shuffling Songs
Vladislav has a playlist consisting of $n$ songs, numbered from $1$ to $n$. Song $i$ has genre $g_i$ and writer $w_i$. He wants to make a playlist in such a way that every pair of adjacent songs either have the same writer or are from the same genre (or both). He calls such a playlist exciting. Both $g_i$ and $w_i$ are...
First of all, always comparing strings takes quite a long time, so, let's map the strings to integers. We can do that by keeping all strings in some array, sorting the array, and mapping each string to its position in the array. This process is called "Normalization" or "Coordinate Compression". Now, we can do a dynami...
[ "bitmasks", "dfs and similar", "dp", "graphs", "hashing", "implementation", "strings" ]
1,900
#include "bits/stdc++.h" using namespace std; #define all(x) x.begin(),x.end() void solve() { int n; cin >> n; vector<int> s(n), g(n); vector<string> aa(n), bb(n); vector<string> vals; for(int i = 0; i < n; ++i) { string a, b; cin >> a >> b; vals.push_back(a); vals.push_bac...
1951
A
Dual Trigger
\begin{quote} Ngọt - LẦN CUỐI (đi bên em xót xa người ơi) \hfill ඞ \end{quote} There are $n$ lamps numbered $1$ to $n$ lined up in a row, initially turned off. You can perform the following operation any number of times (possibly zero): - Choose two \textbf{non-adjacent}${}^\dagger$ lamps that are currently turned of...
The answer is obviously "NO" if there is an odd amount of $\mathtt{1}$ in $s$. When there are zero $\mathtt{1}$'s, the answer is trivially "YES". When there are exactly two $\mathtt{1}$'s in $s$, then we also need to check whether the two $\mathtt{1}$'s are adjacent or not. Otherwise, when there are $k \ge 4$ $\mathtt{...
[ "constructive algorithms", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; int cnt = 0, mi = n, mx = -1; for (int i = 0; i < n; i++) { if (s[i] == '1') { ...
1951
B
Battle Cows
\begin{quote} The HU - Shireg Shireg \hfill ඞ \end{quote} There are $n$ cows participating in a coding tournament. Cow $i$ has a Cowdeforces rating of $a_i$ (all distinct), and is initially in position $i$. The tournament consists of $n-1$ matches as follows: - The first match is between the cow in position $1$ and t...
It is easy to note that the $i$-th match is between cow $i+1$ and the strongest cow among cows $1, 2, \cdots, i$. Therefore, in order to win any match at all, you cow have to be stronger than every cow before her (and cow $2$ if your cow is cow $1$). Consider the following cases: There exists no stronger cow before you...
[ "binary search", "data structures", "greedy" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; k--; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } int x = find_if...
1951
C
Ticket Hoarding
\begin{quote} Maître Gims - Est-ce que tu m'aimes ? \hfill ඞ \end{quote} As the CEO of a startup company, you want to reward each of your $k$ employees with a ticket to the upcoming concert. The tickets will be on sale for $n$ days, and by some time travelling, you have predicted that the price per ticket at day $i$ w...
Note: we will present the intuitive idea first; the formal proof follows later. Let's try to find a way to interpret the raised price at day $i$ from buying on earlier days. We know that every ticket bought on an earlier day than $i$ raised the price per ticket $i$ by $1$; in turn, this "additional tax" will be added t...
[ "greedy", "math", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n, m, k; cin >> n >> m >> k; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin...
1951
D
Buying Jewels
\begin{quote} Nightwish feat. Jonsu - Erämaan Viimeinen \hfill ඞ \end{quote} Alice has $n$ coins and wants to shop at Bob's jewelry store. Today, although Bob has not set up the store yet, Bob wants to make sure Alice will buy \textbf{exactly} $k$ jewels. To set up the store, Bob can erect at most $60$ stalls (each co...
We first assume that $p_i \leq n$ for $1 \leq i \leq s$, since adding stalls with price greater than $n$ doesn't change the result. If $n < k$ then the answer is obviously "NO". If $n = k$ then the answer is obviously "YES" - we can set up a single stall of price $1$. Otherwise, the first stall should have price $p_1 \...
[ "constructive algorithms", "greedy", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int64_t n, k; cin >> n >> k; if (n < k) { cout << "NO\n"; } else if (n == k) { cout << "YES\n1\n1\n"; } ...
1951
E
No Palindromes
\begin{quote} Christopher Tin ft. Soweto Gospel Choir - Baba Yetu \hfill ඞ \end{quote} You are given a string $s$ consisting of lowercase Latin characters. You need to partition$^\dagger$ this string into some substrings, such that each substring is not a palindrome$^\ddagger$. $^\dagger$ A partition of a string $s$ ...
If $s$ is not a palindrome then we are done. If $s$ consists of only one type of character then we're also done. Consider the case when $s$ is a palindrome and there are at least $2$ distinct characters. Let $t$ be the first position where $s_t \neq s_1$, and note that this means $s_{[1, t]}$ is not a palindrome. If $s...
[ "brute force", "constructive algorithms", "divide and conquer", "greedy", "hashing", "implementation", "math", "strings" ]
2,000
#include<bits/stdc++.h> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); int ntest; cin >> ntest; while (ntest--) { string s; cin >> s; int n = s.size(); auto is_palindrome = [&](int l, int r) -> bool { for (int i = l;...
1951
F
Inversion Composition
\begin{quote} My Chemical Romance - Disenchanted \hfill ඞ \end{quote} You are given a permutation $p$ of size $n$, as well as a non-negative integer $k$. You need to construct a permutation $q$ of size $n$ such that $\operatorname{inv}(q) + \operatorname{inv}(q \cdot p) = k {}^\dagger {}^\ddagger$, or determine if it ...
We say that $(i, j)$ is an inverse on permutation $p$ if $i < j$ and $p_i > p_j$, or $i > j$ and $p_i < p_j$. For any two integers $1 \le i < j \le n$, let's observe the "inverseness" of $(p_i, p_j)$ on $q$ and $(i, j)$ on $q \cdot p$: If $(i, j)$ is not an inverse on $p$, then the inverseness of $(p_i, p_j)$ on $q$ an...
[ "constructive algorithms", "data structures", "greedy" ]
2,500
#include <bits/stdc++.h> using namespace std; template<typename T> struct fenwick_tree { vector<T> bit; int n; fenwick_tree(int n) : n(n), bit(n + 1) {} T sum(int x) { T ans = 0; for (; x > 0; x -= x & -x) { ans += bit[x]; } return ans; } T sum...
1951
G
Clacking Balls
\begin{quote} Rammstein - Ausländer \hfill ඞ \end{quote} There are $m$ baskets placed along a circle, numbered from $1$ to $m$ in clockwise order (basket $m$ is next to basket $1$). Furthermore, there are $n$ balls, where ball $i$ is initially placed in basket $a_i$, and no basket contains more than one ball. Alice i...
Note: there are other (more elegant in our opinion) solutions from some of our testers, which you may or may not find under the comment section. We will present here the original solution here. Consider a state with $k \leq n$ balls remaining. Let's represent the state as a sequence $S = (d_1, d_2, \cdots, d_k)$ where ...
[ "combinatorics", "math", "probabilities" ]
3,100
#include <bits/stdc++.h> #include <cassert> #include <numeric> #include <type_traits> #ifdef _MSC_VER #include <intrin.h> #endif #include <utility> #ifdef _MSC_VER #include <intrin.h> #endif namespace atcoder { namespace internal { constexpr long long safe_mod(long long x, long long m) { x %= m; ...
1951
H
Thanos Snap
\begin{quote} Piotr Rubik - Psalm dla Ciebie \hfill ඞ \end{quote} There is an array $a$ of size $2^k$ for some positive integer $k$, which is initially a permutation of values from $1$ to $2^k$. Alice and Bob play the following game on the array $a$. First, a value $t$ between $1$ and $k$ is shown to both Alice and Bo...
Let $n = 2^k$. Let's see how we can solve for each $t$ first. We binary search on the answer, which results in every element being either $0$ or $1$ depending on if it's larger than the threshold, and we now need to check if the answer is $0$ or $1$. Let's instead try to directly construct Alice's strategy to achieve $...
[ "binary search", "dp", "games", "greedy", "trees" ]
3,200
#include <bits/stdc++.h> using namespace std; bool solve(vector<int>& v) { int n = v.size(); vector<int> a(n), b(n); for (int i = 0; i < n; ++i) a[i] = max(1 - v[i], 0), b[i] = max(0, v[i] - 1); for (; n > 1; n /= 2) { for (int i = 0; i < n; i += 2) { a[i / 2] = a[i] + a[i + 1]; ...
1951
I
Growing Trees
\begin{quote} wowaka ft. Hatsune Miku - Ura-Omote Lovers \hfill ඞ \end{quote} You are given an undirected connected simple graph with $n$ nodes and $m$ edges, where edge $i$ connects node $u_i$ and $v_i$, with two positive parameters $a_i$ and $b_i$ attached to it. Additionally, you are also given an integer $k$. A n...
From now on, we say an array $x$ to be good if the graph created by cloning the $i$-th edge $x_i$ times can be partitioned into $k$ forests (this is slightly different from $k$-spanning-tree generators). Let's first discuss how to check whether an array $x$ is good. Let $G'$ be the graph created by cloning the $i$-th e...
[ "binary search", "constructive algorithms", "flows", "graphs", "greedy" ]
3,200
#include <bits/stdc++.h> #include <algorithm> #include <cassert> #include <limits> #include <queue> #include <vector> #include <vector> namespace atcoder { namespace internal { template <class T> struct simple_queue { std::vector<T> payload; int pos = 0; void reserve(int n) { payload.reserve(n);...
1954
A
Painting the Ribbon
Alice and Bob have bought a ribbon consisting of $n$ parts. Now they want to paint it. First, Alice will paint every part of the ribbon into one of $m$ colors. For each part, she can choose its color arbitrarily. Then, Bob will choose \textbf{at most $k$} parts of the ribbon and repaint them \textbf{into the same col...
When is Bob able to get a ribbon where each part has color $i$? There should be at least $n-k$ parts of color $i$. So if the number of parts with color $i$ is less than $n-k$, Bob cannot repaint the whole ribbon into color $i$. So, Alice has to paint the ribbon in such a way that for every color, there are at most $n-k...
[ "constructive algorithms", "greedy", "math" ]
900
t = int(input()) for i in range(t): n, m, k = map(int, input().split()) max_color = (n + m - 1) / m if max_color + k >= n: print('NO') else: print('YES')
1954
B
Make It Ugly
Let's call an array $a$ beautiful if you can make all its elements the same by using the following operation an arbitrary number of times (possibly, zero): - choose an index $i$ ($2 \le i \le |a| - 1$) such that $a_{i - 1} = a_{i + 1}$, and replace $a_i$ with $a_{i - 1}$. You are given a beautiful array $a_1, a_2, \d...
As given in the problem statement, the definition of a beautiful array is not very interesting to us, since checking the beauty of an array is quite complex. Let's try to simplify it. First of all, the first and last elements will never be changed, as it is impossible to choose such $i$ for operations. If they are diff...
[ "implementation", "math" ]
1,200
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) lst = -1 ans = n for i in range(n): if a[i] != a[0]: ans = min(ans, i - lst - 1) lst = i ans = min(ans, n - lst - 1) if ans == n: print(-1) else: print(ans)
1954
C
Long Multiplication
You are given two integers $x$ and $y$ of the same length, consisting of digits from $1$ to $9$. You can perform the following operation any number of times (possibly zero): swap the $i$-th digit in $x$ and the $i$-th digit in $y$. For example, if $x=73$ and $y=31$, you can swap the $2$-nd digits and get $x=71$ and $...
There are two observations to solve the problem: applying the operation does not change the sum of the numbers; the smaller the difference of the numbers, the greater their product (the proof is given below). Proof: let's denote the sum of the numbers as $s$, the smallest number as $\frac{s}{2} - a$ and the largest num...
[ "greedy", "math", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string x, y; cin >> x >> y; int n = x.size(); bool f = false; for (int i = 0; i < n; ++i) { if ((x[i] > y[i]) == f) swap(x[i], y[i]); f |= (x[i] != y[i]); } cout << x << '\n' << y ...
1954
D
Colored Balls
There are balls of $n$ different colors; the number of balls of the $i$-th color is $a_i$. The balls can be combined into groups. Each group should contain at most $2$ balls, and no more than $1$ ball of each color. Consider all $2^n$ sets of colors. For a set of colors, let's denote its value as the minimum number o...
For a fixed set of colors, this is a standard problem with the following solution: let's denote the total number of balls as $s$, then the value of the set is $\left\lceil\frac{s}{2}\right\rceil$; but there is an exception in the case when there is a color with more than $\frac{s}{2}$ balls, then the value is the numbe...
[ "combinatorics", "dp", "math", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; return x; } int mul(int x, int y) { return x * 1LL * y % MOD; } int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) cin >> a[i]; int s = a...
1954
E
Chain Reaction
There are $n$ monsters standing in a row. The $i$-th monster has $a_i$ health points. Every second, you can choose one \textbf{alive} monster and launch a chain lightning at it. The lightning deals $k$ damage to it, and also spreads to the left (towards decreasing $i$) and to the right (towards increasing $i$) to \tex...
Let's solve the problem for a single $k$. We'll start with $k = 1$ for simplicity. The first lightning can be launched at any monster, as it will always spread to all of them. We will continue launching lightnings until a monster dies. When one or more monsters die, the problem breaks down into several independent subp...
[ "binary search", "data structures", "dsu", "greedy", "implementation", "math", "number theory" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; int mx = *max_element(a.begin(), a.end()); vector<long long> pr(mx + 1)...
1954
F
Unique Strings
Let's say that two strings $a$ and $b$ are \textbf{equal} if you can get the string $b$ by cyclically shifting string $a$. For example, the strings 0100110 and 1100100 are equal, while 1010 and 1100 are not. You are given a binary string $s$ of length $n$. Its first $c$ characters are 1-s, and its last $n - c$ charact...
What's common in all strings we can get: each string has no more than $c + k$ ones and at least $c$ consecutive ones. So let's loosen up our constraints a little and just calculate the number of strings with no more than $c + k$ ones and at least $c$ consecutive ones, i. e. this block of ones can be anywhere, can even ...
[ "combinatorics", "dp", "math" ]
3,100
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y ...
1955
A
Yogurt Sale
The price of one yogurt at the "Vosmiorochka" store is $a$ burles, but there is a promotion where you can buy two yogurts for $b$ burles. Maxim needs to buy \textbf{exactly} $n$ yogurts. When buying two yogurts, he can choose to buy them at the regular price or at the promotion price. What is the minimum amount of bu...
You can always buy yogurts one by one without using the promotion, then the answer is $n \cdot a$. Suppose it is more advantageous to buy yogurts on promotion than one by one, that is, $b < 2 \cdot a$. If $n$ is even, the answer is ${n \over 2} \cdot b$, otherwise ${(n - 1) \over 2} \cdot b + a$. Now you just need to c...
[ "math" ]
800
#include <bits/stdc++.h> using ll = signed long long int; using namespace std; void solve() { ll n, a, b; cin >> n >> a >> b; ll ans = n * a; if (b < 2 * a) { ans = (n / 2) * b + (n % 2) * a; } cout << ans << '\n'; } int main() { int t; cin >> t; while (t--) { ...
1955
B
Progressive Square
A progressive square of size $n$ is an $n \times n$ matrix. Maxim chooses three integers $a_{1,1}$, $c$, and $d$ and constructs a progressive square according to the following rules: $$a_{i+1,j} = a_{i,j} + c$$ $$a_{i,j+1} = a_{i,j} + d$$ For example, if $n = 3$, $a_{1,1} = 1$, $c=2$, and $d=3$, then the progressive...
Since $c > 0$ and $d > 0$, the elements of the square increase starting from the top left corner. Thus, $a_{1,1}$ is the minimum element in the square, and consequently in the found elements. Given $n$, $c$, $d$, and the found $a_{1,1}$, we will reconstruct the square. It remains to check that the given numbers in the ...
[ "constructive algorithms", "data structures", "implementation", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() using ll = signed long long int; using pii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vl = vector<ll>; void solve() { int n; ll c, d; cin >> n >> c >> d; vl a(n * n); for (int i...
1955
C
Inhabitant of the Deep Sea
$n$ ships set out to explore the depths of the ocean. The ships are numbered from $1$ to $n$ and follow each other in ascending order; the $i$-th ship has a durability of $a_i$. The Kraken attacked the ships $k$ times in a specific order. First, it attacks the first of the ships, then the last, then the first again, a...
To solve the problem, let's model the behavior of the Kraken. Suppose initially there are two or more ships in the sea, we will consider the first and last ship, denote their durabilities as $a_l$ and $a_r$, and also let $m = \min(a_l, a_r)$, initially setting $l = 1$ and $r = n$. After two attacks, the durability of b...
[ "greedy", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() using ll = signed long long int; void solve() { int n; ll k; cin >> n >> k; deque<ll> dq(n); for (int i = 0; i < n; ++i) { cin >> dq[i]; } while (dq.size() > 1 && k) { ll mn = min(dq.front...
1955
D
Inaccurate Subsequence Search
Maxim has an array $a$ of $n$ integers and an array $b$ of $m$ integers ($m \le n$). Maxim considers an array $c$ of length $m$ to be good if the elements of array $c$ can be rearranged in such a way that at least $k$ of them match the elements of array $b$. For example, if $b = [1, 2, 3, 4]$ and $k = 3$, then the ar...
How to check if two arrays are good? For each element of $b$, try to pair it with an element from array $a$. If we managed to create $k$ or more pairs, then the arrays are good. Since rearranging the elements of the array is allowed, we will maintain three multisets $C$, $D$, and $E$. In $D$, we will store all elements...
[ "data structures", "two pointers" ]
1,400
#include <bits/stdc++.h> using ll = signed long long int; #define all(x) (x).begin(), (x).end() using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; using namespace std; void solve() { int n, m; size_t k; cin >> n >> m >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { ...
1955
E
Long Inversions
A binary string $s$ of length $n$ is given. A binary string is a string consisting only of the characters '1' and '0'. You can choose an integer $k$ ($1 \le k \le n$) and then apply the following operation any number of times: choose $k$ consecutive characters of the string and invert them, i.e., replace all '0' with ...
No substring of the string needs to be inverted twice, as it does not change the string in any way. Let's fix $k$ and try to check if all the characters of the string can be made equal to 1. Suppose the first $i$ characters are already equal to 1, and $s_{i + 1}=0$. Then we need to invert all the bits starting from the...
[ "brute force", "greedy", "implementation", "sortings" ]
1,700
#include <bits/stdc++.h> using ll = signed long long int; #define all(x) (x).begin(), (x).end() using pii = std::array<int, 2>; using pll = std::array<ll, 2>; using vi = std::vector<int>; using vl = std::vector<ll>; using namespace std; void solve() { int n; string s; cin >> n >> s; for (int k...
1955
F
Unfair Game
Alice and Bob gathered in the evening to play an exciting game on a sequence of $n$ integers, each integer of the sequence \textbf{doesn't exceed $4$}. The rules of the game are too complex to describe, so let's just describe the winning condition — Alice wins if the bitwise XOR of all the numbers in the sequence is no...
Let's try to solve the problem if all the numbers in the sequence are equal to $4$. If the number of elements is even, the bitwise XOR is zero, and if it's odd, then it's equal to $4$. By removing one $4$ at a time, Eve will change the parity, so the answer will be $\lfloor {p_4 \over 2} \rfloor$. Suppose there are som...
[ "dp", "games", "greedy", "math", "schedules" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 201; int dp[N][N][N]; void precalc() { dp[0][0][0] = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { for (int k = 0; k < N; ++k) { int prev = 0; if (i) prev = max(prev, dp[i - 1...
1955
G
GCD on a grid
Not long ago, Egor learned about the Euclidean algorithm for finding the greatest common divisor of two numbers. The greatest common divisor of two numbers $a$ and $b$ is the largest number that divides both $a$ and $b$ without leaving a remainder. With this knowledge, Egor can solve a problem that he once couldn't. V...
First, let's learn how to check for a fixed $x$ if there exists a path from $(1,1)$ to $(n,m)$ with a GCD of $x$. It is necessary for all numbers along the path to be divisible by $x$. Let's define a grid $b$ of size $n$ by $m$, where $b_{i,j} = 1$ if $a_{i,j}$ is divisible by $x$, and $b_{i,j} = 0$ otherwise. If there...
[ "brute force", "dfs and similar", "dp", "implementation", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using ll = signed long long int; #define all(x) (x).begin(), (x).end() using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; using namespace std; void solve() { int n, m; cin >> n >> m; vector<vector<int> > a(n, vector<int>(m)); for (int i = 0; i < n; ++i) { ...
1955
H
The Most Reckless Defense
You are playing a very popular Tower Defense game called "Runnerfield 2". In this game, the player sets up defensive towers that attack enemies moving from a certain starting point to the player's base. You are given a grid of size $n \times m$, on which $k$ towers are already placed and a path is laid out through whi...
Let's solve the problem for a single tower. The tower's area of effect is a circle, so the theoretically possible number of cells in which a tower with radius $r$ will deal damage is $\pi \cdot r ^ 2$. In total, the tower will deal $p_i \cdot \pi \cdot r^2$ damage to the enemy. At the same time, the initial health of t...
[ "bitmasks", "brute force", "constructive algorithms", "dp", "flows", "graph matchings", "shortest paths" ]
2,300
#include <bits/stdc++.h> using ll = signed long long int; #define all(x) (x).begin(), (x).end() using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; using namespace std; const int R = 12, INF = 2e9; bool check(int x, int n) { return (0 <= x && x < n); } void solve() { int n, m, k; cin >...
1956
A
Nene's Game
Nene invented a new game based on an increasing sequence of integers $a_1, a_2, \ldots, a_k$. In this game, initially $n$ players are lined up in a row. In each of the rounds of this game, the following happens: - Nene finds the $a_1$-th, $a_2$-th, $\ldots$, $a_k$-th players in a row. They are kicked out of the game ...
Obviously, a person at place $p$ will be kicked out if and only if $p \ge a_1$. Therefore, the answer is $\min(n,a_1-1)$.
[ "binary search", "brute force", "data structures", "games", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; #define ll long long #define MP make_pair mt19937 rnd(time(0)); int a[105]; void solve(){ int q,k,n;cin>>k>>q; for(int i=1;i<=k;i++) cin>>a[i]; for(int i=1;i<=q;i++){ cin>>n; cout<<min(a[1]-1,n)<<' '; } cout<<endl; } int main(){ ios::sync_with_stdio(false); int _;...
1956
B
Nene and the Card Game
You and Nene are playing a card game. The deck with $2n$ cards is used to play this game. Each card has an integer from $1$ to $n$ on it, and each of integers $1$ through $n$ appears exactly on $2$ cards. Additionally, there is a table where cards are placed during the game (initially, the table is empty). In the begi...
The number of pairs on each side should be the same. For each color (in the following text, "this point" refers to the point someone got by playing a card with this color): If you have both cards of this color in your hand, you will be able to get this point. If you have both cards of this color in your hand, you will ...
[ "games", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; const int MAXN=4e5+5; int cnt[MAXN]; void solve() { int n,ans=0; scanf("%d",&n); fill(cnt+1,cnt+n+1,0); for(int i=1,a;i<=n;++i) scanf("%d",&a),ans+=(++cnt[a]==2); printf("%d\n",ans); } signed main() { int T; scanf("%d",&T); while(T--) solve(); return 0; }
1956
C
Nene's Magical Matrix
The magical girl Nene has an $n\times n$ matrix $a$ filled with zeroes. The $j$-th element of the $i$-th row of matrix $a$ is denoted as $a_{i, j}$. She can perform operations of the following two types with this matrix: - Type $1$ operation: choose an integer $i$ between $1$ and $n$ and a permutation $p_1, p_2, \ldo...
When $n=3$, the optimal matrix is the following: The optimal matrix would be: Construction method: This takes exactly $2n$ operations. For the final matrix, we define $f(x)$ as the number of elements greater or equal to $x$. The sum of all elements in the matrix is $\sum_{i=1}^n f(i)$ because an element with value $x$ ...
[ "constructive algorithms", "greedy", "math" ]
1,600
#include<bits/stdc++.h> using namespace std; #define ll long long #define MP make_pair mt19937 rnd(time(0)); void solve(){ int n;cin>>n; int ans=0; for(int i=1;i<=n;i++) ans+=(2*i-1)*i; cout<<ans<<' '<<2*n<<endl; for(int i=n;i>=1;i--){ cout<<"1 "<<i<<' '; for(int j=1;j<=n;j++) cout<<j<<' ';cout<<endl; cout<<...
1956
D
Nene and the Mex Operator
Nene gave you an array of integers $a_1, a_2, \ldots, a_n$ of length $n$. You can perform the following operation no more than $5\cdot 10^5$ times (possibly zero): - Choose two integers $l$ and $r$ such that $1 \le l \le r \le n$, compute $x$ as $\operatorname{MEX}(\{a_l, a_{l+1}, \ldots, a_r\})$, and simultaneously ...
What is the answer when $a_i = 0$? When $a_i =0$, the sum can hit $n^2$ with making $a_i = n$ at last. Construction: Here, solve(k) will take about $2^k$ operations. Since doing operation $[l,r]$ will make $a_l,\cdots,a_r \le r-l+1$, if for all $l\le i\le r$, $a_i$ is included in at least one of the operations and $a_{...
[ "bitmasks", "brute force", "constructive algorithms", "divide and conquer", "dp", "greedy", "implementation", "math" ]
2,000
#include<bits/stdc++.h> using namespace std; int n,a[20],cnt[20]; vector <array<int,2>> I; void oper(int l,int r) { fill(cnt,cnt+n+1,0); for(int i=l;i<=r;++i) if(a[i]<=n) ++cnt[a[i]]; int mex=0; while(cnt[mex]) ++mex; for(int i=l;i<=r;++i) a[i]=mex; I.push_back({l,r}); } void build(int l,int r) { if(l==r) { if...
1956
E2
Nene vs. Monsters (Hard Version)
This is the hard version of the problem. The only difference between the versions is the constraints on $a_i$. You can make hacks only if both versions of the problem are solved. Nene is fighting with $n$ monsters, located in a circle. These monsters are numbered from $1$ to $n$, and the $i$-th ($1 \le i \le n$) monst...
If three consecutive monsters have energy level $0,x,y\ (x,y>0)$, the monster with energy lever $y$ will "die"(have energy level $0$) at last. If four consecutive monsters have energy levels $0,x,y,z\ (x,y,z>0)$, what will happen to the monster $z$? If four consecutive monsters have energy level $x,y,z,w\ (x,y,z,w>0)$,...
[ "brute force", "greedy", "implementation", "math" ]
2,700
#include<bits/stdc++.h> using namespace std; #define ll long long #define MP make_pair mt19937 rnd(time(0)); const int MAXN=2e5+5; int n,a[MAXN];bool b[MAXN]; bool check(){ a[n+1]=a[1],a[n+2]=a[2],a[n+3]=a[3]; for(int i=1;i<=n;i++) if(a[i]&&a[i+1]&&a[i+2]&&a[i+3]) return true; return false; } void solve(){ cin>>...
1956
F
Nene and the Passing Game
Nene is training her team as a basketball coach. Nene's team consists of $n$ players, numbered from $1$ to $n$. The $i$-th player has an arm interval $[l_i,r_i]$. Two players $i$ and $j$ ($i \neq j$) can pass the ball to each other if and only if $|i-j|\in[l_i+l_j,r_i+r_j]$ (here, $|x|$ denotes the absolute value of $x...
Two people $i$ and $j\ (i<j)$ can pass the ball to each other directly if and only if $[i+l_i,i+r_i]\cap[j-r_j,j-l_j]\neq \varnothing$ According to the hint above, we can build the following graph: There are $2n$ vertices in the graph. Vertice $i$ links to vertices $([n+i-r_i,n+i-l_1]\cup[n+i+l_i,n+i+r_i])\cap[n+1,2n]\...
[ "constructive algorithms", "data structures", "dsu", "graphs", "sortings" ]
3,000
#include<bits/stdc++.h> using namespace std; #define ll long long #define MP make_pair const int MAXN=2e6+5; int n,tot,le[MAXN],ri[MAXN]; int fa[MAXN<<1],s[MAXN],t[MAXN],pre[MAXN],suf[MAXN]; inline int find(int x){ while(x^fa[x]) x=fa[x]=fa[fa[x]]; return x; } void solve(){ cin>>n; for(int i=1;i<=2*n+1;i++) fa[i]=i...
1957
A
Stickogon
You are given $n$ sticks of lengths $a_1, a_2, \ldots, a_n$. Find the maximum number of regular (equal-sided) polygons you can construct simultaneously, such that: - Each side of a polygon is formed by exactly one stick. - No stick is used in more than $1$ polygon. Note: Sticks cannot be broken.
The first observation that needs to be made in this problem is that we have to greedily try to build triangles from the sticks available. The number of triangles that can be created simultaneously by $S$ sticks of the same length is $\left\lfloor \frac{S}{3} \right\rfloor$. Hence, the answer is just the sum of the coun...
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a(101, 0); for (int i = 0; i < n; i++) { int x; cin >> x; a[x]++; } int sum = 0; for (auto& s : a) sum += s / 3; cout << sum << "\n";...
1957
B
A BIT of a Construction
Given integers $n$ and $k$, construct a sequence of $n$ non-negative (i.e. $\geq 0$) integers $a_1, a_2, \ldots, a_n$ such that - $\sum\limits_{i = 1}^n a_i = k$ - The \textbf{number} of $1$s in the binary representation of $a_1 | a_2 | \ldots | a_n$ is maximized, where $|$ denotes the bitwise OR operation.
The case $n = 1$ needs to be handled separately, as we can only output $k$ itself. For $n > 1$, we make the following observations. Let $x$ be the position of the most significant bit in $k$, that is $2^{x} \leq k < 2^{x+1}$. From this, we learn that the bitwise OR of the sequence cannot have more than $x+1$ set bits b...
[ "bitmasks", "constructive algorithms", "greedy", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--) { int n, k; cin >> n >> k; vector<int> a(n); if (n == 1) { a[0] = k; } else { int msb = 0; // find the msb of k for (int i...
1957
C
How Does the Rook Move?
You are given an $n \times n$ chessboard where you and the computer take turns alternatingly to place white rooks & black rooks on the board respectively. While placing rooks, you have to ensure that no two rooks attack each other. Two rooks attack each other if they share the same row or column \textbf{regardless of c...
There are essentially two types of moves: Placing a rook at some $(i, i)$: This reduces the number of free rows and columns available by $1$. Placing a rook at some $(i, j)$, where $i \neq j$: The computer now mirrors this by placing a rook at $(j, i)$, blocking rows $i$ and $j$ along with columns $i$ and $j$. So the n...
[ "combinatorics", "dp", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int dp[(int) 3e5+5]; const int MOD = 1e9 + 7; int main() { cin.tie(0), cout.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int used = 0; for (int i = 0; i < k; i++) { int r...
1957
D
A BIT of an Inequality
You are given an array $a_1, a_2, \ldots, a_n$. Find the number of tuples ($x, y, z$) such that: - $1 \leq x \leq y \leq z \leq n$, and - $f(x, y) \oplus f(y, z) > f(x, z)$. We define $f(l, r) = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_{r}$, where $\oplus$ denotes the bitwise XOR operation.
How can you simplify the given inequality? Use the fact that the XOR of a number with itself is 0. The inequality simplifies to $f(x, z) \oplus a_y > f(x, z)$. For a given $a_y$ what subarrays (that include $a_y$) would satisfy this? First we may rewrite the inequality as $f(x, z) \oplus a_y > f(x, z)$. So, for each in...
[ "bitmasks", "brute force", "dp", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; const int Z = 30; const int MAX_N = 1e5 + 3; int pref[Z][MAX_N][2]; int suff[Z][MAX_N][2]; void solve() { int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 0; i < Z; i++) suff[i][n + 1][0] = suff[i][n + 1][1...
1957
E
Carousel of Combinations
You are given an integer $n$. The function $C(i,k)$ represents the number of distinct ways you can select $k$ distinct numbers from the set {$1, 2, \ldots, i$} and arrange them in a circle$^\dagger$. Find the value of $$ \sum\limits_{i=1}^n \sum\limits_{j=1}^i \left( C(i,j) \bmod j \right). $$ Here, the operation $x \...
For what values of $j$ is $C(i,j) \bmod j = 0$? For all other values of $j$, how can you precompute the result? To precompute, switch around the loop order. The number of distinct ways you can select $k$ distinct numbers from the set {$1, 2, \ldots, i$} and arrange them in a line is $i(i-1)\cdots(i-k+1)$, and since arr...
[ "brute force", "combinatorics", "dp", "math", "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; const int MAX_N = 1e6 + 3; bitset<MAX_N> isprime; vector<int> primes; vector<int> eratosthenesSieve(int lim) { isprime.set(); isprime[0] = isprime[1] = false; for (int i = 4; i < lim; i += 2) isprime[i] = false; for (int i = 3;...
1957
F1
Frequency Mismatch (Easy Version)
\textbf{This is the easy version of the problem. The difference between the two versions of this problem is the constraint on $k$. You can make hacks only if all versions of the problem are solved.} You are given an undirected tree of $n$ nodes. Each node $v$ has a value $a_v$ written on it. You have to answer queries...
Let's try answering a different question. Given two multisets of elements how can we check if they differ? Hashing? How to multiset hash efficiently? Okay if we can now differentiate two multisets of unequal elements, can we try to answer queries by inserting into these hypothetical multisets and binary search the diff...
[ "binary search", "data structures", "divide and conquer", "hashing", "probabilities", "trees" ]
2,600
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; using ll = long long; using dbl = long double; //#define int ll using vi = vector<int>; using vvi = vector<vi>; using pii = pair<int, int>; using vii = vector<pii>; using vvii = vector<vii>; using vll = vector<ll>; #define ff first #define ss sec...
1957
F2
Frequency Mismatch (Hard Version)
\textbf{This is the hard version of the problem. The difference between the two versions of this problem is the constraint on $k$. You can make hacks only if all versions of the problem are solved.} You are given an undirected tree of $n$ nodes. Each node $v$ has a value $a_v$ written on it. You have to answer queries...
Let's start by first solving the problem for $k = 1$, and extend the idea to $k > 1$ later. To solve for $k = 1$, we'll find the smallest value that occurs with different frequencies on the two paths. We'll solve an easier version by solving for two static arrays, instead of solving the problem of two paths. To find th...
[ "binary search", "data structures", "dfs and similar", "hashing", "probabilities", "trees" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MOD1 = 1e9 + 7; const int MOD2 = 998244353; using ll = long long; using dbl = long double; //#define int ll using vi = vector<int>; using vvi = vector<vi>; using pii = pair<int, int>; using vii = vector<pii>; using vvii = vector<vii>; using vll = vector<ll>; ...
1965
A
Everything Nim
Alice and Bob are playing a game on $n$ piles of stones. On each player's turn, they select a positive integer $k$ that is at most the size of the smallest \textbf{nonempty} pile and remove $k$ stones from \textbf{each} nonempty pile at once. The first player who is unable to make a move (because all piles are empty) l...
If the smallest pile is of size $1$, then Alice must choose $k=1$ in her first move. Therefore, we can imagine subtracting $1$ from all piles, and determining who wins given that Bob goes first. We can repeat this process, switching the first player back and forth, until there is no longer a pile of size $1$. At this p...
[ "games", "greedy", "math", "sortings" ]
1,400
t = int(input()) for tc in range(t): n = int(input()) a = list(map(int, input().split())) maxsize = max(a) a.sort() mexsize = 1 for sz in a: if sz == mexsize: mexsize = mexsize + 1 if mexsize > maxsize: print("Alice" if maxsize % 2 == 1 else "Bob") else: ...
1965
B
Missing Subsequence Sum
You are given two integers $n$ and $k$. Find a sequence $a$ of non-negative integers of size at most $25$ such that the following conditions hold. - There is no subsequence of $a$ with a sum of $k$. - For all $1 \le v \le n$ where $v \ne k$, there is a subsequence of $a$ with a sum of $v$. A sequence $b$ is a subsequ...
Notice that for a fixed $k$, a solution for $n=c$ is also a solution for all $n < c$. So we can ignore the value of $n$ and just assume it's always $10^6$. If we didn't have the restriction that no subsequence can add up to $k$, the most natural solution would be $[1, 2, 4, 8, \cdots 2^{19}]$. Every value from $1$ to $...
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
1,800
t = int(input()) for tc in range(t): n, k = map(int, input().split()) i = 0 while (1 << (i + 1)) <= k: i = i + 1 ans = [k - (1 << i), k + 1, k + 1 + (1 << i)] for j in range(20): if j != i: ans.append(1 << j); print(len(ans)) print(*ans)
1965
C
Folding Strip
You have a strip of paper with a binary string $s$ of length $n$. You can fold the paper in between any pair of adjacent digits. A set of folds is considered valid if after the folds, all characters that are on top of or below each other match. Note that all folds are made at the same time, so the characters don't hav...
Define the pattern of a (validly) folded strip to be the set of characters, in order, seen from above after all folds are made. It is always possible to fold the strip in such a way that no two adjacent characters in the pattern are equal. If we fold in between every pair of equal characters, and don't fold in between ...
[ "constructive algorithms", "greedy", "strings" ]
2,300
t = int(input()) for tc in range(t): n = int(input()) s = input() mn = 0 mx = 0 cur = 0 for c in s: if (cur % 2 == 0) == (c == '1'): cur = cur + 1 else: cur = cur - 1 mn = min(mn, cur) mx = max(mx, cur) print(mx - mn)
1965
D
Missing Subarray Sum
There is a hidden array $a$ of $n$ positive integers. You know that $a$ is a \textbf{palindrome}, or in other words, for all $1 \le i \le n$, $a_i = a_{n + 1 - i}$. You are given the sums of all but one of its distinct subarrays, in arbitrary order. The subarray whose sum is not given can be any of the $\frac{n(n+1)}{2...
Let's first look at the set of subarray sums of a palindromic array $a$ of $n$ positive integers. Because $a$ is a palindrome, the sum of the subarray with indices in the range $[l, r]$ is the same as the sum of the subarray with indices in the range $[n + 1 - r, n + 1 - l]$. So if we ignore all subarrays where $l + r ...
[ "constructive algorithms" ]
2,900
def getSubarraySums(a): cts = [] for i in range(len(a)): sm = 0 for j in range(i, len(a)): sm = sm + a[j] cts.append(sm) cts.sort() return cts def getOddOccurringElements(cts): odds = [] for ct in cts: if len(odds) > 0 and ct == odds[-1]: ...
1965
E
Connected Cubes
There are $n \cdot m$ unit cubes currently in positions $(1, 1, 1)$ through $(n, m, 1)$. Each of these cubes is one of $k$ colors. You want to add additional cubes at any integer coordinates such that the subset of cubes of each color is connected, where two cubes are considered connected if they share a face. In othe...
We can show that a solution always exists. This example with $n=3$, $m=5$, $k=4$ will demonstrate the construction we will use: First, extend each of the even columns up by $n+k-1$ spaces, keeping all cubes in a given vertical column the same color: Then, for the odd columns, do something similar, except we use the bot...
[ "constructive algorithms", "games" ]
3,100
n, m, k = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) ans = [] for x in range(n): for y in range(m): for z in range(1, n + 1): if y % 2 == 1: ans.append([x, y, z, a[x][y]]) else: ans.append([x, y...
1965
F
Conference
You have been asked to organize a very important art conference. The first step is to choose the dates. The conference must last for a certain number of consecutive days. Each day, one lecturer must perform, and the same lecturer cannot perform more than once. You asked $n$ potential lecturers if they could participa...
For a segment of days, how can we tell if there's a way to assign a lecturer to each day of the segment? Consider a bipartite graph: the first part consists of the days in the segment, the second part consists of all lecturers, an edge between a day and a lecturer exists if that lecturer is available on that day. We ne...
[ "data structures", "flows" ]
3,300
/** * author: tourist * created: 26.11.2023 09:36:38 **/ #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "algo/debug.h" #else #define debug(...) 42 #endif const long long inf = (long long) 1e18; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; ...
1966
A
Card Exchange
You have a hand of $n$ cards, where each card has a number written on it, and a fixed integer $k$. You can perform the following operation any number of times: - Choose any $k$ cards from your hand that all have the same number. - Exchange these cards for $k-1$ cards, each of which can have \textbf{any} number you cho...
If you don't initially have at least $k$ copies of any number, you can't perform any operations, so the answer is $n$. Otherwise, we can show that we can always get down to $k-1$ cards, with the following algorithm: Choose any card that you have $k$ copies of, and remove those $k$ copies If you have no more cards, take...
[ "constructive algorithms", "games", "greedy" ]
800
t = int(input()) for tc in range(t): n, k = map(int, input().split()) cards = list(map(int, input().split())) ct = {} ans = n for c in cards: if c in ct: ct.update({c: ct[c] + 1}) else: ct.update({c: 1}) if ct[c] >= k: ans = k - 1 ...
1966
B
Rectangle Filling
There is an $n \times m$ grid of white and black squares. In one operation, you can select any two squares of the same color, and color all squares in the subrectangle between them that color. Formally, if you select positions $(x_1, y_1)$ and $(x_2, y_2)$, both of which are currently the same color $c$, set the color...
If either pair of opposite corners is the same color, then we can choose those corners to make everything the same color in one operation. Otherwise, we have four cases for the colors of the corners: Notice that these are all essentially rotations of each other, so we can only consider the first case by symmetry: If an...
[ "constructive algorithms", "implementation" ]
1,100
t = int(input()) for tc in range(t): n, m = map(int, input().split()) gr = [] for i in range(n): gr.append(input()) ans = "YES" if gr[0][0] != gr[n - 1][m - 1]: impossible = True for j in range(m - 1): if gr[0][j] != gr[0][j + 1] or gr[n - 1][j] != gr[n - 1][...
1967
A
Permutation Counting
You have some cards. An integer between $1$ and $n$ is written on each card: specifically, for each $i$ from $1$ to $n$, you have $a_i$ cards which have the number $i$ written on them. There is also a shop which contains unlimited cards of each type. You have $k$ coins, so you can buy $k$ new cards in total, and the c...
If $a_1=a_2=\cdots=a_n$ and $k=0$, it's obvious that the optimal rearrangement is $[1,2,\cdots,n,1,2,\cdots,n,\cdots,1,2,\cdots,n]$, because every subarray of length $n$ is a permutation of $1\sim n$. WLOG, assume that $a_1\ge a_2\ge\cdots a_n=w$. If $k=0$, we can insert more numbers at the back and form more permutati...
[ "binary search", "greedy", "implementation", "math", "sortings" ]
1,400
#include<bits/stdc++.h> using namespace std; void solve() { int n;long long k; cin>>n>>k; vector<long long>a(n); for(int x=0;x<n;x++) cin>>a[x]; sort(a.begin(),a.end()); reverse(a.begin(),a.end()); long long lst=a.back(),cnt=1; a.pop_back(); while(!a.empty()&&lst==a.back())a.pop_...
1967
B1
Reverse Card (Easy Version)
\textbf{The two versions are different problems. You may want to read both versions. You can make hacks only if both versions are solved.} You are given two positive integers $n$, $m$. Calculate the number of ordered pairs $(a, b)$ satisfying the following conditions: - $1\le a\le n$, $1\le b\le m$; - $a+b$ is a mul...
Denote $\gcd(a,b)$ as $d$. Assume that $a=pd$ and $b=qd$, then we know that $\gcd(p,q)=1$. $(b\cdot\gcd(a,b))\mid (a+b)\iff (qd^2)\mid (pd+qd)\iff (qd)\mid (p+q)$. Assume that $p+q=kqd$, then $p=(kd-1)q$. We know $q=1$ because $\gcd(p,q)=1$. Enumerate $d$ from $1$ to $m$, we know $p+1=kd\le\lfloor\frac{n}{d}\rfloor+1$,...
[ "brute force", "math", "number theory" ]
1,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=2000005; int tc,n,m; ll ans; inline void solve(){ cin>>n>>m; ans=0; for(int i=1;i<=m;i++) ans+=(n+i)/(1ll*i*i); cout<<ans-1<<'\n'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>tc; while(tc--) solve(); return 0...
1967
B2
Reverse Card (Hard Version)
\textbf{The two versions are different problems. You may want to read both versions. You can make hacks only if both versions are solved.} You are given two positive integers $n$, $m$. Calculate the number of ordered pairs $(a, b)$ satisfying the following conditions: - $1\le a\le n$, $1\le b\le m$; - $b \cdot \gcd(...
Denote $\gcd(a,b)$ as $d$. Assume that $a=pd$ and $b=qd$, then we know that $\gcd(p,q)=1$. $(a+b)\mid (b\cdot\gcd(a,b))\iff (pd+qd)\mid (qd^2)\iff (p+q)\mid (qd)$. We know that $\gcd(p+q,q)=\gcd(p,q)=1$, so $(p+q)\mid d$. We also know that $p\ge 1,q\ge 1$, so $p < d=\frac{a}{p}\le \frac{n}{p}$ and thus $p^2 < n$. Simil...
[ "brute force", "math", "number theory" ]
2,200
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL ifstream cin("i...
1967
C
Fenwick Tree
Let $\operatorname{lowbit}(x)$ denote the value of the lowest binary bit of $x$, e.g. $\operatorname{lowbit}(12)=4$, $\operatorname{lowbit}(8)=8$. For an array $a$ of length $n$, if an array $s$ of length $n$ satisfies $s_k=\left(\sum\limits_{i=k-\operatorname{lowbit}(k)+1}^{k}a_i\right)\bmod 998\,244\,353$ for all $k...
It's well-known that Fenwick Tree is the data structure shown in the image below, and the sum of each subtree is stored at each vertex (i.e. $c=f(a)$ and $c_u=\sum\limits_{v\textrm{ in subtree of }u}a_v$). Denote the depth of a vertex $u$ as $\operatorname{dep}(u)$. Assume that $b=f^k(a)$. Consider a vertex $u$ and one...
[ "bitmasks", "brute force", "combinatorics", "data structures", "dp", "math", "trees" ]
2,300
//By: OIer rui_er #include <bits/stdc++.h> #define rep(x, y, z) for(int x = (y); x <= (z); ++x) #define per(x, y, z) for(int x = (y); x >= (z); --x) #define debug(format...) fprintf(stderr, format) #define fileIO(s) do {freopen(s".in", "r", stdin); freopen(s".out", "w", stdout);} while(false) #define endl '\n' using na...
1967
D
Long Way to be Non-decreasing
Little R is a magician who likes non-decreasing arrays. She has an array of length $n$, initially as $a_1, \ldots, a_n$, in which each element is an integer between $[1, m]$. She wants it to be non-decreasing, i.e., $a_1 \leq a_2 \leq \ldots \leq a_n$. To do this, she can perform several magic tricks. Little R has a f...
Binary search on the answer of magics. You may come up with many $\mathcal O(m\log m + n\log^2 m)$ solutions with heavy data structures. Unfortunately, none of them is helpful. The key is to judge $\mathcal O(m\log n)$ times whether vertex $u$ is reachable from vertex $v$ in $k$ steps, instead of querying the minimal v...
[ "binary search", "dfs and similar", "graphs", "implementation", "shortest paths", "two pointers" ]
2,800
#include <bits/stdc++.h> namespace FastIO { template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; } template <typename T> inline void write...
1967
E1
Again Counting Arrays (Easy Version)
\textbf{This is the easy version of the problem. The differences between the two versions are the constraints on $n, m, b_0$ and the time limit. You can make hacks only if both versions are solved.} Little R has counted many sets before, and now she decides to count arrays. Little R thinks an array $b_0, \ldots, b_n$...
It can be easily proven that for a given $a$, we can always try to get the largest $b_i$ from $1$ to $n$ one by one. A perceptual understanding is that if not so, we can't escape from some gap in $a$ either. Thus, it's easy to get a $\mathcal O(nm)$ solution: Let $dp_{i,j}$ be, in the optimal $b$ determination progress...
[ "combinatorics", "dp", "fft", "math" ]
3,100
#include <bits/stdc++.h> namespace FastIO { template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; } template <typename T> inline void write...
1967
E2
Again Counting Arrays (Hard Version)
\textbf{This is the hard version of the problem. The differences between the two versions are the constraints on $n, m, b_0$ and the time limit. You can make hacks only if both versions are solved.} Little R has counted many sets before, and now she decides to count arrays. Little R thinks an array $b_0, \ldots, b_n$...
The definition of the function $f$ is the same as that in G1 editorial. Please read that first. Consider the process of the reflection method. We don't need to enumerate the place from where the contribution is $0$. We can just consider the contribution of each path. Note that each step is either $x\gets x+1$ or $y\get...
[ "combinatorics", "dp", "math" ]
3,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 2e6+5; int inv[N]; int inversemod(int p, int q) { // assumes p > 0 // https://codeforces.com/blog/entry/23365 return (p > 1 ? q-1LL*inversemod(q%p, p)*q/p : 1); } void add(int& x, int y) { x += y; if (x >= MOD) x -= M...
1967
F
Next and Prev
Let $p_1, \ldots, p_n$ be a permutation of $[1, \ldots, n]$. Let the $q$-subsequence of $p$ be a permutation of $[1, q]$, whose elements are in the same relative order as in $p_1, \ldots, p_n$. That is, we extract all elements not exceeding $q$ together from $p$ in the original order, and they make the $q$-subsequence...
Consider an array with length $n+x-1$. For each integer $k$ from $n$ to $1$, consider $i$ s.t. $p_i = k$, we tag the untagged (that is, a position will not be tagged for a second time) positions in the range $[i, i + x)\cap \mathbb{Z}$. By examining the total number of positions tagged, we have $\begin{aligned} n + x -...
[ "brute force", "data structures", "implementation" ]
3,200
#include<bits/stdc++.h> using namespace std; constexpr int maxn=300010,maxq=100010,B=400; int n,bn,a[maxn],b[maxn],idx[maxn],nxt[maxn],add[maxn/B+5],mxadd[maxn/B+5],mx[maxn/B+5],se[maxn/B+5],t[maxn]; long long ans[maxq]; vector<int>val[maxn/B+5],mxval[maxn/B+5],pre[maxn/B+5],mxpre[maxn/B+5],pos[maxn/B+5],ks[maxn]; ...
1968
A
Maximize?
You are given an integer $x$. Your task is to find any integer $y$ $(1\le y<x)$ such that $\gcd(x,y)+y$ is maximum possible. \textbf{Note that if there is more than one $y$ which satisfies the statement, you are allowed to find any.} $\gcd(a,b)$ is the Greatest Common Divisor of $a$ and $b$. For example, $\gcd(6,4)=2...
The core idea is to find the upper bound of $\gcd(x,y)+y$. Let us look closer at the formula $\gcd(x,y)+y$. It is a well-known fact that $\gcd(a,b)=\gcd(a-b,b)$ for $a\geq b$. Applying it to our formula, we get $\gcd(x-y,y)+y$. Using the fact that $\gcd(x-y,y)\le x-y$, we get $\gcd(x-y,y)+y\le x-y+y=x$. Hence, $\gcd(x,...
[ "brute force", "math", "number theory" ]
800
#include<iostream> using namespace std; int main(){ int t; cin>>t; while(t--){ int x; cin>>x; cout<<x-1<<"\n"; } }
1968
B
Prefiquence
You are given two binary strings $a$ and $b$. A binary string is a string consisting of the characters '0' and '1'. Your task is to determine the maximum possible number $k$ such that a prefix of string $a$ of length $k$ is a subsequence of string $b$. A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be o...
We will be solving this task using dynamic programming. Let us define $dp_i$ as the maximal prefix of $a$ that is contained in $b_1,\dots,b_i$ as a subsequence. Then the transitions are as follows: if $b_i$ is equal to $a_{dp_{i-1}+1}$ then $dp_i = dp_{i-1} + 1$. otherwise $dp_i=dp_{i-1}$. The answer is $dp_{m}$.
[ "greedy", "two pointers" ]
800
#include<iostream> #include<vector> using namespace std; int main(){ int t; cin>>t; while(t--){ int n,m; cin>>n>>m; vector<char>a(n+1),b(m+1); for(int i=1;i<=n;i++){ cin>>a[i]; } for(int i=1;i<=m;i++){ cin>>b[i]; } vector<int>dp(m+1); dp[1]=(a[1]==b[1]?1:0); for(int i=2;i<=m;i++){ if(dp[...
1968
C
Assembly via Remainders
You are given an array $x_2,x_3,\dots,x_n$. Your task is to find \textbf{any} array $a_1,\dots,a_n$, where: - $1\le a_i\le 10^9$ for all $1\le i\le n$. - $x_i=a_i \bmod a_{i-1}$ for all $2\le i\le n$. Here $c\bmod d$ denotes the remainder of the division of the integer $c$ by the integer $d$. For example $5 \bmod 2 =...
Notice that $((a+b) \bmod a)=b$ for $0\le b< a$. So we may try to generate a sequence with $b=x_i$. Let us take $a_1=1000$, because $1000$ is larger than any of $x_i$. Then, we can take $a_i$ as $a_{i-1}+x_i$, since $((a_{i-1}+x_i)\bmod a_{i-1})=x_i$ will be hold. The maximal value of $a$ will be at most $1000+500n$ wh...
[ "constructive algorithms", "number theory" ]
1,000
#include<iostream> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int S=1000; cout<<S<<" "; for(int i=2;i<=n;i++){ int x; cin>>x; S+=x; cout<<S<<" "; } cout<<"\n"; } }
1968
D
Permutation Game
Bodya and Sasha found a permutation $p_1,\dots,p_n$ and an array $a_1,\dots,a_n$. They decided to play a well-known "Permutation game". A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a per...
Because $p$ is a permutation, it will be divided into cycles. For every player it is optimal to move during the first $min(n,k)$ turns. We will answer the question by calculating maximal possible score for both players. Let us define $sum_i$ and $pos_i$: sum of values in the positions that occur during the first $i$ tu...
[ "brute force", "dfs and similar", "games", "graphs", "greedy", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; long long score(vector<int>&p,vector<int>&a,int s,int k){ int n=p.size(); long long mx=0,cur=0; vector<bool>vis(n); while(!vis[s]&&k>0){ vis[s]=1; mx=max(mx,cur+1ll*k*a[s]); cur+=a[s]; k--; s=p[s]; } return mx; } int main(){ int t; cin>>t; while(t--){ in...
1968
E
Cells Arrangement
You are given an integer $n$. You choose $n$ cells $(x_1,y_1), (x_2,y_2),\dots,(x_n,y_n)$ in the grid $n\times n$ where $1\le x_i\le n$ and $1\le y_i\le n$. Let $\mathcal{H}$ be the set of \textbf{distinct} Manhattan distances between any pair of cells. Your task is to maximize the size of $\mathcal{H}$. Examples of s...
Author: JuicyGrape What is the maximal possible size of $\mathcal{H}$? Can you always get that size for $n\geq 4$? Consider odd and even distances independently. Let us find an interesting pattern for $n\geq 4$. Can you generalize the pattern? We put $n-2$ cells on the main diagonal. Then put two cells at $(n-1,n)$ and...
[ "constructive algorithms" ]
1,600
#include<iostream> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; for(int i=1;i<=n-2;i++){ cout<<i<<' '<<i<<"\n"; } cout<<n-1<<' '<<n<<"\n"<<n<<' '<<n<<"\n"; } }
1968
F
Equal XOR Segments
Let us call an array $x_1,\dots,x_m$ interesting if it is possible to divide the array into $k>1$ parts so that bitwise XOR of values from each part are equal. More formally, you must split array $x$ into $k$ consecutive segments, each element of $x$ must belong to \textbf{exactly} $1$ segment. Let $y_1,\dots,y_k$ be ...
Observation: any division on more than $k>3$ segments can be reduced to at most $3$ segments. Proof: suppose the XORs of elements from the segments are $x_1,\dots,x_k$. The condition $x_1=x_2=\dots=x_k$ must be fulfilled. If $k>3$ we may take any three consecutive segments and merge them into one, because $x\oplus x\op...
[ "binary search", "data structures" ]
1,800
#include<bits/stdc++.h> using namespace std; const int N=200005; int a[N]; int main(){ int t; cin>>t; while(t--){ int n,q; cin>>n>>q; map<int,vector<int>>id; id[0].push_back(0); for(int i=1;i<=n;i++){ cin>>a[i]; a[i]^=a[i-1]; id[a[i]].push_back(i); } while(q--){ int l,r; cin>>l>>r; if...
1968
G1
Division + LCP (easy version)
\textbf{This is the easy version of the problem. In this version $l=r$.} You are given a string $s$. For a fixed $k$, consider a division of $s$ into exactly $k$ continuous substrings $w_1,\dots,w_k$. Let $f_k$ be the maximal possible $LCP(w_1,\dots,w_k)$ among all divisions. $LCP(w_1,\dots,w_m)$ is the length of the...
Consider $F_{\ell}$ is a function which returns true iff it is possible to divide the string into at least $k$ segments with their LCP equal to $\ell$. Notice that $F_{\ell}$ implies $F_{\ell - 1}$ for $\ell > 0$. So we may find the maximal $\ell$ using binary search, which will be the answer for the problem. How to co...
[ "binary search", "data structures", "dp", "hashing", "string suffix structures", "strings" ]
1,900
#include<bits/stdc++.h> using namespace std; vector<int>Zfunc(string& str){ int n=str.size(); vector<int>z(n); int l=0,r=0; for(int i=1;i<n;i++){ if(i<=r){ z[i]=min(r-i+1,z[i-l]); } while(i+z[i]<n&&str[z[i]]==str[i+z[i]]){ z[i]++; } if(i+z[i]-1>r){ l=i; r=i+z[i]-1; } } return z; } int f(ve...
1968
G2
Division + LCP (hard version)
\textbf{This is the hard version of the problem. In this version $l\le r$.} You are given a string $s$. For a fixed $k$, consider a division of $s$ into exactly $k$ continuous substrings $w_1,\dots,w_k$. Let $f_k$ be the maximal possible $LCP(w_1,\dots,w_k)$ among all divisions. $LCP(w_1,\dots,w_m)$ is the length of ...
In general, in this version we must answer for each $k\in\{1,2,\dots,n\}$. We will use a similar idea as in the easy version considering two cases: $k\le \sqrt{n}$. We may calculate these values as in the easy version in $O(n\sqrt{n}\log n)$. $k> \sqrt{n}$. As we divide the string into $k$ segments and the LCP is $\ell...
[ "binary search", "brute force", "data structures", "dp", "hashing", "math", "string suffix structures", "strings" ]
2,200
#include<bits/stdc++.h> using namespace std; vector<int>Zfunc(string& str){ int n=str.size(); vector<int>z(n); int l=0,r=0; for(int i=1;i<n;i++){ if(i<=r){ z[i]=min(r-i+1,z[i-l]); } while(i+z[i]<n&&str[z[i]]==str[i+z[i]]){ z[i]++; } if(i+z[i]-1>r){ l=i; r=i+z[i]-1; } } return z; } int f(ve...
1969
A
Two Friends
Monocarp wants to throw a party. He has $n$ friends, and he wants to have at least $2$ of them at his party. The $i$-th friend's best friend is $p_i$. All $p_i$ are distinct, and for every $i \in [1, n]$, $p_i \ne i$. Monocarp can send invitations to friends. The $i$-th friend comes to the party if \textbf{both the $...
Obviously, you can't send fewer than $2$ invitations. Since all $p_i \neq i$, you need to send at least $2$ invitations ($i$ and $p_i$) in order for at least some friend $i$ to come. On the other hand, you never need to send more than $3$ invitations. You can always send invitations to friends $i, p_i$, and $p_{p_i}$, ...
[ "constructive algorithms", "implementation", "math" ]
800
for _ in range(int(input())): n = int(input()) p = [int(x) - 1 for x in input().split()] ans = 3 for i in range(n): if p[p[i]] == i: ans = 2 print(ans)
1969
B
Shifts and Sorting
Let's define a cyclic shift of some string $s$ as a transformation from $s_1 s_2 \dots s_{n-1} s_{n}$ into $s_{n} s_1 s_2 \dots s_{n-1}$. In other words, you take one last character $s_n$ and place it before the first character while moving all other characters to the right. You are given a binary string $s$ (a string...
Let's look at the operation as the following: you choose $(l, r)$, erase the element at position $r$ and then insert it before the element at position $l$. We can also interpret the cost of such operation as the following: you pay $1$ for the element at position $r$ you "teleport" to the left and $1$ for each element y...
[ "constructive algorithms", "greedy" ]
1,000
fun main() { repeat(readln().toInt()) { val s = readln().map { it.code - '0'.code } val zeroes = s.count { it == 0 } val cnt = intArrayOf(0, 0) var ans = 0L for (c in s) { cnt[c]++ if (c == 0) ans += if (cnt[1] > 0) 1 else 0 ...
1969
C
Minimizing the Sum
You are given an integer array $a$ of length $n$. You can perform the following operation: choose an element of the array and replace it with any of its neighbor's value. For example, if $a=[3, 1, 2]$, you can get one of the arrays $[3, 3, 2]$, $[3, 2, 2]$ and $[1, 1, 2]$ using one operation, but not $[2, 1, 2$] or $...
The small values of $k$ leads to the idea that expected solution is dynamic programming. In fact, we can actually design a dynamic programming solution. Let $dp_{i, j}$ be the minimum sum, if we considered the first $i$ elements and already done $j$ operations. Note that, we can turn a segment of length $d+1$ into a mi...
[ "dp", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; using li = long long; const li INF = 1e18; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<li> a(n); for (auto& x : a) cin >> x; vector<vector<li>> dp(n + 1, vector<li>(k + 1, INF)); dp[0][0] = 0; for (int i ...
1969
D
Shop Game
Alice and Bob are playing a game in the shop. There are $n$ items in the shop; each item has two parameters: $a_i$ (item price for Alice) and $b_i$ (item price for Bob). Alice wants to choose a subset (possibly empty) of items and buy them. After that, Bob does the following: - if Alice bought less than $k$ items, Bo...
Let's sort the array in descending order based on the array $b$. For a fixed set of Alice's items, Bob will take the first $k$ of them for free (because they are the most expensive) and pay for the rest. Now we can iterate over the first item that Bob will pay (denote it as $i$). Alice has to buy the cheapest $k$ items...
[ "data structures", "greedy", "math", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) using li = long long; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n), b(n); for (auto& x : a) cin >> x; for (auto& x : b) cin >> x; vector<int> ord(n); iota(ord.begin(...
1969
E
Unique Array
You are given an integer array $a$ of length $n$. A subarray of $a$ is one of its contiguous subsequences (i. e. an array $[a_l, a_{l+1}, \dots, a_r]$ for some integers $l$ and $r$ such that $1 \le l < r \le n$). Let's call a subarray unique if there is an integer that occurs exactly once in the subarray. You can perf...
When we replace an element, we can always choose an integer that is not present in the array. So, if we replace the $i$-th element, every subarray containing it becomes unique; and the problem can be reformulated as follows: consider all non-unique subarrays of the array, and calculate the minimum number of elements yo...
[ "binary search", "data structures", "divide and conquer", "dp", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) vector<int> t, p; void push(int v) { if (v * 2 + 2 >= sz(t)) return; t[v * 2 + 1] += p[v]; p[v * 2 + 1] += p[v]; t[v * 2 + 2] += p[v]; p[v * 2 + 2] += p[v]; p[v] = 0; } void upd(int v, int l, int r, int L, int R, int x) { if (L ...
1969
F
Card Pairing
There is a deck of $n$ cards, each card has one of $k$ types. You are given the sequence $a_1, a_2, \dots, a_n$ denoting the types of cards in the deck from top to bottom. Both $n$ and $k$ are even numbers. You play a game with these cards. First, you draw $k$ topmost cards from the deck. Then, the following happens e...
It's pretty obvious that every time we have a pair of equal cards in hand, we should play one of these pairs. If you're interested in a formal proof, please read the paragraph in italic, otherwise skip it. Formal proof: suppose we have a pair of cards of type $x$, but we play a card of type $y$ and a card of type $z$ i...
[ "dp", "greedy", "hashing", "implementation" ]
3,000
#include<bits/stdc++.h> using namespace std; mt19937_64 rnd(12341234); int n, k; vector<int> deck; vector<int> dp; vector<vector<bool>> odd; vector<bool> full_odd; vector<long long> val; vector<long long> hs; bool bad(const vector<bool>& v) { for(int i = 0; i < k; i++) if(!v[i]) return...
1970
A1
Balanced Shuffle (Easy)
A parentheses sequence is a string consisting of characters "(" and ")", for example "(()((". A balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and operations into it, for example "(()(()))". The balance of a parentheses sequence is defi...
The problem statement describes exactly what needs to be done, so we just need to implement it carefully, using a $O(n\log n)$ sorting algorithm from the standard library. If you're using Python for this problem, the time limit can be a bit tight so you might need to optimize a bit. For example, tuples are much faster ...
[ "implementation", "sortings" ]
1,000
null
1970
A2
Balanced Unshuffle (Medium)
\textbf{The differences with the easy version of this problem are highlighted in bold.} A parentheses sequence is a string consisting of characters "(" and ")", for example "(()((". A balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and o...
In a balanced parentheses sequence each opening parenthesis corresponds (would form a pair enclosing a subexpression in a mathematical expression) to exactly one closing parenthesis and vice versa. In such a pair the balance before the opening parenthesis is always 1 less than the balance before the closing parenthesis...
[ "brute force", "constructive algorithms", "trees" ]
2,400
null
1970
A3
Balanced Unshuffle (Hard)
\textbf{The only difference with the medium version is the maximum length of the input.} A parentheses sequence is a string consisting of characters "(" and ")", for example "(()((". A balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and ...
Solving this problem requires a more careful implementation of the algorithm described in the previous subtask. Since we only ever insert new parentheses into the current string after an unmatched parenthesis, we can use a linked list of characters instead of a string to represent it, and also store a vector of pointer...
[ "constructive algorithms", "trees" ]
2,400
null
1970
B1
Exact Neighbours (Easy)
\textbf{The only difference between this and the hard version is that all $a_{i}$ are even.} After some recent attacks on Hogwarts Castle by the Death Eaters, the Order of the Phoenix has decided to station $n$ members in Hogsmead Village. The houses will be situated on a picturesque $n\times n$ square field. Each wiz...
Place all houses on the diagonal. Notice that for each house $i$ either to the left or to the right, on the diagonal, there will be a house with the desired distance $a_{i}$
[ "constructive algorithms" ]
1,900
null
1970
B2
Exact Neighbours (Medium)
\textbf{The only difference between this and the hard version is that $a_{1} = 0$.} After some recent attacks on Hogwarts Castle by the Death Eaters, the Order of the Phoenix has decided to station $n$ members in Hogsmead Village. The houses will be situated on a picturesque $n\times n$ square field. Each wizard will ...
We don't care about satisfying the condition for the first house, since this house will always be at a distance $0$ from itself. There are at least two approaches for constructing the desired placement. Approach 1: Let's sort all $a_{i}$ in non-increasing order, then we can place houses in the zigzag order the followin...
[ "constructive algorithms" ]
2,100
null
1970
B3
Exact Neighbours (Hard)
After some recent attacks on Hogwarts Castle by the Death Eaters, the Order of the Phoenix has decided to station $n$ members in Hogsmead Village. The houses will be situated on a picturesque $n\times n$ square field. Each wizard will have their own house, and every house will belong to some wizard. Each house will tak...
Let's divide all valid arrays $a$ into three cases and solve the problem for each of them. First case There exists $i$ such that $a_{i} = 0$. We can use the solution to Medium. Now we can assume $1 \leq a_{i} \leq n$. Second case There are two numbers $i \neq j$, such that $a_{i} = a_{j}$. We can adapt the algorithm fr...
[ "constructive algorithms" ]
2,300
null
1970
C1
Game on Tree (Easy)
\textbf{This is the easy version of the problem. The difference in this version is that $t=1$ and we work on an array-like tree.} Ron and Hermione are playing a game on a tree of $n$ nodes that are initially inactive. This tree is special because it has exactly two leaves. It can thus be seen as an array. The game con...
We are given a linked list with an initial coin at index $1 \leq i \leq n$. There are $i-1$ nodes to its left and $n-i$ nodes to its right. Note that after the first move, all the remaining moves are fixed since there will be exactly one inactive neighbor. If one of $i-1, n-i$ is odd, Ron should move to the correspondi...
[ "games" ]
1,400
null
1970
C2
Game on Tree (Medium)
\textbf{This is the medium version of the problem. The difference in this version is that $t=1$ and we work on trees.} Ron and Hermione are playing a game on a tree of $n$ nodes that are initially inactive. The game consists of $t$ rounds, each of which starts with a stone on exactly one node, which is considered as a...
Let's root the tree at node $u_1$ (the start node). By doing so, we guarantee that if the coin is at node $v$, the parent of $v$ is already active and thus we can only go down in the tree. This means that each subtree can be seen as its own independent game. So, each node is either a winning or losing position (w.r.t. ...
[ "dfs and similar", "dp", "games", "trees" ]
1,700
null
1970
C3
Game on Tree (Hard)
\textbf{This is the hard version of the problem. The only difference in this version is the constraint on $t$.} Ron and Hermione are playing a game on a tree of $n$ nodes that are initially inactive. The game consists of $t$ rounds, each of which starts with a stone on exactly one node, which is considered as activate...
Repeating the previous solution for each $u_i$ is too slow as it gives a $O(n.t)$ solution. Instead, we will reuse the computations we did when assigning losing/winning positions. We do so using the re-rooting technique. Let's first compute the positions of the nodes in the tree rooted at 0. We will now find in linear ...
[ "dfs and similar", "dp", "games", "trees" ]
1,900
null
1970
D1
Arithmancy (Easy)
Professor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatenating two magic words together. The power of a spell is equal to the number of its different non-...
Given that we need to output 3 words only, we can manually (trying a few options on paper until we find a solution) construct 3 words such that all 9 spell powers are different.
[ "brute force", "constructive algorithms", "interactive", "strings" ]
2,100
null
1970
D2
Arithmancy (Medium)
\textbf{The only difference between the versions of this problem is the maximum value of $n$.} Professor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatena...
Now we need to find 30 words, so manually solving on paper is out of question. However, "just trying" still works: what we can do is to keep generating random words until we find 30 that have all 900 corresponding spell powers different. Depending on how you fast is your computation of the spell power you can either do...
[ "constructive algorithms", "interactive", "probabilities", "strings" ]
2,600
null
1970
D3
Arithmancy (Hard)
\textbf{The only difference between the versions of this problem is the maximum value of $n$.} Professor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatena...
The previous approach of just generating random words does not even come close to working for $n=1000$ (in fact, it is hard to push it beyond roughly $n=50$). Now we need to add our own insights to the process. The first idea is: in order to answer the queries, we will likely need to know the spell power for all $n^2$ ...
[ "interactive" ]
3,100
null
1970
E1
Trails (Easy)
Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are $m$ cabins, numbered 1 to $m$. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either \underline{short} or \underline{long}. Cabin $i$ is connected with $s_i$ short trails and ...
Let $t_i := s_i + l_i$. The number of possible paths between cabin $i$ and cabin $j$ is $t_i t_j - l_i l_j$. Let $\mathbf{v}_{k,i}$ be the number of paths that ends in cabin $i$ after walking for $k$ days. We then have $\mathbf{v}_{0,1} = 1, \\ \mathbf{v}_{0,i} = 0 \text{ for } i \neq 1,$ $\mathbf{v}_{k+1,i} = \sum_{j ...
[ "dp" ]
1,800
null
1970
E2
Trails (Medium)
Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are $m$ cabins, numbered 1 to $m$. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either \underline{short} or \underline{long}. Cabin $i$ is connected with $s_i$ short trails and ...
Let $t_i := s_i + l_i$. The number of possible paths between cabin $i$ and cabin $j$ is $t_i t_j - l_i l_j$. Let $\mathbf{v}_{k}$ be the vector whose $i$th entry is the number of paths that ends in cabin $i$ after walking for $k$ days. We then have $\mathbf{v}_0 = (1, 0, \dots, 0),$ $(\mathbf{v}_{k+1})_i = \sum_{j = 1}...
[ "dp", "matrices" ]
2,000
null
1970
E3
Trails (Hard)
Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are $m$ cabins, numbered 1 to $m$. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either \underline{short} or \underline{long}. Cabin $i$ is connected with $s_i$ short trails and ...
Let $t_i := s_i + l_i$. The number of possible paths between cabin $i$ and cabin $j$ is $t_i t_j - l_i l_j$. Let $\mathbf{v}_{k}$ be the vector whose $i$th entry is the number of paths that ends in cabin $i$ after walking for $k$ days. We then have $\mathbf{v}_0 = (1, 0, \dots, 0),$ $(\mathbf{v}_{k+1})_i = \sum_{j = 1}...
[ "dp", "matrices" ]
2,200
null
1970
F3
Playing Quidditch (Hard)
This afternoon, you decided to enjoy the first days of Spring by taking a walk outside. As you come near the Quidditch field, you hear screams. Once again, there is a conflict about the score: the two teams are convinced that they won the game! To prevent this problem from happening one more time, you decide to get inv...
This subject does not contain theoretical difficulty: it is only needed to simulate the game following the rules described in the statement. To be able to perform the simulation easily, it is useful to store wisely the current state of the game. the position of the goals, either in a grid, a set or a list the position ...
[ "implementation" ]
2,300
null
1970
G1
Min-Fund Prison (Easy)
\textbf{In the easy version, $m = n-1$ and there exists a path between $u$ and $v$ for all $u, v$ ($1 \leq u, v \leq n$).} After a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate...
The cells and corridors in this subtask form a tree. No matter how we divide the prison into two complexes, there will be at least one existing corridor connecting them, but we must have at most one such corridor, which means that we do not need to build any more corridors. For each existing corridor, removing it split...
[ "dfs and similar", "trees" ]
1,900
null
1970
G2
Min-Fund Prison (Medium)
\textbf{In the medium version, $2 \leq \sum n \leq 300$ and $1 \leq \sum m \leq 300$} After a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate the prison to ensure that the Dement...
The graph is no longer a tree in this problem, but we can try to generalize the solution for the first subtask. First of all, suppose the graph is connected. Similar to the first subtask, there will always be at least one existing corridor connecting the two complexes, so we do not need to build new corridors. Moreover...
[ "brute force", "dfs and similar", "dp", "graphs", "trees" ]
2,200
null
1970
G3
Min-Fund Prison (Hard)
\textbf{In the hard version, $2 \leq \sum n \leq 10^5$ and $1 \leq \sum m \leq 5 \times 10^{5}$} After a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate the prison to ensure that...
In the hard subtask, the $O(n^2)$ solution is too slow. One way to get it accepted is to use bitsets to speed it up, as the knapsack transitions can simply be expressed as a bitwise shift + bitwise or. However, there is also an asymptotically faster approach. First of all, instead of remembering the possible splits usi...
[ "bitmasks", "dfs and similar", "dp", "graphs", "trees" ]
2,400
null
1971
A
My First Sorting Problem
You are given two integers $x$ and $y$. Output two integers: the minimum of $x$ and $y$, followed by the maximum of $x$ and $y$.
You can use, for example, an if-statement or some inbuilt $\texttt{min}$ and $\texttt{max}$ function available in most languages (like Python or C++).
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int x, y; cin >> x >> y; cout << min(x, y) << ' ' << max(x, y) << '\n'; } int main() { int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1971
B
Different String
You are given a string $s$ consisting of lowercase English letters. Rearrange the characters of $s$ to form a new string $r$ that is \textbf{not equal} to $s$, or report that it's impossible.
Since the string is length at most $10$, we can try all swaps of two characters of the string. This is $\mathcal{O}(|s|^2)$ per test case, which is fast enough. If none of them create a different string, then all characters in the original string are the same, so the answer is NO. Bonus: Actually, it's enough to try al...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { string s; cin >> s; bool ok = false; for (int i = 1; i < (int)(s.length()); i++) { if (s[i] != s[0]) {swap(s[i], s[0]); ok = true; break;} } if (!ok) { cout << "NO\n"; return; } cout <...
1971
C
Clock and Strings
There is a clock labeled with the numbers $1$ through $12$ in clockwise order, as shown below. \begin{center} {\small In this example, $(a,b,c,d)=(2,9,10,6)$, and the strings intersect.} \end{center} Alice and Bob have four \textbf{distinct} integers $a$, $b$, $c$, $d$ not more than $12$. Alice ties a red string conn...
There are many ways to implement the solution, but many involve a lot of casework. Below is the shortest solution we know of. Walk around the clock in the order $1$, $2$, $\dots$, $12$. If we pass by two red strings or two blue strings in a row, the strings don't intersect; otherwise, they do. This is because if we don...
[ "implementation" ]
900
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int a, b, c, d; cin >> a >> b >> c >> d; string s; for (int i = 1; i <= 12; i++) { if (i == a || i == b) {s += "a";} if (i == c || i == d) {s += "b";} } cout << (s == "abab" || s == "baba...
1971
D
Binary Cut
You are given a binary string$^{\dagger}$. Please find the minimum number of pieces you need to cut it into, so that the resulting pieces can be rearranged into a sorted binary string. Note that: - each character must lie in exactly one of the pieces; - the pieces must be contiguous substrings of the original string;...
First, note that it's always optimal to divide the string into "blocks" of equal values; there is no use having two strings $\texttt{111}|\texttt{11}$ when we can just have $\texttt{11111}$ and use fewer pieces. Now note that to sort the string, we need all blocks of $\texttt{0}$ to come before all blocks of $\texttt{1...
[ "dp", "greedy", "implementation", "sortings", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { string s; cin >> s; int res = 1; bool ex = false; for (int i = 0; i + 1 < (int)(s.size()); i++) { res += (s[i] != s[i + 1]); ex |= (s[i] == '0' && s[i + 1] == '1'); } cout << res - ex <<...
1971
E
Find the Car
Timur is in a car traveling on the number line from point $0$ to point $n$. The car starts moving from point $0$ at minute $0$. There are $k+1$ signs on the line at points $0, a_1, a_2, \dots, a_k$, and Timur knows that the car will arrive there at minutes $0, b_1, b_2, \dots, b_k$, respectively. The sequences $a$ and...
For each query, we binary search to find the last sign we passed (since the array $a$ is sorted). Say it is $a_r$. Then, $b_r$ minutes have passed. To find out how much time has passed since we left that sign, we know that the speed between sign $r$ and $r+1$ is $\frac{a_{r+1} - a_r}{b_{r+1} - b_r} \, \frac{\text{dista...
[ "binary search", "math", "sortings" ]
1,500
#include <iostream> #include <algorithm> #include <vector> #include <array> #include <set> #include <map> #include <queue> #include <stack> #include <list> #include <chrono> #include <random> #include <cstdlib> #include <cmath> #include <ctime> #include <cstring> #include <iomanip> #include <bitset> #include <cassert> ...
1971
F
Circle Perimeter
Given an integer $r$, find the number of lattice points that have a Euclidean distance from $(0, 0)$ \textbf{greater than or equal to} $r$ but \textbf{strictly less} than $r+1$. A lattice point is a point with integer coordinates. The Euclidean distance from $(0, 0)$ to the point $(x,y)$ is $\sqrt{x^2 + y^2}$.
There are many solutions to this problem, some of which involve binary search, but we will present a solution that doesn't use it. In fact, our solution is basically just brute force, but with some small observations that make it pass. See the implementation for more detail. First, we can only count points $(x,y)$ such...
[ "binary search", "brute force", "dfs and similar", "geometry", "implementation", "math" ]
1,600
#include <iostream> using namespace std; void solve() { long long r; cin >> r; long long height = r; long long ans = 0; for(long long i = 0; i <= r; i++) { while(i*i+height*height >= (r+1)*(r+1)) { height--; } long long cop = height; while(i*...
1971
G
XOUR
You are given an array $a$ consisting of $n$ nonnegative integers. You can swap the elements at positions $i$ and $j$ if $a_i~\mathsf{XOR}~a_j < 4$, where $\mathsf{XOR}$ is the bitwise XOR operation. Find the lexicographically smallest array that can be made with any number of swaps. An array $x$ is lexicographicall...
Note that if $a_i~\mathsf{XOR}~a_j < 4$, then $a_i$ and $a_j$ must share all bits in their binary representation, except for the last $2$ bits. This is because if they have a mismatch in any greater bit, their $\mathsf{XOR}$ will include this bit, making its value $\geq 2^2=4$. This means that we can group the numbers ...
[ "data structures", "dsu", "sortings" ]
1,700
#include <iostream> #include <algorithm> #include <vector> #include <map> #include <queue> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); map<int, priority_queue<int>> mp; for(int i = 0; i < n; i++) { cin >> a[i]; mp[a[i]>>2].push(-a[i]); } f...
1971
H
±1
Bob has a grid with $3$ rows and $n$ columns, each of which contains either $a_i$ or $-a_i$ for some integer $1 \leq i \leq n$. For example, one possible grid for $n=4$ is shown below: $$\begin{bmatrix} a_1 & -a_2 & -a_3 & -a_2 \\ -a_4 & a_4 & -a_1 & -a_3 \\ a_1 & a_2 & -a_2 & a_4 \end{bmatrix}$$ Alice and Bob play a...
The problem statement is somewhat reminiscent of SAT. Indeed, treating $+1$ as true and $-1$ as false, we have clauses of length $3$, and we need at least $2$ of the variables to be true. We can reduce this to 2-SAT with the following observation: at least $2$ of $(x,y,z)$ are true $\iff$ at least one of $(x,y)$ is tru...
[ "2-sat", "dfs and similar", "graphs" ]
2,100
#include <bits/stdc++.h> #include <algorithm> #include <utility> #include <vector> namespace atcoder { namespace internal { template <class E> struct csr { std::vector<int> start; std::vector<E> elist; csr(int n, const std::vector<std::pair<int, E>>& edges) : start(n + 1), elist(edges.size()...