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
1696
H
Maximum Product?
You are given a positive integer $k$. For a multiset of integers $S$, define $f(S)$ as the following. - If the number of elements in $S$ is less than $k$, $f(S)=0$. - Otherwise, define $f(S)$ as the maximum product you can get by choosing exactly $k$ integers from $S$. More formally, let $|S|$ denote the number of el...
Find a way to calculate the maximum product that can be turned into counting. Use monotonicity to reduce the complexity. First, we describe a strategy to find the answer for a single subset. If the whole subset is negative, the answer is the product of the $K$ maximum numbers in it. Otherwise, take $K$ numbers with the...
[ "brute force", "combinatorics", "dp", "greedy", "implementation", "math", "two pointers" ]
3,500
null
1697
A
Parkway Walk
You are walking through a parkway near your house. The parkway has $n+1$ benches in a row numbered from $1$ to $n+1$ from left to right. The distance between the bench $i$ and $i+1$ is $a_i$ meters. Initially, you have $m$ units of energy. To walk $1$ meter of distance, you spend $1$ unit of your energy. You can't wal...
If you have at least $sum(a_i)$ units of energy, then the answer is $0$, because you can just walk to the end. Otherwise, the answer is $sum(a_i) - m$, because you can just sit on the first bench and then just go. Time complexity: $O(n)$.
[ "greedy", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", H"r", stdin); // freopen("output.txt", "w", stdout); #endif int tc; cin >> tc; while (tc--) { int n, m; cin >> n >> m; int sum = 0; for (int i = 0; i < n; ++i) { ...
1697
B
Promo
The store sells $n$ items, the price of the $i$-th item is $p_i$. The store's management is going to hold a promotion: if a customer purchases at least $x$ items, $y$ cheapest of them are free. The management has not yet decided on the exact values of $x$ and $y$. Therefore, they ask you to process $q$ queries: for th...
First of all, there is an answer with exactly $x$ items bought. Suppose items worth $p_1 \le p_2 \le\dots \le p_m$ ($x < m$) were purchased. Then by removing $p_1$ from this set, the sum of $y$ the cheapest items in the set will change by $p_{y+1}-p_1\ge 0$, which means the answer will not decrease. The second fact tha...
[ "greedy", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, q; cin >> n >> q; vector<long long> p(n), s(n + 1); for (auto& x : p) cin >> x; sort(p.begin(), p.end()); for (int i = 0; i < n; ++i) s[i + 1] = s[i] + p[i]; while (q--) { int x, y; cin >...
1697
C
awoo's Favorite Problem
You are given two strings $s$ and $t$, both of length $n$. Each character in both string is 'a', 'b' or 'c'. In one move, you can perform one of the following actions: - choose an occurrence of "ab" in $s$ and replace it with "ba"; - choose an occurrence of "bc" in $s$ and replace it with "cb". You are allowed to pe...
First, check that the counts of all letters are the same in both strings. Then consider the following restatement of the moves. The letters 'b' in the string $s$ are stationary. Letters 'a' and 'c', however, move around the string. The move of the first type moves a letter 'a' to the right. The move of the second type ...
[ "binary search", "constructive algorithms", "data structures", "greedy", "implementation", "strings", "two pointers" ]
1,400
for _ in range(int(input())): n = int(input()) s = input() t = input() if s.count('b') != t.count('b'): print("NO") continue j = 0 for i in range(n): if s[i] == 'b': continue while t[j] == 'b': j += 1 if s[i] != t[j] or (s[i] == 'a' and i > j) or (s[i] == 'c' and i < j): print("NO") break ...
1697
D
Guess The String
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentati...
There are several ways to solve this problem. The model solution does it as follows: Restore the characters of $s$ from left to right. The first character is restored by query ? 1 1. For each of the next characters, let's ask if this character is new (by querying ? 2 1 i and comparing the result with the number of diff...
[ "binary search", "constructive algorithms", "interactive" ]
1,900
#include<bits/stdc++.h> using namespace std; char ask_character(int i) { cout << "? 1 " << i << endl; cout.flush(); string s; cin >> s; return s[0]; } int ask_cnt(int l, int r) { cout << "? 2 " << l << " " << r << endl; cout.flush(); int x; cin >> x; return x; } int main() { ...
1697
E
Coloring
You are given $n$ points on the plane, the coordinates of the $i$-th point are $(x_i, y_i)$. No two points have the same coordinates. The distance between points $i$ and $j$ is defined as $d(i,j) = |x_i - x_j| + |y_i - y_j|$. For each point, you have to choose a color, represented by an integer from $1$ to $n$. For e...
Let's call a point $i$ isolated if its color does not match the color of any other point. If a point is not isolated, then it has the same color as the points with minimum distance to it (and only these points should have this color). Let's build a directed graph where the arc $i \rightarrow j$ means that the point $j$...
[ "brute force", "combinatorics", "constructive algorithms", "dp", "geometry", "graphs", "greedy", "implementation", "math" ]
2,400
#include<bits/stdc++.h> using namespace std; const int N = 143; const int K = 5; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z ...
1697
F
Too Many Constraints
You are asked to build an array $a$, consisting of $n$ integers, each element should be from $1$ to $k$. The array should be non-decreasing ($a_i \le a_{i+1}$ for all $i$ from $1$ to $n-1$). You are also given additional constraints on it. Each constraint is of one of three following types: - $1~i~x$: $a_i$ \textbf{...
Imagine there were no constraints of the second or the third types. Then it would be possible to solve the problem with some greedy algorithm. Unfortunately, when both these constraints are present, it's not immediately clear how to adapt the greedy. Dynamic programming is probably also out of question, because you can...
[ "2-sat", "constructive algorithms", "graphs", "implementation" ]
2,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct constraint{ int tp, i, j, x; }; vector<vector<int>> g, tg; vector<char> used; vector<int> clr, ord; void ts(int v){ used[v] = true; for (int u : g[v]) if (!used[u]) ts(u); ord.push_back(v); } void dfs(in...
1698
A
XOR Mixup
There is an array $a$ with $n-1$ integers. Let $x$ be the bitwise XOR of all elements of the array. The number $x$ is added to the end of the array $a$ (now it has length $n$), and then the elements are shuffled. You are given the newly formed array $a$. What is $x$? If there are multiple possible values of $x$, you c...
Any element of the array works. Let's use $\oplus$ for $\mathsf{XOR}$. Suppose that the original array is $[a_1, \dots, a_{n-1}]$. Then $x=a_1 \oplus \dots \oplus a_{n-1}$. Let's show that $a_1$ is the $\mathsf{XOR}$ of all other elements of the array; that is, $a_1 = a_2 \oplus \dots \oplus a_{n-1} \oplus x$. Substitu...
[ "bitmasks", "brute force" ]
800
for t in range(int(input())): n = int(input()) print([int(x) for x in input().split()][0])
1698
B
Rising Sand
There are $n$ piles of sand where the $i$-th pile has $a_i$ blocks of sand. The $i$-th pile is called too tall if $1 < i < n$ and $a_i > a_{i-1} + a_{i+1}$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.) You are given an ...
Note that two piles in a row can't be too tall, since a pile that is too tall has strictly more sand than its neighbours. If $k=1$ then we can make every other pile too tall, excluding the ends of the array. For example, if $a=[1,2,3,4,5,6]$, we can make piles $2$ and $4$ too tall by performing some large number of ope...
[ "constructive algorithms", "greedy", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n, k; cin >> n >> k; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } if (k > 1) { int res = 0; for (int i = 1; i < n - 1; i++) { res += (a[i] > a[i - 1] + a[i +...
1698
C
3SUM Closure
You are given an array $a$ of length $n$. The array is called 3SUM-closed if for all distinct indices $i$, $j$, $k$, the sum $a_i + a_j + a_k$ is an element of the array. More formally, $a$ is 3SUM-closed if for all integers $1 \leq i < j < k \leq n$, there exists some integer $1 \leq l \leq n$ such that $a_i + a_j + a...
Let's consider some array which is 3SUM-closed. If the array has at least three positive elements, consider the largest three $x$, $y$, and $z$. Notice that $x+y+z$ is strictly larger than $x$, $y$, and $z$, which means that $x+y+z$ is not an element of the array (since $x$, $y$, $z$ were the largest elements). Therefo...
[ "brute force", "data structures" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; vector<int> pos, neg, a; for (int i = 0; i < n; i++) { int x; cin >> x; if (x > 0) {pos.push_back(x);} else if (x < 0) {neg.push_back(x);} else { if (a.size() < 2) {a.pu...
1698
D
Fixed Point Guessing
This is an interactive problem. Initially, there is an array $a = [1, 2, \ldots, n]$, where $n$ is an odd positive integer. The jury has selected $\frac{n-1}{2}$ \textbf{disjoint} pairs of elements, and then the elements in those pairs are swapped. For example, if $a=[1,2,3,4,5]$, and the pairs $1 \leftrightarrow 4$ a...
Note that $\left\lceil\log_2 10^4\right\rceil = 14$, which is less than the number of queries. If we can answer a question of the form "given a subarray, does it contain the fixed point?", then we can binary search on this subarray until we find the fixed point. Given a subarray $[a_l, \dots, a_r]$, let's count the num...
[ "binary search", "constructive algorithms", "interactive" ]
1,600
for t in range(int(input())): n = int(input()) l = 1 r = n while l < r: m = l + (r - l) // 2 print("?", l, m, flush=True) if (sum(l <= i <= m for i in [int(x) for x in input().split()]) % 2): r = m else: l = m + 1 print("!", l, flush=True)
1698
E
PermutationForces II
You are given a permutation $a$ of length $n$. Recall that permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. You have a strength of $s$ and perform $n$ moves on the permutation $a$. The $i$-th move consists of the following: - Pick two integers $x$ and $y$ such that $i \l...
Suppose that we know the elements of $b$. We claim that the minimum strength needed is $\max_{i=1}^n a_i - b_i$. Let's prove it. Proof. For simplicity let's sort the elements of $b$ from $1$ to $n$, and rearrange the corresponding elements of $a$ in the same way. In other words, we only need to turn this new array $a$ ...
[ "brute force", "combinatorics", "greedy", "sortings", "trees", "two pointers" ]
2,300
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 998244353; bool cmp(const pair<int, int>& a, const pair<int, int>& b) { return (a.second < b.second); } void solve() { int n, s; cin >> n >> s; pair<int, int> a[n + 1]; bool vis[n + 1]; for (int i = 1; i <= n; i++) { c...
1698
F
Equal Reversal
There is an array $a$ of length $n$. You may perform the following operation on it: - Choose two indices $l$ and $r$ where $1 \le l \le r \le n$ and $a_l = a_r$. Then, reverse the subsegment from the $l$-th to the $r$-th element, i. e. set $[a_l, a_{l + 1}, \ldots, a_{r - 1}, a_r]$ to $[a_r, a_{r-1}, \ldots, a_{l+1}, ...
Consider the following invariants of the array: $a_1$ and $a_n$ don't change as a result of the operations. The set of unordered pairs of adjacent elements doesn't change as a result of the operations. In other words, if you build a graph $\mathcal{G}$ whose vertices are labelled $1$ to $n$, and make an edge connecting...
[ "constructive algorithms", "graphs", "implementation", "math" ]
2,800
#include <bits/stdc++.h> using namespace std; const int MAX = 1007; const int MOD = 1000000007; void solve() { int n; cin >> n; int a[n], b[n]; vector<pair<int, int>> ax, bx; for (int i = 0; i < n; i++) { cin >> a[i]; if (i > 0) {ax.emplace_back(min(a[i - 1], a[i]), max(a[i - 1], a[i]));} } for (...
1698
G
Long Binary String
There is a binary string $t$ of length $10^{100}$, and initally all of its bits are $0$. You are given a binary string $s$, and perform the following operation some times: - Select some substring of $t$, and replace it with its XOR with $s$.$^\dagger$ After several operations, the string $t$ has exactly two bits $1$;...
Ignore leading zeroes of $s$. We can add them back at the end. Let's view the string as a polynomial $P(x)$ in $\mathrm{GF}(2)$. Then in an operation we can multiply $P(x)$ by any monomial $x^k$ for some $k$, so after some number of operations we can multiply $P(x)$ by some other polynomial $Q(x)$. At the end, we have ...
[ "bitmasks", "math", "matrices", "meet-in-the-middle", "number theory" ]
2,900
#include <bits/stdc++.h> using namespace std; #define int long long #define ll long long #define endl '\n' #define rep(x, start, end) \ for (auto x = (start) - ((start) > (end)); x != (end) - ((start) > (end)); \ ((start) < (end) ? x++ : x--)) #define...
1699
A
The Third Three Number Problem
You are given a positive integer $n$. Your task is to find \textbf{any} three integers $a$, $b$ and $c$ ($0 \le a, b, c \le 10^9$) for which $(a\oplus b)+(b\oplus c)+(a\oplus c)=n$, or determine that there are no such integers. Here $a \oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \oplus 4 = 6$ and...
An answer exists only when $n$ is even. $a \oplus a = 0$ $a \oplus 0 = a$ First and foremost, it can be proven that $(a \oplus b) + (b \oplus c) + (a \oplus c)$ is always even, for all possible non-negative values of $a$, $b$ and $c$. Firstly, $a \oplus b$ and $a+b$ have the same parity, since $a + b = a \oplus b + 2 \...
[ "constructive algorithms", "math" ]
800
#include<bits/stdc++.h> using namespace std; void testcase(){ int n; cin>>n; if(n%2==0) cout<<"0 "<<n/2<<' '<<n/2<<'\n'; else cout<<"-1\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--) testcase(); return 0; }
1699
B
Almost Ternary Matrix
You are given two \textbf{even} integers $n$ and $m$. Your task is to find \textbf{any} binary matrix $a$ with $n$ rows and $m$ columns where every cell $(i,j)$ has \textbf{exactly} two neighbours with a different value than $a_{i,j}$. Two cells in the matrix are considered neighbours if and only if they share a side....
The general construction consists of a $2 \times 2$ checkerboard with a $1$-thick border. Here is the intended solution for $n=6$ and $m=8$: Time complexity per testcase: $O(nm)$.
[ "bitmasks", "constructive algorithms", "matrices" ]
900
#include<bits/stdc++.h> using namespace std; typedef long long ll; void testcase(){ ll n,m; cin>>n>>m; for(ll i=1;i<=n;i++){ for(ll j=1;j<=m;j++){ cout<<((i%4<=1)!=(j%4<=1))<<" \n"[j==m]; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; c...
1699
C
The Third Problem
You are given a permutation $a_1,a_2,\ldots,a_n$ of integers from $0$ to $n - 1$. Your task is to find how many permutations $b_1,b_2,\ldots,b_n$ are similar to permutation $a$. Two permutations $a$ and $b$ of size $n$ are considered similar if for all intervals $[l,r]$ ($1 \le l \le r \le n$), the following condition...
Let $p[x]$ be the position of $x$ in permutation $a$. Since $MEX([a_{p[0]}])=1$, the only possible position of $0$ in permutation $b$ is exactly $p[0]$. Continuing this line of thought, where can $1$ be placed in permutation $b$? Without loss of generality, we will assume that $p[0] \lt p[1]$. If $p[2] \lt p[0]$, then ...
[ "combinatorics", "constructive algorithms", "math" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll NMAX=1e5+5,MOD=1e9+7; ll v[NMAX],pos[NMAX]; void tc(){ ll n,l,r,ans=1; cin>>n; for(ll i=0;i<n;i++){ cin>>v[i]; pos[v[i]]=i; } l=r=pos[0]; for(ll i=1;i<n;i++){ if(pos[i]<l) l=pos[i]; else ...
1699
D
Almost Triple Deletions
You are given an integer $n$ and an array $a_1,a_2,\ldots,a_n$. In one operation, you can choose an index $i$ ($1 \le i \lt n$) for which $a_i \neq a_{i+1}$ and delete both $a_i$ and $a_{i+1}$ from the array. After deleting $a_i$ and $a_{i+1}$, the remaining parts of the array are concatenated. For example, if $a=[1,...
Consider the opposite problem: What is the smallest possible length of a final array? For which arrays is the smallest possible final length equal to $0$? Considering the second hint, it is possible to completely remove some subarrays from the array. Lemma: An array $a_1,a_2,\ldots, a_n$ can be fully deleted via a sequ...
[ "data structures", "dp", "greedy" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll NMAX=5e3+5; ll dp[NMAX],v[NMAX],fr[NMAX]; void testcase(){ ll n,ans=0; cin>>n; for(ll i=1;i<=n;i++){ cin>>v[i]; dp[i]=0; } for(ll i=0;i<=n;i++){ if(i && dp[i]==0) continue; ll frmax=0; ...
1699
E
Three Days Grace
Ibti was thinking about a good title for this problem that would fit the round theme (numerus ternarium). He immediately thought about the third derivative, but that was pretty lame so he decided to include the best band in the world — Three Days Grace. You are given a multiset $A$ with initial size $n$, whose element...
We can see that in the final multiset, each number $A_i$ from the initial multiset will be assigned to a subset of values $x_1, x_2,....,x_k$ such that their product is $A_i$. Every such multiset can be created. Also let $vmax$ be the maximum value in the initial multiset. Consider iterating through the minimum value. ...
[ "data structures", "dp", "greedy", "math", "number theory", "two pointers" ]
2,600
#include <bits/stdc++.h> using namespace std; using ll = long long; const int nmax = 5e6 + 5; int appear[nmax]; int mxval[nmax]; int toggle[nmax]; int main() { cin.tie(nullptr)->sync_with_stdio(false); int t; cin >> t; while (t--) { int n, m, mn = nmax, mx = 0; cin >> n >> m; ...
1700
A
Optimal Path
You are given a table $a$ of size $n \times m$. We will consider the table rows numbered from top to bottom from $1$ to $n$, and the columns numbered from left to right from $1$ to $m$. We will denote a cell that is in the $i$-th row and in the $j$-th column as $(i, j)$. In the cell $(i, j)$ there is written a number $...
Let's notice that the optimal path looks like the following: $(1, 1) \rightarrow (1, 2) \rightarrow \ldots \rightarrow (1, m) \rightarrow (2, m) \rightarrow \ldots \rightarrow (n, m)$. The proof is relatively easy - all paths from $(1, 1)$ to $(n, m)$ consist of $n + m - 1$ cells and in the optimal path we have minimiz...
[ "constructive algorithms", "greedy", "math" ]
800
null
1700
B
Palindromic Numbers
During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For examp...
Let X be the number in input. Consider two cases: first digit of X is 9 and not 9. If the first digit of input number is not 9, we can simply output 9999...999 ($n$ digits) - X. If the first digit is 9, we can output 111...1111 ($n + 1$ digits) - X. It is easy to show that this number will be exactly $n$-digit. To simp...
[ "constructive algorithms", "implementation", "math" ]
1,100
null
1700
C
Helping the Nature
Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees. There are $n$ trees growing near the path, the current levels of moisture of each...
Consider the difference array $d_i = a_{i + 1} - a_{i}$. Note that for $d_i > 0$ it is necessary to make $d_i$ subtractions on the suffix. For $d_i < 0$, you need to make $-d_i$ subtractions on the prefix. Let's add them to the answer. Let's calculate the final array using prefix and suffix sums for $O(n)$. Note that i...
[ "constructive algorithms", "data structures", "greedy" ]
1,700
null
1700
D
River Locks
Recently in Divanovo, a huge river locks system was built. There are now $n$ locks, the $i$-th of them has the volume of $v_i$ liters, so that it can contain any amount of water between $0$ and $v_i$ liters. Each lock has a pipe attached to it. When the pipe is open, $1$ liter of water enters the lock every second. Th...
To begin with, we note that it makes sense to open only some pipe prefix, because we need to fill all the locks, and more left pipes affect the total volume of the baths, which is obviously beneficial. Let's enumerate how many pipes we will open, namely which prefix of pipes we will open and calculate $dp_i$ - how long...
[ "binary search", "dp", "greedy", "math" ]
1,900
null
1700
E
Serega the Pirate
Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest. A puzzle is a table of $n$ rows and $m$ columns, whose cells contain each number from $1$ to $n \cdot m$ exactly once. To solve a puzzle, you have to find a sequence of cells in the table, such that an...
We need to find a simple criteria of a solvable puzzle. It can be shown that for every cell, except cell with value $1$, it should have a neighbour with a smaller value. Indeed, if the puzzle is solvable, a cell going before the first occurence of our cell always has the smaller value. Conversely, if each cell has a sm...
[ "brute force", "constructive algorithms" ]
2,600
null
1700
F
Puzzle
Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $2$ rows and $n$ columns, every element of which is either $0$ or $1$. In one move you can swap two values in neighboring cells. More formally, let's number...
We are asked to find a minimum cost perfect matching between $1$'s in the matrices, where the cost between $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$. Notice that the answer exists only if the number of $1$'s is equal in both matrices. Consider that this is the case. Notice that every $1$ either stays...
[ "constructive algorithms", "dp", "greedy" ]
2,600
null
1701
A
Grass Field
There is a field of size $2 \times 2$. Each cell of this field can either contain grass or be empty. The value $a_{i, j}$ is $1$ if the cell $(i, j)$ contains grass, or $0$ otherwise. In one move, you can choose \textbf{one row} and \textbf{one column} and cut all the grass in this row and this column. In other words,...
If there is no grass on the field, the answer is $0$. If the whole field is filled with grass, the answer is $2$, because there always will be one cell that we can't clear with one move. Otherwise, the answer is $1$. This is because if the cell $(i, j)$ is empty, we can just choose other row than $i$ and other column t...
[ "implementation" ]
800
for _ in range(int(input())): a = [list(map(int, input().split())) for i in range(2)] cnt = sum([sum(a[i]) for i in range(2)]) if cnt == 0: print(0) elif cnt == 4: print(2) else: print(1)
1701
B
Permutation
Recall that a permutation of length $n$ is an array where each element from $1$ to $n$ occurs exactly once. For a fixed positive integer $d$, let's define the cost of the permutation $p$ of length $n$ as the number of indices $i$ $(1 \le i < n)$ such that $p_i \cdot d = p_{i + 1}$. For example, if $d = 3$ and $p = [5...
Let's notice that for a fixed value of $d$, the answer (the cost of permutation) does not exceed $\frac{n}{d}$, because only numbers from $1$ to $\frac{n}{d}$ can have a pair. It turns out that it is always possible to construct a permutation with the cost of exactly $\frac{n}{d}$. It is enough to consider the number "...
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; cout << 2 << '\n'; for (int i = 1; i <= n; ++i) if (i % 2 != 0) for (int j = i; j <= n; j *= 2) cout << j << ' '; cout << '\n'; ...
1701
C
Schedule Management
There are $n$ workers and $m$ tasks. The workers are numbered from $1$ to $n$. Each task $i$ has a value $a_i$ — the index of worker who is proficient in this task. Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in $1$ hour. Otherwise, it takes them $2$ hours. ...
The statement should instantly scream binary search at you. Clearly, if you can assign the workers in such a way that the tasks are completed by time $t$, you can complete them all by $t+1$ or more as well. How to check if the tasks can be completed by some time $t$? What that means is that all workers have $t$ hours t...
[ "binary search", "greedy", "implementation", "two pointers" ]
1,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int t; scanf("%d", &t); while (t--){ int n, m; scanf("%d%d", &n, &m); vector<int> a(m); forn(i, m){ scanf("%d", &a[i]); --a[i]; } vector<int> cnt(n); forn(i, m) ++cnt[a[i]]; auto ch...
1701
D
Permutation Restoration
Monocarp had a permutation $a$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once). Then Monocarp calculated an array of integers $b$ of size $n$, where $b_i = \left\lfloor \frac{i}{a_i} \right\rfloor$. For example, if the permutation $a$ is $[2, 1, 4, ...
We have $b_i = \left\lfloor \frac{i}{a_i} \right\rfloor$ for each $i$, we can rewrite this as follows: $a_i \cdot b_i \le i < a_i \cdot (b_i+1)$, or $\frac{i}{b_i + 1} < a_i \le \frac{i}{b_i}$. From here we can see that for each $i$ there is a segment of values that can be assigned to $a_i$. So we have to match each nu...
[ "binary search", "data structures", "greedy", "math", "sortings", "two pointers" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n), b(n); for (int& x : b) cin >> x; vector<pair<int, int>> ev(n); for (int i = 0; i < n; ++i) ev[i] = {(i + 1) / (b[i...
1701
E
Text Editor
You wanted to write a text $t$ consisting of $m$ lowercase Latin letters. But instead, you have written a text $s$ consisting of $n$ lowercase Latin letters, and now you want to fix it by obtaining the text $t$ from the text $s$. Initially, the cursor of your text editor is at the end of the text $s$ (after its last c...
Of course, there is no need to press "home" more than once (and no need to press "end" at all), because suppose we did something on suffix, then pressed "home", did something on prefix and then pressed "end" and continue doing something on suffix. Then we can merge these two sequences of moves on suffix and press "home...
[ "brute force", "dp", "greedy", "strings" ]
2,500
#include <bits/stdc++.h> using namespace std; vector<int> zf(const string &s) { int n = s.size(); vector<int> z(n); int l = 0, r = 0; for (int i = 1; i < n; ++i) { if (i <= r) { z[i] = min(r - i + 1, z[i - l]); } while (i + z[i] < n && s[z[i]] == s[i + z[i]]) { ...
1701
F
Points
A triple of points $i$, $j$ and $k$ on a coordinate line is called \textbf{beautiful} if $i < j < k$ and $k - i \le d$. You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: - add a point; - remove a point; - calculate the number of beautiful triples consisti...
We are going to calculate the answer as follows: for every point $i$, let $f(i)$ be the number of points $j$ such that $1 \le j - i \le d$ (i. e. the number of points that are to the right of $i$ and have distance at most $d$ from it). Then, the number of beautiful triples where $i$ is the leftmost point is $\dfrac{f(i...
[ "combinatorics", "data structures", "implementation", "math", "matrices" ]
2,500
#include<bits/stdc++.h> using namespace std; const int N = 200043; const int M = 200001; typedef array<long long, 3> vec; typedef array<vec, 3> mat; vec operator+(const vec& a, const vec& b) { vec c; for(int i = 0; i < 3; i++) c[i] = a[i] + b[i]; return c; } vec operator-(const vec& a, const vec& b) { ...
1702
A
Round Down the Price
At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $10$ is called a round number. For example, the numbers $10^0 = 1$, $10^1 = 10$, $10^2 = 100$ are round numbers, but $20$, $110$ and $256$ are not round numbers. So, if an item is worth $m$ bourles (the value of ...
Note that the number $m$ and the nearest round number not exceeding $m$ have the same size (consist of the same number of digits in the record). Denote the size of $m$ by $len$. Then we can construct the nearest round number. It will consist of one and $len - 1$ zeros.
[ "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void solve() { int m; cin >> m; string t = to_string(m); string s = "1"; for (int i = 1; i < sz(t); i++) { s...
1702
B
Polycarp Writes a String from Memory
Polycarp has a poor memory. Each day he can remember no more than $3$ of different letters. Polycarp wants to write a non-empty string of $s$ consisting of lowercase Latin letters, taking \textbf{minimum} number of days. In how many days will he be able to do it? Polycarp initially has an empty string and can only ad...
Let us simulate the process. We store a set $v$ consisting of letters that Polycarp memorizes on one day. Gradually dial the set $s$. If the size of $v$ exceeds $3$, we add $1$ to the day counter $ans$ and clear $v$.
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void solve() { string s; cin >> s; set<char> v; int ans = 0; for (int i = 0; i < sz(s); i++) { v.insert(s[i]...
1702
C
Train and Queries
Along the railroad there are stations indexed from $1$ to $10^9$. An express train always travels along a route consisting of $n$ stations with indices $u_1, u_2, \dots, u_n$, where ($1 \le u_i \le 10^9$). The train travels along the route from left to right. It starts at station $u_1$, then stops at station $u_2$, the...
To solve the problem, we will use the dictionary. Each station will be matched with a pair of integers - the indices of its first and last entries in the route. Then we will sequentially process queries. If at least one of the stations $a_j$ or $b_j$ is missing in the dictionary - the answer is NO. Otherwise, check: If...
[ "data structures", "greedy" ]
1,100
#include<bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) void solve(){ int n, k; cin >> n >> k; map<int, pair<int, int>>m; forn(i, n){ int u; cin >> u; if(!m.count(u)) { m[u].first = i; m[u].second = i; } ...
1702
D
Not a Cheap String
Let $s$ be a string of lowercase Latin letters. Its price is the sum of the indices of letters (an integer between 1 and 26) that are included in it. For example, the price of the string abca is $1+2+3+1=7$. The string $w$ and the integer $p$ are given. Remove the minimal number of letters from $w$ so that its price b...
The main idea is that it is always better to remove the most expensive symbol. To do this quickly, we will count all the symbols and remove them from the most expensive to the cheapest, counting how many times we have removed each. During the output, we will skip the characters the number of times that we deleted.
[ "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { string s; cin >> s; int p; cin >> p; string w(s); sort(w.rbegin(), w.rend()); int cost = 0; forn(i,...
1702
E
Split Into Two Sets
Polycarp was recently given a set of $n$ (number $n$ — even) dominoes. Each domino contains two integers from $1$ to $n$. Can he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets. For example, if he has $4$ dom...
Polycarp has $n$ dominoes, on each domino there are $2$ numbers - it turns out, there will be $2n$ numbers in total. We need to divide $2n$ numbers (each number from $1$ to $n$) into two sets so that all numbers in each set are different - each set will consist of $n$ numbers. It turns out that all numbers from $1$ to ...
[ "dfs and similar", "dsu", "graphs" ]
1,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) map<int, vector<int>> m; vector<bool> used; int go(int v) { used[v] = true; for (auto now : m[v]) { if (!used[now]) { return go(now) + 1; } } return 1;...
1702
F
Equate Multisets
Multiset —is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. Two multisets are equal when each value occurs the same number of times. For example, the multisets $\{2,2,4\}$ and $\{2,4,2\}$ are equal, but the multisets $\{1,2,2\}$ and $\{1,1,2\}$ — are not. You are g...
We divide each number from the multiset $a$ by $2$ as long as it is divisible without a remainder. Because if we can get a new number from the multiset $a$, we can also increase it to the original number by multiplication by $2$. Now notice that it does not make sense to use the first operation (multiplication by $2$),...
[ "constructive algorithms", "data structures", "greedy", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back const int INF = 1e9; void solve() { int n; cin >> n; multiset<int> a, b; forn(i, n) { int x; cin >> x; w...
1702
G1
Passable Paths (easy version)
\textbf{This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.} Polycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles. He calls...
If the answer is YES, then we can choose a subset of the tree vertices forming a simple path and containing all the vertices of our set. Let's choose the minimum possible path, its ends - vertices from the set. The constraints allow us to answer the query in $\mathcal{O}(n)$, hang the tree by one of the ends and check ...
[ "dfs and similar", "trees" ]
1,900
#include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const int inf = 1e15; const int M ...
1702
G2
Passable Paths (hard version)
\textbf{This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.} Polycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles. He calls ...
Recall that the path in the rooted tree - ascends from one end to the least common ancestor ($lca$) of the ends and descends to the other end (possibly by 0). Then our set is divided into two simple ways. To check this, you only need to count $lca$. We will first calculate the depths, as for solving an easy version of ...
[ "data structures", "dfs and similar", "trees" ]
2,000
#include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const int inf = 1e15; const int M ...
1703
A
YES or YES?
There is a string $s$ of length $3$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.
You should implement what is written in the statement. Here are three ways to do it: Check that the first character is $\texttt{Y}$ or $\texttt{y}$, check that the second character is $\texttt{E}$ or $\texttt{e}$, and check the third character is $\texttt{S}$ or $\texttt{s}$. Make an array storing all acceptable string...
[ "brute force", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { string s; cin >> s; if (s[0] != 'y' && s[0] != 'Y') {cout << "NO\n";} else if (s[1] != 'e' && s[1] != 'E') {cout << "NO\n";} else if (s[2] != 's' && s[2] != 'S') {cout << "NO\n";} else {cout << "YES...
1703
B
ICPC Balloons
In an ICPC contest, balloons are distributed as follows: - Whenever a team solves a problem, that team gets a balloon. - The first team to solve a problem gets an additional balloon. A contest has 26 problems, labelled $\textsf{A}$, $\textsf{B}$, $\textsf{C}$, ..., $\textsf{Z}$. You are given the order of solved prob...
Let's keep an array $a$ of booleans, $a_i$ denoting whether or not some team has solved the $i$th problem already. Now we can iterate through the string from left to right and keep a running total $\mathrm{tot}$. If $a_i$ is true (the $i$-th problem has already been solved), increase $\mathrm{tot}$ by $1$; otherwise, i...
[ "data structures", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s; cin >> s; bool vis[26] = {}; int res = 0; for (char c : s) { if (!vis[c - 'A']) {res += 2; vis[c - 'A'] = true;} else {res++;} } cout << res << '\n'; } int mai...
1703
C
Cypher
Luca has a cypher made up of a sequence of $n$ wheels, each with a digit $a_i$ written on it. On the $i$-th wheel, he made $b_i$ moves. Each move is one of two types: - up move (denoted by $U$): it increases the $i$-th digit by $1$. After applying the up move on $9$, it becomes $0$. - down move (denoted by $D$): it de...
We will perform each move in reverse from the final sequence of the cypher. down move: it increases the $i$-th digit by $1$. After applying the up move on $9$, it becomes $0$. up move (denoted by $\texttt{D}$): it decreases the $i$-th digit by $1$. After applying the down move on $0$, it becomes $9$.
[ "brute force", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int a[n]; for(int i = 0; i < n; i++) { cin >> a[i]; } for(int i = 0; i < n; i++) { int b; cin >> b; if(b == 0) { continue; } string now; ...
1703
D
Double Strings
You are given $n$ strings $s_1, s_2, \dots, s_n$ of length at most $\mathbf{8}$. For each string $s_i$, determine if there exist two strings $s_j$ and $s_k$ such that $s_i = s_j + s_k$. That is, $s_i$ is the concatenation of $s_j$ and $s_k$. Note that $j$ \textbf{can} be equal to $k$. Recall that the concatenation of...
Use some data structure that allows you to answer queries of the form: "does the string $t$ appear in the array $s_1, \dots, s_n$?" For example, in C++ you can use a map<string, bool>, while in Python you can use a dictionary dict. Afterwards, for each string $s$, brute force all strings $x$ and $y$ such that $s = x + ...
[ "brute force", "data structures", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s[n]; map<string, bool> mp; for (int i = 0; i < n; i++) { cin >> s[i]; mp[s[i]] = true; } for (int i = 0; i < n; i++) { bool ok = false; for (int j = 1; j < s[i]....
1703
E
Mirror Grid
You are given a square grid with $n$ rows and $n$ columns. Each cell contains either $0$ or $1$. In an operation, you can select a cell of the grid and flip it (from $0 \to 1$ or $1 \to 0$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $0^{\circ}$, $90^{\circ}$, ...
Let's rotate the grid by $0^{\circ}$, $90^{\circ}$, $180^{\circ}$, and $270^{\circ}$, and mark all cells that map to each other under these rotations. For example, for $4 \times 4$ and $5 \times 5$ grids, mirror grid must have the following patterns, the same letters denoting equal values: $\begin{matrix} a & b & c & a...
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int a[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { char c; cin >> c; a[i][j] = c-'0'; } } int ans = 0; for(int i = 0; i < (n+1)/...
1703
F
Yet Another Problem About Pairs Satisfying an Inequality
You are given an array $a_1, a_2, \dots a_n$. Count the number of pairs of indices $1 \leq i, j \leq n$ such that $a_i < i < a_j < j$.
Call a pair good if it satisfies the condition. Let's split the inequality into three parts: $a_i < i$, $i < a_j$, $a_j < j$. Note that if $a_i \geq i$ for any $i$, then it can't be an element of a good pair, because it fails the first and third conditions. So we can throw out all elements of the array satisfying $a_i ...
[ "binary search", "data structures", "dp", "greedy", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; int a[n + 1]; for (int i = 1; i <= n; i++) { cin >> a[i]; } long long res = 0; vector<int> v; for (int i = 1; i <= n; i++) { if (a[i] >= i) {continue;} res += (long long)...
1703
G
Good Key, Bad Key
There are $n$ chests. The $i$-th chest contains $a_i$ coins. You need to open all $n$ chests \textbf{in order from chest}$1$\textbf{to chest}$n$. There are two types of keys you can use to open a chest: - a good key, which costs $k$ coins to use; - a bad key, which does not cost any coins, but will halve all the coin...
We will prove it is always optimal to use good keys for a prefix then only use bad keys. Consider we have used a bad key then a good key, by doing this we obtain $\lfloor\frac{a_i}{2}\rfloor + \lfloor\frac{a_{i+1}}{2}\rfloor - k$ coins. If we switch and use a good key first, the a bad key then we obtain $a_i + \lfloor\...
[ "bitmasks", "brute force", "dp", "greedy", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; int a[n]; for(int i = 0; i < n; i++) { cin >> a[i]; } long long ans = 0; long long sum = 0; for(int i = -1; i < n; i++) { long long now = sum; for(int j = i+1; j < min(...
1704
A
Two 0-1 Sequences
AquaMoon has two binary sequences $a$ and $b$, which contain only $0$ and $1$. AquaMoon can perform the following two operations any number of times ($a_1$ is the first element of $a$, $a_2$ is the second element of $a$, and so on): - Operation 1: if $a$ contains at least two elements, change $a_2$ to $\operatorname{m...
Considering that whichever the operation you use, the length of $a$ would decrease $1$. So you can only modify the first $n-m+1$ elements of $a$, otherwise the length of $a$ can't be equal to the length of $b$. That means $\{a_{n-m+2},\dots,a_n\}$ must equals to $\{b_2,\dots,b_m\}$. And about the first element of $b$: ...
[ "constructive algorithms", "greedy" ]
800
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int T; cin >> T; while (T--) { int n, m; cin >> n >> m; string a, b; cin >> a >> b; if (n < m) { ...
1704
B
Luke is a Foodie
Luke likes to eat. There are $n$ piles of food aligned in a straight line in front of him. The $i$-th pile contains $a_i$ units of food. Luke will walk from the $1$-st pile towards the $n$-th pile, and he wants to eat every pile of food without walking back. When Luke reaches the $i$-th pile, he can eat that pile if a...
For $a_i$, if $|v-a_i| \leq x$, then $a_i-x \leq v \leq a_i+x$. Then consider using the greedy strategy. We will only change $v$ when we cannot find any possible $v$ to satisfy the current conditions. Therefore, we can determine the range of $v$. Initially, set $l=a_1-x,r=a_1+x$, then $v \in [l,r]$. For $a_i$, change $...
[ "brute force", "greedy", "implementation" ]
1,000
#include <stdio.h> #include <string.h> #include <vector> #include <set> #include <queue> #include <string> #include <map> #include <chrono> #include <stdlib.h> #include <time.h> #include <algorithm> #include <iostream> #include <memory> #include <cstdio> #include <assert.h> #include <iostream> const int MAXN = 300005; ...
1704
C
Virus
There are $n$ houses numbered from $1$ to $n$ on a circle. For each $1 \leq i \leq n - 1$, house $i$ and house $i + 1$ are neighbours; additionally, house $n$ and house $1$ are also neighbours. Initially, $m$ of these $n$ houses are infected by a deadly virus. Each \textbf{morning}, Cirno can choose a house which is u...
First, considering it is easier to calculate the number of houses which are not infected, so we focus on it firstly. Conspicuously, if between $a_i$ and $a_{i+1}$ there are $x$ houses (Array $a$ has been sorted.), and the infection will last $y$ days, there will remain $x-2 \times y$ houses on the end. Simultaneously, ...
[ "greedy", "implementation", "sortings" ]
1,200
#include<bits/stdc++.h> using namespace std; const int N = 500005, inf = 2147483647, M = 1004535809; int n, m, a[N], T, k; struct str { int x, y; }t[N]; int main() { scanf("%d", &T); while (T--) { k = 0; scanf("%d %d", &n, &m); for (int i = 1; i <= m; ++i) scanf("%d", &a[i]); sort(a + 1, a + 1 + m); for...
1704
D
Magical Array
Eric has an array $b$ of length $m$, then he generates $n$ additional arrays $c_1, c_2, \dots, c_n$, each of length $m$, from the array $b$, by the following way: Initially, $c_i = b$ for every $1 \le i \le n$. Eric secretly chooses an integer $k$ $(1 \le k \le n)$ and chooses $c_k$ to be the special array. There are...
First, let's focus on $\textbf{operation 1}$ and do some calculations: 1. $a_{i-1} \times (i-1) + a_i \times i + a_j \times j + a_{j+1} \times (j+1) = i \times (a_{i-1}+a_i) + j \times (a_j+a_{j+1}) -a_{i-1} + a_{j+1}$ 2. $(a_{i-1}+1) \times (i-1) + (a_i-1) \times i + (a_j-1) \times j + (a_{j+1}+1) \times (j+1)$ $\ \ \...
[ "constructive algorithms", "hashing", "implementation", "math" ]
1,900
#include <stdio.h> #include <string.h> #include <vector> #include <map> #include <cassert> const int MAXN = 500005; std::vector<long long> numbers[MAXN]; std::map<long long, long long> val_to_index; int main() { int t; int n, m; scanf("%d ", &t); while (t--) { val_to_index.clear(); scanf("%d %d", &n, &m); lo...
1704
E
Count Seconds
Cirno has a DAG (Directed Acyclic Graph) with $n$ nodes and $m$ edges. The graph has exactly one node that has no out edges. The $i$-th node has an integer $a_i$ on it. Every second the following happens: - Let $S$ be the set of nodes $x$ that have $a_x > 0$. - For all $x \in S$, $1$ is subtracted from $a_x$, and the...
For the sink point, We can find that it may be zero at some time $t$ and $t \leq n$, then it will be full for some continous time, and then will be zero forever. That's because for time $t\ge n$, for some certain $a_x>0$, all roads from $x$ to the sink point must be greater than $0$ since $n$ rounds are enough for such...
[ "brute force", "constructive algorithms", "dp", "graphs", "implementation", "math" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = 500005, inf = 2147483647, M = 998244353; int n, m, a[N], u, v, i, d[N], q[N], r, mx; int b[N], tmp[N]; vector<int> g[N], z[N]; long long s[N]; int p[15]; void NEX(int M) { for (int i = 1; i <= n; ++i) if (b[i]) { tmp[i] += b[i] - 1; for (auto it : g[i]...
1704
F
Colouring Game
Alice and Bob are playing a game. There are $n$ cells in a row. Initially each cell is either red or blue. Alice goes first. On each turn, Alice chooses two neighbouring cells which contain at least one red cell, and paints that two cells white. Then, Bob chooses two neighbouring cells which contain at least one blue ...
First, when the number red cells and blue cells are not equal, the player who owns a larger numberof his/her corresponding cells will win (Alice owns red and Bob owns blue). His/Her strategy can be: each time paint one segment of RB or BR white until there is none. This operation doesn't change the difference between t...
[ "constructive algorithms", "dp", "games" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N=500005,inf=2147483647,M=998244353; int n,i,t,f[N],vis[N]; char c[N]; int main(){ for(int i=1;i<=1000;++i){ for(int j=0;j<=i-2;++j) vis[f[j]^f[i-2-j]]=1; int j; for(j=0;vis[j];++j); f[i]=j; for(int j=0;j<=i;+...
1704
G
Mio and Lucky Array
Mio has an array $a$ consisting of $n$ integers, and an array $b$ consisting of $m$ integers. Mio can do the following operation to $a$: - Choose an integer $i$ ($1 \leq i \leq n$) that has \textbf{not} been chosen before, then add $1$ to $a_i$, subtract $2$ from $a_{i+1}$, add $3$ to $a_{i+2}$ an so on. Formally, th...
Let's define $f_i = a_i + 2 a_{i-1} + a_{i-2}, g_i = b_i + 2b_{i-1} + b_{i-2}$. Cosidering after the operation on some index $i$, for any $j\ne i$, $f_j$ will remain the same; For $j=i$, $f_j$ will be increased by $1$. Then we can find the operation on $a$ is a single point operation on $f$. It can be proved that the f...
[ "constructive algorithms", "fft", "math", "strings" ]
3,500
#include<bits/stdc++.h> using namespace std; const int M1=998244353,M2=1004535809,M3=469762049,E=524288,N=200005; struct poly{ const int M; poly(int _M):M(_M){} int R[N*4]; long long qpow(long long a,long long b){ long long ans=1; while(b){ if(b&1) ans=ans*a%M...
1704
H1
Game of AI (easy version)
\textbf{This is the easy version of this problem. The difference between easy and hard versions is the constraint on $k$ and the time limit. Also, in this version of the problem, you only need to calculate the answer when $n=k$. You can make hacks only if both versions of the problem are solved.} Cirno is playing a wa...
Consider calculate the number of possible sequences $a$ for a fixed sequence $b$. We can find that if $b_i\ne i$, that means $i$ is occupied by $b_i$ finally, so we have $a_{b_i}$=i. If $b_i=i$, that means for all $j$ that $a_j=i$, $j$ is occupied before it begins its attack. As a result, we must have $b_j\ne j$. The s...
[ "combinatorics", "constructive algorithms", "dp", "fft", "math" ]
3,200
#include<bits/stdc++.h> using namespace std; const int N=200005,E=15000005; const long long inf=1000000000000000000ll; int n,M,mi[5005][5005]; long long fac[N],inv[N],ans; long long C(int n,int m){ return fac[n]*inv[m]%M*inv[n-m]%M; } long long qpow(long long a,long long b){ long long s=a,ans=1; while(b){ ...
1704
H2
Game of AI (hard version)
\textbf{This is the hard version of this problem. The difference between easy and hard versions is the constraint on $k$ and the time limit. Notice that you need to calculate the answer for all positive integers $n \in [1,k]$ in this version. You can make hacks only if both versions of the problem are solved.} Cirno i...
Given $b$, The conclusion of possible array $a$ remains. If we fix array $a$, we will find that for each $i$, $b_i$ will only be $j$ that $a_j=i$ or $j=i$. For any pair $(x,y)$, if $a_x=y$, we will find that $b_x=x$ and $b_y=y$ at the same time is impossible. All arrays $b$ which satisfies the above conditions are vali...
[ "combinatorics", "fft", "math" ]
3,500
#include<bits/stdc++.h> using namespace std; const int N=100005,inf=2147483647; const long long sq5=200717101; int M; namespace poly{ int R[N*4]; long long qpow(long long a,long long b){ long long ans=1; while(b){ if(b&1) ans=ans*a%M; a=a*a%M; ...
1705
A
Mark the Photographer
Mark is asked to take a group photo of $2n$ people. The $i$-th person has height $h_i$ units. To do so, he ordered these people into two rows, the front row and the back row, each consisting of $n$ people. However, to ensure that everyone is seen properly, the $j$-th person of the back row must be at least $x$ units t...
First, sort $h_1 \leq h_2 \leq \dots \leq h_{2n}$. There is a very explicit description to which $h_i$'s work. What is the optimal arrangement that maximizes the minimum difference across all pairs? We have a very explicit description of whether the arrangement is possible. Sort the heights so that $h_1 \leq h_2 \leq \...
[ "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n, x; cin >> n >> x; vector<int> a(2 * n); for (int i = 0; i < 2 * n; ++i) cin >> a[i]; sort(a.begin(), a.end()); bool ok = true; for (int i = 0; i < n; ++i) if (a[n + i] - a[i] < x) ok = false; cout << (o...
1705
B
Mark the Dust Sweeper
Mark is cleaning a row of $n$ rooms. The $i$-th room has a nonnegative dust level $a_i$. He has a magical cleaning machine that can do the following three-step operation. - Select two indices $i<j$ such that the dust levels $a_i$, $a_{i+1}$, $\dots$, $a_{j-1}$ are all strictly greater than $0$. - Set $a_i$ to $a_i-1$....
The optimal way is to fill all the zero entries first. Delete the leading zeroes in the array $a$ (i.e., the first $t$ numbers of $a$ that are zero) so that now $a_1\ne 0$. Let $k$ be the number of $0$'s in $a_1,a_2,\dots,a_{n-1}$. The answer is $(a_1+a_2+\dots + a_{n-1}) + k.$ To see why, let Mark keep filling the hol...
[ "constructive algorithms", "greedy", "implementation" ]
900
#include <iostream> #include <vector> #define ll long long using namespace std; void solve(){ int n; cin >> n; vector<int> a(n); for(int i = 0; i < n; ++i) cin >> a[i]; ll ans = 0; int ptr = 0; while(ptr < n && a[ptr] == 0) ptr++; for(int i = ptr; i < n-1; ++i){ an...
1705
C
Mark and His Unfinished Essay
One night, Mark realized that there is an essay due tomorrow. He hasn't written anything yet, so Mark decided to randomly copy-paste substrings from the prompt to make the essay. More formally, the prompt is a string $s$ of initial length $n$. Mark will perform the copy-pasting operation $c$ times. Each operation is d...
What's in common between all letters that were copied at the same time? The answer is the difference between the current position and the position where it came from. That's what you need to store. By tracking the difference, you can recurse to the previously-copied substring. This is an implementation problem. What yo...
[ "brute force", "implementation" ]
1,400
#include<bits/stdc++.h> #define ll long long using namespace std; void solve(){ int n, c, q; cin >> n >> c >> q; string s; cin >> s; vector<ll> left(c+1), right(c+1), diff(c+1); left[0] = 0; right[0] = n; for(int i=1; i<=c; ++i){ ll l, r; cin >> l >> r; l--; r--; left[i] = rig...
1705
D
Mark and Lightbulbs
Mark has just purchased a rack of $n$ lightbulbs. The state of the lightbulbs can be described with binary string $s = s_1s_2\dots s_n$, where $s_i=1$ means that the $i$-th lightbulb is turned on, while $s_i=0$ means that the $i$-th lightbulb is turned off. Unfortunately, the lightbulbs are broken, and the only operat...
Look at all the $01$'s and $10$'s carefully. The sum of the number of $01$'s and $10$'s is constant. Consider all positions of $01$'s and $10$'s. How does it change in each operation? As explained in the sample explanations, the operation cannot change the first or the last bit. Thus, if either $s_1\ne t_1$ or $s_n\ne ...
[ "combinatorics", "constructive algorithms", "greedy", "math", "sortings" ]
1,800
#include <bits/stdc++.h> #define ll long long using namespace std; void solve(){ int n; cin >> n; string s,t; cin >> s >> t; vector<ll> pos_s, pos_t; if(s[0] != t[0] || s[n-1] != t[n-1]){ cout << -1 << "\n"; return; } for(int i=0; i<n-1; i++){ if(s[i] != s[i+1]) pos_s....
1705
E
Mark and Professor Koro
After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $n$ positive integers $a_1, a_2,\dots,a_n$ on it. Then, professor Koro comes in. He can perform the following operation: - select an integer $x$ that appears at least $2$ times on...
Find a concise description of the answer first. Think about power of two. The sum $2^{a_1}+2^{a_2}+\dots+2^{a_n}$ is constant. Show that the answer must be the most significant bit of that. Use either bitset or lazy segment tree to simulate the addition/subtraction. The key observation is the following. Claim: The answ...
[ "binary search", "bitmasks", "brute force", "combinatorics", "data structures", "greedy" ]
2,300
#include<bits/stdc++.h> using namespace std; struct LazySeg { int l, r; int val = 0, tag = 0; bool is_lazy = false; LazySeg * l_child = NULL, * r_child = NULL; LazySeg(int _l, int _r) { l = _l; r = _r; if (r - l > 1) { int m = (l + r) / 2; l_child = ...
1705
F
Mark and the Online Exam
Mark is administering an online exam consisting of $n$ true-false questions. However, he has lost all answer keys. He needs a way to retrieve the answers before his client gets infuriated. Fortunately, he has access to the grading system. Thus, for each query, you can input the answers to all $n$ questions, and the gr...
Unfortunately, a harder version of this problem has appeared in a Chinese contest here and here. You can look at their solution here. We thank many contestants who pointed it out. It's possible to solve this problem without any randomization. See the subsequent hints for how to do so. Observe that we can take differenc...
[ "bitmasks", "constructive algorithms", "interactive", "probabilities" ]
2,900
#include <bits/stdc++.h> using namespace std; int n; int query(string s){ cout << s << endl; cout.flush(); int x; cin >> x; if(x==n) exit(0); return x; } int main(){ cin >> n; //query true count string all_T(n, 'T'), ans(n, '?'); int cnt_T = query(all_T); //query TF ...
1706
A
Another String Minimization Problem
You have a sequence $a_1, a_2, \ldots, a_n$ of length $n$, consisting of integers between $1$ and $m$. You also have a string $s$, consisting of $m$ characters B. You are going to perform the following $n$ operations. - At the $i$-th ($1 \le i \le n$) operation, you replace either the $a_i$-th \textbf{or} the $(m + 1...
Let's iterate through the elements of $a$. For convenience, we'll make $a_i = \min(a_i, m + 1 - a_i)$. If the $a_i$-th character of $s$ is not currently A, then we should replace it. Otherwise, we replace the $(m+1-a_i)$-th character. This is because if we have the choice between replacing two characters, replacing the...
[ "2-sat", "constructive algorithms", "greedy", "string suffix structures", "strings" ]
800
#include "bits/stdc++.h" using namespace std; #define ll long long const int MAXN = 55; int t, n, m; int cnt[MAXN]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; while (t--) { cin >> n >> m; for (int i = 0; i < m; i++) cnt[i] = 0; for (int i = 0; i < ...
1706
B
Making Towers
You have a sequence of $n$ colored blocks. The color of the $i$-th block is $c_i$, an integer between $1$ and $n$. You will place the blocks down in sequence on an infinite coordinate grid in the following way. - Initially, you place block $1$ at $(0, 0)$. - For $2 \le i \le n$, if the $(i - 1)$-th block is placed at...
When can two blocks of the same color form two consecutive elements of a tower? Formally, if we have two blocks of the same color at indices $i$ and $j$ such that $i < j$, how can we tell if it is possible to place them at $(x_i, y_i)$ and $(x_i, y_i + 1)$ respectively? As it turns out, they can be placed like this if ...
[ "dp", "greedy", "math" ]
1,100
#include "bits/stdc++.h" using namespace std; #define ll long long const int MAXN = 100100; int t, n; vector<int> a[MAXN]; int solve(int x) { if (!a[x].size()) return 0; int curr = a[x][0]; int ans = 1; for (int i : a[x]) { if ((i & 1) != (curr & 1)) { ans++; curr = i; } } ...
1706
C
Qpwoeirut And The City
Qpwoeirut has taken up architecture and ambitiously decided to remodel his city. Qpwoeirut's city can be described as a row of $n$ buildings, the $i$-th ($1 \le i \le n$) of which is $h_i$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $i$ is taller than the bu...
The first observation to be made is that no two adjacent building can both be cool at the same time. This means that, for odd $n$, there must be $\frac{n-1}{2}$ cool buildings arranged in the following configuration... 01010...01010(0 - normal (not cool) building, 1 - cool building) For even $n$, there must be $\frac{n...
[ "dp", "flows", "greedy", "implementation" ]
1,400
#include "bits/stdc++.h" using namespace std; #define ll long long const int MAXN = 100100; int t, n; ll a[MAXN]; ll get(int i) { return max(0ll, max(a[i - 1], a[i + 1]) - a[i] + 1); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; while (t--) { cin >> n; for (i...
1706
D1
Chopping Carrots (Easy Version)
\url{CDN_BASE_URL/51167bab54119df1f721947703725ebd}
Let's iterate over integers $v = 0, 1, \ldots, a_1$. We'll construct an answer assuming that the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$ is at least $v$. For all $1 \le i \le n$, we set $p_i = \min(k, \lfloor \frac{a_i}{v} \rfloor)$: the maximum value $p_i$ such that $1 \le p_i \le k$ and $v \le \lfloor \fra...
[ "binary search", "brute force", "constructive algorithms", "greedy", "number theory" ]
1,700
#include "bits/stdc++.h" using namespace std; #define ll long long const int MAXN = 3030; int t, n, k; int a[MAXN]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; while (t--) { cin >> n >> k; for (int i = 0; i < n; i++) cin >> a[i]; int ans = 1e9; fo...
1706
D2
Chopping Carrots (Hard Version)
This is the hard version of the problem. The only difference between the versions is the constraints on $n$, $k$, $a_i$, and the sum of $n$ over all test cases. You can make hacks only if both versions of the problem are solved. \textbf{Note the unusual memory limit.} You are given an array of integers $a_1, a_2, \ld...
Solution 1 Let's fix $v$, the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$. Then, for all $1 \le i \le n$, we find the maximum value $p_i$ such that $p_i \le k$ and $\lfloor \frac{a_i}{p_i} \rfloor \ge v$. For some minimum value $v$, let's call the array described above $P(v)$, and let's define $M(v) = \max\limit...
[ "brute force", "constructive algorithms", "data structures", "dp", "greedy", "math", "number theory", "two pointers" ]
2,400
// AUTHOR: AlperenT #include <bits/stdc++.h> using namespace std; const long long N = 1e5 + 5, INF = (long long)2e18 + 5; long long t, n, k, arr[N], closest[N], mn, ans; vector<pair<long long, long long>> v; void solve(){ ans = INF; cin >> n >> k; for(int i = 1; i <= n; i++) cin >> arr[i]; arr[0] ...
1706
E
Qpwoeirut and Vertices
You are given a connected undirected graph with $n$ vertices and $m$ edges. Vertices of the graph are numbered by integers from $1$ to $n$ and edges of the graph are numbered by integers from $1$ to $m$. Your task is to answer $q$ queries, each consisting of two integers $l$ and $r$. The answer to each query is the sm...
If $l = r$, answer is $0$. From now on we assume $l < r$. Say we have a function $f(i)$ that tells us for some $2 \le i \le n$ the answer for the query $[i - 1, i]$. Then for some query $[l, r]$, the answer will be $k = \max(f(l+1), f(l+2), \ldots, f(r-1), f(r))$. This is true because: Since all consecutive nodes are c...
[ "binary search", "data structures", "dfs and similar", "divide and conquer", "dsu", "greedy", "trees" ]
2,300
#include <bits/stdc++.h> using namespace std; struct dsu { vector<int> ds, wt; dsu(int n) { ds.assign(n, -1); wt.assign(n, INT_MAX); } int find(int i) { return ds[i] < 0 ? i : find(ds[i]); } void merge(int i, int j, int weight) { i = find(i), j = find(j); if (i != j) { if (ds[i] > ds[j]) swap(i...
1707
A
Doremy's IQ
Doremy is asked to test $n$ contests. Contest $i$ can only be tested on day $i$. The difficulty of contest $i$ is $a_i$. Initially, Doremy's IQ is $q$. On day $i$ Doremy will choose whether to test contest $i$ or not. She can only test a contest if her current IQ is strictly greater than $0$. If Doremy chooses to test...
Solution 1 We call contests that will decrease Doremy's IQ bad contests and the other good contests. In the best solution(testing the maximum number of contests), there is always an index $x$. Contest $i$ ($i < x$) is tested, if Contest $i$ is good; Contest $i$ ($i \ge x$) is tested, no matter what kind of contest it i...
[ "binary search", "constructive algorithms", "greedy", "implementation" ]
1,600
#include<cstdio> int a[100005],b[100005]; int main(){ int T; scanf("%d",&T); while(T--){ int n,iq; scanf("%d%d",&n,&iq); for(int i=1;i<=n;++i) scanf("%d",&a[i]); int sum=0,nq=0; for(int i=n;i>=1;--i){ if(a[i]<=nq)b[i]=1; else if(nq<iq)++nq,b[i]=1; else b[i]=0; } for(int i=1;i<=n;++i) p...
1707
B
Difference Array
You are given an array $a$ consisting of $n$ non-negative integers. It is guaranteed that $a$ is sorted from small to large. For each operation, we generate a new array $b_i=a_{i+1}-a_{i}$ for $1 \le i < n$. Then we sort $b$ from small to large, replace $a$ with $b$, and decrease $n$ by $1$. After performing $n-1$ op...
Let's prove that the brute-force solution (considering zeros differently) can pass. Define $S=\sum\limits_{i=1}^{n} a_i$ and it changes when an operation is performed. After sorting the array $a$ and ignoring $0$ s, the fact $\begin{aligned} n-1+a_n &\le S & (a_i \ge 1)\\ n-1 &\le S - a_n \end{aligned}$ is always true....
[ "brute force", "data structures", "implementation", "sortings" ]
1,900
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ch() getchar() #define pc(x) putchar(x) using namespace std; template<typename T>void read(T&x){ static char c;static int f; for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f; } templat...
1707
C
DFS Trees
You are given a connected undirected graph consisting of $n$ vertices and $m$ edges. The weight of the $i$-th edge is $i$. Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph: \begin{verbatim} vis := an array of length n s := a set of edges function dfs(u): vis[u] := true iterate through eac...
Minimum spanning tree is unique in the given graph. If $\operatorname{findMST}$(x) creates an MST, there is no cross edge in the graph. So if you can determine whether there is a cross edge starting DFS from every node, the problem is solved. Pay attention to every edge that is not in the MST. Let's focus on one single...
[ "dfs and similar", "dsu", "graphs", "greedy", "sortings", "trees" ]
2,400
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ch() getchar() #define pc(x) putchar(x) using namespace std; template<typename T>void read(T&x){ static char c;static int f; for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f; } templat...
1707
D
Partial Virtual Trees
Kawashiro Nitori is a girl who loves competitive programming. One day she found a rooted tree consisting of $n$ vertices. The root is vertex $1$. As an advanced problem setter, she quickly thought of a problem. Kawashiro Nitori has a vertex set $U=\{1,2,\ldots,n\}$. She's going to play a game with the tree and the set...
First ignore the requirement that the virtual tree cannot be the entire tree. Then we count the number of ways without this requirement for all $k$ using DP. $dp_{x,i}$ is the number of ways to delete everything in the subtree of $x$ in exact $i$ operations. Node $x$ must be deleted at some time $j \le i$ and all but a...
[ "combinatorics", "dfs and similar", "dp", "math", "trees" ]
3,000
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define __FILE(x)\ freopen(#x".in" ,"r" ,stdin);\ freopen(#x".out" ,"w" ,stdout) #define LL long long const int MX = 2000 + 23; LL MOD; using namespace std; int read(){ char k = getchar(); int x = 0; while(k < '0' || k > '9') k = get...
1707
E
Replace
You are given an integer array $a_1,\ldots, a_n$, where $1\le a_i \le n$ for all $i$. There's a "replace" function $f$ which takes a pair of integers $(l, r)$, where $l \le r$, as input and outputs the pair $$f\big( (l, r) \big)=\left(\min\{a_l,a_{l+1},\ldots,a_r\},\, \max\{a_l,a_{l+1},\ldots,a_r\}\right).$$ Consider...
Let $f([l,r])$ be the "replace" function. That means $f([l,r])=[\min\{a_i|l\le i\le r\},\max\{a_i|l\le i\le r\}]$. $f^k([l,r])$ means applying the function $k$ times. When $[a_1,b_1]\bigcap[a_2,b_2]\ne \emptyset$, Let $j=\max\{a_1,a_2\}$, then $j\in[a_1,b_1]$ and $j\in[a_{2},b_{2}]$. So $a_j\in f([a_1,b_1])$ and $a_j\i...
[ "binary search", "data structures" ]
3,500
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ch() getchar() #define pc(x) putchar(x) using namespace std; template<typename T>void read(T&x){ static char c;static int f; for(f=1,c=ch();c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch()){x=x*10+(c&15);}x*=f; } templ...
1707
F
Bugaboo
A transformation of an array of positive integers $a_1,a_2,\dots,a_n$ is defined by replacing $a$ with the array $b_1,b_2,\dots,b_n$ given by $b_i=a_i\oplus a_{(i\bmod n)+1}$, where $\oplus$ denotes the bitwise XOR operation. You are given integers $n$, $t$, and $w$. We consider an array $c_1,c_2,\dots,c_n$ ($0 \le c_...
We can first solve an easier condition when $n=2^h(h\ge 0)$. We know for any array $a_1,a_2,\ldots,a_{2^h}$, transforming it for $2^h$ times $a_i=0$. If you transform it more than $2^h$ times it is also guaranteed that $a_i=0$. So in this condition, if $t\ge 2^h$, we only need to test whether for all $i$, $c_i$ can be ...
[ "bitmasks", "constructive algorithms", "dp", "number theory" ]
3,500
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<assert.h> #define ch() getchar() #define pc(x) putchar(x) template<typename T>void read(T&x){ static char c;static int f; for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f; for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f; } template<...
1708
A
Difference Operations
You are given an array $a$ consisting of $n$ positive integers. You are allowed to perform this operation any number of times (possibly, zero): - choose an index $i$ ($2 \le i \le n$), and change $a_i$ to $a_i - a_{i-1}$. Is it possible to make $a_i=0$ for all $2\le i\le n$?
Solution 1 For all $i \ge 2$, $a_i$ is the multiple of $a_1$ is equivalent to the YES answer. Proof of necessity $a_2$ must be the multiple of $a_1$. Otherwise $a_2$ cannot become zero. In the whole process, $a_2$ is always the multiple of $a_1$. So $a_3$ must be the multiple of $a_1$. Otherwise $a_3$ cannot become zer...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define LL long long const LL MOD = 1e9 + 7; const int MX = 1e5 + 23; int read(){ char k = getchar(); LL x = 0; while(k < '0' || k > '9') k = getchar(); while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar(); return x; } int n ,a[...
1708
B
Difference of GCDs
You are given three integers $n$, $l$, and $r$. You need to construct an array $a_1,a_2,\dots,a_n$ ($l\le a_i\le r$) such that $\gcd(i,a_i)$ are all distinct or report there's no solution. Here $\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
$\gcd(i,a_i)\le i$. Because all $\gcd(i,a_i)$ are different, then $\gcd(i,a_i)=i$, which means $a_i$ is the multiple of $i$. To check if there is such $a_i$, just check if $a_i=\left(\lfloor \frac{l-1}{i} \rfloor +1\right)\cdot i$ (the minimum multiple of $i$ that is strictly bigger than $l-1$) is less than $r$. Time c...
[ "constructive algorithms", "math" ]
1,100
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define __FILE(x)\ freopen(#x".in" ,"r" ,stdin);\ freopen(#x".out" ,"w" ,stdout) #define LL long long const int MX = 1e5 + 23; const LL MOD = 998244353; int read(){ char k = getchar(); int x = 0; while(k < '0' || k > '9') k = getchar(); wh...
1709
A
Three Doors
There are three doors in front of you, numbered from $1$ to $3$ from left to right. Each door has a lock on it, which can only be opened with a key with the same number on it as the number on the door. There are three keys — one for each door. Two of them are hidden behind the doors, so that there is no more than one ...
Note that we never have a choice in what door should we open. First, we open the door with the same number as the key in our hand. Then, the door with the same number as the key behind the first opened door. Finally, the door with the same number as the key behind the second opened door. If any of the first and second ...
[ "brute force", "greedy", "implementation", "math" ]
800
for _ in range(int(input())): x = int(input()) a = [0] + [int(x) for x in input().split()] print("YES" if a[x] != 0 and a[a[x]] != 0 else "NO")
1709
B
Also Try Minecraft
You are beta testing the new secret Terraria update. This update will add quests to the game! Simply, the world map can be represented as an array of length $n$, where the $i$-th column of the world has height $a_i$. There are $m$ quests you have to test. The $j$-th of them is represented by two integers $s_j$ and $t...
So, the first idea that is coming into mind is prefix sums. Let's define two values $l_i = max(0, a_i - a_{i + 1})$ and $r_i = max(0, a_{i + 1} - a_i)$. The value $l_i$ means the amount of fall damage when we are going to the right from the column $i$ to the column $i + 1$, and $r_i$ means the amount of fall damage whe...
[ "data structures", "dp", "implementation" ]
900
n, m = map(int, input().split()) a = list(map(int, input().split())) l = [0] + [max(0, a[i] - a[i + 1]) for i in range(n - 1)] r = [0] + [max(0, a[i] - a[i - 1]) for i in range(1, n)] for i in range(n - 1): l[i + 1] += l[i] r[i + 1] += r[i] for _ in range(m): s, t = map(int, input().split()) if s < t: ...
1709
C
Recover an RBS
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: - bracket sequence...
There are many different approaches to this problem, but I think the model solution has the most elegant one. First of all, let's construct an RBS from the given string (it always exists, so it is always possible). By calculating the number of opening brackets, closing brackets and questions in the given string, we can...
[ "constructive algorithms", "greedy", "implementation", "strings" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { auto check = [](const string& s) { int bal = 0; for (char c : s) { if (c == '(') ++bal; if (c == ')') --bal; if (bal < 0) return false; } return bal == 0; }; ios::sync_with_stdio(false); cin.tie(0); int t; cin >>...
1709
D
Rorororobot
There is a grid, consisting of $n$ rows and $m$ columns. The rows are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. The $i$-th column has the bottom $a_i$ cells blocked (the cells in rows $1, 2, \dots, a_i$), the remaining $n - a_i$ cells are unblocked. A rob...
What if there were no blocked cells? Then the movement is easy. From cell $(x, y)$ we can go to cells $(x + k, y)$, $(x, y + k)$, $(x - k, y)$ or $(x, y - k)$. Thus, we can visit all cells that have the same remainder modulo $k$ over both dimensions. The answer would be "YES" if $x_s \bmod k = x_f \bmod k$ and $y_s \bm...
[ "binary search", "data structures", "greedy", "math" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n, m; scanf("%d%d", &n, &m); vector<int> a(m); forn(i, m) scanf("%d", &a[i]); int l = 0; while ((1 << l) <= m) ++l; vector<vector<int>> st(l, vector<int>(m)); forn(i, m) st[0][i] = a[i]; for ...
1709
E
XOR Tree
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$. Recall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tre...
To begin with, we note that there are no restrictions on the values that can be written on the vertices, so we can use numbers of the form $2^{30+x}$ for the $x$-th replacement. Then, if we replaced the value of a vertex, then no path passing through this vertex has weight $0$. Let's root the tree at the vertex number ...
[ "bitmasks", "data structures", "dfs and similar", "dsu", "greedy", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 13; int n; int a[N], b[N]; vector<int> g[N]; set<int> vals[N]; void init(int v, int p) { b[v] = a[v]; if (p != -1) b[v] ^= b[p]; for (int u : g[v]) if (u != p) init(u, v); } int ans; void calc(int v, int p) { bool bad = false; ...
1709
F
Multiset of Strings
You are given three integers $n$, $k$ and $f$. Consider all binary strings (i. e. all strings consisting of characters $0$ and/or $1$) of length from $1$ to $n$. For every such string $s$, you need to choose an integer $c_s$ from $0$ to $k$. A multiset of binary strings of length \textbf{exactly} $n$ is considered be...
First of all, let's visualize the problem in a different way. We have to set some constraints on the number of strings which have some kind of prefix. Let's think about a data structure that would allow us to understand it better. One of the most common data structures to store strings which works with their prefixes a...
[ "bitmasks", "brute force", "dp", "fft", "flows", "graphs", "math", "meet-in-the-middle", "trees" ]
2,500
null
1710
A
Color the Picture
A picture can be represented as an $n\times m$ grid ($n$ rows and $m$ columns) so that each of the $n \cdot m$ cells is colored with one color. You have $k$ pigments of different colors. You have a limited amount of each pigment, more precisely you can color at most $a_i$ cells with the $i$-th pigment. A picture is co...
The picture must consist of some stripes with at least $2$ rows or at least $2$ columns. When $n$ is odd and all $\lfloor \frac{a_i}{m} \rfloor=2$, we cannot draw a beautiful picture using row stripes. Let's first prove hint1 first. If there is a pair of toroidal neighbors with different colors. For example, $col_{x,y}...
[ "constructive algorithms", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; #define MAXN 100010 int n,m,k; int a[MAXN]; void work() { cin>>n>>m>>k; for (int i=1;i<=k;i++) cin>>a[i]; bool flag; long long tot=0; flag=0; tot=0; for (int i=1;i<=k;i++) { if (a[i]/n>2) flag=1; if (a[i]/n>=2) tot+=a[i]/n; } if (tot>=m && (flag || m%2...
1710
B
Rain
You are the owner of a harvesting field which can be modeled as an infinite line, whose positions are identified by integers. It will rain for the next $n$ days. On the $i$-th day, the rain will be centered at position $x_i$ and it will have intensity $p_i$. Due to these rains, some rainfall will accumulate; let $a_j$...
The maximum can always be achieved in the center position of one day's rain. $a_i$ is a piecewise linear function and the slope of $a_i$ will only change for $O(n)$ times. Supposing you know an invalid position $j$ where $a_j>m$, what are the properties of a rain that, if erase, makes it valid? Let's call position $j$ ...
[ "binary search", "brute force", "data structures", "geometry", "greedy", "implementation", "math" ]
2,100
#include <bits/stdc++.h> #define MAXN 200100 #define LL long long using namespace std; typedef pair<LL,LL> pll; LL n,m; LL x[MAXN],p[MAXN]; vector<pll> diff; pll key; pll getIntersection(pll p1,pll p2) { LL tx=max(p1.first+p1.second,p2.first+p2.second); LL ty=max(p1.second-p1.first,p2.second-p2.first); return {(tx...
1710
C
XOR Triangle
You are given a positive integer $n$. Since $n$ may be very large, you are given its binary representation. You should compute the number of triples $(a,b,c)$ with $0 \leq a,b,c \leq n$ such that $a \oplus b$, $b \oplus c$, and $a \oplus c$ are the sides of a non-degenerate triangle. Here, $\oplus$ denotes the bitwis...
Consider the same bit of three integers at the same time. $a\bigoplus b \leq a+b$ Define $cnt_{i_1 i_2 i_3}$ as: $j$th bit of $cnt_{i_1 i_2 i_3}$ is $1$ iif $i_1=a_j,i_2=b_j,i_3=c_j$ e.g. $a=(10)_2,b=(11)_2,c=(01)_2$ then $cnt_{110}=(10)_2,cnt_{011}=(01)_2$, other $cnt$ is 0. $a=cnt_{100}+cnt_{101}+cnt_{110}+cnt_{111}$...
[ "bitmasks", "brute force", "constructive algorithms", "dp", "greedy", "math" ]
2,500
#include <bits/stdc++.h> #define MAXN 200100 #define LL long long #define MOD 998244353 using namespace std; LL dp[MAXN][8][8]; string s; int main() { cin>>s; dp[0][0][0]=1; for (int i=0;i<s.size();i++) for (int mask1=0;mask1<8;mask1++) for (int mask2=0;mask2<8;mask2++) { dp[i][mask1][mask2]%=MOD; f...
1710
D
Recover the Tree
Rhodoks has a tree with $n$ vertices, but he doesn't remember its structure. The vertices are indexed from $1$ to $n$. A segment $[l,r]$ ($1 \leq l \leq r \leq n$) is good if the vertices with indices $l$, $l + 1$, ..., $r$ form a connected component in Rhodoks' tree. Otherwise, it is bad. For example, if the tree is...
Thank dario2994, the key part of the proof is from him. If interval $A,B$ are all good and $A \cap B \neq \emptyset$, then $A \cap B$ is good, too. If interval $A,B$ are all good and $A \cap B \neq \emptyset$, then $A \cup B$ is good, too. Consider enumerating good intervals according to their length. Let's consider th...
[ "constructive algorithms", "trees" ]
3,400
#include <bits/stdc++.h> using namespace std; #define MAXN 5100 typedef pair<int,int> pii; int n; char good[MAXN][MAXN]; int lv[MAXN],rv[MAXN]; vector<pii> ans; void work() { ans.clear(); cin>>n; for (int i=1;i<=n;i++) { lv[i]=rv[i]=i; cin>>(good[i]+i); } for (int len=2;len<=n;len++) for (int l=1;l<=n+1-l...
1710
E
Two Arrays
You are given two arrays of integers $a_1,a_2,\dots,a_n$ and $b_1,b_2,\dots,b_m$. Alice and Bob are going to play a game. Alice moves first and they take turns making a move. They play on a grid of size $n \times m$ (a grid with $n$ rows and $m$ columns). Initially, there is a rook positioned on the first row and fir...
Since they are very smart, they know the result of the game at the beginning. If the result is $x$, then Alice will end the game when Bob moves to a cell with score less than $x$, and something analogous holds for Bob. Thus, Alice can only move to a certain subset of cells, and the same holds for Bob. Knowing the above...
[ "binary search", "games", "graph matchings" ]
2,400
#include <bits/stdc++.h> using ll=long long; using std::cin; using std::cerr; using std::cout; using std::min; using std::max; template<class T> void ckmx(T &A,T B){ A<B?A=B:B; } const int N=2e5+7; int n,m,va,vb; int a[N],b[N]; int da[N],db[N]; bool check(int x){ ll sm=0,f1=0,f2=0; for(int j=m,i=0;j>=1;--j){ ...
1711
A
Perfect Permutation
You are given a positive integer $n$. The weight of a permutation $p_1, p_2, \ldots, p_n$ is the number of indices $1\le i\le n$ such that $i$ divides $p_i$. Find a permutation $p_1,p_2,\dots, p_n$ with the minimum possible weight (among all permutations of length $n$). A permutation is an array consisting of $n$ dis...
The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$.
[ "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; }
1711
B
Party
A club plans to hold a party and will invite some of its $n$ members. The $n$ members are identified by the numbers $1, 2, \dots, n$. If member $i$ is not invited, the party will gain an unhappiness value of $a_i$. There are $m$ pairs of friends among the $n$ members. As per tradition, if both people from a friend pai...
See the party as a graph. Divide the vertices into two categories according to their degrees' parity. Let's consider the case where $m$ is odd only, since if $m$ is even the answer is $0$. Assume that you delete $x$ vertices with even degrees and $y$ vertices with odd degrees. If $y \geq 1$, then only deleting one vert...
[ "brute force", "graphs" ]
1,300
#include <bits/stdc++.h> using namespace std; #define MAXN 100010 int x[MAXN],y[MAXN],a[MAXN],degree[MAXN]; int n,m; void work() { cin>>n>>m; for (int i=1;i<=n;i++) { degree[i]=0; cin>>a[i]; } for (int i=1;i<=m;i++) { cin>>x[i]>>y[i]; degree[x[i]]++; degree[y[i]]++; } int ans=INT_MAX; if (m%2==0) a...
1712
A
Wonderful Permutation
\begin{quote} God's Blessing on This PermutationForces! \hfill A Random Pebble \end{quote} You are given a permutation $p_1,p_2,\ldots,p_n$ of length $n$ and a positive integer $k \le n$. In one operation you can choose two indices $i$ and $j$ ($1 \le i < j \le n$) and swap $p_i$ with $p_j$. Find the minimum number ...
For any permutation $p$ of length $n$, the final sum $p_1 + p_2 + \ldots + p_k$ after some number of operations can't be less than $1 + 2 + \ldots + k$. This means that we need to apply the operation at least once for every $i$ such that $1 \le i \le k$ and $p_i > k$. Every time we apply it, we have to choose some inde...
[ "greedy", "implementation" ]
800
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { ...
1712
B
Woeful Permutation
\begin{quote} I wonder, does the falling rain \end{quote} \begin{quote} Forever yearn for it's disdain? \hfill Effluvium of the Mind \end{quote} You are given a positive integer $n$. Find any permutation $p$ of length $n$ such that the sum $\operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorn...
A well know fact is that $\gcd(a,b) \cdot \operatorname{lcm}(a,b) = a \cdot b$ for any two positive integers $a$ and $b$. Since $\gcd(x, x + 1) = 1$ for all positive $x$, we get that $\operatorname{lcm}(x,x+1) = x \cdot (x + 1)$. All of this should hint that for even $n$, the optimal permutation looks like this: $2,1,4...
[ "constructive algorithms", "greedy", "number theory" ]
800
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { ...
1712
C
Sort Zero
\begin{quote} An array is sorted if it has no inversions \hfill A Young Boy \end{quote} You are given an array of $n$ \textbf{positive} integers $a_1,a_2,\ldots,a_n$. In one operation you do the following: - Choose \textbf{any} integer $x$. - For all $i$ such that $a_i = x$, do $a_i := 0$ (assign $0$ to $a_i$). Fin...
An array is sorted in non-decreasing order if and only if there is no index $i$ such that $a_i > a_{i + 1}$. This leads to a strategy: while there is at least one such index $i$, apply one operation with $x = a_i$. Why is this optimal? Since our operation can only decrease values, and we must decrease $a_i$ so that $a_...
[ "greedy", "sortings" ]
1,100
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--)...
1712
D
Empty Graph
\begin{quote} — Do you have a wish? \end{quote} \begin{quote} — I want people to stop gifting each other arrays. \hfill O_o and Another Young Boy \end{quote} An array of $n$ \textbf{positive} integers $a_1,a_2,\ldots,a_n$ fell down on you from the skies, along with a positive integer $k \le n$. You can apply the fol...
First of all, we will always use the operation to assign $10^9$ to $a_i$. 1. Suppose $u < v$. Then $\operatorname{d}(u, v) = \min(\min(a_u \ldots a_v), 2 \cdot \min(a_1 \ldots a_n))$. Proof: since the weight of an edge is always $\ge \min(a_1 \ldots a_n)$, the best we can do with one edge is $\min(a_u \ldots a_v)$. And...
[ "binary search", "constructive algorithms", "data structures", "greedy", "shortest paths" ]
2,000
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const int inf = 1000000000; bool f(vector<int> a, int k, int ans) { int n = gsize(a); ...
1712
E2
LCM Sum (hard version)
\begin{quote} We are sum for we are many \hfill Some Number \end{quote} \textbf{This version of the problem differs from the previous one only in the constraint on $t$. You can make hacks only if both versions of the problem are solved.} You are given two positive integers $l$ and $r$. Count the number of distinct t...
Let's count the number of bad triplets that don't satisfy the condition, i.e. $\operatorname{lcm}(i,j,k) < i + j + k$. Then the answer for one test case is $\frac{(r - l + 1) \cdot (r - l) \cdot (r - l - 1)}{6} -$ the number of bad triplets. Since $i < j < k$, a triplet is bad only when $\operatorname{lcm}(i,j,k) = k$ ...
[ "brute force", "data structures", "math", "number theory", "two pointers" ]
2,500
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const int maxn = 200000; int t[(maxn + 1) * 4]; void update(int v, int tl, int tr,...
1712
F
Triameter
\begin{quote} — What is my mission? \end{quote} \begin{quote} — To count graph diameters. \hfill You and Your Submission \end{quote} A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The degree of a vertex is the number of edges connected to this vertex. You a...
We will solve the problem independently $q$ times. Let $f_v$ be the distance to the closest leaf from vertex $v$, can be found using a simple bfs with multiple start sources. Let $d'(u, v)$ be the distance in the resulting graph. Then $d'(u, v) = \min(f_u + f_v + x, d(u, v))$. A short proof: we'll either go through an ...
[ "binary search", "data structures", "dfs and similar", "trees" ]
3,200
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const int maxn = 1000000; int f[maxn], d[maxn]; vector<int> g[maxn], g2[maxn], val[maxn]...
1713
A
Traveling Salesman Problem
You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down). More formally, if you are standing at the point $(x, y)$, you can: - go left, and move to $(x - 1, y)$, or - go right, and move to $(x + 1, y)$, or - go up...
Suppose we only have boxes on the $Ox+$ axis, then the optimal strategy is going in the following way: $(0, 0), (x_{max}, 0), (0, 0)$. There is no way to do in less than $2 \cdot |x_{max}|$ moves. What if we have boxes on two axis? Let's assume it is $Oy+$, suppose we have a strategy to go in the following way: $(0, 0)...
[ "geometry", "greedy", "implementation" ]
800
def solve(): n = int(input()) minX, minY, maxX, maxY = 0, 0, 0, 0 for i in range(n): x, y = list(map(int, input().split())) minX = min(x, minX) maxX = max(x, maxX) minY = min(y, minY) maxY = max(y, maxY) print(2 * (maxX + maxY - minX - minY)) test = int(input())...
1713
B
Optimal Reduction
Consider an array $a$ of $n$ positive integers. You may perform the following operation: - select two indices $l$ and $r$ ($1 \leq l \leq r \leq n$), then - decrease all elements $a_l, a_{l + 1}, \dots, a_r$ by $1$. Let's call $f(a)$ the minimum number of operations needed to change array $a$ into an array of $n$ ze...
Let's call $M = max(a_1, a_2, \dots, a_n)$. The problem asks us to make all its elements become $0$ in some operations. And for each operation, we subtract each elements in an subarray by $1$. Thus, every largest elements of the array have to be decreased in at least $M$ operations. And also because of that, $min(f(p))...
[ "constructive algorithms", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, a[N]; int main() { int tc; for (cin >> tc; tc--; ) { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; int preLen = 1; while (preLen < n && a[preLen] <= a[preLen + 1]) preLen...
1713
C
Build Permutation
A \textbf{$\mathbf{0}$-indexed} array $a$ of size $n$ is called good if for all valid indices $i$ ($0 \le i \le n-1$), $a_i + i$ is a perfect square$^\dagger$. Given an integer $n$. Find a permutation$^\ddagger$ $p$ of $[0,1,2,\ldots,n-1]$ that is good or determine that no such permutation exists. $^\dagger$ An integ...
First, let's prove that the answer always exists. Let's call the smallest square number that is not smaller than $k$ is $h$. Therefore $h \leq 2 \cdot k$, which means $h - k \leq k$. Proof. So we can fill $p_i = h - i$ for $(h - k \leq i \leq k)$. Using this method we can recursively reduce $k$ to $h - k - 1$, then all...
[ "constructive algorithms", "dp", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, ans[N]; void recurse(int r) { if (r < 0) return; int s = sqrt(2*r); s *= s; int l = s - r; recurse(l - 1); for (; l <= r; l++, r--) { ans[l] = r; ans[r] = l; } } int main() { int tc; cin >> tc; while (tc--) { cin >> n; recurse(n ...
1713
D
Tournament Countdown
This is an interactive problem. There was a tournament consisting of $2^n$ contestants. The $1$-st contestant competed with the $2$-nd, the $3$-rd competed with the $4$-th, and so on. After that, the winner of the first match competed with the winner of second match, etc. The tournament ended when there was only one c...
There is a way to erase $3$ participants in every $2$ queries. Since there are $2^n - 1$ participants to be removed, the number of queries will be $\left \lceil (2^n - 1) \cdot \frac{2}{3} \right \rceil = \left \lfloor \frac{2^{n + 1}}{3} \right \rfloor$. Suppose there are only $4$ participants. In the first query we w...
[ "constructive algorithms", "greedy", "interactive", "number theory", "probabilities" ]
1,800
#include <bits/stdc++.h> using namespace std; int ask(vector<int> &k) { cout << "? " << k[0] << ' ' << k[2] << endl; int x; cin >> x; if (x == 1) { cout << "? " << k[0] << ' ' << k[3] << endl; cin >> x; if (x == 1) return k[0]; return k[3]; } else if (x == 2) { cout << "? " << k[1] << ' ' << k[2] <<...
1713
E
Cross Swapping
You are given a square matrix $A$ of size $n \times n$ whose elements are integers. We will denote the element on the intersection of the $i$-th row and the $j$-th column as $A_{i,j}$. You can perform operations on the matrix. In each operation, you can choose an integer $k$, then for each index $i$ ($1 \leq i \leq n$...
Let's take a look at what the lexicographically smallest matrix is. Let's call $(x, y)$ a cell that is in the intersection of row $x$ and column $y$ of the matrix, and the integer written on that cell is $A_{x, y}$. A cell $(x_p, y_p)$ of this matrix is called more significant than the another cell $(x_q, y_q)$ if and ...
[ "2-sat", "data structures", "dsu", "greedy", "matrices" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 2e3 + 5; int n, a[N][N]; int par[N]; int getPar(int u) { if (u < 0) return -getPar(-u); if (u == par[u]) return u; return par[u] = getPar(par[u]); } void join(int u, int v) { u = getPar(u); v = getPar(v); if (abs(u) != abs(v)) { ...
1713
F
Lost Array
\begin{quote} {{My orzlers, we can optimize this problem from $O(S^3)$ to $O\left(T^\frac{5}{9}\right)$!}} \hfill — Spyofgame, founder of Orzlim religion \end{quote} A long time ago, Spyofgame invented the famous array $a$ ($1$-indexed) of length $n$ that contains information about the world and life. After that, he d...
First, we can see that $a_i$ contribute $\binom{(n - i) + (j - 1)}{j - 1}$ times to $b_{j, n}$, which can calculate similar to Pascal's Triangle. It's easy to see that the value that $a_i$ contribute to $b_{j, n}$ equal to $a_i$ when $\binom{(n - i) + (j - 1)}{j - 1}$ is odd, $0$ otherwise. Let's solve the inverse prob...
[ "bitmasks", "combinatorics", "constructive algorithms", "dp", "math" ]
2,900
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define endl '\n' #define fi first #define se second #define For(i, l, r) for (auto i = (l); i < (r); i++) #define ForE(i, l, r) for (auto i = (l); i <= (r); i++) #def...