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
2055
B
Crafting
\begin{center} \begin{tabular}{c} \hline {\small As you'd expect, Florida is home to many bizarre magical forces, and Florida Man seeks to tame them.} \ \hline \end{tabular} \end{center} There are $n$ different types of magical materials, numbered from $1$ to $n$. Initially, you have $a_i$ units of material $i$ for ea...
The order of the moves is pretty much irrelevant. What happens if we try to make two different materials? The key observation is that we will never use the operation to craft two different types of materials $i, j$. This is because if we were to combine the net change in resources from these two operations, we would lo...
[ "constructive algorithms", "greedy", "sortings" ]
1,000
// #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> // using namespace __gnu_pbds; // typedef tree<int, null_type, std::less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; #include <bits/stdc++.h> #define f first #define s second #define pb push_back typedef long l...
2055
C
The Trail
\begin{center} \begin{tabular}{c} \hline {\small There are no mountains in Florida, and Florida Man cannot comprehend their existence. As such, he really needs your help with this one.} \ \hline \end{tabular} \end{center} In the wilderness lies a region of mountainous terrain represented as a rectangular grid with $n$...
Pick $x$, and find the sum of the whole grid. What does this tell you? Once you know $x$, the top left cell is fixed. What about the next cell on the trail? The naive solution of writing out a linear system and solving them will take $O((n + m)^3)$ time, which is too slow, so we will need a faster algorithm. We begin b...
[ "brute force", "constructive algorithms", "greedy", "math", "two pointers" ]
1,400
#include <bits/stdc++.h> #define f first #define s second #define pb push_back typedef long long int ll; typedef unsigned long long int ull; using namespace std; typedef pair<int,int> pii; typedef pair<ll,ll> pll; template<typename T> int die(T x) { cout << x << endl; return 0; } #define mod 1000000007 #define INF ...
2055
D
Scarecrow
\begin{center} \begin{tabular}{c} \hline {\small At his orange orchard, Florida Man receives yet another spam letter, delivered by a crow. Naturally, he's sending it back in the most inconvenient manner possible.} \ \hline \end{tabular} \end{center} A crow is sitting at position $0$ of the number line. There are $n$ s...
Should you ever change the order of scarecrows? What's the first thing that the leftmost scarecrow should do? What's the only way to save time? Think in terms of distances and not times. Look at the points where the crow "switches over" between scarecrows. Greedy. We make a few preliminary observations: (1) The order o...
[ "greedy", "implementation", "math" ]
2,000
#include <bits/stdc++.h> #define f first #define s second #define pb push_back typedef long long int ll; typedef unsigned long long int ull; using namespace std; typedef pair<int,int> pii; typedef pair<ll,ll> pll; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while (T--...
2055
E
Haystacks
\begin{center} \begin{tabular}{c} \hline {\small On the next new moon, the universe will reset, beginning with Florida. It's up to Florida Man to stop it, but he first needs to find an important item.} \ \hline \end{tabular} \end{center} There are $n$ haystacks labelled from $1$ to $n$, where haystack $i$ contains $a_...
Let's say you have to empty the haystacks in a fixed order. What's the best way to do it? Write the expression for the number of moves for a given order. In an optimal ordering, you should not gain anything by swapping two entries of the order. Using this, describe the optimal order. The constraint only limits what you...
[ "brute force", "constructive algorithms", "data structures", "greedy", "sortings" ]
2,800
#include <bits/stdc++.h> #define f first #define s second #define pb push_back typedef long long int ll; typedef unsigned long long int ull; using namespace std; typedef pair<int,int> pii; typedef pair<ll,ll> pll; template<typename T> int die(T x) { cout << x << endl; return 0; } #define LNF 1e15 int N; vector<pll...
2055
F
Cosmic Divide
\begin{center} \begin{tabular}{c} \hline {\small With the artifact in hand, the fabric of reality gives way to its true master — Florida Man.} \ \hline \end{tabular} \end{center} A polyomino is a connected$^{\text{∗}}$ figure constructed by joining one or more equal $1 \times 1$ unit squares edge to edge. A polyomino ...
The results of the partition must be convex. Can you see why? The easier cases are when the polyomino must be cut vertically or horizontally. Let's discard those for now, and consider the "diagonal cuts". I.e. let one polyomino start from the top row, and another starting from some row $c$. WLOG the one starting on row...
[ "brute force", "geometry", "hashing", "math", "strings" ]
3,200
#include <bits/stdc++.h> #define f first #define s second typedef long long int ll; typedef unsigned long long int ull; using namespace std; typedef pair<int,int> pii; typedef pair<ll,ll> pll; void print_set(vector<int> x) { for (auto i : x) { cout << i << " "; } cout << endl; } void print_set(v...
2056
A
Shape Perimeter
There is an $m$ by $m$ square stamp on an infinite piece of paper. Initially, the bottom-left corner of the square stamp is aligned with the bottom-left corner of the paper. You are given two integer sequences $x$ and $y$, each of length $n$. For each step $i$ from $1$ to $n$, the following happens: - Move the stamp $...
Look at the picture. I mean, look at the picture. Consider coordinates $x$ and $y$ separately. Consider coordinates $x$ and $y$ separately. Since $1 \le x_i, y_i \le m - 1$, after each step both coordinates increase and remain connected with the previous square. From the picture we can see that each coordinate spans fr...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<int> x(n), y(n); for(int i = 0; i < n; i++) { cin >> x[i] >> y[i]; } int ans = 2 * (accumulate(x.begin(), x.end(), 0) + m - x[0] + accumulate(y.begin(), y.end(), 0) + m - y[0]); cout << ans...
2056
B
Find the Permutation
You are given an undirected graph with $n$ vertices, labeled from $1$ to $n$. This graph encodes a hidden permutation$^{\text{∗}}$ $p$ of size $n$. The graph is constructed as follows: - For every pair of integers $1 \le i < j \le n$, an undirected edge is added between vertex $p_i$ and vertex $p_j$ if and only if $p_...
"It can be proven that permutation $p$ can be uniquely determined" This means that there is an order of elements. How to determine whether $x$ should be earlier in that order than $y$? Consider two elements $x < y$. Suppose their positions in $p$ are $i$ and $j$ correspondigly. How can we determine if $i < j$? If $i < ...
[ "brute force", "dfs and similar", "graphs", "implementation", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<string> g(n); for(auto &i : g) { cin >> i; } vector<int> p(n); iota(p.begin(), p.end(), 0); sort(p.begin(), p.end(), [&](int x, int y) { if(g[x][y] == '1') return x < y; e...
2056
C
Palindromic Subsequences
For an integer sequence $a = [a_1, a_2, \ldots, a_n]$, we define $f(a)$ as the length of the longest subsequence$^{\text{∗}}$ of $a$ that is a palindrome$^{\text{†}}$. Let $g(a)$ represent the number of subsequences of length $f(a)$ that are palindromes. In other words, $g(a)$ counts the number of palindromic subseque...
Analyze the example with $n = 6$. If $[a_1, a_2, \ldots, a_k, a_{n - k + 1}, a_{n - k + 2}, \ldots, a_n]$ is a palindrome, then $[a_1, a_2, \ldots, a_k, a_i, a_{n - k + 1}, a_{n - k + 2}, \ldots, a_n]$ is also a palindrome for all $k < i < n - k + 1$. If $[a_1, a_2, \ldots, a_k, a_{n - k + 1}, a_{n - k + 2}, \ldots, a_...
[ "brute force", "constructive algorithms", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; if (n == 6) { cout << "1 1 2 3 1 2\n"; } else if(n == 9) { cout << "7 3 3 7 5 3 7 7 3\n"; } else if(n == 15) { cout << "15 8 8 8 15 5 8 1 15 5 8 15 15 15 8\n"; } else { for...
2056
D
Unique Median
An array $b$ of $m$ integers is called good if, \textbf{when it is sorted}, $b_{\left\lfloor \frac{m + 1}{2} \right\rfloor} = b_{\left\lceil \frac{m + 1}{2} \right\rceil}$. In other words, $b$ is good if both of its medians are equal. In particular, $\left\lfloor \frac{m + 1}{2} \right\rfloor = \left\lceil \frac{m + 1}...
Solve the problem when $a_i \le 2$. Assign $b_i = 1$ if $a_i = 2$ and $b_i = -1$ if $a_i = 1$ and calculate the number of bad subarrays. Extend this solution for $a_i \le 10$, however, you need to take overcounting into account. When is a subarray $a[l, r]$ not good? If $r - l + 1$ is odd, $a[l, r]$ can't be bad. Other...
[ "binary search", "brute force", "combinatorics", "data structures", "divide and conquer", "dp" ]
2,200
#include <bits/stdc++.h> using namespace std; const int MAX = 11; int main() { int tests; cin >> tests; for(int test = 0; test < tests; test++) { int n; cin >> n; vector<int> a(n); for(auto &i : a) { cin >> i; } long long ans = 0; for(in...
2056
E
Nested Segments
A set $A$ consisting of pairwise distinct segments $[l, r]$ with integer endpoints is called good if $1\le l\le r\le n$, and for any pair of distinct segments $[l_i, r_i], [l_j, r_j]$ in $A$, exactly one of the following conditions holds: - $r_i < l_j$ or $r_j < l_i$ (the segments do not intersect) - $l_i \le l_j \le ...
Forget about counting. What is the maximum size of $T$ if $m = 0$? It is $2n - 1$. What if $m$ isn't $0$? It is still $2n - 1$. To prove this represent a good set as a forest. We can always add $[1, n]$ and $[i, i]$ for all $1 \le i \le n$ to $S$. Now the tree of $S$ has exactly $n$ leaves. What if a vertex has more th...
[ "combinatorics", "dfs and similar", "dp", "dsu", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; const int MAX = 4e5 + 42; int fact[MAX], inv[MAX], inv_fact[MAX]; int C(int n, int k) { if(n < k || k < 0) return 0; return (long long) fact[n] * inv_fact[k] % mod * inv_fact[n - k] % mod; } int Cat(int n) { return (long long) C(2...
2056
F2
Xor of Median (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the constraints on $t$, $k$, and $m$ are higher. You can hack only if you solved all versions of this problem.} A sequence $a$ of $n$ integers is called good if the following condition holds: - Let $\text{cnt...
The order of the sequence doesn't matter. What if we fix the sequence $\text{cnt}$ and then calculate its contribution to the answer? By Lucas's theorem the contribution is odd iff for each set bit in $n$ there is exactly one $i$ such that $\text{cnt}_i$ has this bit set, and $\sum\limits_{i = 0}^{m - 1} \text{cnt}_i =...
[ "bitmasks", "brute force", "combinatorics", "dp", "math" ]
3,000
#include <bits/stdc++.h> using namespace std; int S(int n, int k) { return !(n - k & (k - 1 >> 1)); } int get(int n, int m) { int L = __lg(n) + 1; int up = 1 << L; vector<int> dp(up); for(int i = 0; i < n; i++) dp[i] = S(n, i + 1); for(int j = 0; j < L; j++) { for(int i = 0; i < up; i...
2057
A
MEX Table
One day, the schoolboy Mark misbehaved, so the teacher Sasha called him to the whiteboard. Sasha gave Mark a table with $n$ rows and $m$ columns. His task is to arrange the numbers $0, 1, \ldots, n \cdot m - 1$ in the table (each number must be used exactly once) in such a way as to maximize the sum of MEX$^{\text{∗}}...
Note that $0$ appears in exactly one row and exactly one column. As for $1$, if it exists, it can only be placed in one of the rows or columns that contain $0$, so the answer does not exceed $\operatorname{max}(n, m) + 1$, since only one column or row can have an answer greater than one, and in another one there can be...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using i64 = long long; void solve() { int n, m; std::cin >> n >> m; std::cout << std::max(n, m) + 1 << "\n"; } signed main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int t = 1; std::cin >> t; while (t--) { solve(); } }
2057
B
Gorilla and the Exam
Due to a shortage of teachers in the senior class of the "T-generation", it was decided to have a huge male gorilla conduct exams for the students. However, it is not that simple; to prove his competence, he needs to solve the following problem. For an array $b$, we define the function $f(b)$ as the smallest number of...
Note that $f(a)$ is the number of distinct numbers in the array. Since it is beneficial for us to always choose the entire array as the segment, because we will eventually remove the minimum element, it is advantageous to remove it from the entire array at once. Therefore, our task has been reduced to changing no more ...
[ "greedy", "sortings" ]
1,000
#include <bits/stdc++.h> using i64 = long long; void solve() { int n, k; std::cin >> n >> k; std::vector<int> a(n); for (int i = 0; i < n; i++) { std::cin >> a[i]; } std::sort(a.begin(), a.end()); std::vector<int> cnt = {1}; for (int i = 1; i < n; i++) { if (a[i] == a[i...
2057
C
Trip to the Olympiad
In the upcoming year, there will be many team olympiads, so the teachers of "T-generation" need to assemble a team of three pupils to participate in them. Any three pupils will show a worthy result in any team olympiad. But winning the olympiad is only half the battle; first, you need to get there... Each pupil has an...
Let's take a look at the $i$-th bit. If it appears in all numbers or in none, it contributes nothing to the answer; however, if it appears in one or two numbers, it adds $2^{i + 1}$ to the answer. Therefore, let's examine the most significant bit, let's say the $k$-th bit, which differs in the numbers $l$ and $r$, and ...
[ "bitmasks", "constructive algorithms", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using i64 = long long; void solve() { int l, r; std::cin >> l >> r; int k = 31 - __builtin_clz(l ^ r); int a = l | ((1 << k) - 1), b = a + 1, c = (a == l ? r : l); std::cout << a << " " << b << " " << c << "\n"; } signed main() { std::ios::sync_with_stdio(false); ...
2057
D
Gifts Order
"T-Generation" has decided to purchase gifts for various needs; thus, they have $n$ different sweaters numbered from $1$ to $n$. The $i$-th sweater has a size of $a_i$. Now they need to send some subsegment of sweaters to an olympiad. It is necessary that the sweaters fit as many people as possible, but without having ...
To begin with, let's take a look at what an optimal segment of coats looks like. I claim that in the optimal answer, the maximum and minimum are located at the edges of the segment. Suppose this is not the case; then we can narrow the segment (from the side where the extreme element is neither the minimum nor the maxim...
[ "data structures", "greedy", "implementation", "math", "matrices" ]
2,000
#include <bits/stdc++.h> using i64 = long long; template<class Info> struct SegmentTree { int n; std::vector<Info> info; SegmentTree() : n(0) {} SegmentTree(int n_, Info v_ = Info()) { init(n_, v_); } template<class T> SegmentTree(std::vector<T> init_) { init(init_); ...
2057
E1
Another Exercise on Graphs (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, there is an additional constraint on $m$. You can hack only if you solved all versions of this problem.} Recently, the instructors of "T-generation" needed to create a training contest. They were missing one p...
We will learn how to check if there exists a path from $a$ to $b$ such that the $k$-th maximum on this path is less than or equal to $x$. For a fixed $x$, the edges are divided into two types: light (weight less than or equal to $x$) and heavy (weight strictly greater than $x$). We assign a weight of $0$ to all light e...
[ "binary search", "brute force", "dp", "dsu", "graphs", "shortest paths", "sortings" ]
2,300
#include <bits/stdc++.h> using i64 = long long; void solve() { int n, m, q; std::cin >> n >> m >> q; std::vector<std::array<int, 3>> edges(m); for (int i = 0; i < m; i++) { int v, u, w; std::cin >> v >> u >> w; v--, u--; edges[i] = {v, u, w}; } std::sort(edges...
2057
E2
Another Exercise on Graphs (hard version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, there is no additional constraint on $m$. You can hack only if you solved all versions of this problem.} Recently, the instructors of "T-generation" needed to create a training contest. They were missing one p...
Please read the solution to problem E1. Let's return to the process where we sequentially changed the weights of the edges from $1$ to $0$. If we replace the weight of another edge with $0$ and it connects vertices that are at a distance of $0$, it means that the shortest paths between each pair of vertices will not ch...
[ "binary search", "dfs and similar", "dp", "dsu", "graphs", "shortest paths", "sortings" ]
2,500
#include <bits/stdc++.h> using i64 = long long; struct DSU { std::vector<int> p, sz, h; DSU(int n = 0) : p(n), sz(n, 1), h(n) { std::iota(p.begin(), p.end(), 0); } int leader(int x) { if (x == p[x]) { return x; } return leader(p[x]); } bool ...
2057
F
Formation
One day, the teachers of "T-generation" decided to instill discipline in the pupils, so they lined them up and made them calculate in order. There are a total of $n$ pupils, the height of the $i$-th pupil in line is $a_i$. The line is comfortable, if for each $i$ from $1$ to $n - 1$, the following condition holds: $a_...
Hint 1: how much does a single index affect those before him? Hint 2: try looking at the formula for making an index a maximum differently Hint 3: do you need to answer all queries online? Hint 4: do you need to consider all indexes? Solution: Let's fix the index that we want our maximum to be on - let it be $i$. Then,...
[ "binary search", "data structures", "dp", "sortings", "two pointers" ]
3,300
// Parallel binary search technique optimizes log^3 => log^2 // SegmentTree might be faster then std::multiset // sl[i] should equals max(a) at the begining cause IDK how to explain but it's obviously important #include <bits/stdc++.h> #include <algorithm> using namespace std; using ll = long long; constexpr int ...
2057
G
Secret Message
Every Saturday, Alexander B., a teacher of parallel X, writes a secret message to Alexander G., a teacher of parallel B, in the evening. Since Alexander G. is giving a lecture at that time and the message is very important, Alexander B. has to write this message on an interactive online board. The interactive online b...
We will divide the infinite grid into $5$ sets of cells $L_1$, $L_2$, $L_3$, $L_4$, and $L_5$, where $L_i = \{ (x, y) \in \mathbb{Z}^2 \space | \space (x + 2 y) \equiv i \pmod{5} \}$. Note that for any pair $(x,y)$, all $5$ cells $(x,y)$, $(x-1, y)$, $(x+1, y)$, $(x, y-1)$, $(x, y+1)$ belong to different sets $L_1, \ld...
[ "constructive algorithms", "dfs and similar", "math" ]
3,000
#include <bits/stdc++.h> using namespace std; using pi = pair<int, int>; void solve() { int n, m; cin >> n >> m; vector<string> v(n); for (auto& w : v) cin >> w; auto col = [](int x, int y) { int c = (x+2*y)%5; if (c < 0) c += 5; return c; }; auto cell = [&](int x, int...
2057
H
Coffee Break
There are very long classes in the T-Generation. In one day, you need to have time to analyze the training and thematic contests, give a lecture with new material, and, if possible, also hold a mini-seminar. Therefore, there is a break where students can go to drink coffee and chat with each other. There are a total o...
Let's call the elementary action $E_j$ the operation after which $a_j$ decreases by $2$, and the values $a_{j-1}$ and $a_{j+1}$ increase by $1$. Let $A$ be some set of actions that can be performed in some order; then this same set of actions can be performed greedily, each time performing any available elementary acti...
[ "data structures", "greedy", "math" ]
3,500
#include <bits/stdc++.h> using namespace std; using vi = vector<int>; using ll = long long; vector<ll> a, lhs, rhs; vector<int> st; vector<ll> get_right_out(const vector<ll>& a, vector<ll>& res) { const int n = a.size(); st.clear(); res.assign(n+1, 0); for (int i = 0; i < n; ++i) { ll x = a[...
2059
A
Milya and Two Arrays
An array is called good if for any element $x$ that appears in this array, it holds that $x$ appears at least twice in this array. For example, the arrays $[1, 2, 1, 1, 2]$, $[3, 3]$, and $[1, 2, 4, 1, 2, 4]$ are good, while the arrays $[1]$, $[1, 2, 1]$, and $[2, 3, 4, 4]$ are not good. Milya has two \textbf{good} ar...
If there are at least three distinct values in any of the arrays, the answer is $yes$. We can select any three elements from the other array and arrange them in increasing order, then the corresponding sums will also increase. If each array contains exactly two distinct values, the answer is also $yes$. If we find elem...
[ "constructive algorithms", "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int a[55],b[55]; void solve(){ int n;cin>>n; set<int> sa,sb; for(int i=1;i<=n;i++)cin>>a[i],sa.insert(a[i]); for(int i=1;i<=n;i++)cin>>b[i],sb.insert(b[i]); if(sa.size()+sb.size()<4){ cout<<"NO\n"; }else{ cout<<"YES\n"; } } ...
2059
B
Cost of the Array
You are given an array $a$ of length $n$ and an \textbf{even} integer $k$ ($2 \le k \le n$). You need to split the array $a$ into exactly $k$ non-empty subarrays$^{\dagger}$ such that each element of the array $a$ belongs to exactly one subarray. Next, all subarrays with even indices (second, fourth, $\ldots$, $k$-th)...
If $k = n$, then the partition is unique and the answer can be explicitly found. In all other cases, the answer does not exceed $2$. We want the second subarray of our partition to start not with $1$, while we can ignore all other subarrays, since in this case the answer will be $1$. We will iterate over the starting p...
[ "brute force", "constructive algorithms", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; k /= 2; vector<int> a(n); for (auto &it: a) cin >> it; if (2 * k == n) { for (int i = 1; i < n; i += 2) { if (a[i] != (i + 1) / 2) { cout << (i + 1) / 2 << '\n'; ...
2059
C
Customer Service
Nikyr has started working as a queue manager at the company "Black Contour." He needs to choose the order of servicing customers. There are a total of $n$ queues, each initially containing $0$ people. In each of the next $n$ moments of time, there are \textbf{two sequential} events: - New customers arrive in all queue...
At the last moment in time, we clear some queue, and it will have an empty number of people left, so among the $x_i$, there is guaranteed to be a $0$. To maximize the value of $MEX$, it is necessary for the value $1$ to appear among the $x_i$. However, a positive number of people was added to each queue at the last mom...
[ "brute force", "constructive algorithms", "graph matchings", "greedy", "math", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N=305; int a[N][N],suff[N]; void solve(){ int n;cin>>n; for(int i=1;i<=n;i++){ suff[i]=0; for(int j=1;j<=n;j++){ cin>>a[i][j]; } } for(int i=1;i<=n;i++){ for(int j=n;j>=1;j--){ if(a[i][j...
2059
D
Graph and Graph
You are given two connected undirected graphs with the same number of vertices. In both graphs, there is a token located at some vertex. In the first graph, the token is initially at vertex $s_1$, and in the second graph, the token is initially at vertex $s_2$. The following operation is repeated an \textbf{infinite} n...
First, we need to understand when the answer is less than infinity. For this to happen, the first token in the first graph must be at vertex $v$, and the second token in the second graph must also be at the vertex with the same number $v$. Additionally, there must be an identical edge from $v$ to $u$ in both graphs for...
[ "data structures", "graphs", "greedy", "shortest paths" ]
1,900
#include "bits/stdc++.h" using namespace std; #define int long long #define eb emplace_back const int INF = 1e18; void solve() { int n, s1, s2; cin >> n >> s1 >> s2; s1--, s2--; vector<vector<int>> g1(n), g2(n); vector<bool> good(n); set<pair<int, int>> edges; int m1; cin >> m1; ...
2059
E1
Stop Gaming (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version you only need to find the minimum number of operations. You can hack only if you solved all versions of this problem.} You are given $n$ arrays, each of which has a length of $m$. Let the $j$-th element of the ...
Let's connect the hints together: we will iterate through the prefix of elements that were originally in the array and have not been removed from the end. We still need to understand when the prefix can be extended to the final array. We will look at the positions of elements from the current prefix, after which in the...
[ "brute force", "constructive algorithms", "greedy", "hashing", "strings" ]
2,500
#include "bits/stdc++.h" using namespace std; void solve() { int n, m; cin >> n >> m; vector<int> a(n * m + 1), b(n * m + 1); vector<deque<int>> mat(n + 1, deque<int> (m)); for (int i = 1; i <= n; i++) { for (int j = 0; j < m; j++) { int ind = j + 1 + (i - 1) * m; m...
2059
E2
Stop Gaming (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version you need to output all the operations that need to be performed. You can hack only if you solved all versions of this problem.} You are given $n$ arrays, each of which has a length of $m$. Let the $j$-th elemen...
Let's find the answer to problem E1. We just need to restore the necessary sequence of actions. Let's take a closer look at the inductive proof from E1. Notice that it represents an algorithm where at each step we find the rightmost element at the end of some array after which we need to add something. Thus, such an al...
[ "brute force", "constructive algorithms", "data structures", "hashing", "strings" ]
2,900
#include <bits/stdc++.h> using namespace std; #define eb emplace_back #define int long long #define all(x) x.begin(), x.end() #define fi first #define se second const int INF = 1e9 + 1000; struct segtree { vector<pair<int, int>> tree; vector<int> ass; int size = 1; void init(vector<int> &a) { ...
2060
A
Fibonacciness
There is an array of $5$ integers. Initially, you only know $a_1,a_2,a_4,a_5$. You may set $a_3$ to any positive integer, negative integer, or zero. The Fibonacciness of the array is the number of integers $i$ ($1 \leq i \leq 3$) such that $a_{i+2}=a_i+a_{i+1}$. Find the maximum Fibonacciness over all integer values of...
We can notice that the possible values of $a_3$ ranges from $-99$ to $200$. Thus, we can iterate over all values of $a_3$ from $-99$ to $200$, and for each value, compute the Fibonacciness of the sequence. The maximal of all these values gives the solution to the problem. Time Complexity : $O(3*a_{max})$ $a_3$ can be r...
[ "brute force" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { vll ve(4); for (ll &i : ve) cin >> i; set <ll> st; st.insert(ve[3]-ve[2]); st.insert(ve[2]-ve[1]); st.insert(ve[0]+ve[1]); cout << 4-s...
2060
B
Farmer John's Card Game
Farmer John's $n$ cows are playing a card game! Farmer John has a deck of $n \cdot m$ cards numbered from $0$ to $n \cdot m-1$. He distributes $m$ cards to each of his $n$ cows. Farmer John wants the game to be fair, so each cow should only be able to play $1$ card per round. He decides to determine a turn order, dete...
Assume the cows are initially ordered correctly. A solution exists if the first cow can place $0$, the second cow can place $1$, and so on, continuing with the first cow placing $n$, the second cow placing $n+1$, and so forth. Observing the pattern, the first cow must be able to place ${0, n, 2n, \dots}$, the second ${...
[ "greedy", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { ll n, m; cin >> n >> m; vector <vll> ve(n, vll(m)); vll p(n, -16); bool val = true; ll c = 0; for (vll &we : ve) { for (ll &i ...
2060
C
Game of Mathletes
Alice and Bob are playing a game. There are $n$ (\textbf{$n$ is even}) integers written on a blackboard, represented by $x_1, x_2, \ldots, x_n$. There is also a given integer $k$ and an integer score that is initially $0$. The game lasts for $\frac{n}{2}$ turns, in which the following events happen sequentially: - Ali...
Note that Bob has all the power in this game, because the order in which Alice picks numbers is irrelevant, since Bob can always pick the optimal number to give himself a point. Therefore, we can just ignore Alice and play the game from Bob's perspective. From this point on, a "paired" number is any number $a$ on the b...
[ "games", "greedy", "sortings", "two pointers" ]
900
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { ll n, k; cin >> n >> k; vll ve(n); for (ll &i : ve) cin >> i; vll th(k+1, 0); for (ll i : ve) { if (i >= k) continue; th[i...
2060
D
Subtract Min Sort
You are given a sequence $a$ consisting of $n$ positive integers. You can perform the following operation any number of times. - Select an index $i$ ($1 \le i < n$), and subtract $\min(a_i,a_{i+1})$ from both $a_i$ and $a_{i+1}$. Determine if it is possible to make the sequence \textbf{non-decreasing} by using the o...
For clarity, let's denote $op_i$ as an operation performed on $a_i$ and $a_{i+1}$. Claim: if it is possible, then the sequence of operations $op_1,op_2,\ldots,op_{n-1}$ will sort the array. Proof: Let $b$ be any sequence of operations that will sort the array. Let's transform the sequence $b$ such that it becomes $[op_...
[ "greedy" ]
1,100
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { ll n; cin >> n; vll ve(n); for (ll &i : ve) cin >> i; ll j = 0; for (ll i = 1; i < n; i++) { if (ve[i-1] > ve[i]) j = i; } ...
2060
E
Graph Composition
You are given two simple undirected graphs $F$ and $G$ with $n$ vertices. $F$ has $m_1$ edges while $G$ has $m_2$ edges. You may perform one of the following two types of operations any number of times: - Select two integers $u$ and $v$ ($1 \leq u,v \leq n$) such that there is an edge between $u$ and $v$ in $F$. Then,...
Let's solve the problem for each operation. First, consider the operation that removes an edge from $F$. Divide $G$ into its connected components and assign each vertex a component index. Then, for each edge in $F$, if it connects vertices with different component indices, remove it and increment the operation count. T...
[ "dfs and similar", "dsu", "graphs", "greedy" ]
1,500
#include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(time(nullptr)); const int inf = 1e9; con...
2060
F
Multiplicative Arrays
You're given integers $k$ and $n$. For each integer $x$ from $1$ to $k$, count the number of integer arrays $a$ such that all of the following are satisfied: - $1 \leq |a| \leq n$ where $|a|$ represents the length of $a$. - $1 \leq a_i \leq k$ for all $1 \leq i \leq |a|$. - $a_1 \times a_2 \times \dots \times a_{|a|}=...
When $n$ is large, many of the array's elements will be $1$. The number of non-$1$ elements can't be so large. Try to precompute all arrays without $1$ and then use combinatorics. The naive solution is to define $f_k(n)$ as the number of arrays containing $n$ elements with a product of $k$. We could then try to compute...
[ "combinatorics", "dp", "number theory" ]
2,200
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using TemplateF; #if !PROBLEM SolutionF a = new(); a.Solve(); #endif namespace TemplateF { internal class SolutionF { ...
2060
G
Bugged Sort
Today, Alice has given Bob arrays for him to sort in increasing order again! At this point, no one really knows how many times she has done this. Bob is given two sequences $a$ and $b$, both of length $n$. All integers in the range from $1$ to $2n$ appear exactly once in either $a$ or $b$. In other words, the concaten...
Consider $(a_i, b_i)$ as the $i$-th pair. Can two elements ever become unpaired? No. Every operation keeps the pairs intact. The best way to think about the operation is like this: Swap the pairs at index $i$ and index $j$. Swap the pairs at index $i$ and index $j$. Flip each pair (swap $a_i$ with $b_i$, and $a_j$ with...
[ "dp", "greedy", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; #define F0R(i, n) for (int i = 0; i < n; i++) #define FOR(i, m, n) for (int i = m; i < n; i++) #define print pair<int, int> #define vp vector<print> #define ALL(x) (x).begin(), (x).end() void solve() { int n; cin >> n; vp pairs(n); F0R(i, n) { c...
2061
A
Kevin and Arithmetic
To train young Kevin's arithmetic skills, his mother devised the following problem. Given $n$ integers $a_1, a_2, \ldots, a_n$ and a sum $s$ initialized to $0$, Kevin performs the following operation for $i = 1, 2, \ldots, n$ in order: - Add $a_i$ to $s$. If the resulting $s$ is even, Kevin earns a point and repeated...
After the first operation, $s$ is always odd. You can only earn points when $a_i$ is odd after this operation. However, during the first operation, you can only earn a point if $a_i$ is even. Let $c_0$ and $c_1$ be the number of even and odd numbers, respectively. If there is at least one even number, you can place it ...
[ "math" ]
800
null
2061
B
Kevin and Geometry
Kevin has $n$ sticks with length $a_1,a_2,\ldots,a_n$. Kevin wants to select $4$ sticks from these to form an isosceles trapezoid$^{\text{∗}}$ with a positive area. Note that rectangles and squares are also considered isosceles trapezoids. Help Kevin find a solution. If no solution exists, output $-1$. \begin{footnot...
Let $a$ and $b$ be the lengths of the two bases, and let $c$ be the length of the two legs. A necessary and sufficient condition for forming an isosceles trapezoid with a positive area is $|a - b| < 2c$, as the longest edge must be shorter than the sum of the other three edges. To determine whether an isosceles trapezo...
[ "binary search", "geometry" ]
1,100
null
2061
C
Kevin and Puzzle
Kevin enjoys logic puzzles. He played a game with $n$ classmates who stand in a line. The $i$-th person from the left says that there are $a_i$ liars to their left (not including themselves). Each classmate is either honest or a liar, with the restriction that \textbf{no two liars can stand next to each other}. Hones...
For the $i$-th person, there are at most two possible cases: If they are honest, there are exactly $a_i$ liars to their left. If they are a liar, since two liars cannot stand next to each other, the $(i-1)$-th person must be honest. In this case, there are $a_{i-1} + 1$ liars to their left. Let $dp_i$ represent the num...
[ "2-sat", "combinatorics", "dp" ]
1,600
null
2061
D
Kevin and Numbers
Kevin wrote an integer sequence $a$ of length $n$ on the blackboard. Kevin can perform the following operation any number of times: - Select two integers $x, y$ on the blackboard such that $|x - y| \leq 1$, erase them, and then write down an integer $x + y$ instead. Kevin wants to know if it is possible to transform...
It can be challenging to determine how to merge small numbers into a larger number directly. Therefore, we approach the problem in reverse. Instead of merging numbers, we consider transforming the number $b$ back into $a$. For each number $x$, it can only be formed by merging $\lceil \frac{x}{2} \rceil$ and $\lfloor \f...
[ "bitmasks", "data structures" ]
1,600
null
2061
E
Kevin and And
Kevin has an integer sequence $a$ of length $n$. At the same time, Kevin has $m$ types of magic, where the $i$-th type of magic can be represented by an integer $b_i$. Kevin can perform at most $k$ (possibly zero) magic operations. In each operation, Kevin can do the following: - Choose two indices $i$ ($1\leq i\leq ...
For a fixed $p$, let $f(S)$ represent the number obtained after applying the operations in set $S$ to $p$. Define $g(i)$ as the minimum value of $f(S)$ for all subsets $S$ with $|S| = i$, i.e., $g(i) = \min_{|S| = i} f(S)$. - Lemma: The function $g$ is convex, that is for all $i$ ($1 \leq i < m$), the inequality $2g(i)...
[ "bitmasks", "brute force", "dp", "greedy", "math", "sortings" ]
2,000
null
2061
F2
Kevin and Binary String (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, string $t$ consists of '0', '1' and '?'. You can hack only if you solved all versions of this problem.} Kevin has a binary string $s$ of length $n$. Kevin can perform the following operation: - Choose two adj...
First, we divide the string $s$ into blocks. Let's analyze the properties of the blocks in $s$ that do not move (to simplify corner cases, we can add a block with a different number at both ends of $s$): These blocks must alternate between $0$ and $1$. Between two immovable blocks, the $0$s will shift toward the same s...
[ "data structures", "dp" ]
3,500
null
2061
G
Kevin and Teams
This is an interactive problem. Kevin has $n$ classmates, numbered $1, 2, \ldots, n$. Any two of them may either be friends or not friends. Kevin wants to select $2k$ classmates to form $k$ teams, where each team contains exactly $2$ people. Each person can belong to at most one team. Let $u_i$ and $v_i$ be two peop...
Using graph theory terminology, let edges labeled as $0$ be represented in red and edges labeled as $1$ be represented in blue. - We can prove that if a graph has $3k + 1$ vertices, the maximum matching will be at most $k$. To see this, you can construct a blue clique of size $2k+1$, with all other edges colored red. I...
[ "constructive algorithms", "graphs", "interactive" ]
2,900
null
2061
H2
Kevin and Stones (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to output a valid sequence of operations if one exists. You can hack only if you solved all versions of this problem.} Kevin has an undirected graph with $n$ vertices and $m$ edges. Initially, some ve...
Necessary and Sufficient Conditions First, if $s = t$, the transformation is trivially feasible. Beyond this trivial case, let us consider the necessary conditions: The initial state must allow at least one valid move. The target state must allow at least one valid move. For every connected component, the number of sto...
[ "flows", "graphs" ]
3,500
null
2061
I
Kevin and Nivek
Kevin and Nivek are competing for the title of "The Best Kevin". They aim to determine the winner through $n$ matches. The $i$-th match can be one of two types: - \textbf{Type 1}: Kevin needs to spend $a_i$ time to defeat Nivek and win the match. If Kevin doesn't spend $a_i$ time on it, Nivek will win the match. - \t...
First, there is a straightforward dynamic programming solution with a time complexity of $O(n^2)$. Let $dp(i, j)$ represent the minimum cost for Kevin to achieve $j$ victories in the first $i$ games. However, optimizing this dynamic programming solution directly is difficult because it lacks convexity. Therefore, we us...
[ "divide and conquer", "dp" ]
3,500
null
2062
A
String
You are given a string $s$ of length $n$ consisting of $\mathtt{0}$ and/or $\mathtt{1}$. In one operation, you can select a non-empty subsequence $t$ from $s$ such that any two adjacent characters in $t$ are different. Then, you flip each character of $t$ ($\mathtt{0}$ becomes $\mathtt{1}$ and $\mathtt{1}$ becomes $\ma...
Let $c$ be the number of $1$s. On one hand, each operation can decrease $c$ by at most $1$, so the answer is at least $c$. On the other hand, by only operating on $1$s each time, it takes exactly $c$ operations, so the answer is at most $c$. Therefore, the answer is $c$.
[ "constructive algorithms", "greedy", "math", "strings" ]
800
for _ in range(int(input())): print(input().count('1'))
2062
B
Clockwork
You have a sequence of $n$ time clocks arranged in a line, where the initial time on the $i$-th clock is $a_i$. In each second, the following happens in order: - Each clock's time decreases by $1$. If any clock's time reaches $0$, you lose immediately. - You can choose to move to an adjacent clock or stay at the clock...
On one hand, traveling from $i$ to $1$ and back takes time $2(i-1)$, and traveling from $i$ to $n$ and back takes time $2(n-i)$. Therefore, it must hold that $t_i > 2\max(i-1, n-i)$. On the other hand, if this condition is satisfied, one can simply move back and forth between $1$ and $n$ directly.
[ "greedy", "math" ]
900
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) for i in range(n): if a[i]<=max(i,n-i-1)*2: print('NO') break else: print('YES')
2062
C
Cirno and Operations
Cirno has a sequence $a$ of length $n$. She can perform either of the following two operations for any (possibly, zero) times \textbf{unless} the current length of $a$ is $1$: - Reverse the sequence. Formally, $[a_1,a_2,\ldots,a_n]$ becomes $[a_n,a_{n-1},\ldots,a_1]$ after the operation. - Replace the sequence with it...
Let the reversal be called operation $1$, and the difference be called operation $2$. Consider swapping two adjacent operations: $12 \to 21$. If the sequence before the operations is $[a_1, a_2, \dots, a_n]$, then after the operations, the sequence changes from $[a_{n-1} - a_n, a_{n-2} - a_{n-1}, \dots, a_1 - a_2]$ to ...
[ "brute force", "math" ]
1,200
from math import * for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ans=sum(a) while n>1: n-=1 a=[a[i+1]-a[i] for i in range(n)] ans=max(ans,abs(sum(a))) print(ans)
2062
D
Balanced Tree
You are given a tree$^{\text{∗}}$ with $n$ nodes and values $l_i, r_i$ for each node. You can choose an initial value $a_i$ satisfying $l_i\le a_i\le r_i$ for the $i$-th node. A tree is balanced if all node values are equal, and the value of a balanced tree is defined as the value of any node. In one operation, you ca...
First, assume that the values of $a_i$ have already been determined and $1$ is the root of the tree. For any edge connecting $x$ and $\text{fa}(x)$, to make $a_x=a_{\text{fa}(x)}$, the only useful operation is to set $u=x,v=\text{fa}(x)$ or $v=x,u=\text{fa}(x)$. After the operation, $a_x-a_{\text{fa}(x)}$ changes by $1...
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
2,200
for _ in range(int(input())): n = int(input()) l,r=[],[] for i in range(n): L,R=map(int,input().split()) l.append(L) r.append(R) e=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) e[u-1].append(v-1) e[v-1].append(u-1) stk=[0] f=[-1]*n nfd=[] while stk: u=stk.pop() nfd.ap...
2062
E1
The Game (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, you only need to find one of the possible nodes Cirno may choose. You can hack only if you solved all versions of this problem.} Cirno and Daiyousei are playing a game with a tree$^{\text{∗}}$ of $n$ nodes, ro...
In the first round, the node $u$ chosen by Cirno must satisfy: there exists a node $v$ outside the subtree of $u$ such that $w_v > w_u$. If no such node exists, then Cirno will lose. Among these nodes, Cirno can choose the node with the largest $w_u$. After this, Daiyousei can only select nodes that do not satisfy the ...
[ "data structures", "dfs and similar", "games", "graphs", "greedy", "trees" ]
2,000
for _ in range(int(input())): n = int(input()) w=[int(x) for x in input().split()] wb=[[] for i in range(n)] for i in range(n): w[i]-=1 wb[w[i]].append(i) e=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) e[u-1].append(v-1) e[v-1].append(u-1) stk=[0] f,dfn=[-1]*n,[0]*n nfd=[]...
2062
E2
The Game (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to find all possible nodes Cirno may choose. You can hack only if you solved all versions of this problem.} Cirno and Daiyousei are playing a game with a tree$^{\text{∗}}$ of $n$ nodes, rooted at node...
In the first round, the node $u$ chosen by Cirno must satisfy: there exists a node $v$ outside the subtree of $u$ such that $w_v > w_u$. If no such node exists, then Cirno will lose. Similar to Cirno's strategy in E1, if Daiyousei can choose a node such that Cirno can still make a move after the operation, then Daiyous...
[ "data structures", "dfs and similar", "games", "graphs", "implementation", "trees" ]
3,000
#include "bits/stdc++.h" using namespace std; #define all(x) (x).begin(),(x).end() const int N = 5e5 + 2; vector<int> e[N]; int dfn[N], nfd[N], low[N]; int id, n; void dfs(int u) { nfd[dfn[u] = ++id] = u; for (int v : e[u]) erase(e[v], u), dfs(v); low[u] = id; } int main() { ios::sync_with_stdio(0); cin.tie(0); co...
2062
F
Traveling Salescat
You are a cat selling fun algorithm problems. Today, you want to recommend your fun algorithm problems to $k$ cities. There are a total of $n$ cities, each with two parameters $a_i$ and $b_i$. Between any two cities $i,j$ ($i\ne j$), there is a bidirectional road with a length of $\max(a_i + b_j , b_i + a_j)$. The cos...
Let $x_i = \frac{a_i + b_i}{2}$, $y_i = \frac{a_i - b_i}{2}$. Then $\max(a_i + b_j , b_i + a_j) = \max( x_i + y_i + x_j - y_j , x_i - y_i + x_j + y_j) = x_i + x_j + \max(y_i - y_j, y_j - y_i)$ $= x_i + x_j + |y_i - y_j|$. Consider a road that passes through $k$ different cities, and consider the contribution as two par...
[ "constructive algorithms", "dp", "geometry", "graphs", "greedy", "math", "sortings" ]
2,900
class Q: def __init__(this,x,y): this.x,this.y=x+y,x-y def __lt__(this,rhs): return this.y<rhs.y for _ in range(int(input())): n=int(input()) a=[0]*n for i in range(n): x,y=map(int,input().split()) a[i]=Q(x,y) a.sort() l=[10**18]*(n+1) sl=l.copy();slt=l.copy();slrt=l.copy() s=10**18 for m,t in enumera...
2062
G
Permutation Factory
You are given two permutations $p_1,p_2,\ldots,p_n$ and $q_1,q_2,\ldots,q_n$ of length $n$. In one operation, you can select two integers $1\leq i,j\leq n,i\neq j$ and swap $p_i$ and $p_j$. The cost of the operation is $\min (|i-j|,|p_i-p_j|)$. Find the minimum cost to make $p_i = q_i$ hold for all $1\leq i\leq n$ and...
Because the cost of an operation is $\min(|i-j|,|p_i-p_j|)$, we can consider this operation as two operations with different costs, one costing $|i-j|$ and the other costing $|p_i-p_j|$. Consider each number in the permutation as a point $(i, p_i)$ on a two-dimensional plane. So the first operation can be seen as movin...
[ "flows", "geometry", "graph matchings", "graphs" ]
3,500
#include<bits/stdc++.h> using namespace std; struct linex{ int v; int w; int nxt; int c; }; int head[210],cnt,cpos[210],vis[210],qvis[210],totc,dis[210],inf=1000000000; linex l[21000]; queue<int>que; void add(int u,int v,int w,int c){ l[cnt].nxt=head[u]; head[u]=cnt; l[cnt].v=v; l[cnt].w=w; l[cnt].c=c; cnt++;...
2062
H
Galaxy Generator
In a two-dimensional universe, a star can be represented by a point $(x,y)$ on a two-dimensional plane. Two stars are directly connected if and only if their $x$ or $y$ coordinates are the same, and there are no other stars on the line segment between them. Define a galaxy as a connected component composed of stars con...
We will refer to the smallest rectangle containing a galaxy whose edges are parallel to the coordinate axis as the boundary rectangle of a galaxy. For two galaxies, if the projections of their boundary rectangles intersect on the x or y axis, we can merge these two galaxies in one operation. Proof: Let's assume that th...
[ "bitmasks", "combinatorics", "dp" ]
3,500
#include<bits/stdc++.h> using namespace std; const long long mod=1000000007; string s; long long dp[15][15][1<<14],vl[200],sgvl[15][15][15][15]; long long dp2[15][1<<14],dpvl2[15][1<<14]; int psum[15][15]; long long getvl(long long l,long long r,long long x,long long y){ if(l>=r||x>=y)return 0; return vl[psum[r][y]-p...
2063
A
Minimal Coprime
\begin{center} {\small Today, Little John used all his savings to buy a segment. He wants to build a house on this segment.} \end{center} A segment of positive integers $[l,r]$ is called coprime if $l$ and $r$ are coprime$^{\text{∗}}$. A coprime segment $[l,r]$ is called minimal coprime if it does not contain$^{\text...
It is easy to see that two integers $l$ and $l+1$ are always coprime, due to $\gcd(l,l+1)=\gcd(1,l)=\gcd(0,1)=1$. Thus, all segments in the form $[l,l+1]$ are coprime, and all minimal coprime segments must have a size of at most $2$ (otherwise, it will contain another segment of size $2$). It can be observed that the o...
[ "math", "number theory" ]
800
for i in range(int(input())): x,y=map(int,input().split()) if x==y==1: print(1) else: print(y-x)
2063
B
Subsequence Update
\begin{center} {\small After Little John borrowed expansion screws from auntie a few hundred times, eventually she decided to come and take back the unused ones.But as they are a crucial part of home design, Little John decides to hide some in the most unreachable places — under the eco-friendly wood veneers.} \end{cen...
To solve this problem, it is important to observe and prove the following claim: Claim: It is not beneficial to choose indices $i<l$ and $j>r$ at the same time. Notice that we only care about values that end up on indices in $[l,r]$. If we choose $i_1,i_2,\ldots,i_k$ such that $i_1<l$ and $i_k>r$, $i_1$ and $i_k$ will ...
[ "constructive algorithms", "data structures", "greedy", "sortings" ]
1,100
import sys input=lambda:sys.stdin.readline().rstrip() for _ in range(int(input())): n,l,r=map(int,input().split());l-=1 arr=[*map(int,input().split())] brr=arr[:l]+sorted(arr[l:]) crr=sorted(arr[:r])[::-1]+arr[r:] print(min(sum(brr[l:r]),sum(crr[l:r])))
2063
C
Remove Exactly Two
\begin{center} {\small Recently, Little John got a tree from his aunt to decorate his house. But as it seems, just one tree is not enough to decorate the entire house. Little John has an idea. Maybe he can remove a few vertices from the tree. That will turn it into more trees! Right?} \end{center} You are given a tree...
The main observation behind this task is that the number of connected components increases by $\text{deg}-1$, where $\text{deg}$ is the degree of the removed vertex at the time of removing. Thus, the number of connected components after removing two vertices $i$ and $j$ is: $d_i+d_j-1$ if $i$ and $j$ are not adjacent; ...
[ "brute force", "data structures", "dfs and similar", "dp", "graphs", "greedy", "sortings", "trees" ]
1,600
import sys input=lambda:sys.stdin.readline().rstrip() for i in range(int(input())): n=int(input()) deg=[0]*n adj=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) u-=1;v-=1 deg[u]+=1 deg[v]+=1 adj[u].append(v) adj[v].append(u) an...
2063
D
Game With Triangles
\begin{center} {\small Even Little John needs money to buy a house. But he recently lost his job; how will he earn money now? Of course, by playing a game that gives him money as a reward! Oh well, maybe not those kinds of games you are thinking about.} \end{center} There are $n+m$ distinct points $(a_1,0), (a_2,0), \...
Whenever the operation is performed, your score increases by $a_j-a_i$ or $b_j-b_i$, where $i$, $j$ are the indices you choose two points on (WLOG $a_i<a_j$ or $b_i<b_j$, but this assumption is not necessary). For simplicity, we will call an operation where you choose two on $y=0$ "Operation A", and those where you cho...
[ "binary search", "brute force", "data structures", "geometry", "greedy", "implementation", "math", "ternary search", "two pointers" ]
2,000
#include<bits/stdc++.h> using namespace std; using ll=long long; int main() { cin.tie(0)->sync_with_stdio(0); int t;cin>>t; while(t--) { int n,m;cin>>n>>m; vector<ll>arr(n),brr(m); for(ll&i:arr)cin>>i; for(ll&i:brr)cin>>i; sort(begin(arr),end(arr)); sort(begin(brr),end(brr)); vecto...
2063
E
Triangle Tree
\begin{center} {\small One day, a giant tree grew in the countryside. Little John, with his childhood eagle, decided to make it his home. Little John will build a structure on the tree with galvanized square steel. However, little did he know, he could not build what is physically impossible.} \end{center} You are giv...
In this editorial, we will denote the depth of vertex $v$ as $d_v$, and the subtree size of vertex $v$ as $s_v$. They can be easily calculated using DFS. Let us try to first understand what $f(x,y)$ means. If the two edge lengths are $a$ and $b$ (WLOG $a \le b$), the third edge length $L$ must satisfy $a+b>L$ and $a+L>...
[ "data structures", "dfs and similar", "dp", "greedy", "trees" ]
2,300
#include<bits/stdc++.h> using namespace std; using ll=long long; int main() { cin.tie(0)->sync_with_stdio(0); int t;cin>>t; while(t--) { ll n;cin>>n; vector<ll>d(n,0),s(n),dc(n),dcs; vector<vector<ll>>adj(n); for(int i=1;i<n;i++) { int u,v;cin>>u>>v; ...
2063
F1
Counting Is Not Fun (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, the limits on $t$ and $n$ are smaller. You can hack only if you solved all versions of this problem.} \begin{center} {\small Now Little John is rich, and so he finally buys a house big enough to fit himself an...
To solve the easy subtask, you can derive some helpful properties from the usual stack-based algorithm to determine whether a bracket sequence is balanced. Note the following well-known fact. Fact: The good pairs are exactly the pairs of brackets that are popped "together" in the stack-based algorithm. Considering this...
[ "combinatorics", "data structures", "dfs and similar", "dp", "dsu", "graphs", "hashing", "implementation", "math", "trees" ]
2,400
#include<bits/stdc++.h> using namespace std; using ll=long long; const ll md=998244353; int main() { int t;cin>>t; vector<ll>ctl(5050); ctl[0]=1; for(int n=1;n<5050;n++) { for(int i=1;i<=n;i++) { ctl[n]=(ctl[n]+ctl[i-1]*ctl[n-i]%md)%md; } } while(t--) ...
2063
F2
Counting Is Not Fun (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the limits on $t$ and $n$ are bigger. You can hack only if you solved all versions of this problem.} \begin{center} {\small Now Little John is rich, and so he finally buys a house big enough to fit himself and...
If you have not read the editorial for the easy subtask, I strongly suggest you to read it first. It contains some important observations that carry on to the solution of the hard subtask. The easy subtask's solution relied on enumerating the "minimal balanced subsequences". (We will use this same term repeatedly in th...
[ "combinatorics", "data structures", "dfs and similar", "dsu", "graphs", "implementation", "trees" ]
2,700
#pragma GCC optimize("O3,unroll-loops") #include <iostream> #include <numeric> #include <vector> constexpr int MAX_N = 3e5; constexpr long long MOD = 998244353; struct _inv_small { long long data[MAX_N + 2] = {0}; constexpr _inv_small() { data[1] = 1; for (int i = 2; i <= MAX_N; i += 2) { data[i] =...
2064
A
Brogramming Contest
One day after waking up, your friend challenged you to a brogramming contest. In a brogramming contest, you are given a binary string$^{\text{∗}}$ $s$ of length $n$ and an initially empty binary string $t$. During a brogramming contest, you can make either of the following moves any number of times: - remove some suff...
Notice that if $s$ starts with a $1$ we must move the entire string $s$ to $t$ at some point. Also Notice that if we perform the operation, the total number of occurrences of $01$ and $10$ across both strings can only decrease by one. This gives us an upper bound on the answer being the number of occurrences of $01$ an...
[ "greedy", "strings" ]
800
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2064
B
Variety is Discouraged
Define the score of an arbitrary array $b$ to be the length of $b$ minus the number of distinct elements in $b$. For example: - The score of $[1, 2, 2, 4]$ is $1$, as it has length $4$ and only $3$ distinct elements ($1$, $2$, $4$). - The score of $[1, 1, 1]$ is $2$, as it has length $3$ and only $1$ distinct element ...
The first thing to notice is that if we remove an element from $a$ then our score will never increase. Because removing one element will cause $|a|$ to decrease by $1$ and $\mathrm{distinct}(a)$ will decrease by at most $1$ and so the $|a|$ - $\mathrm{distinct}(a)$ will never increase. This means that we should be tryi...
[ "binary search", "constructive algorithms", "greedy", "two pointers" ]
1,100
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2064
C
Remove the Ends
You have an array $a$ of length $n$ consisting of \textbf{non-zero} integers. Initially, you have $0$ coins, and you will do the following until $a$ is empty: - Let $m$ be the current size of $a$. Select an integer $i$ where $1 \le i \le m$, gain $|a_i|$$^{\text{∗}}$ coins, and then: - if $a_i < 0$, then replace $a$ ...
First see that at any point we should either remove the leftmost positive element or the rightmost negative element, as if we were to take a positive element that is not the leftmost one we could have just taken the leftmost one first and had a higher score, a similar argument can be made for taking the rightmost negat...
[ "brute force", "constructive algorithms", "dp", "greedy" ]
1,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2064
D
Eating
There are $n$ slimes on a line, the $i$-th of which has weight $w_i$. Slime $i$ is able to eat another slime $j$ if $w_i \geq w_j$; afterwards, slime $j$ disappears and the weight of slime $i$ becomes $w_i \oplus w_j$$^{\text{∗}}$. The King of Slimes wants to run an experiment with parameter $x$ as follows: - Add a n...
First notice that if we are unable to eat the next slime then this slime must have had a $\mathrm{msb}$ (most significant bit) at least as large as the current value of $x$. Subsequently this means that if a slime has a $\mathrm{msb}$ strictly less than $x$ we can always eat it. Now see that if we eat a slime with lowe...
[ "binary search", "bitmasks", "brute force", "data structures", "dp", "greedy", "trees", "two pointers" ]
1,900
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2064
E
Mycraft Sand Sort
Steve has a permutation$^{\text{∗}}$ $p$ and an array $c$, both of length $n$. Steve wishes to sort the permutation $p$. Steve has an infinite supply of coloured sand blocks, and using them he discovered a physics-based way to sort an array of numbers called gravity sort. Namely, to perform gravity sort on $p$, Steve ...
The first thing to notice is that the first column of sand will be identical to $c$ after sorting. This means that it must be true that $c' = c$. Now that we know $c' = c$ we need to find how many ways we can re-arrange $p$ such that the sand layout is the same. Something we can notice is that $p'$ must be able to obta...
[ "combinatorics", "data structures", "dsu", "greedy", "math", "sortings" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2064
F
We Be Summing
You are given an array $a$ of length $n$ and an integer $k$. Call a non-empty array $b$ of length $m$ epic if there exists an integer $i$ where $1 \le i < m$ and $\min(b_1,\ldots,b_i) + \max(b_{i + 1},\ldots,b_m) = k$. Count the number of epic subarrays$^{\text{∗}}$ of $a$. \begin{footnotesize} $^{\text{∗}}$An array...
For an arbitrary array $b$ first notice that $\min(b_1,\ldots,b_i)$ and $\max(b_{i + 1},\ldots,n)$ is both non-increasing as we increase $i$. This means that if an array $b$ is epic then there exists a unique pair of integers $x, y$ such that $x + y = k$ and there exists $i, (1 \le i < |b|)$ such that $\min(b_1,\ldots,...
[ "binary search", "data structures", "dp", "two pointers" ]
2,600
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout << #x << " = " << x << "\n"; #define vdebug(a) cout << #a << " = "; for(auto x: a) cout << x << " "; cout << "\n"; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int uid(int a, int b) { return uniform_int_dist...
2065
A
Skibidus and Amog'u
Skibidus lands on a foreign planet, where the local Amog tribe speaks the Amog'u language. In Amog'u, there are two forms of nouns, which are singular and plural. Given that the root of the noun is transcribed as $S$, the two forms are transcribed as: - Singular: $S$ $+$ "us" - Plural: $S$ $+$ "i" Here, $+$ denotes ...
Let $n$ be the length of the string. Output the first $n-2$ characters of the string (to remove the suffix "us"), then the lowercase letter "i".
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { string str; cin >> str; str.pop_back(); str.pop_back(); cout << str + "i" << '\n'; } int main () { cin.tie(nullptr) -> sync_with_stdio(...
2065
B
Skibidus and Ohio
Skibidus is given a string $s$ that consists of lowercase Latin letters. If $s$ contains more than $1$ letter, he can: - Choose an index $i$ ($1 \leq i \leq |s| - 1$, $|s|$ denotes the current length of $s$) such that $s_i = s_{i+1}$. Replace $s_i$ with any lowercase Latin letter of his choice. Remove $s_{i+1}$ from t...
Note that if you can ever do an operation, the answer is $1$. This is because once you've done an operation on a string of length $k$, you are free to choose any character to replace $s_i$ with. Therefore, if you replace $s_i$ either with the character directly before it, or the character directly after it, you will en...
[ "strings" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { string str; cin >> str; for (ll i = 1; i < str.size(); i++) { if (str[i-1] == str[i]) { cout << "1\n"; return; ...
2065
C2
Skibidus and Fanum Tax (hard version)
\textbf{This is the hard version of the problem. In this version, $m \leq 2\cdot 10^5$.} Skibidus has obtained two arrays $a$ and $b$, containing $n$ and $m$ elements respectively. For \textbf{each} integer $i$ from $1$ to $n$, he is allowed to perform the operation \textbf{at most once}: - Choose an integer $j$ such...
The overall idea for both subtasks is that you need to iterate from left to right, and upon each element, pick the operation such that you obtain the smallest value of $a_i$ that is greater than $a_{i-1}$. For C1, you only have two values to consider for each index - $b_1-a_i$ and $a_i$. First, set $a_1 = min(a_1, b_1-...
[ "binary search", "greedy" ]
1,300
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; const ll INF = ll(1E18)+16; void tc () { ll n, m; cin >> n >> m; vll va(n), vb(m); for (ll &i : va) cin >> i; for (ll &i : vb) cin >> i; sort(vb.beg...
2065
D
Skibidus and Sigma
Let's denote the score of an array $b$ with $k$ elements as $\sum_{i=1}^{k}\left(\sum_{j=1}^ib_j\right)$. In other words, let $S_i$ denote the sum of the first $i$ elements of $b$. Then, the score can be denoted as $S_1+S_2+\ldots+S_k$. Skibidus is given $n$ arrays $a_1,a_2,\ldots,a_n$, each of which contains $m$ elem...
It is clear that the score of an array $b$ of length $n$ can be expressed as $n * b_1 + (n-1) * b_2 + (n-2) * b_3 \dots + 1 * b_n$. Let's solve this problem with $m=1$ for $n$ arrays with $1$ element in each. Due to the above fact, it's clear that the optimal way to arrange this array is to sort the elements from large...
[ "greedy", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; void tc () { ll n, m; cin >> n >> m; vector <vll> ve(n, vll(m)); for (vll &ve2 : ve) { for (ll &i : ve2) cin >> i; } vll vsum(n, 0); for (...
2065
E
Skibidus and Rizz
With the approach of Valentine's Day, Skibidus desperately needs a way to rizz up his crush! Fortunately, he knows of just the way: creating the perfect Binary String! Given a binary string$^{\text{∗}}$ $t$, let $x$ represent the number of $0$ in $t$ and $y$ represent the number of $1$ in $t$. Its \textbf{balance-valu...
Claim 1: It is impossible when $k < |n-m|$ Proof 1: The entire string will have a balance value greater than $k$. Claim 2: It is impossible when $k > max(n, m)$ Proof 2: The maximal possible balance value of any string with $n$ ones and $m$ zeroes is $max(m, n)$, as it is impossible due to the balance value definition....
[ "constructive algorithms", "greedy", "strings" ]
1,600
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ int n, m, k; cin >> n >> m >> k; if(max(n, m) - min(n, m) > k || k > max(n, m)){ cout << "-1" << endl; continue; } else{ pair<int, int> use1 = {n, 0}, use2 = {m, 1}; if(m > n) swap(use1, use2); for(int i = 0...
2065
F
Skibidus and Slay
Let's define the majority of a sequence of $k$ elements as the unique value that appears strictly more than $\left \lfloor {\frac{k}{2}} \right \rfloor$ times. If such a value does not exist, then the sequence does \textbf{not} have a majority. For example, the sequence $[1,3,2,3,3]$ has a majority $3$ because it appea...
Assume that a sequence a of length $n$ contains two types of elements, $1$ denoting majority and $0$ denoting "not majority". Then, if a contains a majority and $n \ge 2$, the following condition holds. a must contain either $[1,1]$ or $[1,0,1]$. This can be shown by contradiction. It is given that there are $k$ instan...
[ "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
1,700
#include <bits/stdc++.h> using namespace std; #define f first #define s second #define ll long long #define pii pair<int,int> #define amin(a,b) a = min(a,b) #define amax(a,b) a = max(a,b) vector<int> adj[500005]; int a[500005]; int s[500005]; int d[500005]; int t[1000005]; vector<int> v[500005]; int timer = 0; void ...
2065
G
Skibidus and Capping
Skibidus was abducted by aliens of Amog! Skibidus tries to talk his way out, but the Amog aliens don't believe him. To prove that he is not totally capping, the Amog aliens asked him to solve this task: An integer $x$ is considered a semi-prime if it can be written as $p \cdot q$ where $p$ and $q$ are (not necessarily...
Let $a_i=x$ and $a_j=y$ for any pair $(i,j)$ that we count. First, let's note that since $x|lcm(x,y)$, we don't need to consider any cases where $x$ or $y$ has more than two prime factors. There are three cases we must consider: $x$ and $y$ are primes, and $x\neq y$. Then, $lcm(x,y)=x\cdot y$ and has two prime factors....
[ "combinatorics", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; using ll = long long; vector<int> prime_factors(int x){ vector<int> pf; for(ll i = 2; i * i <= x; i++){ while(x % i == 0){ pf.push_back(i); x /= i; } } if(x > 1) pf.push_back(x); return pf; } int main(){ int t; cin >> t; while(t--){ int n; cin >> n; l...
2065
H
Bro Thinks He's Him
Skibidus thinks he's Him! He proved it by solving this difficult task. Can you also prove yourself? Given a binary string$^{\text{∗}}$ $t$, $f(t)$ is defined as the minimum number of contiguous substrings, each consisting of identical characters, into which $t$ can be partitioned. For example, $f(00110001) = 4$ becaus...
A brute attempt at a solution would be to go through each non-empty subset of ${1,2,...,n}$ and, for every pair of adjacent indices $(i, j)$ in the subset, increase $ans$ if $s[i] \neq s[j]$ In other words, increase ans every time $s[i]$ and $s[j]$ create a new border This is extremely slow at $O(2^n*n)$; however, we c...
[ "combinatorics", "data structures", "divide and conquer", "dp", "math", "matrices" ]
2,200
#include <bits/stdc++.h> using namespace std; using ll = long long; using vll = vector <ll>; using ii = pair <ll, ll>; using vii = vector <ii>; const ll MAXN = 2E5+16, MOD = 998244353; ll pw2[MAXN]; struct SegTree { vll tree; ll n; SegTree (ll n): tree(2*n, 0), n(n) {} void update (ll id, ll val) { ...
2066
A
Object Identification
This is an interactive problem. You are given an array $x_1, \ldots, x_n$ of integers from $1$ to $n$. The jury also has a fixed but hidden array $y_1, \ldots, y_n$ of integers from $1$ to $n$. The elements of array $y$ are \textbf{unknown} to you. Additionally, it is known that for all $i$, $x_i \neq y_i$, and all pa...
Note that if Object A is chosen, we can receive the number $0$ in response to some query, while if Object B is chosen, we cannot: since $(x_i,y_i) \neq (x_j,y_j)$. If the array $x_1, x_2, \ldots, x_n$ is not a permutation of the numbers from $1$ to $n$, then there will be some number $1 \leq a \leq n$ that is not prese...
[ "graphs", "greedy", "implementation", "interactive" ]
1,400
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> x(n + 1), isx(n + 1); for (int i = 1; i <= n; i++) { cin >> x[i]; isx[x[i]] = 1; } if (accumulate(isx.begin(), isx.end(), 0) == n) { int i1 = 0, in = 0; for (int i = 1; i...
2066
B
White Magic
We call a sequence $a_1, a_2, \ldots, a_n$ magical if for all $1 \leq i \leq n-1$ it holds that: $\operatorname{min}(a_1, \ldots, a_i) \geq \operatorname{mex}(a_{i+1}, \ldots, a_n)$. In particular, any sequence of length $1$ is considered magical. The minimum excluded (MEX) of a collection of integers $a_1, a_2, \ldot...
Note that for those suffixes where there is no number $0$, $\operatorname{mex}$ will be equal to $0$, and thus the condition will be satisfied, since at least on the left side it is definitely $\geq 0$. That is, any array without zeros is magical. However, if there are at least two zeros in the array, it can no longer ...
[ "constructive algorithms", "data structures", "dp", "greedy", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; bool check(vector<int> a) { int n = (int) a.size(); vector<int> suf_mex(n); vector<int> used(n + 1, false); int mex = 0; for (int i = n - 1; i >= 1; i--) { if (a[i] <= n) { used[a[i]] = true; } while (used[mex]) me...
2066
C
Bitwise Slides
You are given an array $a_1, a_2, \ldots, a_n$. Also, you are given three variables $P,Q,R$, initially equal to zero. You need to process all the numbers $a_1, a_2, \ldots, a_n$, \textbf{in the order from $1$ to $n$}. When processing the next $a_i$, you must perform \textbf{exactly} one of the three actions of your ch...
Let us denote $pref_i = a_1 \oplus \ldots \oplus a_i$ - the array of prefix $XOR$s. Notice that after the $i$-th action, it is always true that $P \oplus Q \oplus R = pref_i$, regardless of which actions were chosen. With this knowledge, we can say that after the $i$-th action, the condition "the numbers $P, Q, R$ are ...
[ "bitmasks", "combinatorics", "dp", "math" ]
2,300
#include <bits/stdc++.h> #define int long long using namespace std; const int M = 1'000'000'000 + 7; void solve() { int n; cin >> n; vector<int> a(n + 1), p(n + 1); for (int i = 1; i <= n; i++) { cin >> a[i]; p[i] = a[i] ^ p[i - 1]; } map<int, int> dp; dp[0] = 1; fo...
2066
D1
Club of Young Aircraft Builders (easy version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, all $a_i = 0$. You can hack only if you solved all versions of this problem.} There is an $n$-story building, with floors numbered from $1$ to $n$ from bottom to top. There is exactly one person living on each...
The problem is naturally solved using dynamic programming. The author's dynamic programming approach is as follows: Let's think: at which indices can the elements $a_i = 1$ be located? Notice that a person on the first floor can see every airplane, so the positions $a_{c+1} \ldots a_m$ cannot contain a one. However, it...
[ "combinatorics", "dp", "math" ]
2,400
#include <bits/stdc++.h> #define int long long using namespace std; const int N = 105; int fact[N * N], inv_fact[N * N]; const int M = (int) 1e9 + 7; int binpow(int a, int x) { int ans = 1; while (x) { if (x % 2) { ans *= a; ans %= M; } a *= a; a %= M;...
2066
D2
Club of Young Aircraft Builders (hard version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, not necessary $a_i = 0$. You can hack only if you solved all versions of this problem.} There is a building with $n$ floors, numbered from $1$ to $n$ from bottom to top. There is exactly one person living on e...
In fact, the states in the dynamic programming for the complex version will be the same as in the simple version, but to handle non-zero elements, we will need a slightly different perspective. The conceptual basis, as we define the array that we want to consider in the answer, remains the same: we look at where in the...
[ "combinatorics", "dp", "math" ]
2,900
#include <bits/stdc++.h> #define int long long using namespace std; const int N = 105; int fact[N * N], inv_fact[N * N]; const int M = (int) 1e9 + 7; int binpow(int a, int x) { int ans = 1; while (x) { if (x % 2) { ans *= a; ans %= M; } a *= a; a %= M;...
2066
E
Tropical Season
You have $n$ barrels of infinite capacity. The $i$-th barrel initially contains $a_i$ kilograms of water. In this problem, we assume that all barrels weigh the same. You know that \textbf{exactly} one of the barrels has a small amount of tropical poison distributed on its surface, with a total weight of $0.179$ kilogr...
If all values $a_1, a_2, \ldots, a_n$ are distinct, we immediately lose (except for $n=1$). Suppose initially there are two barrels of equal weight $a_i = a_j$. Then we look at what the scales indicate for the pair $(i, j)$. If it shows "greater" or "less" - we understand that the poisonous barrel is respectively $i$ o...
[ "binary search", "data structures", "greedy", "implementation" ]
3,300
#include <bits/stdc++.h> using namespace std; #define int long long typedef long long ll; typedef long double ld; #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define pb push_back #define ar(x) array<int, x> const int MAXA = 1'000'009; const int INF = (int) 1e18; struct SegTree...
2066
F
Curse
You are given two arrays of integers: $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_m$. You need to determine if it is possible to transform array $a$ into array $b$ using the following operation several (possibly, zero) times. - Among all non-empty subarrays$^{\text{∗}}$ of $a$, choose any with the maximum sum, a...
$\operatorname{MSS}(a)$ - the maximum sum of a non-empty subarray $a$. A detailed proof of the solution will be at the end of the analysis. First, we need to characterize all arrays reachable from $a$ through operations. Often, in such cases, we want to find some property that remains unchanged during operations or cha...
[ "constructive algorithms", "dp", "math" ]
3,300
#include <bits/stdc++.h> using namespace std; // #define int long long typedef long long ll; typedef long double ld; #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define sum(x) accumulate(all(x), 0) const int INF = 2'000'000'000; const int PLACEHOLDER = INF; vector<vector<int>>...
2067
A
Adjacent Digit Sums
You are given two numbers $x, y$. You need to determine if there exists an integer $n$ such that $S(n) = x$, $S(n + 1) = y$. Here, $S(a)$ denotes the sum of the digits of the number $a$ in the decimal numeral system.
Let's look at the last digit of the number $n$. If it is not equal to $9$, then in the number $n+1$, this last digit will be increased by $1$, while the rest of the number will remain unchanged. Thus, for such $n$, we have $S(n+1) = S(n) + 1$. In general, if the number $n$ ends with $k$ consecutive digits of $9$, then ...
[ "brute force", "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int x, y; cin >> x >> y; if (x + 1 >= y && (x + 1 - y) % 9 == 0) { cout << "Yes\n"; } else { cout << "No\n"; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; wh...
2067
B
Two Large Bags
You have two large bags of numbers. Initially, the first bag contains $n$ numbers: $a_1, a_2, \ldots, a_n$, while the second bag is empty. You are allowed to perform the following operations: - Choose any number from the first bag and move it to the second bag. - Choose a number from the first bag that is also present...
Note that when a number goes into the second bag, it remains unchanged there until the end of the entire process: our operations cannot interact with this number in any way. Therefore, every time we send a number to the second bag, we must keep in mind that an equal number must remain in the first bag by the end of the...
[ "brute force", "dp", "greedy", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); int mx = 0; for (int i = 0; i < n; i += 2) { if (max(mx, a[i]) != max(mx, a[i + 1])) { co...
2067
C
Devyatkino
You are given a positive integer $n$. In one operation, you can add to $n$ any positive integer whose decimal representation contains only the digit $9$, possibly repeated several times. What is the minimum number of operations needed to make the number $n$ contain at least one digit $7$ in its decimal representation?...
The first idea: the answer does not exceed $9$, since we can add $9$ and keep track of the last digit; with each addition, it will decrease by $1$ (going from $0$ to $9$), so after $9$ additions, the last digit will complete a full cycle and will be $7$ exactly once during the process. The second idea: it is quite diff...
[ "brute force", "dfs and similar", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; for (int l = 0; l <= 9; l++) { string s = to_string(n - l); int md = 0; for (auto c: s) { if (c <= '7') { md = max(md, c - '0'); } } if (l >= 7 - ...
2068
A
Condorcet Elections
It is a municipality election year. Even though the leader of the country has not changed for two decades, the elections are always transparent and fair. There are $n$ political candidates, numbered from $1$ to $n$, contesting the right to govern. The elections happen using a variation of the \underline{Ranked Voting ...
This problem is inspired by Condorcet's paradox. To put it simply, Condorcet's paradox states that for certain voters preferences, it's impossible to always resolve the elections fairly. No matter the outcome, more than half of the voters would prefer to change the result to some other outcome. This is illustrated by t...
[ "constructive algorithms", "graphs", "greedy", "probabilities" ]
2,300
null
2068
B
Urban Planning
You are responsible for planning a new city! The city will be represented by a rectangular grid, where each cell is either a park or a built-up area. The residents will naturally want to go for walks in the city parks. In particular, a \underline{rectangular walk} is a rectangle consisting of the grid cells, which is ...
Solutions that do not work First of all, let us consider a square with side $n$, consisting only of parks. It has $\left(\frac{n(n-1)}{2}\right)^2$ rectangular walks, since there are $\frac{n(n-1)}{2}$ ways to choose the top and bottom rows, and $\frac{n(n-1)}{2}$ ways to choose the left and right columns. We will deno...
[ "constructive algorithms" ]
3,100
null
2068
C
Ads
You have $n$ videos on your watchlist on the popular platform YooCube. The $i$-th video lasts $d_i$ minutes. YooCube has recently increased the frequency of their ads. Ads are shown only between videos. After finishing a video, an ad is shown if either of these two conditions is true: - three videos have been watched...
The result is equal to $g-1$ where $g$ is the number of groups of videos. Therefore, you want to minimize the number of groups and you can do this by creating large groups: first of size 3, then of size 2 and of size 1 with whatever is left. To create groups of size 3, we will pick the shortest video ($m$) as the first...
[ "binary search", "greedy", "two pointers" ]
2,100
null
2068
D
Morse Code
Morse code is a classical way to communicate over long distances, but there are some drawbacks that increase the transmission time of long messages. In Morse code, each character in the alphabet is assigned a sequence of dots and dashes such that \textbf{no sequence is a prefix of another}. To transmit a string of cha...
Any assignment of Morse codes to characters can be represented with a binary tree, where going to a left child appends a dot and going to a right child appends a dash. We then associate each character with a leaf in the tree. This ensures that the codes will not be prefixes of each other. Each vertex, both leafs and in...
[ "dp", "sortings", "trees" ]
3,100
null
2068
E
Porto Vs. Benfica
FC Porto and SL Benfica are the two largest football teams in Portugal. Naturally, when the two play each other, a lot of people travel from all over the country to watch the game. This includes the Benfica supporters' club, which is going to travel from Lisbon to Porto to watch the upcoming game. To avoid tensions bet...
We start by making a few definitions that will help us: Definition. Denote by $f(v)$ the minimum number of roads the supporters' club needs to travel if they start from vertex $v$ and want to end up at vertex $n$, and the police can still block exactly one road. So $f(1)$ is the answer to the problem and $f(n) = 0$. De...
[ "data structures", "dfs and similar", "dsu", "graphs", "shortest paths" ]
2,800
null
2068
F
Mascot Naming
When organizing a big event, organizers often handle side tasks outside their expertise. For example, the chief judge of EUC 2025 must find a name for the event's official mascot while satisfying certain constraints: - The name must include specific words as subsequences$^{*}$, such as the event name and location. You...
This problem requires constructing a string that contains each of the given strings $s_1, s_2, \dots, s_n$ as subsequences but does not contain $t$ as a subsequence. Key Observation. If $t$ is a subsequence of any $s_i$, then any string containing $s_i$ as a subsequence must also contain $t$. In this case, the answer i...
[ "brute force", "greedy", "implementation", "strings" ]
1,900
null
2068
G
A Very Long Hike
You are planning a hike in the Peneda-Gerês National Park in the north of Portugal. The park takes its name from two of its highest peaks: Peneda (1340 m) and Gerês (1545 m). For this problem, the park is modelled as an infinite plane, where each position $(x, y)$, with $x, y$ being integers, has a specific altitude. ...
Before diving into the solution, let us make a few key observations to build intuition for tackling the problem. Our goal is to count the number of distinct cells that can be reached within a time limit of $10^{20}$. To gain insight into this, consider first the simpler question: given a distant cell $(x, y)$ (where $x...
[ "shortest paths" ]
3,500
null
2068
H
Statues
The mayor of a city wants to place $n$ statues at intersections around the city. The intersections in the city are at all points $(x, y)$ with integer coordinates. Distances between intersections are measured using Manhattan distance, defined as follows: $$ \text{distance}((x_1, y_1), (x_2, y_2)) = |x_1 - x_2| + |y_1 -...
Let $d_0 = a + b$ be the distance between the first and the $n$-th statue. We are going to prove that a valid arrangement exists if and only if the following two conditions are satisfied: $d_0 + d_1 + \dots + d_{n-1}$ is even; $d_i \leq d_0 + \dots + d_{i-1} + d_{i+1} + \dots + d_{n-1}$ for all $0 \leq i \leq n-1$. To ...
[ "constructive algorithms", "greedy", "math" ]
2,700
null
2068
I
Pinball
You are playing a pinball-like game on a $h \times w$ grid. The game begins with a small ball located at the center of a specific cell marked as $S$. Each cell of the grid is either: - A block-type wall ($#$) that prevents the ball from entering the cell, reflecting it instead. - A thin oblique wall, either left-lean...
Let's decompose the whole grid into regions delimited by the movement of the ball without altering the walls. These regions are depicted in the picture below by colored lines. The path described by the solution is bolded. Let's build a graph over the set of all regions where we add an edge $(i, j)$ if regions $i$ and $...
[ "graphs", "shortest paths" ]
3,500
null
2068
J
The Ultimate Wine Tasting Event
Rumors of the excellence of Gabriella's wine tasting events have toured the world and made it to the headlines of prestigious wine magazines. Now, she has been asked to organize an event at the EUC 2025! This time she selected $2n$ bottles of wine, of which exactly $n$ are of white wine, and exactly $n$ of red wine. S...
We will find a simple necessary and sufficient condition on the string $s$ for the operation to be successful. Then, it will be trivial to check whether this condition is satisfied. First, suppose that it is possible to rearrange the bottles as described in the statement. That is, there esist two subsets $A = \{a_1, \,...
[ "combinatorics", "greedy" ]
2,000
null
2068
K
Amusement Park Rides
Ivan, Dmitrii, and Pjotr are celebrating Ivan's birthday at an amusement park with $n$ attractions. The $i$-th attraction operates at minutes $a_i, 2a_i, 3a_i, \dots$ (i.e., every $a_i$ minutes). Each minute, the friends can either ride exactly one available attraction \textbf{together} or wait. Since the rides are ve...
Assume that among the numbers $a_i$ there are $k$ distinct values, denoted by $p_1, p_2, \dots, p_k$. Suppose each $p_j$ appears $q_j$ times in the sequence $\{a_i\}$. We now construct a flow graph as follows: Define the vertex set as $V = \{S, T\} \cup \{A_1, A_2, \dots, A_k\}$. For each vertex $A_i$ (with $1 \le i \l...
[ "flows", "graphs" ]
3,000
null
2069
A
Was there an Array?
For an array of integers $a_1, a_2, \dots, a_n$, we define its \textbf{equality characteristic} as the array $b_2, b_3, \dots, b_{n-1}$, where $b_i = 1$ if the $i$-th element of the array $a$ is equal to both of its neighbors, and $b_i = 0$ if the $i$-th element of the array $a$ is not equal to at least one of its neig...
Let's try to find some contradiction of the following kind for the given array: we know for sure that some element $a$ must be equal to its neighbors, but the corresponding value $b_i$ is zero, or vice versa. If both $b_{i-1}$ and $b_{i+1}$ are equal to $1$, it means that the $i$-th element is equal to both of its neig...
[ "graph matchings", "greedy" ]
800
t = int(input()) for i in range(t): n = int(input()) s = list(input().split()) s = "".join(s) if "101" in s: print('NO') else: print('YES')
2069
B
Set of Strangers
You are given a table of $n$ rows and $m$ columns. Initially, the cell at the $i$-th row and the $j$-th column has color $a_{i, j}$. Let's say that two cells are strangers if they \textbf{don't} share a side. Strangers are allowed to touch with corners. Let's say that the set of cells is a set of strangers if all pai...
Let's fix some color and look at all cells of that color. We can decide either to leave this color as the resulting one and then we can ignore all these cells. Or we should get rid of this color, and it would cost at least one operation. If all cells are pairwise strangers, then one operation is enough to recolor all o...
[ "greedy", "matrices" ]
1,200
for _ in range(int(input())): n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(n)] hasColor = [0] * (n * m) hasBad = [0] * (n * m) for i in range(n): for j in range(m): hasColor[a[i][j] - 1] = 1 if i + 1 < n and a[i][j] == a[i + 1][...
2069
C
Beautiful Sequence
Let's call an integer sequence \textbf{beautiful} if the following conditions hold: - its length is at least $3$; - for every element except the first one, there is an element to the left less than it; - for every element except the last one, there is an element to the right larger than it; For example, $[1, 4, 2, 4,...
Let's change the definition of a beautiful sequence a bit. We can prove that the condition "for every element except the first one, there is an element to the left less than it" is equivalent to "the first element is less than every other element in the sequence". We can prove that these two conditions are equivalent b...
[ "combinatorics", "dp", "greedy", "two pointers" ]
1,500
#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 main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> dp(4, 0); dp[0] = 1; while (n--) { int x; cin >> x; ...
2069
D
Palindrome Shuffle
You are given a string $s$ consisting of lowercase Latin letters. You can perform the following operation with the string $s$: choose a contiguous substring (possibly empty) of $s$ and shuffle it (reorder the characters in the substring as you wish). Recall that a palindrome is a string that reads the same way from t...
I will describe a solution in $O(n \log n)$. It is possible to solve the problem in $O(n)$ with careful implementation of two pointers method, but $O(n \log n)$ is more intuitive and easier to understand, in my opinion. First, while the first character of the string is equal to the last character of the string, let's g...
[ "binary search", "greedy", "hashing", "strings", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int n = s.size(); int i = 0; while (i < n / 2 && s[i] == s[n - i - 1]) ++i; n -= 2 * i; s = s.substr(i, n); int ans = n; for (int z = 0; z < 2; ++z) { int l = ...
2069
E
A, B, AB and BA
You are given a string $s$ consisting of characters A and B. Your task is to split it into blocks of length $1$ and $2$ in such a way that - there are no more than $a$ strings equal to "A"; - there are no more than $b$ strings equal to "B"; - there are no more than $ab$ strings "AB"; - there are no more than $ba$ str...
Firstly, let's find the solution that maximizes the number of used blocks of length $2$ (AB and BA). Each used block of length $2$ frees us one A and B, so we don't lose anything. Secondly, since we don't have AA and BB, any pair of equal neighboring characters will be split in-between in any possible partition. So, le...
[ "constructive algorithms", "greedy", "sortings", "strings" ]
2,300
#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; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y << ")"; } template<class A> ostrea...
2069
F
Graph Inclusion
A connected component of an undirected graph is defined as a set of vertices $S$ of this graph such that: - for every pair of vertices $(u, v)$ in $S$, there exists a path between vertices $u$ and $v$; - there is no vertex outside $S$ that has a path to a vertex within $S$. For example, the graph in the picture below...
First, let's understand how to solve the problem without queries (given two graphs $A$ and $B$, add the minimum number of edges to $A$ so that it includes graph $B$), and then we'll deal with query processing. Let's understand what it means for graph $A$ to not include $B$. This means that some component of graph $B$ i...
[ "data structures", "dfs and similar", "divide and conquer", "dsu", "graphs" ]
2,800
#include<bits/stdc++.h> using namespace std; const int N = 400043; const int BUF = N * 20; int* where[BUF]; int val[BUF]; int cur = 0; void change(int& x, int y) { val[cur] = x; where[cur] = &x; x = y; cur++; } void rollback() { cur--; (*where[cur]) = val[cur]; } struct DSU { ...
2070
A
FizzBuzz Remixed
FizzBuzz is one of the most well-known problems from coding interviews. In this problem, we will consider a remixed version of FizzBuzz: Given an integer $n$, process all integers from $0$ to $n$. For every integer such that its remainders modulo $3$ and modulo $5$ are the same (so, for every integer $i$ such that $i ...
The key observation in this problem is that, if you pick two integers $x$ and $x+15$, both their remainders modulo $3$ and modulo $5$ are the same. So, the number of integers we need to count in $[0, 14]$ is the same as in $[15, 29]$, the same as in $[30, 44]$, and so on. So, you can calculate the number of segments of...
[ "brute force", "math" ]
800
t = int(input()) for i in range(t): n = int(input()) ans = 3 * (n // 15) n %= 15 for j in range(n + 1): if j % 3 == j % 5: ans += 1 print(ans)