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
2001
E1
Deterministic Heap (Easy Version)
\textbf{This is the easy version of the problem. The difference between the two versions is the definition of deterministic max-heap, time limit, and constraints on $n$ and $t$. You can make hacks only if both versions of the problem are solved.} Consider a perfect binary tree with size $2^n - 1$, with nodes numbered ...
Consider subtask - decision version of the problem (i.e. yes/no problem) as follow: "Given a sequence $a$ resulting from $k$ operations, check whether such $a$ is a deterministic max-heap.", what property $a$ should have? Try to fix the position of leaf being popped, what property are needed on the path from root to it...
[ "combinatorics", "dp", "math", "trees" ]
2,400
#include <iostream> #include <vector> using namespace std; using ll = long long; int binpow(ll a, ll b, ll p) { ll c = 1; while(b) { if (b & 1) c = c * a % p; a = a * a % p, b >>= 1; } return c; } int main() { int t; cin >> t; while(t--) { int n, k, p; cin >> n >> k >> p; vector<ll> fac...
2001
E2
Deterministic Heap (Hard Version)
\textbf{This is the hard version of the problem. The difference between the two versions is the definition of deterministic max-heap, time limit, and constraints on $n$ and $t$. You can make hacks only if both versions of the problem are solved.} Consider a perfect binary tree with size $2^n - 1$, with nodes numbered ...
Fix the position of first and second leaf being popped, what's the property needed for $a$ to be determinitic? Does the position of first leaf being popped really matters? Fix the position of first leaf being popped, do we really need to consider all possible position of second leaf being popped? Make good use of symme...
[ "combinatorics", "dp", "trees" ]
2,900
#include <iostream> #include <vector> using namespace std; using ll = long long; int binpow(ll a, ll b, ll p) { ll c = 1; while(b) { if (b & 1) c = c * a % p; a = a * a % p, b >>= 1; } return c; } int main() { int t; cin >> t; while(t--) { int n, k, p; cin >> n >> k >> p; vector<ll> fac...
2002
A
Distanced Coloring
You received an $n\times m$ grid from a mysterious source. The source also gave you a magic positive integer constant $k$. The source told you to color the grid with some colors, satisfying the following condition: - If $(x_1,y_1)$, $(x_2,y_2)$ are two distinct cells with the same color, then $\max(|x_1-x_2|,|y_1-y_2...
Consider the case with $n=m=k$. Generalize the solution for all $n,m,k$. It can be shown that for any $k\times k$ subgrid, the colors we use must be pairwise distinct. Thus, we have an lower bound of $\min(n,k)\cdot\min(m,k)$. We can show that this lower bound is indeed achievable by coloring the upper-left $\min(n,k)\...
[ "constructive algorithms", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int t, n, m, k; int main() { scanf("%d", &t); while (t--) { scanf("%d%d%d", &n, &m, &k); printf("%d\n", min(n, k)*min(m, k)); } return 0; }
2002
B
Removals Game
Alice got a permutation $a_1, a_2, \ldots, a_n$ of $[1,2,\ldots,n]$, and Bob got another permutation $b_1, b_2, \ldots, b_n$ of $[1,2,\ldots,n]$. They are going to play a game with these arrays. In each turn, the following events happen in order: - Alice chooses either the first or the last element of her array and r...
Find some conditions that Bob need to win. A general idea is that it is very difficult for Bob to win. We make some observations regarding the case where Bob wins. It is intuitive to see that for any subarray $[A_l,A_{l+1},\cdots,A_r]$, the elements' positions in $B$ must also form an interval. If $A[l:r]$ does not for...
[ "constructive algorithms", "games" ]
1,000
#include <bits/stdc++.h> #define ll long long #define lc(x) ((x) << 1) #define rc(x) ((x) << 1 | 1) #define ru(i, l, r) for (int i = (l); i <= (r); i++) #define rd(i, r, l) for (int i = (r); i >= (l); i--) #define mid ((l + r) >> 1) #define pii pair<int, int> #define mp make_pair #define fi first #define se second #def...
2002
C
Black Circles
There are $n$ circles on a two-dimensional plane. The $i$-th circle is centered at $(x_i,y_i)$. Initially, all circles have a radius of $0$. The circles' radii increase at a rate of $1$ unit per second. You are currently at $(x_s,y_s)$; your goal is to reach $(x_t,y_t)$ without touching the circumference of any circl...
The problem can't be that hard, find some simple strategy. We consider a simple strategy: walk towards the goal in a straight line. If some circle reaches the goal first, it is obvious that we have no chance of succeeding, no matter what path we take. Otherwise, it can be proven that we will not pass any circles on our...
[ "brute force", "geometry", "greedy", "math" ]
1,200
#include <bits/stdc++.h> #define ll long long using namespace std; int t, n, x[100011], y[100011], xs, ys, xt, yt; ll dis(int x1, int y1, int x2, int y2) { return 1ll * (x2 - x1) * (x2 - x1) + 1ll * (y2 - y1) * (y2 - y1); } int main() { scanf("%d", &t); while (t--) { scanf("%d", &n); for (...
2002
D2
DFS Checker (Hard Version)
\textbf{This is the hard version of the problem. In this version, you are given a generic tree and the constraints on $n$ and $q$ are higher. You can make hacks only if both versions of the problem are solved.} You are given a rooted tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$, and the r...
Try to find some easy checks that can be maintained. The problem revolves around finding a check for dfs orders that's easy to maintain. We have discovered several such checks, a few checks and their proofs are described below, any one of these checks suffices to tell whether a dfs order is valid. For every $u$, all of...
[ "binary search", "data structures", "dfs and similar", "graphs", "hashing", "trees" ]
2,300
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define fi first #define se second #define int long long void dbg_out() { cerr << endl; } template <typename H, typename... T> void dbg_out(H h, T... t) { cerr << ' ' << h; dbg_out(t...); } #define dbg(...) { cerr << #__VA_ARGS__ <<...
2002
E
Cosmic Rays
Given an array of integers $s_1, s_2, \ldots, s_l$, every second, cosmic rays will cause all $s_i$ such that $i=1$ or $s_i\neq s_{i-1}$ to be deleted simultaneously, and the remaining parts will be concatenated together in order to form the new array $s_1, s_2, \ldots, s_{l'}$. Define the \textbf{strength} of an array...
Consider an incremental solution. Use stacks. The problems asks for the answer for every prefix, which hints at an incremental solution. To add a new pair to the current prefix, we need to somehow process the new block merging with old ones. Thus, we should use some structure to store the information on the last block ...
[ "brute force", "data structures", "dp" ]
2,300
#include <bits/stdc++.h> #define ll long long #define N 3000011 #define pii pair<ll,int> #define s1 first #define s2 second using namespace std; int t, n, prv[N], nxt[N], b[N]; ll a[N]; priority_queue<pair<ll, int>> pq, del; ll sum = 0, ans[N]; int main() { scanf("%d", &t); while (t--) { scanf("%d", &n...
2002
F1
Court Blue (Easy Version)
\textbf{This is the easy version of the problem. In this version, $n=m$ and the time limit is lower. You can make hacks only if both versions of the problem are solved.} In the court of the Blue King, Lelle and Flamm are having a performance match. The match consists of several rounds. In each round, either Lelle or F...
Primes are powerful. Prime gaps are small. We view the problem as a walk on grid, starting at $(1,1)$. WLOG, we suppose $l>f$, thus only cells $(a,b)$ where $a<b$ would be considered. Notice that when $n$ is large enough, the largest prime $p\le n$ satisfies $2p>n$. As such, all cells $(p,i)$ where $i<p$ will be unbloc...
[ "brute force", "dfs and similar", "dp", "math", "number theory" ]
2,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 2e7 + 5; bool ntp[N]; int di[405][405]; bool bad[405][405]; int pos[N], g = 0, m = 3; int prime[2000005], cnt = 0; void sieve(int n) { int i, j; for (i = 2; i <= n; i++) { if (!ntp[i]) prime[++cnt] = i; ...
2002
F2
Court Blue (Hard Version)
\textbf{This is the hard version of the problem. In this version, it is not guaranteed that $n=m$, and the time limit is higher. You can make hacks only if both versions of the problem are solved.} In the court of the Blue King, Lelle and Flamm are having a performance match. The match consists of several rounds. In e...
Try generalizing the solution of F1. Write anything and pray that it will pass because of number theory magic. We generalize the solution in F1. Let $p$ be the largest prime $\le m$ and $q$ be the largest prime $\le\min(n,p-1)$. The problem is that there might be $\gcd(q,i)\neq1$ for some $p+1\le i\le m$, thus invalida...
[ "brute force", "dp", "math", "number theory" ]
2,800
#include <bits/stdc++.h> #define ll long long #define N 20000011 using namespace std; int t, n, m, a, b; bool is[N]; int pr[N / 10]; int gcd(int a, int b) { while (b) a %= b, swap(a, b); return a; } ll ans = 0; bool vis[1011][1011]; pair<int, int> vv[200011]; int vn, c; bool flg = 0; inline ll V(int i,...
2002
G
Lattice Optimizing
Consider a grid graph with $n$ rows and $n$ columns. Let the cell in row $x$ and column $y$ be $(x,y)$. There exists a directed edge from $(x,y)$ to $(x+1,y)$, with non-negative integer value $d_{x,y}$, for all $1\le x < n, 1\le y \le n$, and there also exists a directed edge from $(x,y)$ to $(x,y+1)$, with non-negativ...
We apologize for unintended solutions passing, and intended solutions failing with large constants. Brute force runs very fast on $n=18$, which forced us to increase constraints. Meet in the middle with a twist. Union of sets is hard. Disjoint union of sets is easy. The problem hints strongly at meet in the middle, at ...
[ "bitmasks", "brute force", "hashing", "meet-in-the-middle" ]
3,400
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define fi first #define se second #define int long long void dbg_out() { cerr << endl; } template <typename H, typename... T> void dbg_out(H h, T... t) { cerr << ' ' << h; dbg_out(t...); } #define dbg(...) { cerr << #__...
2002
H
Counting 101
It's been a long summer's day, with the constant chirping of cicadas and the heat which never seemed to end. Finally, it has drawn to a close. The showdown has passed, the gates are open, and only a gentle breeze is left behind. Your predecessors had taken their final bow; it's your turn to take the stage. Sorting th...
Try to solve Problem 101 with any approach. Can you express the states in the solution for Problem 101 with some simple structures? Maybe dp of dp? Try finding some unnecessary states and pruning them, to knock a $n$ off the complexity. We analyse Problem 101 first. A dp solution will be, let $f_{l,r,v}$ be the minimum...
[ "greedy" ]
3,500
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #define L(i, j, k) for(int i = (j); i <= (k); ++i) #define R(i, j, k) for(int i = (j); i >= (k); --i) #define ll long long #define vi vector <i...
2003
A
Turtle and Good Strings
Turtle thinks a string $s$ is a good string if there exists a sequence of strings $t_1, t_2, \ldots, t_k$ ($k$ is an arbitrary integer) such that: - $k \ge 2$. - $s = t_1 + t_2 + \ldots + t_k$, where $+$ represents the concatenation operation. For example, $abc = a + bc$. - For all $1 \le i < j \le k$, the first chara...
A necessary condition for $s$ to be good is that $s_1 \ne s_n$. For a string $s$ where $s_1 \ne s_n$, let $t_1$ be a string composed of just the single character $s_1$, and let $t_2$ be a string composed of the $n - 1$ characters from $s_2$ to $s_n$. In this way, the condition is satisfied. Therefore, if $s_1 \ne s_n$,...
[ "greedy", "strings" ]
800
#include <cstdio> const int maxn = 110; int n; char s[maxn]; void solve() { scanf("%d%s", &n, s + 1); puts(s[1] != s[n] ? "Yes" : "No"); } int main() { int T = 1; scanf("%d", &T); while (T--) { solve(); } return 0; }
2003
B
Turtle and Piggy Are Playing a Game 2
Turtle and Piggy are playing a game on a sequence. They are given a sequence $a_1, a_2, \ldots, a_n$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.). The game goes as follows: - Let the current length of the sequence be $...
The problem can be rephrased as follows: the first player can remove a number adjacent to a larger number, while the second player can remove a number adjacent to a smaller number. To maximize the value of the last remaining number, in the $i$-th round of the first player's moves, he will remove the $i$-th smallest num...
[ "games", "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; const int maxn = 100100; int n, a[maxn]; void solve() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); } sort(a + 1, a + n + 1, greater<int>()); printf("%d\n", a[(n + 1) / 2]); } int main() { int T = 1; scanf("%d", &T); while (T--) { sol...
2003
C
Turtle and Good Pairs
Turtle gives you a string $s$, consisting of lowercase Latin letters. Turtle considers a pair of integers $(i, j)$ ($1 \le i < j \le n$) to be a pleasant pair if and only if there exists an integer $k$ such that $i \le k < j$ and \textbf{both} of the following two conditions hold: - $s_k \ne s_{k + 1}$; - $s_k \ne s_...
Partition the string $s$ into several maximal contiguous segments of identical characters, denoted as $[l_1, r_1], [l_2, r_2], \ldots, [l_m, r_m]$. For example, the string "aabccc" can be divided into $[1, 2], [3, 3], [4, 6]$. We can observe that a pair $(i, j)$ is considered a "good pair" if and only if the segments c...
[ "constructive algorithms", "greedy", "sortings", "strings" ]
1,200
#include <bits/stdc++.h> #define pb emplace_back #define fst first #define scd second #define mkp make_pair #define mems(a, x) memset((a), (x), sizeof(a)) using namespace std; typedef long long ll; typedef double db; typedef unsigned long long ull; typedef long double ldb; typedef pair<int, int> pii; const int maxn =...
2003
D1
Turtle and a MEX Problem (Easy Version)
\textbf{The two versions are different problems. In this version of the problem, you can choose the same integer twice or more. You can make hacks only if both versions are solved.} One day, Turtle was playing with $n$ sequences. Let the length of the $i$-th sequence be $l_i$. Then the $i$-th sequence was $a_{i, 1}, a...
Let the smallest non-negative integer that does not appear in the $i$-th sequence be denoted as $u_i$, and the second smallest non-negative integer that does not appear as $v_i$. In one operation of choosing index $i$, if $x = u_i$, then $x$ changes to $v_i$; otherwise, $x$ changes to $u_i$. It can be observed that if ...
[ "greedy", "math" ]
1,500
#include <bits/stdc++.h> #define pb emplace_back #define fst first #define scd second #define mkp make_pair #define mems(a, x) memset((a), (x), sizeof(a)) using namespace std; typedef long long ll; typedef double db; typedef unsigned long long ull; typedef long double ldb; typedef pair<ll, ll> pii; const int maxn = 2...
2003
D2
Turtle and a MEX Problem (Hard Version)
\textbf{The two versions are different problems. In this version of the problem, you can't choose the same integer twice or more. You can make hacks only if both versions are solved.} One day, Turtle was playing with $n$ sequences. Let the length of the $i$-th sequence be $l_i$. Then the $i$-th sequence was $a_{i, 1},...
Please first read the solution for problem D1. Construct a directed graph. For the $i$-th sequence, add a directed edge from $u_i$ to $v_i$. In each operation, you can either move along an outgoing edge of $x$ or move to any vertex $u$ and remove one of its outgoing edges. Let $f_i$ be the maximum vertex number that ca...
[ "dfs and similar", "dp", "graphs", "greedy", "implementation", "math" ]
2,100
#include <bits/stdc++.h> #define pb emplace_back #define fst first #define scd second #define mkp make_pair #define mems(a, x) memset((a), (x), sizeof(a)) using namespace std; typedef long long ll; typedef double db; typedef unsigned long long ull; typedef long double ldb; typedef pair<ll, ll> pii; const int maxn = 2...
2003
E1
Turtle and Inversions (Easy Version)
\textbf{This is an easy version of this problem. The differences between the versions are the constraint on $m$ and $r_i < l_{i + 1}$ holds for each $i$ from $1$ to $m - 1$ in the easy version. You can make hacks only if both versions of the problem are solved.} Turtle gives you $m$ intervals $[l_1, r_1], [l_2, r_2], ...
Divide all numbers into two types: small numbers ($0$) and large numbers ($1$), such that any small number is less than any large number. In this way, a permutation can be transformed into a $01$ sequence. A permutation is interesting if and only if there exists a way to divide all numbers into two types such that, for...
[ "brute force", "divide and conquer", "dp", "greedy", "math" ]
2,600
#include <bits/stdc++.h> #define pb emplace_back #define fst first #define scd second #define mkp make_pair #define mems(a, x) memset((a), (x), sizeof(a)) using namespace std; typedef long long ll; typedef double db; typedef unsigned long long ull; typedef long double ldb; typedef pair<ll, ll> pii; const int maxn = 5...
2003
E2
Turtle and Inversions (Hard Version)
\textbf{This is a hard version of this problem. The differences between the versions are the constraint on $m$ and $r_i < l_{i + 1}$ holds for each $i$ from $1$ to $m - 1$ in the easy version. You can make hacks only if both versions of the problem are solved.} Turtle gives you $m$ intervals $[l_1, r_1], [l_2, r_2], \...
Compared to problem E1, this version contains the situation where intervals can overlap. Consider a pair of overlapping intervals $[l_1, r_1]$ and $[l_2, r_2]$ (assuming $l_1 \le l_2$). The range $[l_1, l_2 - 1]$ must consist entirely of $0$s, and the range $[r_1 + 1, r_2]$ must consist entirely of $1$s. Then, you can ...
[ "brute force", "data structures", "divide and conquer", "dp", "greedy", "math", "two pointers" ]
2,700
#include <bits/stdc++.h> #define pb emplace_back #define fst first #define scd second #define mkp make_pair #define mems(a, x) memset((a), (x), sizeof(a)) using namespace std; typedef long long ll; typedef double db; typedef unsigned long long ull; typedef long double ldb; typedef pair<int, int> pii; const int maxn =...
2003
F
Turtle and Three Sequences
Piggy gives Turtle three sequences $a_1, a_2, \ldots, a_n$, $b_1, b_2, \ldots, b_n$, and $c_1, c_2, \ldots, c_n$. Turtle will choose a subsequence of $1, 2, \ldots, n$ of length $m$, let it be $p_1, p_2, \ldots, p_m$. The subsequence should satisfy the following conditions: - $a_{p_1} \le a_{p_2} \le \cdots \le a_{p_...
If the number of possible values for $b_i$ is small, you can use bitmask DP. Define $f_{i, S, j}$ as the maximum result considering all numbers up to $i$, where $S$ is the current set of distinct $b_i$ values in the subsequence, and $j$ is the value of $a$ for the last element of the subsequence. The transitions can be...
[ "brute force", "data structures", "dp", "greedy", "math", "probabilities", "two pointers" ]
2,800
#include <bits/stdc++.h> #define pb emplace_back #define fst first #define scd second #define mkp make_pair #define mems(a, x) memset((a), (x), sizeof(a)) using namespace std; typedef long long ll; typedef double db; typedef unsigned long long ull; typedef long double ldb; typedef pair<ll, ll> pii; const int maxn = 3...
2004
A
Closest Point
Consider a set of points on a line. The distance between two points $i$ and $j$ is $|i - j|$. The point $i$ from the set is \textbf{the closest} to the point $j$ from the set, if there is no other point $k$ in the set such that the distance from $j$ to $k$ is \textbf{strictly less} than the distance from $j$ to $i$. I...
This problem can be solved "naively" by iterating on the point we add and checking that it becomes the closest point to all elements from the set. However, there is another solution which is faster and easier to implement. When we add a point, it can become the closest only to two points from the set: one to the left, ...
[ "implementation", "math" ]
800
t = int(input()) for i in range(t): n = int(input()) x = list(map(int, input().split())) if n > 2 or x[0] + 1 == x[-1]: print('NO') else: print('YES')
2004
B
Game with Doors
There are $100$ rooms arranged in a row and $99$ doors between them; the $i$-th door connects rooms $i$ and $i+1$. Each door can be either locked or unlocked. Initially, all doors are unlocked. We say that room $x$ is reachable from room $y$ if all doors between them are unlocked. You know that: - Alice is in some r...
Let's find the segment of rooms where both Alice and Bob can be. This segment is $[\max(L, l), \min(R, r)]$. If it is empty, then it is sufficient to simply block any door between Alice's segment and Bob's segment, so the answer is $1$. If it is not empty, let's denote by $x$ the number of doors in this segment - $\min...
[ "brute force", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int l, r, L, R; cin >> l >> r >> L >> R; int inter = min(r, R) - max(l, L) + 1; int ans = inter - 1; if (inter <= 0) { ans = 1; } else { ans += (l != L); ans += (r != R); } ...
2004
C
Splitting Items
Alice and Bob have $n$ items they'd like to split between them, so they decided to play a game. All items have a cost, and the $i$-th item costs $a_i$. Players move in turns starting from Alice. In each turn, the player chooses one of the remaining items and takes it. The game goes on until no items are left. Let's s...
Let's sort the array in descending order and consider the first two moves of the game. Since Alice goes first, she takes the maximum element in the array ($a_1$). Then, during his turn, Bob takes the second-largest element ($a_2$) to minimize the score difference. Bob can increase his element in advance; however, he ca...
[ "games", "greedy", "sortings" ]
1,100
fun main() { repeat(readln().toInt()) { val (n, k) = readln().split(" ").map { it.toInt() } val a = readln().split(" ").map { it.toInt() }.sortedDescending().toIntArray() var score = 0L var rem = k for (i in a.indices) { if (i % 2 == 0) { score +=...
2004
D
Colored Portals
There are $n$ cities located on a straight line. The cities are numbered from $1$ to $n$. Portals are used to move between cities. There are $4$ colors of portals: blue, green, red, and yellow. Each city has portals of two different colors. You can move from city $i$ to city $j$ if they have portals of the same color ...
If cities $x$ and $y$ have a common portal, then the cost of the path is $|x-y|$. Otherwise, we have to move from city $x$ to some intermediate city $z$. It's important to note that the type of city $z$ should be different from the type of city $x$. Otherwise, we could skip city $z$ and go directly from $x$ to the next...
[ "binary search", "brute force", "data structures", "graphs", "greedy", "implementation", "shortest paths" ]
1,600
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; const string vars[] = {"BG", "BR", "BY", "GR", "GY", "RY"}; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n, q; cin >> n >> q; vector<int> a(n); for (int i = 0; i < n; ++i) { ...
2004
E
Not a Nim Problem
Two players, Alice and Bob, are playing a game. They have $n$ piles of stones, with the $i$-th pile initially containing $a_i$ stones. On their turn, a player can choose any pile of stones and take any positive number of stones from it, with one condition: - let the current number of stones in the pile be $x$. It is ...
So, okay, this is actually a problem related to Nim game and Sprague-Grundy theorem. If you're not familiar with it, I recommend studying it here. The following tutorial expects you to understand how Grundy values are calculated, which you can read there. The first (naive) solution to this problem would be to calculate...
[ "brute force", "games", "math", "number theory" ]
2,100
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = int(1e7) + 43; int lp[N + 1]; vector<int> pr; int idx[N + 1]; void precalc() { for (int i = 2; i <= N; i++) { if (lp[i] == 0) { lp[i] = i; pr.push_back(i); } for (int j = 0; j < pr.size() && pr[j] <= lp[i] ...
2004
F
Make a Palindrome
You are given an array $a$ consisting of $n$ integers. Let the function $f(b)$ return the minimum number of operations needed to make an array $b$ a palindrome. The operations you can make are: - choose two adjacent elements $b_i$ and $b_{i+1}$, remove them, and replace them with a single element equal to $(b_i + b_{...
To begin with, let's find out how to solve the problem for a single subarray in linear time. If equal numbers are at both ends, we can remove them and reduce the problem to a smaller size (thus, we have decreased the length of the array by $2$ in $0$ operations, or by $1$ if there is only one element). Otherwise, we ha...
[ "binary search", "brute force", "data structures", "greedy", "math" ]
2,600
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto& x : a) cin >> x; vector<int> p(n + 1); for (int i = 0; i < n; ++i) p[i + 1] = p[i] + a[i]; map<int, int> cnt; long long ans = 0; for (int l...
2004
G
Substring Compression
Let's define the operation of compressing a string $t$, consisting of at least $2$ digits from $1$ to $9$, as follows: - split it into an \textbf{even} number of non-empty substrings — let these substrings be $t_1, t_2, \dots, t_m$ (so, $t = t_1 + t_2 + \dots + t_m$, where $+$ is the concatenation operation); - write ...
Let's start with learning how to solve the problem for a single string with any polynomial complexity. One immediately wants to use dynamic programming. For example, let $\mathit{dp}_i$ be the minimum length of the compressed string from the first $i$ characters. Then, for the next transition, we could iterate over the...
[ "data structures", "dp", "matrices" ]
3,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int D = 10; const int INF = 1e9; typedef array<array<int, D>, D> mat; mat mul(const mat &a, const mat &b, bool fl){ mat c; forn(i, D) forn(j, D) c[i][j] = INF; if (fl){ forn(i, D) forn(j, D){ c[j][i...
2005
A
Simple Palindrome
Narek has to spend 2 hours with some 2-year-old kids at the kindergarten. He wants to teach them competitive programming, and their first lesson is about palindromes. Narek found out that the kids only know the vowels of the English alphabet (the letters $\mathtt{a}$, $\mathtt{e}$, $\mathtt{i}$, $\mathtt{o}$, and $\ma...
If the the numbers of vowels are fixed, how to arrange them to get the best possible answer? How to choose the numbers of vowels? Should they be as close, as possible? Let's define the numbers of vowels by $a_0, \cdots, a_4$ and assume we have fixed them. Obviously, $a_0 + \cdots + a_4 = n$. At first, let's not conside...
[ "combinatorics", "constructive algorithms", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; const string VOWELS = "aeiou"; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; // test cases while (t--) { int n; cin >> n; // string length vector<int> v(5, n / 5); // n - (n % 5) numbers should be (n / 5...
2005
B2
The Strict Teacher (Hard Version)
\textbf{This is the hard version of the problem. The only differences between the two versions are the constraints on $m$ and $q$. In this version, $m, q \le 10^5$. You can make hacks only if both versions of the problem are solved.} Narek and Tsovak were busy preparing this round, so they have not managed to do their...
There are only few cases. Try finding them and handling separately. For the easy version, there are three cases and they can be considered separately. Case 1: David is in the left of both teachers. In this case, it is obvious that he needs to go as far left as possible, which is cell $1$. Then, the time needed to catch...
[ "binary search", "greedy", "math", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; // test cases while (t--) { int n, m, q; cin >> n >> m >> q; vector<int> a(m); for (int i = 0; i < m; i++) cin >> a[i]; sort(a.begin(), a.end()); for (int i = 1; i <...
2005
C
Lazy Narek
Narek is too lazy to create the third problem of this contest. His friend Artur suggests that he should use ChatGPT. ChatGPT creates $n$ problems, each consisting of $m$ letters, so Narek has $n$ strings. To make the problem harder, he combines the problems by selecting some of the $n$ strings \textbf{possibly none} an...
A greedy approach doesn't work because the end of one string can connect to the beginning of the next. Try thinking in terms of dynamic programming. Before processing the next string, we only need to know which letter we reached from the previous selections. Let's loop through the $n$ strings and define $dp_i$ as the m...
[ "dp", "implementation", "strings" ]
1,800
#include <bits/stdc++.h> using namespace std; const string narek = "narek"; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; // test cases while (t--) { int n, m; cin >> n >> m; vector<string> s(n); for (int i = 0; i < n; i++) cin >> s[i]; vector<int> dp(5, int(...
2005
D
Alter the GCD
You are given two arrays $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$. You must perform the following operation \textbf{exactly once}: - choose any indices $l$ and $r$ such that $1 \le l \le r \le n$; - swap $a_i$ and $b_i$ for all $i$ such that $l \leq i \leq r$. Find the maximum possible value of $\text{gcd...
Find the the maximal sum of $\gcd$-s first. Try checking whether it is possible to get some fixed $\gcd$-s for $a$ and $b$ (i.e. fix the $\gcd$-s and try finding a sufficient range to swap) Choosing a range is equivalent to choosing a prefix and a suffix. Which prefixes and suffixes are needed to be checked to find the...
[ "binary search", "brute force", "data structures", "divide and conquer", "implementation", "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 200005; int a[N], b[N]; int pa[N], pb[N], sa[N], sb[N]; int n; ll dp[N][3]; ll solve_one(ll ga, ll gb) { if (ga <= 0 || gb <= 0) return 0; // invalid fixed gcd(s) if (b[1] % gb) return 0; // ivanlid gcd of b for (int i = 0; i <= n...
2005
E2
Subtangle Game (Hard Version)
\textbf{This is the hard version of the problem. The differences between the two versions are the constraints on all the variables. You can make hacks only if both versions of the problem are solved.} Tsovak and Narek are playing a game. They have an array $a$ and a matrix $b$ of integers with $n$ rows and $m$ columns...
What happens, when some number appears in $a$ more than once? How to use the constraint on the numbers of the array and the matrix? Let's say some number $x$ accures in $a$ more than once. Let's define by $u$ and $v$ the first two indexes of $a$, such that $u<v$ and $a_u=a_v=x$. When a player reahces $a_u = x$, it is a...
[ "data structures", "dp", "games", "greedy", "implementation" ]
2,500
#include <bits/stdc++.h> using namespace std; const int L = 1505, N = 1505, M = 1505; int a[L], b[N][M]; int l, n, m; int ind[N * M]; int dp0[N][M], dp1[N][M]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; // test cases while (t--) { int i, j; cin >> l >> n >> m...
2006
A
Iris and Game on the Tree
Iris has a tree rooted at vertex $1$. Each vertex has a value of $\mathtt 0$ or $\mathtt 1$. Let's consider a leaf of the tree (the vertex $1$ is never considered a leaf) and define its weight. Construct a string formed by the values of the vertices on the path starting at the root and ending in this leaf. Then the we...
Consider a formed string. Let's delete the useless part that doesn't contribute to the number of $\tt{01}$ and $\tt{10}$ substrings. We will get a string where each pair of adjacent bits is different. For example, $\tt{110001}\rightarrow\tt{101}$. Then the weight of a leaf depends on the parity of the length of the str...
[ "constructive algorithms", "dfs and similar", "games", "graphs", "greedy", "trees" ]
1,700
T = int(input()) for _ in range(T) : n = int(input()) x, y, z, w = 0, 0, 0, 0 deg = [0] * (n + 1) for __ in range(n - 1) : u, v = map(int, input().split()) deg[u] += 1 deg[v] += 1 s = " " + input() for i in range(2, n + 1) : if deg[i] == 1 : if s[i] ...
2006
B
Iris and the Tree
Given a rooted tree with the root at vertex $1$. For any vertex $i$ ($1 < i \leq n$) in the tree, there is an edge connecting vertices $i$ and $p_i$ ($1 \leq p_i < i$), with a weight equal to $t_i$. Iris does not know the values of $t_i$, but she knows that $\displaystyle\sum_{i=2}^n t_i = w$ and each of the $t_i$ is ...
The nodes are numbered by dfs order, which tells us the vertex numbers in one subtree are always consecutive. Let's consider an edge connecting vertex $i$ and $p_i$. Suppose the size of the subtree $i$ is $s_i$, so the vertices are numbered between $[i,i+s_i-1]$. Then for each $j$ that $i\le j<i+s_i-1$, the path betwee...
[ "brute force", "data structures", "dfs and similar", "dsu", "math", "trees" ]
1,800
#include <bits/stdc++.h> namespace FastIO { template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; } template <typename T> inline void write...
2006
C
Eri and Expanded Sets
Let there be a set that contains \textbf{distinct} positive integers. To expand the set to contain as many integers as possible, Eri can choose two integers $x\neq y$ from the set such that their average $\frac{x+y}2$ is still a positive integer and isn't contained in the set, and add it to the set. The integers $x$ an...
Let's consider the elements in the final set $a$, and take $b_i=a_i-a_{i-1}$ as its difference array. Observation 1: $b_i$ is odd. Otherwise we can turn $b_i$ into two $\frac{b_i}{2}$. Observation 2: Adjacent $b_i$ are not different. Suppose $b_i$ and $b_{i+1}$ are different and odd, then $a_{i+1}-a_{i-1}$ is even, and...
[ "data structures", "divide and conquer", "math", "number theory", "two pointers" ]
2,300
#include<bits/stdc++.h> using namespace std; #define int long long #define pii pair<int,int> #define all(v) v.begin(),v.end() #define pb push_back #define REP(i,b,e) for(int i=(b);i<(int)(e);++i) #define over(x) {cout<<x<<endl;return;} #define cntbit(x) __buitin_popcount(x) int n; i...
2006
D
Iris and Adjacent Products
Iris has just learned multiplication in her Maths lessons. However, since her brain is unable to withstand too complex calculations, she could not multiply two integers with the product greater than $k$ together. Otherwise, her brain may explode! Her teacher sets a difficult task every day as her daily summer holiday ...
Read the hints. Let's consider how to reorder the array. Let the sorted array be $a_1,a_2,\dots,a_n$. We can prove that it is optimal to reorder it like this: $a_n,a_1,a_{n-1},a_2,a_{n-2},\dots$. You can find the proof at the end of the tutorial. From the proof or anything we can discover the restriction is: for all $i...
[ "data structures", "greedy", "implementation", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; #define all(v) v.begin(),v.end() #define pb push_back #define REP(i,b,e) for(int i=(b);i<(int)(e);++i) #define over(x) {cout<<(x)<<endl;return;} int n,q,r; int a[300005]; int sum[300005]; int ql[300005],qr[300005]; int ans[300005]; int cnt[300005],cnt2[300...
2006
E
Iris's Full Binary Tree
Iris likes full binary trees. Let's define the depth of a rooted tree as the maximum number of \textbf{vertices} on the simple paths from some vertex to the root. A full binary tree of depth $d$ is a binary tree of depth $d$ with exactly $2^d - 1$ vertices. Iris calls a tree a $d$-binary tree if some vertices and edg...
Here're two lemmas that will be used in the solution. Lemma 1: Among all the points on a tree with the greatest distance from a certain point, one of which must be one of the two endpoints of a certain diameter. Lemma 2: After merging two trees, at least one new diameter is generated at the four endpoints of two certai...
[ "brute force", "data structures", "dfs and similar", "trees" ]
3,100
#include<bits/stdc++.h> using namespace std; #define int long long #define pii pair<int,int> #define all(v) v.begin(),v.end() #define pb push_back #define REP(i,b,e) for(int i=(b);i<(int)(e);++i) #define over(x) {cout<<(x)<<endl;return;} struct ds{ int seg[2000005],tag[2000005]; voi...
2006
F
Dora's Paint
Sadly, Dora poured the paint when painting the class mural. Dora considers the mural as the matrix $b$ of size $n \times n$. Initially, $b_{i,j} = 0$ for all $1 \le i, j \le n$. Dora has only two brushes which have two different colors. In one operation, she can paint the matrix with one of two brushes: - The first b...
Read the hints. From the hints, you may understand that, when given the degrees of each node, you can get the initial beauty of a matrix in $\mathcal O(n)$. To quickly perform topological sort, you should use addition tags to maintain the degrees of each node. Also, this is equal to sorting them by degrees. Brute-force...
[ "brute force", "combinatorics", "constructive algorithms", "graphs", "implementation" ]
3,500
#if defined(LOCAL) or not defined(LUOGU) #pragma GCC optimize(3) #pragma GCC optimize("Ofast,unroll-loops") #endif #include<bits/stdc++.h> using namespace std; struct time_helper { #ifdef LOCAL clock_t time_last; #endif time_helper() { #ifdef LOCAL time_last=clock(); #endif } void test() { #ifdef LOCAL auto t...
2007
A
Dora's Set
Dora has a set $s$ containing integers. In the beginning, she will put all integers in $[l, r]$ into the set $s$. That is, an integer $x$ is initially contained in the set if and only if $l \leq x \leq r$. Then she allows you to perform the following operations: - Select three \textbf{distinct} integers $a$, $b$, and ...
In a pair of $(a, b, c)$ there are at least two odd integers and at most one even integer. That's because if two even integers occur at the same time, their $\gcd$ will be at least $2$. It's optimal to make full use of the odd integers, so we try to choose two odd integers in a pair. In fact, this is always possible. N...
[ "greedy", "math", "number theory" ]
800
T = int(input()) for _ in range(T) : l, r = map(int, input().split()) print(((r + 1) // 2 - l // 2) // 2)
2007
B
Index and Maximum Value
After receiving yet another integer array $a_1, a_2, \ldots, a_n$ at her birthday party, Index decides to perform some operations on it. Formally, there are $m$ operations that she is going to perform in order. Each of them belongs to one of the two types: - $+ l r$. Given two integers $l$ and $r$, for all $1 \leq i ...
We take a maximum value from the initial array. Let's call it $a_{pos}$. We can see that $a_{pos}$ will always be one of the maximum values after any number of operations. Proof: Consider the value $x$ (which should be less than or equal to $a_{pos}$) before a particular operation. If $x = a_{pos}$, then $x = a_{pos}$ ...
[ "data structures", "greedy" ]
900
T = int(input()) for _ in range(T) : n, m = map(int, input().split()) v = max(map(int, input().split())) for __ in range(m) : c, l, r = input().split() l = int(l) r = int(r) if (l <= v <= r) : if (c == '+') : v = v + 1 else : v = v - 1 print(v, end = ' ' if __ != m - 1 else '\n')
2007
C
Dora and C++
Dora has just learned the programming language C++! However, she has completely misunderstood the meaning of C++. She considers it as two kinds of adding operations on the array $c$ with $n$ elements. Dora has two integers $a$ and $b$. In one operation, she can choose one of the following things to do. - Choose an in...
Read the hints. Consider $a = b$. First, the answer is less than $a$. Otherwise, you can always increase the minimum value by $a$ so that all elements are greater than $\max(c_i) - a$. Let's go over all possible minimum values, say $m$, and we can do the operations so that all elements are in the range $[m, m + a - 1]$...
[ "math", "number theory" ]
1,500
import math T = int(input()) for _ in range(T) : n, a, b = map(int, input().split()) d = math.gcd(a, b) a = list(map(int, input().split())) a = [x % d for x in a] a.sort() res = a[n - 1] - a[0] for i in range(1, n) : res = min(res, a[i - 1] + d - a[i]) print(res)
2008
A
Sakurako's Exam
Today, Sakurako has a math exam. The teacher gave the array, consisting of $a$ ones and $b$ twos. In an array, Sakurako \textbf{must} place either a '+' or a '-' in front of each element so that the sum of all elements in the array equals $0$. Sakurako is not sure if it is possible to solve this problem, so determine...
First of all, this task is the same as: "divide an array into two arrays with equal sum". So, obviously, we need to check if the sum of all elements is even which implies that the number of ones is even. Then, we can out half of 2s in one array and the other half in another, but if number of 2s is odd, then one array w...
[ "brute force", "constructive algorithms", "greedy", "math" ]
800
t=int(input()) for _ in range(t): a,b=map(int,input().split()) if a%2==1: print("NO") continue if a==0 and b%2==1: print("NO") continue print("YES")
2008
B
Square or Not
A beautiful binary matrix is a matrix that has ones on its edges and zeros inside. \begin{center} {\small Examples of four beautiful binary matrices.} \end{center} Today, Sakurako was playing with a beautiful binary matrix of size $r \times c$ and created a binary string $s$ by writing down all the rows of the matrix...
Assume that string was created from the beautiful binary matrix with size $r\times c$. If $r\le 2$ or $c\le 2$, then the whole matrix consists of '1'. This means that the string will have only one character and this is the only case such happening. So, if the whole string is constructed out of '1', we print "Yes" only ...
[ "brute force", "math", "strings" ]
800
for _ in range(int(input())): n=int(input()) s=input() i=0 while i<n and s[i]=='1': i+=1 if i==n: if n==4: print("Yes") else: print("No") continue i-=1 if i*i==n: print("Yes") else: print("No")
2008
C
Longest Good Array
Today, Sakurako was studying arrays. An array $a$ of length $n$ is considered good if and only if: - the array $a$ is increasing, meaning $a_{i - 1} < a_i$ for all $2 \le i \le n$; - the differences between adjacent elements are increasing, meaning $a_i - a_{i-1} < a_{i+1} - a_i$ for all $2 \le i < n$. Sakurako has c...
We can solve this problem greedily. Let's choose the first element equal to $l$. Then, the second element should be $l+1$. The third $l+3$, and so on. In general, the $i-$th element is equal to $l+\frac{i\cdot (i+1)}{2}$. Proof of this solution: Assume that array $a$ is the array made by our algorithm and $b$ is the ar...
[ "binary search", "brute force", "math" ]
800
for _ in range(int(input())): a, b = map(int, input().split()) i = 0 while a + i <= b: a += i i += 1 print(i)
2008
D
Sakurako's Hobby
For a certain permutation $p$$^{\text{∗}}$ Sakurako calls an integer $j$ reachable from an integer $i$ if it is possible to make $i$ equal to $j$ by assigning $i=p_i$ a certain number of times. If $p=[3,5,6,1,2,4]$, then, for example, $4$ is reachable from $1$, because: $i=1$ $\rightarrow$ $i=p_1=3$ $\rightarrow$ $i=p...
Any permutation can be divided into some number of cycles, so $F(i)$ is equal to the number of black colored elements in the cycle where $i$ is. So, we can write out all cycles in $O(n)$ and memorize for each $i$ the number of black colored elements in the cycle where it is.
[ "dp", "dsu", "graphs", "math" ]
1,100
t = int(input()) for _ in range(t): n = int(input()) b = [0] * (n + 1) us = [0] * (n + 1) p = [k-1 for k in map(int, input().split())] s = input() for i in range(0, n): if us[i]: continue sz = 0 while not us[i]: us[i] = 1 sz += s[i] == ...
2008
E
Alternating String
Sakurako really loves alternating strings. She calls a string $s$ of lowercase Latin letters an alternating string if characters in the even positions are the same, if characters in the odd positions are the same, and the length of the string is \textbf{even}. For example, the strings 'abab' and 'gg' are alternating, ...
Firstly, since first operation can be used at most 1 time, we need to use it only when string has odd length. Let's assume that the string has even length, then we can look at characters on odd and even positions independently. So, if we change all characters on even positions to the character that which is occurs the ...
[ "brute force", "data structures", "dp", "greedy", "implementation", "strings" ]
1,500
t = int(input()) for _ in range(t): n = int(input()) s = input() res = len(s) if n % 2 == 0: v = [[0] * 26 for _ in range(2)] for i in range(n): v[i % 2][ord(s[i]) - ord('a')] += 1 for i in range(2): mx = max(v[i]) res -= mx print(res) ...
2008
F
Sakurako's Box
Sakurako has a box with $n$ balls. Each ball has it's value. She wants to bet with her friend that if the friend randomly picks two balls from the box (it could be two distinct balls, but they may have the same value), the product of their values will be the same as the number that Sakurako guessed. Since Sakurako has...
By the statement, we need to find the value of this expresion $\frac{\sum_{i=0}^{n}\sum_{j=i+1}^{n} a_i\cdot a_j}{\frac{n\cdot (n-1)}{2}}$. Let's find this two values separately. For the first, we can do it in several ways. We can see that this sum equal to $\sum_{i=0}^{n}a_i\cdot (\sum_{j=i+1}^{n}a_j)$ and compute by ...
[ "combinatorics", "math", "number theory" ]
1,400
import sys; input = sys.stdin.readline for i in range(int(input())): n = int(input()) a = list(map(int, input().split())) ans = 0 s = 0 mod = int(1e9 + 7) for i in range(n): s += a[i] s %= mod for i in range(n): s -= a[i] ans = (ans + a[i] * s) % mod ans = (ans * pow(...
2008
G
Sakurako's Task
Sakurako has prepared a task for you: She gives you an array of $n$ integers and allows you to choose $i$ and $j$ such that $i \neq j$ and $a_i \ge a_j$, and then assign $a_i = a_i - a_j$ or $a_i = a_i + a_j$. You can perform this operation any number of times for any $i$ and $j$, as long as they satisfy the condition...
Let's look at case when $n=1$. We cannot change the value of the element, so we will not change the array. If $n>1$, let's call $g=gcd(a_1,a_2,\dots,a_n)$. Using operations in the statement, we can get only numbers 0 and that have $g$ as a divisor. So, the best array for this task will be $a_i=(i-1)\cdot g$. Now, we ca...
[ "binary search", "greedy", "math", "number theory" ]
1,800
import math t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) g = 0 mx = 0 for i in range(n): g = math.gcd(g, a[i]) mx = max(mx, a[i]) if g == 0: print(k) continue a.sort() q = -g if n != 1: ...
2008
H
Sakurako's Test
Sakurako will soon take a test. The test can be described as an array of integers $n$ and a task on it: Given an integer $x$, Sakurako can perform the following operation any number of times: - Choose an integer $i$ ($1\le i\le n$) such that $a_i\ge x$; - Change the value of $a_i$ to $a_i-x$. Using this operation an...
Let's fix one $x$ and try to solve this task for it. As we know, in $0-$indexed array median is $\lfloor\frac{n}{2}\rfloor$ where $n$ is number of elements in the array, so to find median, we need to find the smallest element which has at least $\lfloor\frac{n}{2}\rfloor$ elements in the array that is less or equal to ...
[ "binary search", "brute force", "greedy", "math", "number theory" ]
2,100
for _ in range(int(input())): n, m = map(int, input().split()) a = list(map(int, input().split())) c = [0] * (n + 1) for i in range(n): c[a[i]] += 1 for i in range(1, n + 1): c[i] += c[i - 1] res = [0] * (n + 1) for x in range(1, n + 1): l, r = 0, ...
2009
A
Minimize!
You are given two integers $a$ and $b$ ($a \leq b$). Over all possible integer values of $c$ ($a \leq c \leq b$), find the minimum value of $(c - a) + (b - c)$.
We choose $c$ between $a$ and $b$ $(a \leq c \leq b)$. The distance is $(c - a) + (b - c) = b - a$. Note that the distance does not depend on the the position $c$ at all.
[ "brute force", "math" ]
800
for _ in range(int(input())): a,b = map(int,input().split()) print(b-a)
2009
B
osu!mania
You are playing your favorite rhythm game, osu!mania. The layout of your beatmap consists of $n$ rows and $4$ columns. Because notes at the bottom are closer, you will process the bottommost row first and the topmost row last. Each row will contain exactly one note, represented as a '#'. For each note $1, 2, \dots, n$...
Implement the statement. Iterate from $n-1$ to $0$ and use the .find() method in std::string in C++ (or .index() in python) to find the '#' character.
[ "brute force", "implementation" ]
800
import sys input=lambda:sys.stdin.readline().rstrip() for i in range(int(input())): n=int(input()) print(*reversed([input().index("#")+1 for i in range(n)]))
2009
C
The Legend of Freya the Frog
Freya the Frog is traveling on the 2D coordinate plane. She is currently at point $(0,0)$ and wants to go to point $(x,y)$. In one move, she chooses an integer $d$ such that $0 \leq d \leq k$ and jumps $d$ spots forward in the direction she is facing. Initially, she is facing the positive $x$ direction. After every mo...
Consider the $x$ and $y$ directions separately and calculate the jumps we need in each direction. The number of jumps we need in the $x$ direction is $\lceil \frac{x}{k} \rceil$ and similarily $\lceil \frac{y}{k} \rceil$ in the $y$ direction. Now let's try to combine them to obtain the total number of jumps. Let's cons...
[ "implementation", "math" ]
1,100
for _ in range(int(input())): x,y,k = map(int,input().split()) print(max(2*((x+k-1)//k)-1,2*((y+k-1)//k)))
2009
D
Satyam and Counting
Satyam is given $n$ distinct points on the 2D coordinate plane. \textbf{It is guaranteed that $0 \leq y_i \leq 1$ for all given points $(x_i, y_i)$.} How many different nondegenerate right triangles$^{\text{∗}}$ can be formed from choosing three different points as its vertices? Two triangles $a$ and $b$ are different...
Initially, the obvious case one might first consider is an upright right triangle (specifically, the triangle with one of its sides parallel to the $y$-axis). This side can only be made with two points in the form $(x, 0)$ and $(x,1)$. We only need to search third point. Turns out, the third point can be any other unus...
[ "geometry", "math" ]
1,400
from collections import Counter for _ in range(int(input())): n = int(input()) nums = [] for i in range(n): x,y = map(int,input().split()) nums.append((x,y)) ans = 0 b = Counter(x[0] for x in nums) check = set(nums) for i in b: if b[i]==2: ans += n-2 for p in chec...
2009
E
Klee's SUPER DUPER LARGE Array!!!
Klee has an array $a$ of length $n$ containing integers $[k, k+1, ..., k+n-1]$ in that order. Klee wants to choose an index $i$ ($1 \leq i \leq n$) such that $x = |a_1 + a_2 + \dots + a_i - a_{i+1} - \dots - a_n|$ is minimized. Note that for an arbitrary integer $z$, $|z|$ represents the absolute value of $z$. Output ...
We can rewrite $x$ as $|a_1+\dots+a_i-(a_{i+1}+\dots+a_n)|$. Essentially, we want to minimize the absolute value difference between the sums of the prefix and the suffix. With absolute value problems. it's always good to consider the positive and negative cases separately. We will consider the prefix greater than the s...
[ "binary search", "math", "ternary search" ]
1,400
import sys input=sys.stdin.readline from math import floor,sqrt f=lambda x: (2*x*x + x*(4*k-2) + (n-n*n-2*k*n))//2 t=int(input()) for _ in range(t): n,k=map(int,input().split()) D=4*k*k + 4*k*(n-1) + (2*n*n-2*n+1) i=(floor(sqrt(D))-(2*k-1))//2 ans=min(abs(f(i)),abs(f(i+1))) print(ans)
2009
F
Firefly's Queries
Firefly is given an array $a$ of length $n$. Let $c_i$ denote the $i$'th cyclic shift$^{\text{∗}}$ of $a$. She creates a new array $b$ such that $b = c_1 + c_2 + \dots + c_n$ where $+$ represents concatenation$^{\text{†}}$. Then, she asks you $q$ queries. For each query, output the sum of all elements in the subarray ...
Let's duplicate the array $a$ and concatenate it with itself. Now, $a$ should have length $2n$ and $a_i = a_{i-n}$ for all $n < i \leq 2n$. Now, the $j$'th element of the $i$'th rotation is $a_{i+j-1}$. It can be shown for any integer $x$, it belongs in rotation $\lfloor \frac{x-1}{n} \rfloor + 1$ and at position $(x-1...
[ "bitmasks", "data structures", "flows", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { int t; cin >> t; while (t--) { ll n, q; cin >> n >> q; vector<ll> a(n), ps(1); for (ll &r : a) { cin >> r; ps.push_back(ps.back() + r); } for (ll &r : a) { ...
2009
G1
Yunli's Subarray Queries (easy version)
\textbf{This is the easy version of the problem. In this version, it is guaranteed that $r=l+k-1$ for all queries.} For an arbitrary array $b$, Yunli can perform the following operation any number of times: - Select an index $i$. Set $b_i = x$ where $x$ is any integer she desires ($x$ is not limited to the interval $...
We first make the sequence $b_i=a_i-i$ for all $i$. Now, if $b_i=b_j$, then $i$ and $j$ are in correct relative order. Now, to solve the problem, we precompute the answer for every window of $k$, and then each query is a lookup. We use a sliding window, maintaining a multiset of frequencies of values of $b$ in the curr...
[ "binary search", "data structures", "two pointers" ]
1,900
#include "bits/stdc++.h" #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx,avx2,sse,sse2") #define fast ios_base::sync_with_stdio(0) , cin.tie(0) , cout.tie(0) #define endl '\n' #define int long long #define f first #define mp make_pair #define s second using namespace std; void solve(){ int n, k, q;...
2009
G2
Yunli's Subarray Queries (hard version)
\textbf{This is the hard version of the problem. In this version, it is guaranteed that $r \geq l+k-1$ for all queries.} For an arbitrary array $b$, Yunli can perform the following operation any number of times: - Select an index $i$. Set $b_i = x$ where $x$ is any integer she desires ($x$ is not limited to the inter...
First, read the solution to the easy version of the problem to compute the answer for every window of $k$. Let $c_i=f([a_i, ..., a_{i+k-1}])$. Now, the problem simplifies to finding $\sum_{j=l}^{r-k+1} ( \min_{i=l}^{j} c_i)$ We will answer the queries offline in decreasing order of $l$. We maintain a lazy segment tree....
[ "binary search", "data structures", "dp" ]
2,200
#include <bits/stdc++.h> #define int long long #define pii pair<int, int> #define fi first #define se second using namespace std; void solve() { int n, k, q; cin >> n >> k >> q; vector<int> a(n); for (int &r : a) cin >> r; vector<int> c(3 * n), v(n); multiset<int> s; for (int i = 0; i < k; i...
2009
G3
Yunli's Subarray Queries (extreme version)
\textbf{This is the extreme version of the problem. In this version, the output of each query is different from the easy and hard versions. It is also guaranteed that $r \geq l+k-1$ for all queries.} For an arbitrary array $b$, Yunli can perform the following operation any number of times: - Select an index $i$. Set ...
I decided to write the Editorial for this problem in a step-by-step manner. Some of the steps are really short and meant to be used as hints but i decided to have a uniform naming for everything. Continuing from the easier versions of the problem, we know we need to compute sum of min of subarrays, and answer subarray ...
[ "data structures", "dp", "implementation" ]
2,700
#include <bits/stdc++.h> #define int long long #define ll long long #define pii pair<int,int> #define piii pair<pii,pii> #define fi first #define se second #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") using namespace std; struct segtree { const static int INF = 1e18, IN...
2013
A
Zhan's Blender
Today, a club fair was held at "NSPhM". In order to advertise his pastry club, Zhan decided to demonstrate the power of his blender. To demonstrate the power of his blender, Zhan has $n$ fruits. The blender can mix up to $x$ fruits per second. In each second, Zhan can put up to $y$ fruits into the blender. After tha...
Let's consider two cases: If $x \geq y$. In this case, the blender will mix $\min(y, c)$ fruits every second (where $c$ is the number of unmixed fruits). Therefore, the answer will be $\lceil \frac{n}{y} \rceil$. If $x < y$. Here, the blender will mix $\min(x, c)$ fruits every second. In this case, the answer will be $...
[ "constructive algorithms", "math" ]
800
#include <iostream> using namespace std; int main(){ int t = 1; cin >> t; while(t--){ int n, x, y; cin >> n >> x >> y; x = min(x, y); cout << (n + x - 1) / x << endl; } }
2013
B
Battle for Survive
Eralim, being the mafia boss, manages a group of $n$ fighters. Fighter $i$ has a rating of $a_i$. Eralim arranges a tournament of $n - 1$ battles, in each of which two not yet eliminated fighters $i$ and $j$ (\textbf{$1 \le i < j \le n$}) are chosen, and as a result of the battle, fighter $i$ is eliminated from the to...
It can be noted that the value of $a_{n-1}$ will always be negative in the final result. Therefore, we can subtract the sum $a_1 + a_2 + \ldots + a_{n-2}$ from $a_{n-1}$, and then subtract $a_{n-1}$ from $a_n$. Thus, the final sum will be $a_1 + a_2 + \ldots + a_{n-2} - a_{n-1} + a_n$. This value cannot be exceeded bec...
[ "constructive algorithms", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod = 1e9 + 7; void solve(){ int n; cin >> n; ll ans = 0; vector<int> a(n); for(int i=0;i<n;i++){ cin >> a[i]; ans += a[i]; } cout << ans - 2 * a[n - 2] << '\n'; } int main(){ ios_base::...
2013
C
Password Cracking
Dimash learned that Mansur wrote something very unpleasant about him to a friend, so he decided to find out his password at all costs and discover what exactly he wrote. Believing in the strength of his password, Mansur stated that his password — is a binary string of length $n$. He is also ready to answer Dimash's qu...
We will initially maintain an empty string $t$ such that $t$ appears as a substring in $s$. We will increase the string $t$ by one character until its length is less than $n$. We will perform $n$ iterations. In each iteration, we will check the strings $t + 0$ and $t + 1$. If one of them appears in $s$ as a substring, ...
[ "constructive algorithms", "interactive", "strings" ]
1,400
#include <iostream> #include <vector> #include <string> #include <array> using namespace std; bool ask(string t) { cout << "? " << t << endl; int res; cin >> res; return res; } void result(string s) { cout << "! " << s << endl; } void solve() { int n; cin >> n; string cur; w...
2013
D
Minimize the Difference
Zhan, tired after the contest, gave the only task that he did not solve during the contest to his friend, Sungat. However, he could not solve it either, so we ask you to try to solve this problem. You are given an array $a_1, a_2, \ldots, a_n$ of length $n$. We can perform any number (possibly, zero) of operations on ...
First statement: if $a_i > a_{i+1}$, then it is always beneficial to perform an operation at position $i$. Therefore, the final array will be non-decreasing. Second statement: if the array is non-decreasing, then performing operations is not advantageous. We will maintain a stack that holds a sorted array. Each element...
[ "binary search", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll a[200200]; int n; void solve(){ cin >> n; for(int i=1;i<=n;i++){ cin >> a[i]; } stack<pair<ll, int>> s; for(int i=1;i<=n;i++){ ll sum = a[i], cnt = 1; while(s.size() && s.top().first >= sum / cnt){ ...
2013
E
Prefix GCD
Since Mansur is tired of making legends, there will be no legends for this task. You are given an array of positive integer numbers $a_1, a_2, \ldots, a_n$. The elements of the array can be rearranged in any order. You need to find the smallest possible value of the expression $$\gcd(a_1) + \gcd(a_1, a_2) + \ldots + \...
Let $g$ be the greatest common divisor $gcd$ of the array $a$. We will divide each element $a_i$ by $g$, and at the end, simply multiply the result by $g$. Now, consider the following greedy algorithm. We will start with an initially empty array $b$ and add to the end of array $b$ the element that minimizes the GCD wit...
[ "brute force", "dp", "greedy", "math", "number theory" ]
2,200
#include <bits/stdc++.h> using namespace std; int a[200200]; int n; void solve(){ cin >> n; int g = 0, cur = 0; long long ans = 0; for(int i=0;i<n;i++){ cin >> a[i]; g = __gcd(g, a[i]); } for(int i=0;i<n;i++){ a[i] /= g; } for(int t=0;t<n;t++){ int nc =...
2013
F1
Game in Tree (Easy Version)
\textbf{This is the easy version of the problem. In this version, $\mathbf{u = v}$. You can make hacks only if both versions of the problem are solved.} Alice and Bob are playing a fun game on a tree. This game is played on a tree with $n$ vertices, numbered from $1$ to $n$. Recall that a tree with $n$ vertices is an ...
First, let's understand how the game proceeds. Alice and Bob start moving toward each other along the path from vertex $1$ to vertex $u$. At some vertex, one of the players can turn into a subtree of a vertex that is not on the path $(1, u)$. After this, both players go to the furthest accessible vertex. Let the path f...
[ "binary search", "brute force", "data structures", "dp", "games", "greedy", "implementation", "trees" ]
2,700
#include <bits/stdc++.h> using namespace std; int dfs(int v, int p, int to, const vector<vector<int>> &g, vector<int> &max_depth) { int ans = 0; bool has_to = false; for (int i : g[v]) { if (i == p) { continue; } int tmp = dfs(i, v, to, g, max_depth); if (tmp ==...
2013
F2
Game in Tree (Hard Version)
\textbf{This is the hard version of the problem. In this version, it is not guaranteed that $u = v$. You can make hacks only if both versions of the problem are solved.} Alice and Bob are playing a fun game on a tree. This game is played on a tree with $n$ vertices, numbered from $1$ to $n$. Recall that a tree with $n...
Read the Solution of the easy version of the problem. The path $(u, v)$ can be divided into two vertical paths $(1, u)$ and $(1, v)$. We will solve for the vertices on the path $(1, u)$, while the path $(1, v)$ is solved similarly. For each vertex on the path $(1, u)$, we define two values: $fa_i$ - the first vertex at...
[ "binary search", "data structures", "trees" ]
3,500
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 12; vector<int> g[maxn], del[maxn], add[maxn]; vector<int> ord; int ans[maxn]; int dp[maxn]; int n, m, k; bool calc(int v, int p, int f){ bool is = 0; if(v == f) is = 1; dp[v] = 1; for(int to:g[v]){ if(to == p){ ...
2014
A
Robin Helps
\begin{quote} There is a little bit of the outlaw in everyone, and a little bit of the hero too. \end{quote} The heroic outlaw Robin Hood is famous for taking from the rich and giving to the poor. Robin encounters $n$ people starting from the $1$-st and ending with the $n$-th. The $i$-th person has $a_i$ gold. If $a_...
This problem requires a simple implementation. Set a variable (initially $0$) to represent the gold Robin has, and update it according to the rules as he scans through $a_i$, adding $1$ to answer whenever Robin gives away a gold.
[ "greedy", "implementation" ]
800
#include <iostream> using namespace std; void work(){ int n,k; cin >> n >> k; int res = 0, gold = 0; for (int i=0;i<n;i++){ int cur; cin >> cur; if (!cur && gold) gold--, res++; else if (cur >= k) gold += cur; } cout << res << '\n'; } int main(){ ...
2014
B
Robin Hood and the Major Oak
\begin{quote} In Sherwood, the trees are our shelter, and we are all children of the forest. \end{quote} The Major Oak in Sherwood is known for its majestic foliage, which provided shelter to Robin Hood and his band of merry men and women. The Major Oak grows $i^i$ new leaves in the $i$-th year. It starts with $1$ le...
The key observation is that $i^i$ has the same even/odd parity as $i$. Therefore, the problem reduces to finding whether the sum of $k$ consecutive integers ending in $n$ is even. This can be done by finding the sum of $n-k+1, n-k+2, ..., n-1, n$ which is $k*(2n-k+1)/2$, and checking its parity. Alternatively, one can ...
[ "math" ]
800
#include <iostream> using namespace std; void work(){ int n,k; cin >> n >> k; cout << (((n+1)*n/2 - (n-k)*(n-k+1)/2)%2?"NO":"YES") << '\n'; } int main(){ int t; cin >> t; while (t--) work(); return 0; }
2014
C
Robin Hood in Town
\begin{quote} In Sherwood, we judge a man not by his wealth, but by his merit. \end{quote} Look around, the rich are getting richer, and the poor are getting poorer. We need to take from the rich and give to the poor. We need Robin Hood! There are $n$ people living in the town. Just now, the wealth of the $i$-th pers...
If we sort the wealth in increasing order, then the $j$-th person must be unhappy for Robin to appear, where $j=\lfloor n/2 \rfloor +1$ if $1$-indexing or $j=\lfloor n/2 \rfloor$ if $0$-indexing. We need $a_j < \frac{s+x}{2*n}$, where $s$ is the original total wealth before $x$ gold from the pot was added. Rearranging ...
[ "binary search", "greedy", "math" ]
1,100
#include <iostream> #include <vector> #include <algorithm> using namespace std; void work(){ int n; cin >> n; long long sum = 0; vector<long long> v(n); for (auto &c : v) cin >> c, sum += c; sort(v.begin(),v.end()); if (n < 3){ cout << "-1\n"; return; } c...
2014
D
Robert Hood and Mrs Hood
\begin{quote} Impress thy brother, yet fret not thy mother. \end{quote} Robin's brother and mother are visiting, and Robin gets to choose the start day for each visitor. All days are numbered from $1$ to $n$. Visitors stay for $d$ continuous days, all of those $d$ days must be between day $1$ and $n$ inclusive. Robi...
Since the number of days $n$ is capped, we can check all possible start day $x$ in range $[1,n-d+1]$ (so that the duration of $d$ days would fit). We would like to find the number of overlapped jobs for each value of $x$. A job between days $l_i$ and $r_i$ would overlap with the visit if the start day $x$ satisfies $l_...
[ "brute force", "data structures", "greedy", "sortings" ]
1,400
#include <iostream> #include <vector> using namespace std; void work(){ int n,k,d; cin >> n >> d >> k; vector<int> ss(n+1),es(n+1); for (int i=0;i<k;i++){ int a,b; cin >> a >> b; ss[a]++; es[b]++; } for (int i=0;i<n;i++) ss[i+1] += ss[i]; for (int i=0...
2014
E
Rendez-vous de Marian et Robin
\begin{quote} In the humble act of meeting, joy doth unfold like a flower in bloom. \end{quote} Absence makes the heart grow fonder. Marian sold her last ware at the Market at the same time Robin finished training at the Major Oak. They couldn't wait to meet, so they both start without delay. The travel network is re...
This problem builds on the standard Dijkstra algorithm. So please familiarise yourself with the algorithm if not already. In Dijkstra algorithm, a distance vector/list is used to store travel times to all vertices, here we need to double the vector/list to store travel times to vertices arriving with and without a hors...
[ "dfs and similar", "graphs", "shortest paths" ]
1,800
#include <iostream> #include <vector> #include <set> using namespace std; void dijkstra(int s, vector<vector<long long>> &d, vector<vector<pair<int,long long>>> &graph, vector<bool> &hs){ auto cmp = [&](auto &a, auto &b){return make_pair(d[a.first][a.second],a) < make_pair(d[b.first][b.second],b);}; set<pa...
2014
F
Sheriff's Defense
\begin{quote} "Why, master," quoth Little John, taking the bags and weighing them in his hand, "here is the chink of gold." \end{quote} The folk hero Robin Hood has been troubling Sheriff of Nottingham greatly. Sheriff knows that Robin Hood is about to attack his camps and he wants to be prepared. Sheriff of Nottingh...
An important observation is that strengthening a base only influences its neighbors, so we can just keep consider adjacent nodes as later ones are not affected. Let's consider induction to solve this problem. Let $d[i][0]$ denote the most gold from node $i$ and all its children if we don't strengthen node $i$ and $d[i]...
[ "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <iostream> #include <vector> using namespace std; void work(){ int n,k; cin >> n >> k; vector<long long> v(n); vector<vector<int>> g(n); for (auto &c : v) cin >> c; for (int i=0;i<n-1;i++){ int a,b; cin >> a >> b; a--,b--; g[a].push_back(b); ...
2014
G
Milky Days
\begin{quote} What is done is done, and the spoilt milk cannot be helped. \end{quote} Little John is as little as night is day — he was known to be a giant, at possibly $2.1$ metres tall. It has everything to do with his love for milk. His dairy diary has $n$ entries, showing that he acquired $a_i$ pints of fresh mil...
The key for this problem is the use of a stack, where last item in is the first item out. As we scan through the diary entries, we will only drink till the day of the next entry. If there is left over milk, we will push them into the stack with number of pints and the day they were acquired. If there isn't enough milk ...
[ "brute force", "data structures", "greedy", "implementation" ]
2,200
#include <iostream> #include <map> #include <list> #include <vector> using namespace std; typedef long long ll; typedef pair<ll,ll> pll; typedef vector<pll> vpll; void work(){ int n,m,k; cin >> m >> n >> k; map<ll,ll> days; for (int i=0;i<m;i++){ int a,b; cin >> a >> b; days...
2014
H
Robin Hood Archery
\begin{quote} At such times archery was always the main sport of the day, for the Nottinghamshire yeomen were the best hand at the longbow in all merry England, but this year the Sheriff hesitated... \end{quote} Sheriff of Nottingham has organized a tournament in archery. It's the final round and Robin Hood is playing...
Sheriff can never win. This is quite obvious as Robin is the first to pick and both just keep picking the current biggest number. This means that Sheriff can at best get a tie - this happens if and only if all elements have even appearance. The segment $a_l \dots a_r$ is a tie if and only if there's no element that app...
[ "data structures", "divide and conquer", "greedy", "hashing" ]
1,900
#Mo's algorithm #include <iostream> #include <vector> #include <algorithm> #include <array> using namespace std; int K = 500; int Cnt[1000001]; void work(){ int n,q; cin >> n >> q; vector<int> v(n); for (auto &c : v) cin >> c, Cnt[c] = 0; vector<array<int,3>> qs(q); for (int i=0;i<q;i+...
2018
A
Cards Partition
\begin{quote} DJ Genki vs Gram - Einherjar Joker \hfill ⠀ \end{quote} You have some cards. An integer between $1$ and $n$ is written on each card: specifically, for each $i$ from $1$ to $n$, you have $a_i$ cards which have the number $i$ written on them. There is also a shop which contains unlimited cards of each typ...
The answer is at most $n$. Solve the problem with $k = 0$. When is the answer $n$? If the answer is not $n$, how can you buy cards? Note that there are $n$ types of cards, so the subsets have size at most $n$, and the answer is at most $n$. If $k = 0$, you can make subsets of size $s$ if and only if the following condi...
[ "2-sat", "brute force", "greedy", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
2018
B
Speedbreaker
\begin{quote} Djjaner - Speedbreaker \hfill ⠀ \end{quote} There are $n$ cities in a row, numbered $1, 2, \ldots, n$ left to right. - At time $1$, you conquer exactly one city, called the starting city. - At time $2, 3, \ldots, n$, you can choose a city adjacent to the ones conquered so far and conquer it. You win if...
When is the answer $0$? Starting from city $x$ is equivalent to setting $a_x = 1$. At some time $t$, consider the minimal interval $[l, r]$ that contains all the cities with $a_i \leq t$ (let's call it "the minimal interval at time $t$"). You have to visit all this interval within time $t$, otherwise there are some cit...
[ "binary search", "data structures", "dp", "greedy", "implementation", "two pointers" ]
1,900
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
2018
C
Tree Pruning
\begin{quote} t+pazolite, ginkiha, Hommarju - Paved Garden \hfill ⠀ \end{quote} You are given a tree with $n$ nodes, rooted at node $1$. In this problem, a leaf is a non-root node with degree $1$. In one operation, you can remove a leaf and the edge adjacent to it (possibly, new leaves appear). What is the minimum nu...
Solve for a fixed final depth of the leaves. Which nodes are "alive" if all leaves are at depth $d$ at the end? If the final depth of the leaves is $d$, it's optimal to keep in the tree all the nodes at depth $d$ and all their ancestors. These nodes are the only ones which satisfy the following two conditions: their de...
[ "brute force", "dfs and similar", "greedy", "sortings", "trees" ]
1,700
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
2018
D
Max Plus Min Plus Size
\begin{quote} EnV - The Dusty Dragon Tavern \hfill ⠀ \end{quote} You are given an array $a_1, a_2, \ldots, a_n$ of positive integers. You can color some elements of the array red, but there cannot be two adjacent red elements (i.e., for $1 \leq i \leq n-1$, at least one of $a_i$ and $a_{i+1}$ must not be red). Your ...
The optimal subsequence must contain at least one occurrence of the maximum. Iterate over the minimum, in decreasing order. You have some "connected components". How many elements can you pick from each component? How to make sure you have picked at least one occurrence of the maximum? The optimal subsequence must cont...
[ "data structures", "dp", "dsu", "greedy", "implementation", "matrices", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
2018
E1
Complex Segments (Easy Version)
\begin{quote} Ken Arai - COMPLEX \hfill ⠀ \end{quote} \textbf{This is the easy version of the problem. In this version, the constraints on $n$ and the time limit are lower. You can make hacks only if both versions of the problem are solved.} A set of (closed) segments is \textbf{complex} if it can be partitioned into...
Solve for a fixed $m$ (size of the subsets). $m = 1$ is easy. Can you do something similar for other $m$? Solve for a fixed $k$ (number of subsets). If you have a $O(n \log n)$ solution for a fixed $m$, note that there exists a faster solution! Let's write a function max_k(m), which returns the maximum $k$ such that th...
[ "binary search", "data structures", "divide and conquer", "dsu", "greedy", "math", "sortings" ]
3,300
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 static constexpr int MAXN = 2.5e4; static constexpr int MAXT = 2 * MAXN; static constexpr int THRESHOL...
2018
E2
Complex Segments (Hard Version)
\begin{quote} Ken Arai - COMPLEX \hfill ⠀ \end{quote} \textbf{This is the hard version of the problem. In this version, the constraints on $n$ and the time limit are higher. You can make hacks only if both versions of the problem are solved.} A set of (closed) segments is \textbf{complex} if it can be partitioned int...
Now let's go back to max_k(m). It turns out you can implement it in $O(n \alpha(n))$. First of all, let's make all the endpoints distinct, in such a way that two intervals intersect if and only if they were intersecting before. Let's maintain a binary string of size $n$, initially containing only ones, that can support...
[ "binary search", "data structures", "divide and conquer", "dsu", "greedy", "math", "sortings" ]
3,400
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int N; struct DSU { int cc; vector<int> arr, ans; int find(int node) { if (...
2018
F3
Speedbreaker Counting (Hard Version)
\begin{quote} NightHawk22 - Isolation \hfill ⠀ \end{quote} \textbf{This is the hard version of the problem. In the three versions, the constraints on $n$ and the time limit are different. You can make hacks only if all the versions of the problem are solved.} This is the statement of \textbf{Problem D1B}: - There ar...
Suppose you are given a starting city and you want to win. Find several strategies to win (if possible) and try to work with the simplest ones. The valid starting cities are either zero, or all the cities in $I := \cap_{i=1}^n [i - a_i + 1, i + a_i - 1] = [l, r]$. Now you have some bounds on the $a_i$. Fix the interval...
[ "dp", "greedy", "math" ]
3,100
#include <bits/stdc++.h> using namespace std; int t,n,p,dp[6011][6011][2],lim[6011],w[6011][6011],ans[3011]; void solve(int x) {//printf("==========================solve(%d)\n",x); for(int i=1;i<=x;++i)lim[i]=x-i+1; for(int i=x+1;i<=n;++i)lim[i]=i-x+1; // printf("lim:");for(int i=1;i<=n;++i)printf("%d ",lim[i...
2019
A
Max Plus Size
\begin{quote} EnV - Dynasty \hfill ⠀ \end{quote} You are given an array $a_1, a_2, \ldots, a_n$ of positive integers. You can color some elements of the array red, but there cannot be two adjacent red elements (i.e., for $1 \leq i \leq n-1$, at least one of $a_i$ and $a_{i+1}$ must not be red). Your score is the max...
Can you reach the score $\max(a) + \lceil n/2 \rceil$? Can you reach the score $\max(a) + \lceil n/2 \rceil - 1$? The maximum red element is $\leq \max(a)$, and the maximum number of red elements is $\lceil n/2 \rceil$. Can you reach the score $\max(a) + \lceil n/2 \rceil$? If $n$ is even, you always can, by either cho...
[ "brute force", "dp", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
2019
B
All Pairs Segments
\begin{quote} Shirobon - FOX \hfill ⠀ \end{quote} You are given $n$ points on the $x$ axis, at increasing positive integer coordinates $x_1 < x_2 < \ldots < x_n$. For each pair $(i, j)$ with $1 \leq i < j \leq n$, you draw the segment $[x_i, x_j]$. The segments are closed, i.e., a segment $[a, b]$ contains the points...
Can you determine fast how many intervals contain point $p$? The intervals that contain point $p$ are the ones with $l \leq p$ and $r \geq p$. Determine how many intervals contain: point $x_1$; points $x_1 + 1, \ldots, x_2 - 1$; point $x_2$; $\ldots$ point $x_n$. First, let's focus on determining how many intervals con...
[ "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 int main() { ios::sync_with_stdio(0); cin.tie(0); #if !ONLINE_JUDGE && !EVAL i...
2020
A
Find Minimum Operations
You are given two integers $n$ and $k$. In one operation, you can subtract any power of $k$ from $n$. Formally, in one operation, you can replace $n$ by $(n-k^x)$ for any non-negative integer $x$. Find the minimum number of operations required to make $n$ equal to $0$.
How many operations will have $x = 0$. Try $k = 2$. Answer will be the number of ones in binary representation of $n$. If $k$ is 1, we can only subtract 1 in each operation, and our answer will be $n$. Now, first, it can be seen that we have to apply at least $n$ mod $k$ operations of subtracting $k^0$ (as all the othe...
[ "bitmasks", "brute force", "greedy", "math", "number theory" ]
800
#include <bits/stdc++.h> using namespace std; int find_min_oper(int n, int k){ if(k == 1) return n; int ans = 0; while(n){ ans += n%k; n /= k; } return ans; } int main() { int t; cin >> t; while(t--){ int n,k; cin >> n >> k; cout << find_min_oper(n,k) << "\n"; } return 0; }
2020
B
Brightness Begins
Imagine you have $n$ light bulbs numbered $1, 2, \ldots, n$. \textbf{Initially, all bulbs are on}. To flip the state of a bulb means to turn it off if it used to be on, and to turn it on otherwise. Next, you do the following: - for each $i = 1, 2, \ldots, n$, flip the state of all bulbs $j$ such that $j$ is divisible...
The final state of $i$th bulb (on or off) is independent of $n$. The final state of the $i$th bulb tells us about the parity of number of divisors of $i$. For any bulb $i$, its final state depends on the parity of the number of divisors of $i$. If $i$ has an even number of divisors, then bulb $i$ will be on; else it wi...
[ "binary search", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ long long k; cin >> k; cout << k + int(sqrtl(k) + 0.5) << "\n"; } return 0; }
2020
C
Bitwise Balancing
You are given three non-negative integers $b$, $c$, and $d$. Please find a non-negative integer $a \in [0, 2^{61}]$ such that $(a\, |\, b)-(a\, \&\, c)=d$, where $|$ and $\&$ denote the bitwise OR operation and the bitwise AND operation, respectively. If such an $a$ exists, print its value. If there is no solution, p...
Try to find some independent operations/combinations. The expression is independent for each digit in binary representation The first observation is that the expression $a$|$b$ - $a$&$c = d$ is bitwise independent. That is, the combination of a tuple of bits of $a, b, and\ c$ corresponding to the same power of 2 will o...
[ "bitmasks", "hashing", "implementation", "math", "schedules", "ternary search" ]
1,400
#include <bits/stdc++.h> #define ll long long using namespace std; void solve() { ll a = 0, b, c, d, pos = 1, bit_b, bit_c, bit_d, mask = 1; cin >> b >> c >> d; for (ll i = 0; i < 62; i++) { if (b&mask) bit_b = 1; else bit_b = 0; if (c&mask) bit_c = 1; else bit_c = 0; ...
2020
D
Connect the Dots
One fine evening, Alice sat down to play the classic game "Connect the Dots", but with a twist. To play the game, Alice draws a straight line and marks $n$ points on it, indexed from $1$ to $n$. Initially, there are no arcs between the points, so they are all disjoint. After that, Alice performs $m$ operations of the ...
The value of $d$ is very small. Try using Disjoint Set Union (DSU). The main idea is to take advantage of the low upper bound of $d_i$ and apply the Disjoint Set Union. We will consider $dp[j][w]$, which denotes the number of ranges that contain the $j$ node in connection by the triplets/ranges with $w$ as $d$ and $j$ ...
[ "brute force", "dp", "dsu", "graphs", "math", "trees" ]
1,800
#include <bits/stdc++.h> #define ll long long using namespace std; const ll N = 2e5+2; const ll C = 10 + 1; vector<ll> par(N), sz(N, 0); vector<vector<ll>> dp(N, vector<ll> (C, 0)), ind(N, vector<ll> (C, 0)), start_cnt(N, vector<ll> (C, 0)), end_cnt(N, vector<ll> (C,0)); ll find_par(ll a) { if (par[a] == a) ret...
2020
E
Expected Power
You are given an array of $n$ integers $a_1,a_2,\ldots,a_n$. You are also given an array $p_1, p_2, \ldots, p_n$. Let $S$ denote the random \textbf{multiset} (i. e., it may contain equal elements) constructed as follows: - Initially, $S$ is empty. - For each $i$ from $1$ to $n$, insert $a_i$ into $S$ with probability...
Try to find the expected value of $f(S)$ rather than $(f(S))^2$. Write the binary representation of $f(S)$ and find $(f(S))^2$. Let the binary representation of the $Power$ be $b_{20}b_{19}...b_{0}$. Now $Power^2$ is $\sum_{i=0}^{20} \sum_{j=0}^{20} b_i b_j * 2^{i+j}$. Now if we compute the expected value of $b_ib_j$ f...
[ "bitmasks", "dp", "math", "probabilities" ]
2,000
#include <bits/stdc++.h> using namespace std; int fast_exp(int b, int e, int mod){ int ans = 1; while(e){ if(e&1) ans = (1ll*ans*b) % mod; b = (1ll*b*b) % mod; e >>= 1; } return ans; } const int mod = 1e9+7; const int bits = 11; int inv(int n){ return fast_exp(n,mod-2,mod); } const int inverse_1e4 = inv(...
2020
F
Count Leaves
Let $n$ and $d$ be positive integers. We build the the divisor tree $T_{n,d}$ as follows: - The root of the tree is a node marked with number $n$. This is the $0$-th layer of the tree. - For each $i$ from $0$ to $d - 1$, for each vertex of the $i$-th layer, do the following. If the current vertex is marked with $x$, c...
$f$ satisfies a special property for fixed d. $f$ is multiplicative i.e. $f(x.y)$ = $f(x) * f(y)$ if $x,y$ are coprime, for fixed d. It can be observed that the number of leaves is equal to the number of ways of choosing $d$ integers $a_0,a_1,a_2...a_d$ with $a_d = n$ and $a_i divides a_{i+1}$ for all $(0 \le i \le d-1...
[ "dp", "math", "number theory" ]
2,900
#include <bits/stdc++.h> #define ll long long #define pb push_back #define mp make_pair #define F first #define S second #define pii pair<int,int> #define pll pair<ll,ll> #define pcc pair<char,char> #define vi vector <int> #define vl vector <ll> #define sd(x) scanf("%d",&x) #define slld(x) scanf("%lld",&x) #define pd(x...
2021
A
Meaning Mean
Pak Chanek has an array $a$ of $n$ positive integers. Since he is currently learning how to calculate the floored average of two numbers, he wants to practice it on his array $a$. While the array $a$ has at least two elements, Pak Chanek will perform the following three-step operation: - Pick two different indices $i...
For now, let's ignore the floor operation, so an operation is merging two elements $a_i$ and $a_j$ into one element $\frac{a_i+a_j}{2}$. Consider the end result. Each initial element in $a$ must contribute a fractional coefficient to the final result. It turns out that the sum of the coefficients is fixed (it must be $...
[ "data structures", "greedy", "math", "sortings" ]
800
null
2021
B
Maximize Mex
You are given an array $a$ of $n$ positive integers and an integer $x$. You can do the following two-step operation any (possibly zero) number of times: - Choose an index $i$ ($1 \leq i \leq n$). - Increase $a_i$ by $x$, in other words $a_i := a_i + x$. Find the maximum value of the $\operatorname{MEX}$ of $a$ if you...
For the $\operatorname{MEX}$ to be at least $k$, then each non-negative integer from $0$ to $k-1$ must appear at least once in the array. First, notice that since there are only $n$ elements in the array, there are at most $n$ different values, so the $\operatorname{MEX}$ can only be at most $n$. And since we can only ...
[ "brute force", "greedy", "math", "number theory" ]
1,200
null
2021
C2
Adjust The Presentation (Hard Version)
\textbf{This is the hard version of the problem. In the two versions, the constraints on $q$ and the time limit are different. In this version, $0 \leq q \leq 2 \cdot 10^5$. You can make hacks only if all the versions of the problem are solved.} A team consisting of $n$ members, numbered from $1$ to $n$, is set to pre...
Firstly, let's relabel the $n$ members such that member number $i$ is the $i$-th member in the initial line configuration in array $a$. We also adjust the values in $b$ (and the future updates) accordingly. For now, let's solve the problem if there are no updates to the array $b$. Consider the first member who presents...
[ "constructive algorithms", "data structures", "greedy", "implementation", "sortings" ]
1,900
null
2021
D
Boss, Thirsty
Pak Chanek has a friend who runs a drink stall in a canteen. His friend will sell drinks for $n$ days, numbered from day $1$ to day $n$. There are also $m$ types of drinks, numbered from $1$ to $m$. The profit gained from selling a drink on a particular day can vary. On day $i$, the projected profit from selling drink...
We can see it as a grid of square tiles, consisting of $n$ rows and $m$ columns. Consider a single row. Instead of looking at the $m$ tiles, we can look at the $m+1$ edges between tiles, including the leftmost edge and the rightmost edge. We number the edges from $0$ to $m$ such that tile $j$ ($1\leq j\leq m$) is the t...
[ "dp", "greedy", "implementation" ]
2,500
null
2021
E3
Digital Village (Extreme Version)
\textbf{This is the extreme version of the problem. In the three versions, the constraints on $n$ and $m$ are different. You can make hacks only if all the versions of the problem are solved.} Pak Chanek is setting up internet connections for the village of Khuntien. The village can be represented as a connected simpl...
Since the cost of a path uses the maximum edge weight in the path, we can use a Kruskal-like algorithm that is similar to finding the MST (Minimum Spanning Tree). Initially, the graph has no edges, and we add each edge one by one starting from the smallest values of $w_i$, while maintaining the connected components in ...
[ "data structures", "dfs and similar", "dp", "dsu", "graphs", "greedy", "math", "trees" ]
2,800
null
2022
A
Bus to Pénjamo
\begin{quote} Ya vamos llegando a Péeeenjamoo ♫♫♫ \end{quote} There are $n$ families travelling to Pénjamo to witness Mexico's largest-ever "walking a chicken on a leash" marathon. The $i$-th family has $a_i$ family members. All families will travel using a single bus consisting of $r$ rows with $2$ seats each. A per...
The key to maximizing happiness is to seat family members together as much as possible. If two members of the same family sit in the same row, both will be happy, and we only use two seats. However, if they are seated separately, only one person is happy, but two seats are still used. Therefore, we prioritize seating f...
[ "constructive algorithms", "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,r; cin>>n>>r; vector<int>arr(n); int leftalone=0; int happy=0; for(int k=0;k<n;k++) { cin>>arr[k]; happy+=(arr[k]/2)*2; r-=arr[k]/2; leftalone+=arr[k]%2; } if(leftalone>r) happy+=r*2-lefta...
2022
B
Kar Salesman
Karel is a salesman in a car dealership. The dealership has $n$ different models of cars. There are $a_i$ cars of the $i$-th model. Karel is an excellent salesperson and can convince customers to buy up to $x$ cars (of Karel's choice), as long as the cars are from different models. Determine the minimum number of cust...
Since no customer can buy more than one car from the same model, the minimum number of clients we need is determined by the model with the most cars. Therefore, we need at least: $\max\{a_1, a_2, \cdots a_n\}$ clients, because even if a customer buys cars from other models, they cannot exceed this limit for any single ...
[ "binary search", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { long long n,x; cin>>n>>x; vector<long long>arr(n); long long sum=0; long long maximo=0; for(int k=0;k<n;k++) { cin>>arr[k]; maximo=max(maximo,arr[k]); sum+=arr[k]; } long long sec=(sum+x-1)/(long long...
2022
C
Gerrymandering
\begin{quote} We all steal a little bit. But I have only one hand, while my adversaries have two. \hfill Álvaro Obregón \end{quote} Álvaro and José are the only candidates running for the presidency of Tepito, a rectangular grid of $2$ rows and $n$ columns, where each cell represents a house. It is guaranteed that $n$...
We will use dynamic programming to keep track of the maximum number of votes Álvaro can secure as we move from column to column (note that there are many ways to implement the DP, we will use the easiest to understand). An important observation is that if you use a horizontal piece in one row, you also have to use it i...
[ "dp", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin>>n; vector<string>cad(n); vector<vector<int> >vot(2,vector<int>(n+8)); for(int k=0;k<2;k++) { cin>>cad[k]; for(int i=0;i<n;i++) if(cad[k][i]=='A') vot[k][i+1]=1; } vector<vector<int> >dp(n+9,vector<int>(3,-1))...
2022
D1
Asesino (Easy Version)
\textbf{This is the easy version of the problem. In this version, you can ask at most $n+69$ questions. You can make hacks only if both versions of the problem are solved.} This is an interactive problem. It is a tradition in Mexico's national IOI trainings to play the game "Asesino", which is similar to "Among Us" o...
Try to do casework for small $n$. It is also a good idea to simulate it. Think about this problem as a directed graph, where for each query there is a directed edge. Observe that if you ask $u \mapsto v$ and $v \mapsto u$, both answers will match if and only if $u$ and $v$ are not the impostor. This can be easily shown...
[ "binary search", "brute force", "constructive algorithms", "implementation", "interactive" ]
1,900
#include <bits/stdc++.h> using namespace std; bool query(int i, int j, int ans = 0) { cout << "? " << i << " " << j << endl; cin >> ans; return ans; } int main() { int tt; for (cin >> tt; tt; --tt) { int n, N; cin >> N; n = N; array<int, 2> candidates = {-1, -1}; while (n > 4) { if (q...
2022
D2
Asesino (Hard Version)
\textbf{This is the hard version of the problem. In this version, you must use the minimum number of queries possible. You can make hacks only if both versions of the problem are solved.} This is an interactive problem. It is a tradition in Mexico's national IOI trainings to play the game "Asesino", which is similar ...
What is the minimal value anyway? Our solution to D1 used $n$ queries if $n$ is even and $n + 1$ queries when $n$ is odd. Is this the optimal strategy? Can we find a lower bound? Can we find the optimal strategy for small $n$? There's only $9$ possible unlabeled directed graphs with $3$ nodes and at most $3$ edges, you...
[ "constructive algorithms", "dp", "interactive" ]
2,700
#include <bits/stdc++.h> using namespace std; int n; void answer (int a) { cout << "! " << a << endl; } int query (int a, int b) { cout << "? " << a << " " << b << endl; int r; cin >> r; if (r == -1) exit(0); return r; } void main_ () { cin >> n; if (n == -1) exit(0); if (n == 3) { i...
2022
E1
Billetes MX (Easy Version)
\textbf{This is the easy version of the problem. In this version, it is guaranteed that $q = 0$. You can make hacks only if both versions of the problem are solved.} An integer grid $A$ with $p$ rows and $q$ columns is called beautiful if: - All elements of the grid are integers between $0$ and $2^{30}-1$, and - For ...
Consider the extremal cases, what is the answer if the grid is empty? What is the answer if the grid is full? What happens if $N = 2$? Observe that if $N = 2$, the xor of every column is constant. Can we generalize this idea? Imagine you have a valid full grid $a$. For each $i$, change $a[0][i]$ to $a[0][0]\oplus a[0][...
[ "2-sat", "binary search", "combinatorics", "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,500
#include <bits/stdc++.h> using namespace std; int const Mxn = 2e5 + 2; long long int const MOD = 1e9 + 7; long long int precalc[Mxn]; vector<vector<array<int, 2>>> adj; bool valid = 1; int pref[Mxn]; void dfs(int node) { for (auto [child, w] : adj[node]) { if (pref[child] == -1) { pref[child] = pref...
2022
E2
Billetes MX (Hard Version)
\textbf{This is the hard version of the problem. In this version, it is guaranteed that $q \leq 10^5$. You can make hacks only if both versions of the problem are solved.} An integer grid $A$ with $p$ rows and $q$ columns is called beautiful if: - All elements of the grid are integers between $0$ and $2^{30}-1$, and ...
Please read the solution to E1 beforehand, as well as all the hints. Through the observations in E1, we can reduce the problem to the following: We have a graph, we add edges, and we want to determine after each addition if all its cycles have xor 0, and the number of connected components in the graph. The edges are ne...
[ "binary search", "combinatorics", "data structures", "dsu", "graphs" ]
2,600
#include <bits/stdc++.h> using namespace std; int const Mxn = 2e5 + 2; long long int const MOD = 1e9 + 7; vector<vector<array<int, 2>>> adj; vector<array<int, 3>> Edges; long long int precalc[Mxn]; struct DSU { vector<int> leader; vector<int> sz; int components; DSU(int N) { leader.resize(N); iota...
2023
A
Concatenation of Arrays
You are given $n$ arrays $a_1$, $\ldots$, $a_n$. The length of each array is two. Thus, $a_i = [a_{i, 1}, a_{i, 2}]$. You need to concatenate the arrays into a single array of length $2n$ such that the number of inversions$^{\dagger}$ in the resulting array is minimized. Note that you \textbf{do not need} to count the ...
Let's sort the arrays in order of non-decreasing sum of elements. It turns out that it is always optimal to concatenate the arrays in this order. To prove this, let's consider some optimal answer. Note that if in the final order there are two adjacent arrays, such that the sum of the elements of the left array is great...
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,300
null