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
1747
E
List Generation
For given integers $n$ and $m$, let's call a pair of arrays $a$ and $b$ of integers \textbf{good}, if they satisfy the following conditions: - $a$ and $b$ have the same length, let their length be $k$. - $k \ge 2$ and $a_1 = 0, a_k = n, b_1 = 0, b_k = m$. - For each $1 < i \le k$ the following holds: $a_i \geq a_{i - ...
Change your point of view from array to grid. Think of pair of arrays as paths in grid of size $(n + 1) \times (m + 1)$. First try counting number of good pair of arrays. Number of good pairs of arrays comes out to be $\sum\limits_{k = 0}{k = \min(n,m} \binom{n}{k} \cdot \binom{m}{k} \cdot 2^{n + m - k - 1}$ Given prob...
[ "combinatorics", "dp", "math" ]
2,900
// Jai Shree Ram #include<bits/stdc++.h> using namespace std; #define rep(i,a,n) for(int i=a;i<n;i++) #define ll long long #define int long long #define pb push_back #define all(v) v.begin(),v.end() #define endl "\n" #define x first #define y ...
1748
A
The Ultimate Square
You have $n$ rectangular wooden blocks, which are numbered from $1$ to $n$. The $i$-th block is $1$ unit high and $\lceil \frac{i}{2} \rceil$ units long. Here, $\lceil \frac{x}{2} \rceil$ denotes the result of division of $x$ by $2$, rounded \textbf{up}. For example, $\lceil \frac{4}{2} \rceil = 2$ and $\lceil \frac{5...
If $n$ is odd, it is possible to create a square using all $n$ blocks. If $n$ is even, it is possible to create a square using only the first $n-1$ blocks, since $n-1$ is odd. Can we use the last block to create a larger square? If $n$ is odd, let $k=\frac{n+1}{2}$ be the width of the last block. It is possible to crea...
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; typedef long long ll; void testcase(){ ll n; cin>>n; cout<<(n+1)/2<<'\n'; } int main() { ll t; cin>>t; while(t--) testcase(); return 0; }
1748
B
Diverse Substrings
A non-empty digit string is diverse if the number of occurrences of each character in it doesn't exceed the number of distinct characters in it. For example: - string "7" is diverse because 7 appears in it $1$ time and the number of distinct characters in it is $1$; - string "77" is \textbf{not} diverse because 7 app...
What is the maximum number of distinct characters in a diverse string? What is the maximum frequency of a character in a diverse string? What is the maximum possible length a diverse string? In a diverse string, there are at most $10$ distinct characters: '0', '1', $\ldots$, '9'. Therefore, each of these characters can...
[ "brute force", "implementation", "strings" ]
1,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; void tc(){ ll n; string s; cin>>n>>s; ll ans=0; for(ll i=0;i<s.size();i++){ int fr[10]{}, distinct=0, max_freq=0; for(ll j=i;j<s.size() && (++fr[s[j]-'0'])<=10;j++){ max_freq=max(max_freq,fr[s[j]-'0'...
1748
C
Zero-Sum Prefixes
The score of an array $v_1,v_2,\ldots,v_n$ is defined as the number of indices $i$ ($1 \le i \le n$) such that $v_1+v_2+\ldots+v_i = 0$. You are given an array $a_1,a_2,\ldots,a_n$ of length $n$. You can perform the following operation multiple times: - select an index $i$ ($1 \le i \le n$) such that $a_i=0$; - then ...
What is the answer if $a_1=0$ and $a_i \neq 0$ for all $2 \le i \le n$? What is the answer if $a_i=0$ and $a_j \neq 0$ for all $1 \le j \le n$, $j \neq i$? What is the answer if there are only two indices $i$ and $j$ for which $a_i=a_j=0$? Let's consider the prefix sum array $s=[a_1,a_1+a_2,\ldots,a_1+a_2+\ldots+a_n]$....
[ "brute force", "data structures", "dp", "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll MAXN=2e5+5; ll a[MAXN]; map<ll,ll> freq; void tc(){ ll n; cin>>n; ll maxfr=0,current_sum=0,ans=0; bool found_wildcard=0; freq.clear(); for(ll i=0;i<n;i++){ cin>>a[i]; if(a[i]==0){ if(fo...
1748
D
ConstructOR
You are given three integers $a$, $b$, and $d$. Your task is to find any integer $x$ which satisfies all of the following conditions, or determine that no such integers exist: - $0 \le x \lt 2^{60}$; - $a|x$ is divisible by $d$; - $b|x$ is divisible by $d$. Here, $|$ denotes the bitwise OR operation.
If at least one of $a$ and $b$ is odd, and $d$ is even, then there are no solutions. Without loss of generality, we will only consider the case when $a$ is odd and $d$ is even. Since the last bit of $a$ is $1$, then the last bit of $a|x$ must also be $1$. Therefore, $a|x$ cannot be a multiple of $d$, as $a|x$ is odd, w...
[ "bitmasks", "chinese remainder theorem", "combinatorics", "constructive algorithms", "math", "number theory" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; void tc(){ ll a,b,d,k=0,inverse_of_2,total_inverse=1; cin>>a>>b>>d; a|=b; if(a%d==0){ cout<<a<<'\n'; return; } while(a%2==0 && d%2==0) a/=2,d/=2,k++; inverse_of_2=(d+1)/2; if(a%2==1 && d%2==0){ ...
1748
E
Yet Another Array Counting Problem
The position of the leftmost maximum on the segment $[l; r]$ of array $x = [x_1, x_2, \ldots, x_n]$ is the smallest integer $i$ such that $l \le i \le r$ and $x_i = \max(x_l, x_{l+1}, \ldots, x_r)$. You are given an array $a = [a_1, a_2, \ldots, a_n]$ of length $n$. Find the number of integer arrays $b = [b_1, b_2, \l...
Let $m$ be the position of the leftmost maximum on the segment $[1;n]$. If $l \le m \le r$, then the position of the leftmost maximum on the segment $[l;r]$ is equal to $m$. If $l \le m \le r$, then the position of the leftmost maximum on the segment $[l;r]$ is equal to $m$. If $l \le r \lt m$, then the leftmost maximu...
[ "binary search", "data structures", "divide and conquer", "dp", "flows", "math", "trees" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll NMAX=2e5+5,LGMAX=18,MOD=1e9+7; int n,m; int leftmost_maximum[LGMAX][NMAX],msb[NMAX]; int v[NMAX]; vector<vector<ll>> dp,sum; int leftmost_maximum_query(int l, int r){ int bit=msb[r-l+1]; if(v[leftmost_maximum[bit][l]]>=v[leftmost_m...
1748
F
Circular Xor Reversal
You have an array $a_0, a_1, \ldots, a_{n-1}$ of length $n$. Initially, $a_i = 2^i$ for all $0 \le i \lt n$. Note that array $a$ is zero-indexed. You want to reverse this array (that is, make $a_i$ equal to $2^{n-1-i}$ for all $0 \le i \lt n$). To do this, you can perform the following operation no more than $250\,000...
How can we perform $a_i=a_i \oplus a_j$ for any $0 \le i,j \lt n$, $i \neq j$? We can swap the values of $a_i$ and $a_j$ by performing the following sequence of xor assignments: $a_i=a_i \oplus a_j$; $a_j=a_j \oplus a_i$; $a_i=a_i \oplus a_j$; Performing $a_i=a_i \oplus a_j$ on its own is pretty wasteful, as it require...
[ "bitmasks", "constructive algorithms" ]
3,000
#include <bits/stdc++.h> using namespace std; vector<int> ans; int n; void add_op(int pos){ ans.push_back(pos%n); } void f(int l, int r){ if(r<l) r+=n; int m=r-l,direction=0,start=l; r--; while(l<=r){ if(direction==0){ for(int i=r;i>=l;i--) add_op(i); ...
1749
A
Cowardly Rooks
There's a chessboard of size $n \times n$. $m$ rooks are placed on it in such a way that: - no two rooks occupy the same cell; - no two rooks attack each other. A rook attacks all cells that are in its row or column. Is it possible to move \textbf{exactly one} rook (you can choose which one to move) into a different...
First, note that $m$ is always less than or equal to $n$. If there were at least $n+1$ rooks on the board, at least two of them would share a row or a column (by pigeonhole principle). If $m < n$, then there is always at least one free row and at least one free column. You can move any rook into that row or column. Oth...
[ "greedy", "implementation" ]
800
#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); forn(_, t){ int n, m; scanf("%d%d", &n, &m); vector<pair<int, int>> a(m); forn(i, m){ scanf("%d%d", &a[i].first, &a[i].second)...
1749
B
Death's Blessing
You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $n$ monsters standing in the row, numbered from $1$ to $n$. The $i$-th monster has $a_i$ health and a special "Death's Blessing" spell of strength $b_i$ attached to it. You are going to kill a...
Note that whichever order you choose, the total time will always contain all initial health $a_i$, in other words, any answer will contain $\sum_{i=1}^{n}{a_i}$ as its part. So the lower the sum of $b_i$ you will add to the answer - the better. Look at some monster $i$. If you kill it while it has both left and right n...
[ "greedy" ]
900
fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toLong() } val b = readLine()!!.split(' ').map { it.toLong() } println(a.sum() + b.sum() - b.maxOrNull()!!) } }
1749
C
Number Game
Alice and Bob are playing a game. They have an array of positive integers $a$ of size $n$. Before starting the game, Alice chooses an integer $k \ge 0$. The game lasts for $k$ stages, the stages are numbered from $1$ to $k$. During the $i$-th stage, Alice must remove an element from the array that is less than or equa...
Note that if Bob has increased some element, then Alice can't remove it on the next stages. Obviously, it is more profitable for Bob to "prohibit" the smallest element of the array. Using this fact, we can iterate over the value of $k$, and then simulate the game process. To simulate the game, we can maintain the set o...
[ "binary search", "data structures", "games", "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; int ans = 0; for (int k = 1; k <= n; ++k) { multiset<int> s(a.begin(), a.end()); for (int i = 0; i < k; ++i) { auto ...
1749
D
Counting Arrays
Consider an array $a$ of length $n$ with elements numbered from $1$ to $n$. It is possible to remove the $i$-th element of $a$ if $gcd(a_i, i) = 1$, where $gcd$ denotes the greatest common divisor. After an element is removed, the elements to the right are shifted to the left by one position. An array $b$ with $n$ int...
We will calculate the answer by subtracting the number of arrays which have only one removal sequence from the total number of arrays. The latter is very simple - it's just $m^1 + m^2 + \dots + m^n$. How do we calculate the number of unambiguous arrays? We can always delete the $1$-st element of an array; so, $[1, 1, 1...
[ "combinatorics", "dp", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; 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 sub(int x, int y) { return add(x, -y); } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, ...
1749
E
Cactus Wall
Monocarp is playing Minecraft and wants to build a wall of cacti. He wants to build it on a field of sand of the size of $n \times m$ cells. Initially, there are cacti in some cells of the field. \textbf{Note that, in Minecraft, cacti cannot grow on cells adjacent to each other by side — and the initial field meets thi...
In order to block any path from the top row to the bottom row, you have to build a path from the left side to the right side consisting of '#'. Since two consecutive cacti in a path cannot be placed side by side, they should be placed diagonally (i.e $(x, y)$ should be followed by $(x \pm 1, y \pm 1)$ on the path). So ...
[ "constructive algorithms", "dfs and similar", "graphs", "shortest paths" ]
2,400
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int dx[] = {0, 1, 0, -1, 1, 1, -1, -1}; int dy[] = {1, 0, -1, 0, -1, 1, -1, 1}; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<string> s(n); for (auto &it ...
1749
F
Distance to the Path
You are given a tree consisting of $n$ vertices. Initially, each vertex has a value $0$. You need to perform $m$ queries of two types: - You are given a vertex index $v$. Print the value of the vertex $v$. - You are given two vertex indices $u$ and $v$ and values $k$ and $d$ ($d \le 20$). You need to add $k$ to the v...
For the purpose of solving the task, let's choose some root in the tree and introduce another operation to the tree: add $k$ to all vertices that are in the subtree of the given vertex $v$ and on the distance $d$ from $v$. For example, if $d = 0$, it's $v$ itself or if $d = 1$ then it's all children of $v$. Let's $p[v]...
[ "data structures", "dfs and similar", "trees" ]
2,800
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const int N = int(2e5) + 55; const int LOG = 18; int n; vector<int> g[N]; inl...
1750
A
Indirect Sort
You are given a permutation $a_1, a_2, \ldots, a_n$ of size $n$, where each integer from $1$ to $n$ appears \textbf{exactly once}. You can do the following operation any number of times (possibly, zero): - Choose any three indices $i, j, k$ ($1 \le i < j < k \le n$). - If $a_i > a_k$, replace $a_i$ with $a_i + a_j$. ...
We claim that we can sort the array if and only if $a_1 = 1$. Necessity We can notice that index $1$ cannot be affected by any swap operation. Let's see what happens to the value $1$. According to the definition of the operation, it can either increase or be swapped. In order to be increased, there must exist some $k$ ...
[ "constructive algorithms", "implementation", "math" ]
800
"#include<bits/stdc++.h>\nusing namespace std;\nint t,n,a[109];\ninline int read(){\n\tint s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\...
1750
B
Maximum Substring
A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $s$. For some non-empty substring$^\dagger$ $t$ of string $s$ containing $x$ characters 0 and $y$ characters 1, define its cost as: - $x \cdot y$, if $x > 0$ and $y > 0$; - $x^2$, if $x > 0$ and $y = 0$; - $y^2$, if $...
Considering that if we want to find the max value of $x \cdot y$, then the whole string is the best to calculate, for it $0$ s and $1$ s are the max. Then considering $x \cdot x$ and $y \cdot y$ : what we need to do is to calculate the max continuous number of $0$ or $1$, compare its square to the first condition, then...
[ "brute force", "greedy", "implementation" ]
800
"#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\nint32_t main()\n{\n\tcin.tie(nullptr)->ios_base::sync_with_stdio(false);\n\tint q;\n\tcin >> q;\n\twhile (q--)\n\t{\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\ts = '$' + s;\n\t\tint cnt0 = 0, cnt1 = 0;\n\t\tfor (int i = 1; i <= n; ++i)\n\t\...
1750
C
Complementary XOR
You have two binary strings $a$ and $b$ of length $n$. You would like to make all the elements of both strings equal to $0$. Unfortunately, you can modify the contents of these strings using only the following operation: - You choose two indices $l$ and $r$ ($1 \le l \le r \le n$); - For every $i$ that respects $l \le...
For each operation, the interval changed by a sequence and b sequence is complementary, so you must judge whether all $[a_i=b_i]$ are the same at the beginning. If they are different, you can't have a solution. Now, if $a = \neg b$, we can do an operation on $a$ and have $a=b$. Now suppose $a_i=b_i=1$ for some $i$ and ...
[ "constructive algorithms", "implementation" ]
1,400
"#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tcin.tie(nullptr)->sync_with_stdio(false);\n\tint q;\n\tcin >> q;\n\twhile (q--)\n\t{\n\t\tint n;\n\t\tstring a, b;\n\t\tcin >> n >> a >> b;\n\t\ta = '$' + a;\n\t\tb = '$' + b;\n\t\tbool ok = true;\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t{\n\t\t\tif (a[i] ...
1750
D
Count GCD
You are given two integers $n$ and $m$ and an array $a$ of $n$ integers. For each $1 \le i \le n$ it holds that $1 \le a_i \le m$. Your task is to count the number of different arrays $b$ of length $n$ such that: - $1 \le b_i \le m$ for each $1 \le i \le n$, and - $\gcd(b_1,b_2,b_3,...,b_i) = a_i$ for each $1 \le i \...
We can notice that if for some $2 \le i \le n$, $a_{i-1}$ is not divisible by $a_{i}$, then the answer is $0$. Else, note that all the prime factors of $a_1$ are also prime factors in all the other values. Thus after factorizing $a_1$ we can quickly factorize every other value. Now let's find the number of ways we can ...
[ "combinatorics", "math", "number theory" ]
1,800
"#include <bits/stdc++.h>\nusing namespace std;\nint mod = 998244353;\nstruct Mint\n{\n int val;\n Mint(int _val = 0)\n {\n val = _val % mod;\n }\n Mint(long long _val = 0)\n {\n val = _val % mod;\n }\n Mint operator+(Mint oth)\n {\n return val + oth.val;\n }\n Mint...
1750
E
Bracket Cost
Daemon Targaryen decided to stop looking like a Metin2 character. He turned himself into the most beautiful thing, a bracket sequence. For a bracket sequence, we can do two kind of operations: - Select one of its substrings$^\dagger$ and cyclic shift it to the right. For example, after a cyclic shift to the right, "(...
Let $a_i=1$ if $s_i=($, $a_i=-1$ if $s_i=)$ and $b_i$ be the prefix sum of $a_i$. Theorem: the cost of $s[l+1,r]$ is $max(b_l,b_r)-min(b_l,b_{l+1},...,b_r)$ Necessity: after one operation, $max(b_l,b_r)-min(b_l,b_{l+1},...,b_r)$ decrease at most one. Sufficiency: If $b_l<b_r$, we can do operation 2, add a right bracket...
[ "binary search", "data structures", "divide and conquer", "dp", "greedy", "strings" ]
2,400
"#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\nstruct bit\n{\n\tvector<int> a;\n\tvoid resize(int n)\n\t{\n\t\ta = vector<int>(n + 1);\n\t}\n\tvoid update(int pos, int val)\n\t{\n\t\tint n = (int)a.size() - 1;\n\t\tfor (int i = pos; i <= n; i += i & (-i))\n\t\t{\n\t\t\ta[i] += val;\n\t\t}\n\t}\...
1750
F
Majority
Everyone was happy coding, until suddenly a power shortage happened and the best competitive programming site went down. Fortunately, a system administrator bought some new equipment recently, including some UPSs. Thus there are some servers that are still online, but we need all of them to be working in order to keep ...
First off, let's try to reduce the given operation to a simpler form. We claim that if it is possible to make the string $111...111$ using the specified operation, we can make it $111...111$ by doing the following new operation : Select two indices $(i,j)$ such that the substring $s_{i...j}$ looks like this $111..100.....
[ "combinatorics", "dp", "math", "strings" ]
2,700
"#include <bits/stdc++.h>\nusing namespace std;\nint p2[5001], dp[5001][5001], sum[5001][5001], sum2[5001][5001];\nint32_t main()\n{\n int n, mod;\n cin >> n >> mod;\n p2[0] = 1;\n for (int i = 1; i <= n; ++i)\n {\n p2[i] = p2[i - 1] + p2[i - 1];\n if (p2[i] >= mod)\n {\n ...
1750
G
Doping
We call an array $a$ of length $n$ fancy if for each $1 < i \le n$ it holds that $a_i = a_{i-1} + 1$. Let's call $f(p)$ applied to a permutation$^\dagger$ of length $n$ as the \textbf{minimum} number of subarrays it can be partitioned such that each one of them is fancy. For example $f([1,2,3]) = 1$, while $f([3,1,2])...
Consider a permutation $p$ that lexicographically smaller than given permutation, assume the first different position is $k$, if we fix $p_k$, the remaining numbers $a_{k+1},a_{k+2},...,a_n$ can be arranged in any order. Denote $S$ as the set of remaining numbers. Let $m$ be the number of consecutive pairs, $m=|{x|x \i...
[ "combinatorics", "dp", "math" ]
3,300
"#include <bits/stdc++.h>\nusing namespace std;\nint mod;\nclass Mint\n{\npublic:\n int val;\n Mint(int _val = 0)\n {\n val = _val % mod;\n }\n Mint(long long _val)\n {\n val = _val % mod;\n }\n Mint operator+(Mint oth)\n {\n return val + oth.val;\n }\n Mint operato...
1750
H
BinaryStringForces
You are given a binary string $s$ of length $n$. We define a maximal substring as a substring that cannot be extended while keeping all elements equal. For example, in the string $11000111$ there are three maximal substrings: $11$, $000$ and $111$. In one operation, you can select two maximal adjacent substrings. Sinc...
We call a maximal sequence of $0$ a $0$ block, a maximal sequence of $1$ a $1$ block. For each $i$, store some disjoint intervals with the following property: For each $j$ that $i<=j$ and $s[j]=1$, j is in one of the intervals if and only if $(i,j)$ is a good substring. We can prove the number of intervals for each $i$...
[ "constructive algorithms", "data structures", "dp" ]
3,500
"#include <bits/stdc++.h>\nusing namespace std;\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\nint random(int st, int dr)\n{\n uniform_int_distribution<mt19937::result_type> gen(st, dr);\n return gen(rng);\n}\nvector<int> lg;\nstruct bit\n{\n vector<int> b;\n void resize(int n)\n {\n ...
1753
A1
Make Nonzero Sum (easy version)
\textbf{This is the easy version of the problem. The difference is that in this version the array can not contain zeros. You can make hacks only if both versions of the problem are solved.} You are given an array $[a_1, a_2, \ldots a_n]$ consisting of integers $-1$ and $1$. You have to build a partition of this array ...
If the sum of all elements of the array is odd, the partitions does not exist because the partition does not affect the parity of the sum. Otherwise the answer exists. Let's build such construction. As the sum of all elements is even, $n$ is even too. Consider pairs of elements with indices $(1, 2)$, $(3, 4)$, ..., $(n...
[ "constructive algorithms", "dp", "greedy" ]
1,300
null
1753
A2
Make Nonzero Sum (hard version)
\textbf{This is the hard version of the problem. The difference is that in this version the array contains zeros. You can make hacks only if both versions of the problem are solved.} You are given an array $[a_1, a_2, \ldots a_n]$ consisting of integers $-1$, $0$ and $1$. You have to build a partition of this array in...
If the sum of all numbers in the array is odd, then splitting is impossible, because splitting does not affect the evenness of the sum. Otherwise, we will build the answer constructively. Suppose we have considered some kind of array prefix. Let's keep going until we get exactly $2$ non-zero numbers. We want to make th...
[ "constructive algorithms", "dp", "greedy" ]
1,500
null
1753
B
Factorial Divisibility
You are given an integer $x$ and an array of integers $a_1, a_2, \ldots, a_n$. You have to determine if the number $a_1! + a_2! + \ldots + a_n!$ is divisible by $x!$. Here $k!$ is a factorial of $k$ — the product of all positive integers less than or equal to $k$. For example, $3! = 1 \cdot 2 \cdot 3 = 6$, and $5! = 1...
Let's create an array $[cnt_1, cnt_2, \ldots, cnt_x]$ where $cnt_i$ equals to number of elements equals to $i$ in the initial array. Note that $a_1!\ + a_2!\ +\ \ldots\ +\ a_n!$ equals to sum of $k! \cdot cnt_k$ over all $k$ from $1$ to $x - 1$, $cnt_x$ does not affect anything because $x!$ divides $x!$ itself. We have...
[ "math", "number theory" ]
1,600
null
1753
C
Wish I Knew How to Sort
You are given a binary array $a$ (all elements of the array are $0$ or $1$) of length $n$. You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until $a$ is sorted: - Choose two random indices $i$ and $j$ such that $i < j$....
Let the number of zeros in the array be $g$. Let $dp[k]$ be the expected number of swaps needed when there are $k$ zeros in the first $g$ positions. Then, we know that $dp[g] = 0$, and we can write down the recurrence equations for $dp[k]$ by considering the case where some element equals to one from the first $g$ posi...
[ "dp", "math", "probabilities" ]
2,000
null
1753
D
The Beach
Andrew loves the sea. That's why, at the height of the summer season, he decided to go to the beach, taking a sunbed with him to sunbathe. The beach is a rectangular field with $n$ rows and $m$ columns. Some cells of the beach are free, some have roads, stones, shops and other non-movable objects. Some of two adjacent...
Let's paint our field in a chess coloring. Now let's consider our operations not as the movement of sunbeds, but as the movement of free cells. Then, a free cell adjacent to the long side of the sunbed can move to a cell of the sunbed that is not adjacent to this one, for $p$ units of discomfort. A free cell adjacent t...
[ "constructive algorithms", "dfs and similar", "graphs", "shortest paths" ]
2,400
null
1753
E
N Machines
You have been invited as a production process optimization specialist to some very large company. The company has $n$ machines at its factory, standing one behind another in the production chain. Each machine can be described in one of the following two ways: $(+,~a_i)$ or $(*,~a_i)$. If a workpiece with the value $x$...
Let $C$ bi the maximum value of the resulting product before any movements. The problem statement says that it is guaranteed that $C \le 2 \cdot 10^9$. Observation 0 - after each movements the value of the resulting product is not greater than $\frac{C^2}{4}$. Observation 1 - each machine of kind $(*, a_i)$ should be m...
[ "binary search", "brute force", "greedy" ]
3,300
null
1753
F
Minecraft Series
Little Misha goes to the programming club and solves nothing there. It may seem strange, but when you find out that Misha is filming a Minecraft series, everything will fall into place... Misha is inspired by Manhattan, so he built a city in Minecraft that can be imagined as a table of size $n \times m$. $k$ students ...
Let's formalize the problem condition. It is required to calculate the number of squares $s$ in the table for which we have inequality $A+B \geq T$, where $A$ is a $\text{MEX}$ of positive integers in the sqare and $B$ is a $\text{MEX}$ of absolute values of all negative integers in the square. Then we denote cost of a...
[ "brute force", "two pointers" ]
3,500
null
1754
A
Technical Support
You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved. Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by...
Let's process each character of the string from left to right and store the number of unanswered questions $cnt$. Initially this value equals to zero. Consider the $i$-th character of the string. If it equals to "Q", increase $cnt$ by one. If it equals to "A", decrease $cnt$ by one. If $cnt$ has become negative, it mea...
[ "greedy" ]
800
null
1754
B
Kevin and Permutation
For his birthday, Kevin received the set of pairwise distinct numbers $1, 2, 3, \ldots, n$ as a gift. He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $p_1, p_2, \ldots, p_n$, he w...
Let's prove that the minimum difference of consecutive elements is not greater than $\lfloor \frac{n}{2} \rfloor$. To do it, let's prove that larger value is not achievable. Consider element of a permutation with value $\lfloor \frac{n}{2} \rfloor + 1$. It will have at least one adjacent element in the constructed perm...
[ "constructive algorithms", "greedy", "math" ]
800
null
1758
A
SSeeeeiinngg DDoouubbllee
A palindrome is a string that reads the same backward as forward. For example, the strings $z$, $aaa$, $aba$, and $abccba$ are palindromes, but $codeforces$ and $ab$ are not. The double of a string $s$ is obtained by writing each character twice. For example, the double of $seeing$ is $sseeeeiinngg$. Given a string $...
Output $s + \text{reverse}(s)$. It works, since each character in $s$ occurs exactly twice (once in $s$, once in $\text{reverse}(s)$), and the result is a palindrome.
[ "constructive algorithms", "strings" ]
800
for _ in range(int(input())): s = input() print(s + s[::-1])
1758
B
XOR = Average
You are given an integer $n$. Find a sequence of $n$ integers $a_1, a_2, \dots, a_n$ such that $1 \leq a_i \leq 10^9$ for all $i$ and $$a_1 \oplus a_2 \oplus \dots \oplus a_n = \frac{a_1 + a_2 + \dots + a_n}{n},$$ where $\oplus$ represents the bitwise XOR. It can be proven that there exists a sequence of integers that...
Let us consider the cases when $n$ is odd and when its even. $n$ is odd: We can see that printing $\underbrace{1,\dots,1}_{n\text{ times}}$ will lead to an average of $1$ and an XOR of $1$ (since $1 \oplus 1 = 0$). Similarly, you could print any integer $n$ times to pass this case. $n$ is even: We use a slight modifica...
[ "constructive algorithms" ]
900
for _ in range(int(input())): n = int(input()) print(*[1] if n == 1 else [1 + n % 2] + [2]*(n-2) + [3 - n % 2])
1758
C
Almost All Multiples
Given two integers $n$ and $x$, a permutation$^{\dagger}$ $p$ of length $n$ is called funny if $p_i$ is a multiple of $i$ for all $1 \leq i \leq n - 1$, $p_n = 1$, and $p_1 = x$. Find the lexicographically minimal$^{\ddagger}$ funny permutation, or report that no such permutation exists. $^{\dagger}$ A permutation of...
We start by giving the answer for $n=12$, $k=2$: $[\color{red}{2}, \color{red}{4}, 3, \color{red}{12}, 5, 6, 7, 8, 9, 10, 11, \color{red}{1}]$ $[\color{red}{3}, 2, \color{red}{6}, 4, 5, \color{red}{12}, 7, 8, 9, 10, 11, \color{red}{1}].$ As you can see, the array is almost the identity permutation, with certain element...
[ "greedy", "number theory" ]
1,400
for _ in range(int(input())): n, x = map(int, input().split()) if n % x: print(-1) continue a = list(range(1, n + 1)) if x == n: a[0], a[-1] = a[-1], a[0] print(*a) continue a[0], a[-1], a[x-1] = x, 1, n x -= 1 for i in range(1, n-1): if a[x]...
1758
D
Range = √Sum
You are given an integer $n$. Find a sequence of $n$ \textbf{distinct} integers $a_1, a_2, \dots, a_n$ such that $1 \leq a_i \leq 10^9$ for all $i$ and $$\max(a_1, a_2, \dots, a_n) - \min(a_1, a_2, \dots, a_n)= \sqrt{a_1 + a_2 + \dots + a_n}.$$ It can be proven that there exists a sequence of \textbf{distinct} integer...
Let us consider the cases when $n$ is odd and when its even. $n$ is odd: First, we can start with the $n$ consecutive distinct numbers centered at $n$. The minimum-maximum difference is $n - 1$, and the sum is $n^2$. If we add 2 to each number, the minimum-maximum difference remains the same, and the sum increases to $...
[ "binary search", "brute force", "constructive algorithms", "math", "two pointers" ]
1,800
for _ in range(int(input())): n = int(input()) if n % 2 == 0: print(*[i for i in range(n//2, n//2 + n + 1) if i != n]) else: a = list(range(n//2 + 3, n//2 + 3 + n)) a[0] -= 1 a[-1] += 1 a[-2] += 1 print(*a)
1758
E
Tick, Tock
Tannhaus, the clockmaker in the town of Winden, makes mysterious clocks that measure time in $h$ hours numbered from $0$ to $h-1$. One day, he decided to make a puzzle with these clocks. The puzzle consists of an $n \times m$ grid of clocks, and each clock always displays some hour exactly (that is, it doesn't lie bet...
Notice that a relationship between two clocks with assigned values on the grid on different rows but the same column, that is, $g_{x, z}$ and $g_{y, z}$, can be represented as $g_{y, z} \equiv g_{x, z} + d \pmod{h}$, where $0 \le d < h$. Now, for every $1 \le i \le m$, $g_{y, i} \equiv g_{x, i} + d \pmod{h}$. Using the...
[ "combinatorics", "dfs and similar", "dsu", "graphs" ]
2,500
import io, os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline for _ in range(int(input())): n, m, h = map(int, input().split()) a = [list(map(int, input().split())) for i in range(n)] graph = [[] for __ in range(n + m)] for i in range(n): for j in range(m): if a[i][j...
1758
F
Decent Division
A binary string is a string where every character is $0$ or $1$. Call a binary string decent if it has an equal number of $0$s and $1$s. Initially, you have an infinite binary string $t$ whose characters are all $0$s. You are given a sequence $a$ of $n$ updates, where $a_i$ indicates that the character at index $a_i$ ...
After each update, we want to maintain the invariant that each interval is balanced, and additionally that there is a gap containing at least one zero in between each pair of consecutive intervals. Since every $\texttt{1}$ must be contained in an interval, this is equivalent to having non-empty gaps between consecutive...
[ "constructive algorithms", "data structures" ]
3,000
class LazySegmentTree: def __init__(self, array): self.n = len(array) self.size = 1 << (self.n - 1).bit_length() self.func = min self.default = float("inf") self.data = [self.default] * (2 * self.size) self.lazy = [0] * (2 * self.size) self.process(array) ...
1759
A
Yes-Yes?
You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row. Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se. ...
Note that it is enough to consider the string $full =$YesYes...Yes, where Yes is written $18$ times, since $18 \cdot 3 = 54$, and our substring $s$ has size $|s| \le 50$. Then we just use the built-in function $find$ to find out if our string $s$ is a substring of the string $full$.
[ "implementation", "strings" ]
800
full = 'Yes' * 18 t = int(input()) for _ in range(t): if full.find(input()) >= 0: print('YES') else: print('NO')
1759
B
Lost Permutation
A sequence of $n$ numbers is called a permutation if it contains all integers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not. Polycarp lost his favorite permutation and found only some of its elements — the num...
Let us add to $s$ the sum of the elements of the array $b$ and try to find a suitable permutation. To do this, greedily add elements $1, 2, \dots, cnt$ until their sum is less than $s$. And at the end we will check that the sum has matched. Also check that the maximal element from $b$: $max(b) \le cnt$, and that the to...
[ "math" ]
800
t = int(input()) for _ in range(t): n, s = map(int, input().split()) a = [int(x) for x in input().split()] s += sum(a) sm = 0 cnt = 0 for i in range(1, s + 1): if sm >= s: break sm += i cnt = i if sm != s or max(a) > cnt or cnt <= n: print("NO"); ...
1759
C
Thermostat
Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $a$. The thermostat can only be set to a temperature from $l$ to $r$ inclusive, the temperature cannot change by less than $x$. Formally, in one operation you can reconfigure the thermostat from temperature $a$ to tempe...
First let's consider the cases when the answer exists: If $a=b$, then the thermostat is already set up and the answer is $0$. else if $|a - b| \ge x$, then it is enough to reconfigure the thermostat in $1$ operation. else if exist such temperature $c$, that $|a - c| \ge x$ and $|b - c| \ge x$, then you can configure th...
[ "greedy", "math", "shortest paths" ]
1,100
def solve(): l, r, x = map(int, input().split()) a, b = map(int, input().split()) if a == b: return 0 if abs(a - b) >= x: return 1 if r - max(a, b) >= x or min(a, b) - l >= x: return 2 if r - b >= x and a - l >= x or r - a >= x and b - l >= x: return 3 return ...
1759
D
Make It Round
Inflation has occurred in Berlandia, so the store needs to change the price of goods. The current price of good $n$ is given. It is allowed to increase the price of the good by $k$ times, with $1 \le k \le m$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum nu...
The answer is $n \cdot k$. First, count two numbers: $cnt_2, cnt_5$ which denote the degree of occurrence of $2$ and $5$ in the number $n$ respectively, that is $n = 2^cnt_2 \cdot 5^cnt_5 \cdot d$. Where $d$ is not divisible by either $2$ or $5$. Now while $cnt_2 \neq cnt_5$ we will increase the corresponding value. Fo...
[ "brute force", "number theory" ]
1,400
#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 using ll = long long; void solve() { ll n,m; cin >> n >> m; ll n0 = n; int cnt2 = 0, cnt5 = 0; ll k = 1; while (n...
1759
E
The Humanoid
There are $n$ astronauts working on some space station. An astronaut with the number $i$ ($1 \le i \le n$) has power $a_i$. An evil humanoid has made his way to this space station. The power of this humanoid is equal to $h$. Also, the humanoid took with him \textbf{two} green serums and \textbf{one} blue serum. In on...
Let's make two obvious remarks: If we can absorb two astronauts with power $x \le y$, then we can always first absorb an astronaut with power $x$, and then an astronaut with power $y$; If we can absorb some astronaut, it is effective for us to do it right now. Let's sort the astronauts powers in increasing order. Now l...
[ "brute force", "dp", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAXN = 200200; int n; int arr[MAXN]; int solve(int i, long long h, int s2, int s3) { if (i == n) return 0; if (arr[i] < h) return solve(i + 1, h + (arr[i] / 2), s2, s3) + 1; int ans1 = (s2 ? solve(i, h * 2, s2 - 1, s3) : 0); int ans2 = (s3 ? solve(i, h *...
1759
F
All Possible Digits
A positive number $x$ of length $n$ in base $p$ ($2 \le p \le 10^9$) is written on the blackboard. The number $x$ is given as a sequence $a_1, a_2, \dots, a_n$ ($0 \le a_i < p$) — the digits of $x$ in order from left to right (most significant to least significant). Dmitry is very fond of all the digits of this number...
If all digits from $0$ to $p-1$ are initially present in the number, then the answer is $0$. Each time we will increase the number by $1$. If the last digit is less than $p-1$, then only it will change. Otherwise, all digits equal to $p-1$ at the end will become equal to $0$, and the previous one will increase by $1$ (...
[ "binary search", "data structures", "greedy", "math", "number theory" ]
1,800
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; typedef long long ll; typedef long double ld; typedef tree<pair<int, int>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; int newDigit =...
1759
G
Restore the Permutation
A sequence of $n$ numbers is called permutation if it contains all numbers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not. For a permutation $p$ of even length $n$ you can make an array $b$ of length $\frac{n}{...
First, let's check the $b$ array for correctness, that is, that it has no repeating elements. Then let's look at the following ideas: each number $b_i$ must be paired with another permutation element $p_j$, with $p_j \lt b_i$ by the definition of array $b$. Then, since we want a lexicographically minimal permutation, i...
[ "binary search", "constructive algorithms", "data structures", "greedy", "math" ]
1,900
#include "bits/stdc++.h" using namespace std; int n; void solve(){ cin >> n; vector<int>b(n / 2), p(n); vector<bool>isUsed(n + 1, false); set<int>unused; for(int i = 0; i < n / 2; i++){ cin >> b[i]; p[i * 2 + 1] = b[i]; isUsed[b[i]] = true; } for(int i = 1; i <= n; ...
1760
A
Medium Number
Given three \textbf{distinct} integers $a$, $b$, and $c$, find the medium number between all of them. The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of $5,2,6$ is $5$, since the minimum is $2$ and the maximum is $6$.
Here are two ways to implement what's given in the problem: Take input as an array $[a_1, a_2, a_3]$, and sort it. Output the middle element. Write two if-statements. The first: if $(a>b \text{ and } a<c) \text{ or } (a<b \text{ and } a>c)$, output $a$. Else, if $(b>a \text{ and } b<c) \text{ or } (b<a \text{ and } b>c...
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int a[3]; cin >> a[0] >> a[1] >> a[2]; sort(a, a + 3); cout << a[1] << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve(...
1760
B
Atilla's Favorite Problem
In order to write a string, Atilla needs to first learn all letters that are contained in the string. Atilla needs to write a message which can be represented as a string $s$. He asks you what is the minimum alphabet size required so that one can write this message. The alphabet of size $x$ ($1 \leq x \leq 26$) conta...
To solve the problem we need to find the character with the highest alphabetical order in our string, since Atilla will need at least that alphabet size and won't need more. To do this iterate through the string and find the character with the highest alphabetical order. Output the maximum alphabetical order found. The...
[ "greedy", "implementation", "strings" ]
800
#include "bits/stdc++.h" using namespace std; using ll = long long; #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1760
C
Advantage
There are $n$ participants in a competition, participant $i$ having a strength of $s_i$. Every participant wonders how much of an advantage they have over the other best participant. In other words, each participant $i$ wants to know the difference between $s_i$ and $s_j$, where $j$ is the strongest participant in the...
Make a copy of the array $s$: call it $t$. Sort $t$ in non-decreasing order, so that $t_1$ is the maximum strength and $t_2$ - the second maximum strength. Then for everyone but the best person, they should compare with the best person who has strength $t_1$. So for all $i$ such that $s_i \neq t_1$, we should output $s...
[ "data structures", "implementation", "sortings" ]
800
#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) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; vector<int> b(a); sort(b.begin(), b.end()); ...
1760
D
Challenging Valleys
You are given an array $a[0 \dots n-1]$ of $n$ integers. This array is called a "valley" if there exists \textbf{exactly one} subarray $a[l \dots r]$ such that: - $0 \le l \le r \le n-1$, - $a_l = a_{l+1} = a_{l+2} = \dots = a_r$, - $l = 0$ or $a_{l-1} > a_{l}$, - $r = n-1$ or $a_r < a_{r+1}$. Here are three examples...
One possible solution is to represent a range of equal element as a single element with that value. Construct this array $b$ and loop through it and check how many element $b_i$ satisfy the conditions $i = 0$ or $b_{i-1} < b_i$ and $i = n-1$ or $b_i > b_{i+1}$. If exactly one index satisfies these conditions, print "YE...
[ "implementation", "two pointers" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a; for(int i = 0; i < n; i++) { int x; cin >> x; if(i == 0 || x != a.back()) { a.push_back(x); } } int num_valley = 0; for(int i = 0; i < a.size()...
1760
E
Binary Inversions
You are given a binary array$^{\dagger}$ of length $n$. You are allowed to perform one operation on it \textbf{at most once}. In an operation, you can choose any element and flip it: turn a $0$ into a $1$ or vice-versa. What is the maximum number of inversions$^{\ddagger}$ the array can have after performing \textbf{a...
Let's find out how to count the number of binary inversions, without flips. This is the number of $1$s that appear before a $0$. To do this, iterate through the array and keep a running total $k$ of the number of $1$s seen so far. When we see a $0$, increase the total inversion count by $k$, since this $0$ makes $k$ in...
[ "data structures", "greedy", "math" ]
1,100
#include "bits/stdc++.h" using namespace std; using ll = long long; #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1760
F
Quests
There are $n$ quests. If you complete the $i$-th quest, you will gain $a_i$ coins. You can only complete at most one quest per day. However, once you complete a quest, you cannot do the same quest again for $k$ days. (For example, if $k=2$ and you do quest $1$ on day $1$, then you cannot do it on day $2$ or $3$, but yo...
Let's fix $k$ and find the maximum number of coins we can get. Here we can do a greedy solution: at every step, we should always take the most rewarding quest. (Intuitively, it makes sense, since doing more rewarding quests earlier allows us to do them again later.) If no quests are available, we do nothing. To impleme...
[ "binary search", "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n, d; long long c; cin >> n >> c >> d; long long a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n, greater<long long>()); int l = 0, r = d + 2; while (l < r) { int m = l +...
1760
G
SlavicG's Favorite Problem
You are given a weighted tree with $n$ vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root. Since trees bore you, you decided to challenge yourself and play a game on the given tree. In ...
Let's ignore the teleporting, and decide how to find the answer. Note that we don't need to ever go over an edge more than once, since going over an edge twice cancels out (since $a~\mathsf{XOR}~a = 0$ for all $a$). In other words, the only possible value of $x$ equals the $\mathsf{XOR}$ of the edges on the unique path...
[ "bitmasks", "dfs and similar", "graphs" ]
1,700
#include "bits/stdc++.h" using namespace std; using ll = long long; #define forn(i,n) for(int i=0;i<n;i++) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) ...
1761
A
Two Permutations
You are given three integers $n$, $a$, and $b$. Determine if there exist two permutations $p$ and $q$ of length $n$, for which the following conditions hold: - The length of the longest common prefix of $p$ and $q$ is $a$. - The length of the longest common suffix of $p$ and $q$ is $b$. A permutation of length $n$ is...
If $a+b+2\leq n$, we can always find such pair, here is a possible construction: $A=\{\color{red}{1,2,\cdots,a},\color{orange}{n-b},\color{green}{a+1,a+2,\cdots,n-b-1},\color{blue}{n-b+1,n-b+2,\cdots,n}\}\\B=\{\color{red}{1,2,\cdots,a},\color{green}{a+1,a+2,\cdots,n-b-1},\color{orange}{n-b},\color{blue}{n-b+1,n-b+2,\cd...
[ "brute force", "constructive algorithms" ]
800
null
1761
B
Elimination of a Ring
Define a cyclic sequence of size $n$ as an array $s$ of length $n$, in which $s_n$ is adjacent to $s_1$. Muxii has a ring represented by a cyclic sequence $a$ of size $n$. However, the ring itself hates equal adjacent elements. So if two adjacent elements in the sequence are equal at any time, \textbf{one of them} wi...
Hint Do we need more than $3$ types of elements? Try to solve the problem with $a_i\leq 3$. Solution First of all, when there're only $2$ types of elements appearing in the sequence, the answer would be $\frac{n}2+1$. Otherwise, the conclusion is that we can always reach $n$ operations when there are more than $2$ type...
[ "constructive algorithms", "greedy", "implementation" ]
1,000
null
1761
C
Set Construction
You are given a binary matrix $b$ (all elements of the matrix are $0$ or $1$) of $n$ rows and $n$ columns. You need to construct a $n$ sets $A_1, A_2, \ldots, A_n$, for which the following conditions are satisfied: - Each set is nonempty and consists of distinct integers between $1$ and $n$ inclusive. - All sets are ...
Hint 1: When you are trying to add an element into a set $S$, you will have to add the element to every set that is meant to include $S$. Hint 2: If $A$ does not include $B$, then $A$ and $B$ are already distinct. If $A$ does include $B$, What is the easiest way of making $A$ and $B$ distinct? Solution: Denote an ances...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
1,400
null
1761
D
Carry Bit
Let $f(x,y)$ be the number of carries of $x+y$ in binary (i. e. $f(x,y)=g(x)+g(y)-g(x+y)$, where $g(x)$ is the number of ones in the binary representation of $x$). Given two integers $n$ and $k$, find the number of ordered pairs $(a,b)$ such that $0 \leq a,b < 2^n$, and $f(a,b)$ equals $k$. Note that for $a\ne b$, $(a...
Hint 1: Try to solve the problem in $O(nk)$ using DP. Hint 2: There is no need for DP. Hint 3: You can consider enumerating the bits to carry, and then counting. Let $a_i$ represents the $i$-th bit of $a$ in binary representation (that is, $2^i \times a_i=a \wedge 2^i$) and define $b_i$ similarly. If you decide which b...
[ "combinatorics", "math" ]
2,100
null
1761
E
Make It Connected
You are given a simple undirected graph consisting of $n$ vertices. The graph doesn't contain self-loops, there is at most one edge between each pair of vertices. Your task is simple: make the graph connected. You can do the following operation any number of times (possibly zero): - Choose a vertex $u$ arbitrarily. -...
Hint 1 Try to figure out the conditions where a task can be solved with $1$ operation. Then $2$ operations, and then even more operations. Hint 2 The answer could be larger than $2$ only when the graph is made up of $2$ cliques, where you could only perform the operations on every vertex in the smaller clique to get th...
[ "binary search", "brute force", "constructive algorithms", "dsu", "graphs", "greedy", "matrices", "trees", "two pointers" ]
2,400
null
1761
F1
Anti-median (Easy Version)
\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.} Let's call an array $a$ of odd length $2m+1$ (with $m \ge 1$) \textbf{bad}, if element $a_{m+1}$ is equal to the median of this arr...
Let's analyze the structure of anti-median permutations. First, if for any $2 \le i \le n-1$ holds $a_{i-1}>a_i>a_{i+1}$, or $a_{i-1}<a_i<a_{i+1}$, then segment $p[i-1:i+1]$ is bad. So, the signs between adjacent elements are alternating. So, consider two cases: all elements on even positions are local maximums, and on...
[ "dp", "math" ]
3,100
null
1761
F2
Anti-median (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.} Let's call an array $a$ of odd length $2m+1$ (with $m \ge 1$) \textbf{bad}, if element $a_{m+1}$ is equal to the median of this arr...
For this version, we have to analyze our dp a bit more. Once again, how do anti-median permutations look? We consider the order of positions on the cycle, as in F1. We choose the position of $n$, and then, for $i$ from $n-1$ to $1$, we choose a position of number $i$ among two options: right to the right of the current...
[ "combinatorics", "dp", "math" ]
3,500
null
1761
G
Centroid Guess
\textbf{This in an interactive problem}. There is an unknown tree consisting of $n$ nodes, which has \textbf{exactly one} centroid. You only know $n$ at first, and your task is to find the centroid of the tree. You can ask the distance between any two vertices for at most $2\cdot10^5$ times. Note that the interactor...
Assuming we have already determined that the centroid of the tree is located on the path between $u$ and $v$, we may now consider how to locate it. Let $c_1,c_2,\dots,c_k$ be the vertices on the path from $u$ to $v$. Let $A_i$ be the set of vertices reachable from $c_i$ (including $c_i$) if we erase all other vertices ...
[ "interactive", "probabilities", "trees" ]
3,500
null
1762
A
Divide and Conquer
An array $b$ is good if the sum of elements of $b$ is even. You are given an array $a$ consisting of $n$ positive integers. In one operation, you can select an index $i$ and change $a_i := \lfloor \frac{a_i}{2} \rfloor$. $^\dagger$ Find the minimum number of operations (possibly $0$) needed to make $a$ good. It can b...
If sum is even, answer is $0$. Otherwise we need to change parity of atleast one element of $a$. It it optimal to change parity of atmost one element. Answer can be atmost $20$, as we need to divide any integer $x$ ($1 \leq x \leq 10^6$) atmost $20$ times to change its parity. We are assuming initial sum is odd. Suppos...
[ "greedy", "math", "number theory" ]
800
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; ll sum=0,ans=21; vector<ll> a(n); for(auto &it:a){ cin>>it; sum+=it; } if(sum&1){ for(auto &it:a){ ll cur=it,now=0; while(!((cur+it)&1)){ ...
1762
B
Make Array Good
An array $b$ of $m$ positive integers is good if for all pairs $i$ and $j$ ($1 \leq i,j \leq m$), $\max(b_i,b_j)$ is divisible by $\min(b_i,b_j)$. You are given an array $a$ of $n$ positive integers. You can perform the following operation: - Select an index $i$ ($1 \leq i \leq n$) and an integer $x$ ($0 \leq x \leq ...
Suppose we have a prime number $p$. Suppose there are two perfect powers of $p$ - $l$ and $r$. Now it is easy to see $\max(l,r)$ is divisible by $\min(l,r)$. So now we need to choose some prime number $p$. Let us start with the smallest prime number $p=2$. Here is one interesting fact. There always exists a power of $2...
[ "constructive algorithms", "implementation", "number theory", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; #define ll long long ll f(ll x){ ll cur=1; while(cur<=x){ cur*=2; } return cur; } void solve(){ ll n; cin>>n; cout<<n<<"\n"; for(ll i=1;i<=n;i++){ ll x; cin>>x; cout<<i<<" "<<f(x)-x<<"\n"; } } int main() ...
1762
C
Binary Strings are Fun
A binary string$^\dagger$ $b$ of odd length $m$ is good if $b_i$ is the median$^\ddagger$ of $b[1,i]^\S$ for all \textbf{odd} indices $i$ ($1 \leq i \leq m$). For a binary string $a$ of length $k$, a binary string $b$ of length $2k-1$ is an extension of $a$ if $b_{2i-1}=a_i$ for all $i$ such that $1 \leq i \leq k$. Fo...
Let us first find $f(s[1,n])$. $f(s[1,n])=2^{len-1}$ where $len$ is the length of longest suffix of $s$ in which all characters are same. How to prove the result in hint $2$? First of all it is easy to see if all characters of $s$ are same, $f(s[1,n])=2^{n-1}$ as median is always $s_i$. Now we assume that $s$ contains ...
[ "combinatorics", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; #define ll long long const ll MOD=998244353; void solve(){ ll n; cin>>n; string s; cin>>s; s=" "+s; ll ans=0,cur=1; for(ll i=1;i<=n;i++){ if(s[i]==s[i-1]){ cur=(2*cur)%MOD; } else{ cur=1; } ...
1762
D
GCD Queries
This is an interactive problem. There is a secret permutation $p$ of $[0,1,2,\ldots,n-1]$. Your task is to find $2$ indices $x$ and $y$ ($1 \leq x, y \leq n$, possibly $x=y$) such that $p_x=0$ or $p_y=0$. In order to find it, you are allowed to ask \textbf{at most} $2n$ queries. In one query, you give two integers $i...
Intended solution uses $2 \cdot (n-2)$. You are allowed to guess two indices. Doesn't this hint towards something? If we can eliminate $n-2$ elements that cannot be $0$ for sure, we are done. Suppose we have three distinct indices $i$, $j$ and $k$. Is it possible to remove one index(say $x$) out of these three indices ...
[ "constructive algorithms", "interactive", "number theory" ]
2,100
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ ll n; cin>>n; ll l=1,r=2; for(ll i=3;i<=n;i++){ ll ql,qr; cout<<"? "<<l<<" "<<i<<endl; cin>>ql; cout<<"? "<<r<<" "<<i<<endl; cin>>qr; if(ql>qr){ r=i; } ...
1762
E
Tree Sum
Let us call an edge-weighted tree with $n$ vertices numbered from $1$ to $n$ good if the weight of each edge is either $1$ or $-1$ and for each vertex $i$, the product of the edge weights of all edges having $i$ as one endpoint is $-1$. You are given a positive integer $n$. There are $n^{n-2} \cdot 2^{n-1}$ distinct$^...
There does not exist any good tree of size $n$ if $n$ is odd. How to prove it? Suppose $f(v)$ gives the product of weight of edges incident to node $v$ in a good tree. We know that $f(i)=-1$ as if tree is good. Now $\prod_{i=1}^{n} f(i) = -1$ if $n$ is odd. There is another way to find $\prod_{i=1}^{n} f(i)$. Look at c...
[ "combinatorics", "math", "trees" ]
2,600
#include <bits/stdc++.h> using namespace std; #define ll long long const ll MOD=998244353; const ll MAX=500500; vector<ll> fact(MAX+2,1),inv_fact(MAX+2,1); ll binpow(ll a,ll b,ll MOD){ ll ans=1; a%=MOD; while(b){ if(b&1) ans=(ans*a)%MOD; b/=2; a=(a*a)%MOD; } ...
1762
F
Good Pairs
You are given an array $a$ consisting of $n$ integers and an integer $k$. A pair $(l,r)$ is good if there exists a sequence of indices $i_1, i_2, \dots, i_m$ such that - $i_1=l$ and $i_m=r$; - $i_j < i_{j+1}$ for all $1 \leq j < m$; and - $|a_{i_j}-a_{i_{j+1}}| \leq k$ for all $1 \leq j < m$. Find the number of pair...
We should have $|a_{i_j}-a_{i_{j+1}}| \leq k$. This seems a bit hard, as we can have $a_{i_{j+1}}$ greater than, smaller than or equal to $a_{i_j}$. Why not solve the easier version first? A pair $(l,r)$ is good if there exists a sequence of indices $i_1, i_2, \dots, i_m$ such that $i_1=l$ and $i_m=r$; $i_j < i_{j+1}$ ...
[ "binary search", "data structures", "dp" ]
2,600
#include <bits/stdc++.h> using namespace std; #define ll long long const ll MAX=1000100; class ST{ public: vector<ll> segs; ll size=0; ll ID=MAX; ST(ll sz) { segs.assign(2*sz,ID); size=sz; } ll comb(ll a,ll b) { return min(a,b); ...
1762
G
Unequal Adjacent Elements
You are given an array $a$ consisting of $n$ positive integers. Find any permutation $p$ of $[1,2,\dots,n]$ such that: - $p_{i-2} < p_i$ for all $i$, where $3 \leq i \leq n$, and - $a_{p_{i-1}} \neq a_{p_i}$ for all $i$, where $2 \leq i \leq n$. Or report that no such permutation exists.
Answer is NO only when there exists an element of $a$ which occurs more that $\lceil \frac{n}{2} \rceil$ times. Let us say an array $b$ is beautiful if length of $b$ is odd and mode(say $x$) of $b$ occurs exactly $\lceil \frac{n}{2} \rceil$ times. If $a$ is beautiful, there exists only one permutation. We have rearrang...
[ "constructive algorithms", "sortings" ]
3,100
#include <bits/stdc++.h> using namespace std; #define ll long long #define all(x) x.begin(),x.end() void solve(){ ll n; cin>>n; vector<ll> a(n+5),freq(n+5,0); for(ll i=1;i<=n;i++){ cin>>a[i]; freq[a[i]]++; } for(ll i=1;i<=n;i++){ ll till=(n+1)/2; if(freq[i]>...
1763
A
Absolute Maximization
You are given an array $a$ of length $n$. You can perform the following operation several (possibly, zero) times: - Choose $i$, $j$, $b$: Swap the $b$-th digit in the binary representation of $a_i$ and $a_j$. Find the maximum possible value of $\max(a) - \min(a)$. In a binary representation, bits are numbered from r...
Which $1$s in the binary representation cannot be changed to $0$. Similarly, Which $0$s in the binary representation cannot be changed to $1$. Considering the last two hints, try to maximize the maximum element and minimize the minimum element. In the minimum element, we want to make every bit $0$ when possible, it won...
[ "bitmasks", "constructive algorithms", "greedy", "math" ]
800
null
1763
B
Incinerate
To destroy humanity, The Monster Association sent $n$ monsters to Earth's surface. The $i$-th monster has health $h_i$ and power $p_i$. With his last resort attack, True Spiral Incineration Cannon, Genos can deal $k$ damage to all monsters alive. In other words, Genos can reduce the health of all monsters by $k$ (if $...
What if the array $p$ was sorted? Is it necessary to decrease the health of each monster manually after every attack? Sort the monsters in ascending order of their powers. Now we iterate through the monsters while maintaining the current attack power and the total damage dealt. Only the monsters with health greater tha...
[ "binary search", "brute force", "data structures", "implementation", "math", "sortings" ]
1,200
"#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define ll long long\n#define el '\\n'\n#define yes cout<<\"YES\"<<el\n#define no cout<<\"NO\"<<el\n#define f(i,a,b) for(ll i = a; i <= b; i++)\n#define fr(i,a,b) for(ll i = a; i >= b; i--)\n#define vi vector<int>\n#define speed ios_base::sync_with...
1763
C
Another Array Problem
You are given an array $a$ of $n$ integers. You are allowed to perform the following operation on it as many times as you want (0 or more times): - Choose $2$ indices $i$,$j$ where $1 \le i < j \le n$ and replace $a_k$ for all $i \leq k \leq j$ with $|a_i - a_j|$ Print the maximum sum of all the elements of the final...
What happens when we apply the same operation twice? What about n = 3 ? Let's first consider the case for $n \geq 4$. The key observation to make here is that we can make all the elements of a subarray $a_l,...a_r$ zero by applying the operation on range $[l,r]$ twice. Then let's assume the maximum element $mx$ of the ...
[ "brute force", "constructive algorithms", "greedy" ]
2,000
#include <bits/stdc++.h> using namespace std; #define int long long #define ll long long #define pii pair<ll, ll> int32_t mod = 1e9 + 7; void solve() { ll n; cin >> n; vector<ll> a(n); for (auto &i : a) cin >> i; if (n == 2) cout << max({2 * abs(a[0] - a[1]), a[0] + a[1]}); els...
1763
D
Valid Bitonic Permutations
You are given five integers $n$, $i$, $j$, $x$, and $y$. Find the number of bitonic permutations $B$, of the numbers $1$ to $n$, such that $B_i=x$, and $B_j=y$. Since the answer can be large, compute it modulo $10^9+7$. A bitonic permutation is a permutation of numbers, such that the elements of the permutation first ...
Can you solve the problem when $x < y$? When $x > y$, perform $i'=n-j+1$, $j'=n-i +1$, $x' = y$, and $y' = x$. Can you solve the problem for a fixed value of $k$? Iterate over possible values of $k$. The total count is the sum of the individual counts. Club the remaining numbers into ranges as follows: $[1,x-1]$, $[x+1...
[ "combinatorics", "dp", "implementation", "math", "number theory" ]
2,200
#include <iostream> #include <vector> using namespace std; const int MOD = 1000000007; vector<int> fac; vector<int> ifac; int binExp(int base, int exp) { base %= MOD; int res = 1; while (exp > 0) { if (exp & 1) { res = (int) ((long long) res * base % MOD); } base = (int...
1763
E
Node Pairs
Let's call an ordered pair of nodes $(u, v)$ in a directed graph unidirectional if $u \neq v$, there exists a path from $u$ to $v$, and there are no paths from $v$ to $u$. A directed graph is called $p$-reachable if it contains exactly $p$ ordered pairs of nodes $(u, v)$ such that $u < v$ and $u$ and $v$ are reachable...
In a directed graph, which nodes are reachable from each other? How many such pairs of nodes exist? Think about a sequence of SCCs. For two nodes $u$ and $v$ to be reachable from each other, they must lie in the same strongly connected component (SCC). Let's define $f(i)$ as the minimum number of nodes required to cons...
[ "dp", "graphs", "math", "number theory" ]
2,200
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; void solve() { int p; cin >> p; vector<int> dp(p + 1, INF); dp[0] = 0; for (int i = 1; i <= p; ++i) for (int s = 1; (s * (s - 1)) / 2 <= i; ++s) dp[i] = min(dp[i], dp[i - (s * (s - 1)) / 2] + s); cout << ...
1763
F
Edge Queries
You are given an undirected, connected graph of $n$ nodes and $m$ edges. All nodes $u$ of the graph satisfy the following: - Let $S_u$ be the set of vertices in the longest simple cycle starting and ending at $u$. - Let $C_u$ be the union of the sets of vertices in any simple cycle starting and ending at $u$. - $S_u =...
What kind of graph meets the conditions given in the statement? A graph with bridges connecting components with a hamiltonian cycle. Which edges will never be counted in answer to any query? Of course, the bridges. Restructure the graph to be able to answer queries. $query(u, v)$ on a tree can be solved efficiently via...
[ "data structures", "dfs and similar", "dp", "dsu", "graphs", "trees" ]
3,000
null
1764
A
Doremy's Paint
Doremy has $n$ buckets of paint which is represented by an array $a$ of length $n$. Bucket $i$ contains paint with color $a_i$. Let $c(l,r)$ be the number of distinct elements in the subarray $[a_l,a_{l+1},\ldots,a_r]$. Choose $2$ integers $l$ and $r$ such that $l \leq r$ and $r-l-c(l,r)$ is maximized.
Assume that you have picked a interval $[L,R]$ as your answer. Now try to move the left point to make the answer larger. Compare $[L,R]$ with $[L-1,R]$. $\Delta(r-l)=1$ because the length of the interval increases by $1$. $\Delta c(l,r)$ increases at most $1$. If $a_L$ appears in $[L,R]$, $c(L,R)=c(L-1,R)$; If $a_L$ do...
[ "greedy" ]
800
#include <iostream> void solve(){ int n; std::cin >> n; for(int i = 1 ,nouse ; i <= n ; ++i){ std::cin >> nouse; } std::cout << "1 " << n << std::endl; } int main(){ int t; std::cin >> t; while(t--) solve(); return 0; }
1764
B
Doremy's Perfect Math Class
"Everybody! Doremy's Perfect Math Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's math class, Doremy is teaching everyone subtraction. Now she gives you a quiz to prove that you are paying attention in class. You are given a set $S$ containing \textbf{positive} integers...
For any two natural numbers $x,y$ , assign $|x-y|$ to the bigger number. Repeat this process until the smaller number becomes $0$, and then the bigger number will become $\gcd(x,y)$. So we can know that if $x,y\in S$, then it is guaranteed that $\gcd(x,y)\in S$. So $\gcd(a_1,a_2,\dots,a_n)\in S$. Let $t=\gcd(a_1,a_2,\d...
[ "math", "number theory" ]
900
#include<bits/stdc++.h> using namespace std; const int maxn=100005; int a[maxn]; int gcd(int a,int b){ return b==0?a:gcd(b,a%b); } int main(){ int t;scanf("%d",&t); while(t--){ int n;scanf("%d",&n); int tmp=0; for(int i=1;i<=n;++i){ scanf("%d",&a[i]); tmp=gcd(tmp,a[i]); } printf("%d\n",a[n]/tmp+(a[1]...
1764
C
Doremy's City Construction
Doremy's new city is under construction! The city can be regarded as a simple undirected graph with $n$ vertices. The $i$-th vertex has altitude $a_i$. Now Doremy is deciding which pairs of vertices should be connected with edges. Due to economic reasons, there should be no self-loops or multiple edges in the graph. ...
We can first assume that no edge links two vertices with the same value, then for each vertex $u$ and his neighbors $S_u$, either $a_u>\max\limits_{v\in S_u}a_v$ or $a_u<\min\limits_{v\in S_u}a_v$. If $a_u>\max\limits_{v\in S_u}a_v$, we paint $u$ black, otherwise we paint it white. Then it's obviously that any edge con...
[ "graphs", "greedy" ]
1,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(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...
1764
D
Doremy's Pegging Game
Doremy has $n+1$ pegs. There are $n$ red pegs arranged as vertices of a regular $n$-sided polygon, numbered from $1$ to $n$ in anti-clockwise order. There is also a blue peg of \textbf{slightly smaller diameter} in the middle of the polygon. A rubber band is stretched around the red pegs. Doremy is very bored today an...
The game will end immediately when the blue peg is not inside the convex formed by all remaining red pegs. Namely, there are $\lfloor \frac{n}{2} \rfloor$ consecutive red pegs removed. It can be proven by geometry. Assume $t=\lfloor \frac{n}{2} \rfloor$, and $n$ is odd. Let's enumerate the ending status: there are $i$ ...
[ "combinatorics", "dp", "math" ]
2,000
#include <cstdio> #include <iostream> #define LL long long const int MX = 5000 + 233; LL C[MX][MX] ,n ,p ,fac[MX]; void init(){ for(int i = 0 ; i < MX ; ++i) C[i][0] = 1; for(int i = 1 ; i < MX ; ++i) for(int j = 1 ; j < MX ; ++j) C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % p; fac[0] = fac[1] = 1 % p; for(i...
1764
E
Doremy's Number Line
Doremy has two arrays $a$ and $b$ of $n$ integers each, and an integer $k$. Initially, she has a number line where no integers are colored. She chooses a permutation $p$ of $[1,2,\ldots,n]$ then performs $n$ moves. On the $i$-th move she does the following: - Pick an \textbf{uncolored} integer $x$ on the number line ...
First if $k$ can be colored with certain color, then any $K<k$ can also be colored the this color. So we only need to calculate what is the biggest number color $1$ can be. Apparently this value will not exceed $x_1+y_1$. If $x_1$ is not maximum among all $x$, you can pick any $j$ such that $x_j\ge x_1$. Color point $x...
[ "dp", "greedy", "sortings" ]
2,400
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define LL long long const int MX = 2e5 + 5; int n ,s; struct Goat{ int x ,y ,id; }A[MX]; bool cmp(Goat a ,Goat b){ return a.x < b.x; } int mx[MX]; int calc(int id){ if(id == 1) return A[id].x; int far = std::max(calc(id - 1) ,...
1764
F
Doremy's Experimental Tree
Doremy has an edge-weighted tree with $n$ vertices whose weights are \textbf{integers} between $1$ and $10^9$. She does $\frac{n(n+1)}{2}$ experiments on it. In each experiment, Doremy chooses vertices $i$ and $j$ such that $j \leq i$ and connects them directly with an edge with weight $1$. Then, there is exactly one ...
If path $(x,y) \subset (X,Y)$, then $f(x,y) > f(X,Y)$. Then we build a graph based on $f(i,j)$, the weight of the edge between $i,j$ is $f(i,j)$. It can be shown that the MST of the graph have the same structure as the original tree. Then we need to compute the weight for each edge. The weight of the edge between $x$ a...
[ "brute force", "constructive algorithms", "dfs and similar", "dsu", "sortings", "trees" ]
2,500
#include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define LL long long const int MX = 3e3 + 5; bool vis[MX]; LL w[MX][MX] ,dis[MX]; std::vector<int> e[MX]; int size[MX]; void dfs(int x ,int f){ size[x] = 1; for(auto i : e[x]){ if(i == f) continue; dfs(i ,x); s...
1764
G3
Doremy's Perfect DS Class (Hard Version)
\textbf{The only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most $\mathbf{20}$ queries. You can make hacks only if all versions of the problem are solved.} This is an interactive problem. "Everybody! Doremy's Perfect Data Str...
If we add an edge between numbers $a,b$ when $\lfloor\frac{a}{2}\rfloor=\lfloor\frac{b}{2}\rfloor$, then when $n$ is an odd number, $1$ is the only one which has no neighbor, so let's consider the odd case at first. Let the number of edges $(u,v)$ satisfying $u,v\in [l,r]$ be $C(l,r)$, then $C(l,r)+Q(l,r,2)=r-l+1$. Tha...
[ "binary search", "interactive" ]
3,300
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int n; int query(int l,int r,int k){ printf("? %d %d %d\n",l,r,k); fflush(stdout);int re;scanf("%d",&re); return re; } void answer(int x){ printf("! %d\n",x); fflush(stdout); } int rt=-1; void divide(int l,int r,int l1,i...
1764
H
Doremy's Paint 2
Doremy has $n$ buckets of paint which is represented by an array $a$ of length $n$. Bucket $i$ contains paint with color $a_i$. Initially, $a_i=i$. Doremy has $m$ segments $[l_i,r_i]$ ($1 \le l_i \le r_i \le n$). Each segment describes an operation. Operation $i$ is performed as follows: - For each $j$ such that $l_i...
The main idea of the solution is that we can try to the answers for position $x,x+1,\ldots,x+k$ all at once. We do this by representing the interval $[x+i,x+k+i)$ as $[x+i,x+k) \cup [x+k,x+k+i)$ and perform sweep line on both halves of interval. Firstly, after applying some operations on the array $a$, we will have $a_...
[ "data structures" ]
3,400
#include <bits/stdc++.h> using namespace std; #define int long long #define ii pair<int,int> #define iii tuple<int,int,int> #define fi first #define se second #define endl '\n' #define pub push_back #define pob pop_back #define puf push_front #define pof pop_front #define lb lower_bound #define ub upper_bound #defin...
1765
A
Access Levels
BerSoft is the biggest IT corporation in Berland, and Monocarp is the head of its security department. This time, he faced the most difficult task ever. Basically, there are $n$ developers working at BerSoft, numbered from $1$ to $n$. There are $m$ documents shared on the internal network, numbered from $1$ to $m$. Th...
Suppose two documents $i$ and $j$ belong to the same access group, and the access level for the document $i$ is greater than the access level for document $j$. Then, every developer which has the access to the document $i$, has the access to the document $j$ as well; so, for every $d \in [1, n]$, the condition $a_{d,i}...
[ "bitmasks", "dsu", "flows", "graph matchings" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n, m, m2; vector<vector<char>> g; int T; vector<int> mt; vector<int> used; bool try_kuhn(int v){ if (used[v] == T) return false; used[v] = T; forn(u, m2) if (g[v][u] && (mt[u] == -1 || try_kuhn...
1765
B
Broken Keyboard
Recently, Mishka started noticing that his keyboard malfunctions — maybe it's because he was playing rhythm games too much. Empirically, Mishka has found out that every other time he presses a key, it is registered as if the key was pressed twice. For example, if Mishka types text, the first time he presses a key, exac...
There are many ways to solve this problem. Basically, we need to check two conditions. The first one is the condition on the number of characters: $n \bmod 3 \ne 2$, since after the first key press, we get the remainder $1$ modulo $3$, after the second key press, we get the remainder $0$ modulo $3$, then $1$ again, the...
[ "greedy" ]
800
for _ in range(int(input())): n = int(input()) s = input() print('YES' if n % 3 != 2 and not False in [s[i * 3 + 1] == s[i * 3 + 2] for i in range(n // 3)] else 'NO')
1765
C
Card Guessing
Consider a deck of cards. Each card has one of $4$ suits, and there are exactly $n$ cards for each suit — so, the total number of cards in the deck is $4n$. The deck is shuffled randomly so that each of $(4n)!$ possible orders of cards in the deck has the same probability of being the result of shuffling. Let $c_i$ be ...
Obviously, linearity of expectation, we are calculating the sum of probability to guess correctly for each position from $1$ to $4n$. Let's start with a minor observation which can help us in calculations. The probability for all positions from $k+1$ onwards is the same. The probability for each position $i$ depends on...
[ "combinatorics", "dp", "probabilities" ]
2,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define fore(i, l, r) for (int i = int(l); i < int(r); i++) using namespace std; const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; return a; } int mul(int a, int b){ return a * 1ll *...
1765
D
Watch the Videos
Monocarp wants to watch $n$ videos. Each video is only one minute long, but its size may be arbitrary. The $i$-th video has the size $a_i$ megabytes. All videos are published on the Internet. A video should be downloaded before it can be watched. Monocarp has poor Internet connection — it takes exactly $1$ minute to do...
In this solution, we assume that the sequence $a_1, a_2, \dots, a_n$ is sorted (if it is not - just sort it before running the solution). Suppose we download and watch the videos in some order. The answer to the problem is $n + \sum a_i$, reduced by $1$ for every pair of adjacent videos that can fit onto the hard disk ...
[ "binary search", "constructive algorithms", "two pointers" ]
1,700
#include <iostream> #include <algorithm> using namespace std; #define N 200000 int a[N], n, s; bool can(int x) { int l = x - 1, r = n - 1; while (l < r) { if (a[r] > s - a[l]) return false; ++l; if (l < r) { if (a[l] > s - a[r]) return false; --r; } ...
1765
E
Exchange
Monocarp is playing a MMORPG. There are two commonly used types of currency in this MMORPG — gold coins and silver coins. Monocarp wants to buy a new weapon for his character, and that weapon costs $n$ silver coins. Unfortunately, right now, Monocarp has no coins at all. Monocarp can earn gold coins by completing ques...
If $a > b$, then Monocarp can go infinite by obtaining just one gold coin: exchanging it for silver coins and then buying it back will earn him $a-b$ silver coins out of nowhere. So, the answer is $1$ no matter what $n$ is. If $a \le b$, then it's suboptimal to exchange gold coins for silver coins and then buy the gold...
[ "brute force", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve() { int n, a, b; cin >> n >> a >> b; int x = (n + a - 1) / a; if(a > b) x = 1; cout << x << endl; } int main() { int t; cin >> t; for(int i = 0; i < t; i++) solve(); }
1765
F
Chemistry Lab
Monocarp is planning on opening a chemistry lab. During the first month, he's going to distribute solutions of a certain acid. First, he will sign some contracts with a local chemistry factory. Each contract provides Monocarp with an unlimited supply of some solution of the same acid. The factory provides $n$ contract...
Let's start without picking the contracts. Buy them all and at least learn to calculate the answer. Obviously, $k$ doesn't really matter for the answer. Linearity of expectation, it will be just something multiplied by $k$. Imagine there's just one contract. Since we can't really mix it with anything, and the probabili...
[ "dp", "geometry", "probabilities" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef long long li; const li INF64 = 1e18; struct base{ int x, w, c; }; li area(const base &a, const base &b){ return (a.c + b.c) * li(abs(a.x - b.x)); } int main() { int n, k; scanf("%d%d", &n, &k...
1765
G
Guess the String
\textbf{This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java or Kotlin — System.out.flush(), and in Python — sys.stdout.flush().} The jury has a string $s$ consisting of characters 0 and/or 1. The first c...
We will design a randomized solution which spends $1.5$ queries on average to guess $2$ characters. First of all, let's ask $p_2$ to learn which character is $s_2$. Depending on whether it is 0 or 1, the details of the solution might change, but the general idea stays the same. We will assume that it is 0. We will divi...
[ "constructive algorithms", "interactive", "probabilities" ]
2,600
#include <bits/stdc++.h> using namespace std; mt19937 rnd(42); uniform_int_distribution<int> d(1, 2); int ask(int t, int i) { cout << t << " " << i + 1 << endl; int x; cin >> x; return x; } void giveAnswer(const string& s) { cout << 0 << " " << s << endl; int x; cin >> x; assert...
1765
H
Hospital Queue
There are $n$ people (numbered from $1$ to $n$) signed up for a doctor's appointment. The doctor has to choose in which order he will appoint these people. The $i$-th patient should be appointed among the first $p_i$ people. There are also $m$ restrictions of the following format: the $i$-th restriction is denoted by t...
Let's solve the problem separately for each patient. Let's assume that we are solving a problem for a patient with the number $s$. Let's iterate through the positions in the queue from the end, and the current position is $i$. Why do we try to construct the queue from the end, and not from its beginning? This allows us...
[ "binary search", "graphs", "greedy", "implementation" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vector<int> a(n); for (auto &x : a) cin >> x; vector<vector<int>> g(n); for (int i = 0; i < m; ++i) { int x, y; cin >> x >> y; g[y - 1].push_back(x - 1); } ve...
1765
I
Infinite Chess
The black king lives on a chess board with an infinite number of columns (files) and $8$ rows (ranks). The columns are numbered with all integer numbers (including negative). The rows are numbered from $1$ to $8$. Initially, the black king is located on the starting square $(x_s, y_s)$, and he needs to reach some targ...
First, we can limit the field to a non-infinite amount of columns. Take the leftmost position, the rightmost one and leave like $10$ more cells from each side so that everything is nice on the borders. If the field wasn't as huge, we could just do a BFS over it. Mark the cells that are taken by the pieces and that are ...
[ "implementation", "shortest paths" ]
2,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const string al = "KQRBN"; const int INF = 1e9; struct mv{ int dx, dy; }; struct piece{ int x, y, t; }; struct seg{ int l, r; }; struct pos{ int x, y; }; bool operator <(const pos &a, const pos &b){ if (a.x != b....
1765
J
Hero to Zero
There are no heroes in this problem. I guess we should have named it "To Zero". You are given two arrays $a$ and $b$, each of these arrays contains $n$ non-negative integers. Let $c$ be a matrix of size $n \times n$ such that $c_{i,j} = |a_i - b_j|$ for every $i \in [1, n]$ and every $j \in [1, n]$. Your goal is to ...
The order of operations is interchangeable, so we assume that we perform mass operations first, and operations affecting single elements last. Suppose $p_i$ is the value we subtract from the $i$-th row using the operations affecting the whole row, and $q_j$ is the value we subtract from the $j$-th column using the oper...
[ "graph matchings", "math" ]
2,900
#include<bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<int> a(n), b(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int i = 0; i < n; i++) scanf("%d", &b[i]); sort(a.begin(), a.end()); sort(b.begin(), b.end()); long long total = 0; for(int i...
1765
K
Torus Path
You are given a square grid with $n$ rows and $n$ columns, where each cell has a non-negative integer written in it. There is a chip initially placed at the top left cell (the cell with coordinates $(1, 1)$). You need to move the chip to the bottom right cell (the cell with coordinates $(n, n)$). In one step, you can ...
Note that you can't visit all vertices on the antidiagonal (vertices $(1, n), (2, n - 1), \dots (n, 1)$) at the same time. Let's prove it: since you are starting outside the antidiagonal then the only way to visit vertex $(x, n + 1 - x)$ is to move from $(x - 1, n + 1 - x)$ or from $(x, n - x)$. In total, there are $n$...
[ "greedy", "math" ]
1,500
#include<bits/stdc++.h> using namespace std; int n; vector< vector<int> > a; bool read() { if (!(cin >> n)) return false; a.resize(n, vector<int>(n)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cin >> a[i][j]; } return true; } void solve() { long lo...
1765
L
Project Manager
There are $n$ employees at Bersoft company, numbered from $1$ to $n$. Each employee works on some days of the week and rests on the other days. You are given the lists of working days of the week for each employee. There are regular days and holidays. On regular days, only those employees work that have the current da...
First, notice that the answer can't be that large. Even the worst case: one developer works one day of the week, responsible for a $2 \cdot 10^5$ part project, the first $2 \cdot 10^5$ of his workdays are holidays. It's just $7 \cdot (2 \cdot 10^5 + 2 \cdot 10^5)$. Thus, we'd like to iterate over time and complete proj...
[ "brute force", "data structures", "implementation" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const string days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; int main() { cin.tie(0); iostream::sync_with_stdio(false); int n, m, k; cin >> n >> m >> k; vect...
1765
M
Minimum LCM
You are given an integer $n$. Your task is to find two positive (greater than $0$) integers $a$ and $b$ such that $a+b=n$ and the least common multiple (LCM) of $a$ and $b$ is the minimum among all possible values of $a$ and $b$. If there are multiple answers, you can print any of them.
Suppose $a \le b$. Let's show that if $b \bmod a \ne 0$, the answer is suboptimal. If $b \bmod a = 0$, then $LCM(a, b) = b$, so the answer is less than $n$. But if $b \bmod a \ne 0$, then $LCM(a, b)$ is at least $2b$, and $b$ is at least $\frac{n}{2}$, so in this case, the answer is at least $n$. Okay, now we know that...
[ "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a = 1; for (int g = 2; g * g <= n; ++g) { if (n % g == 0) { a = n / g; break; } } cout << a << ' ' << n - a << '\n'; } }
1765
N
Number Reduction
You are given a positive integer $x$. You can apply the following operation to the number: remove one occurrence of any digit in such a way that the resulting number \textbf{does not contain any leading zeroes} and \textbf{is still a positive integer}. For example, $10142$ can be converted to $1142$, $1042$, $1012$ or...
To begin with, in order to minimize the answer, we minimize the first (highest) digit of the answer. Let's check if the highest digit can be equal to $1$. To do this, there must be $1$ in the number among the first $k+1$ digits (because we can delete no more than $k$ of them). If $1$ is not among the first $k+1$ digits...
[ "greedy" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { string x; cin >> x; int k; cin >> k; int n = x.size(); vector<vector<int>> pos(10); for (int i = 0; i < n; ++i) pos[x[i] - '0'].push_back(i)...
1766
A
Extremely Round
Let's call a positive integer extremely round if it has only one non-zero digit. For example, $5000$, $4$, $1$, $10$, $200$ are extremely round integers; $42$, $13$, $666$, $77$, $101$ are not. You are given an integer $n$. You have to calculate the number of extremely round integers $x$ such that $1 \le x \le n$.
There are many ways to solve this problem. The most naive one (iterating through all numbers from $1$ to $n$ in each test case and checking if they are extremely round) fails, since it is $O(tn)$, but you can optimize it by noticing that extremely round numbers are rare. So, for example, we can iterate through all numb...
[ "brute force", "implementation" ]
800
def check(x): s = str(x) cnt = 0 for c in s: if c != '0': cnt += 1 return cnt == 1 a = [] for i in range(1, 1000000): if check(i): a.append(i) t = int(input()) for i in range(t): n = int(input()) ans = 0 for x in a: if x <= n: ans += 1 ...
1766
B
Notepad#
You want to type the string $s$, consisting of $n$ lowercase Latin letters, using your favorite text editor Notepad#. Notepad# supports two kinds of operations: - append any letter \textbf{to the end} of the string; - copy a \textbf{continuous} substring of an already typed string and paste this substring \textbf{to ...
Why does the problem ask us only to check if we can do less than $n$ operations instead of just asking the minimum amount? That must be making the problem easier, so let's focus our attention on that. What if it was $\le n$ instead of $< n$? Well, then the problem would be trivial. You can type the word letter by lette...
[ "implementation" ]
1,000
for _ in range(int(input())): n = int(input()) s = input() cur = {} for i in range(n - 1): t = s[i:i+2] if t in cur: if cur[t] < i - 1: print("YES") break else: cur[t] = i else: print("NO")
1766
C
Hamiltonian Wall
Sir Monocarp Hamilton is planning to paint his wall. The wall can be represented as a grid, consisting of $2$ rows and $m$ columns. Initially, the wall is completely white. Monocarp wants to paint a black picture on the wall. In particular, he wants cell $(i, j)$ (the $j$-th cell in the $i$-th row) to be colored black...
Why is there a constraint of each column having at least one black cell? Does the problem change a lot if there were white columns? Well, if such a column was inbetween some black cells, then the answer would be "NO". If it was on the side of the grid, you could remove it and proceed to solve without it. So, that doesn...
[ "dp", "implementation" ]
1,300
for _ in range(int(input())): n = int(input()) s = [input() for i in range(2)] pos = -1 for i in range(n): if s[0][i] != s[1][i]: pos = i if pos == -1: print("YES") continue ok = True cur = 0 if s[0][pos] == 'B' else 1 for i in range(pos + 1, n): if s[cur][i] == 'W': ok = False if s[cur ^ 1][i] ...
1766
D
Lucky Chains
Let's name a pair of positive integers $(x, y)$ lucky if the greatest common divisor of them is equal to $1$ ($\gcd(x, y) = 1$). Let's define a chain induced by $(x, y)$ as a sequence of pairs $(x, y)$, $(x + 1, y + 1)$, $(x + 2, y + 2)$, $\dots$, $(x + k, y + k)$ for some integer $k \ge 0$. The length of the chain is...
Suppose, $\gcd(x + k, y + k) = g$. It means that $(y + k) - (x + k) = (y - x)$ is also divisible by $g$, or $\gcd(x + k, y - x) = h$ is divisible by $g$. And backward: if $\gcd(x + k, y - x) = h$, then $(x + k) + (y - x) = (y + k)$ is also divisible by $h$, or $\gcd(x + k, y + k) = g$ is divisible by $h$. Since $h$ is ...
[ "math", "number theory" ]
1,600
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) typedef long long li; const int INF = int(1e9); const int N = int(1e7) + 5; int mind[N]; void precalc() { fore (i, 0, N) mind[i] = i; for (int p = 2; p < N; p++) { if (mind...
1766
E
Decomposition
For a sequence of integers $[x_1, x_2, \dots, x_k]$, let's define its decomposition as follows: Process the sequence from the first element to the last one, maintaining the list of its subsequences. When you process the element $x_i$, append it to the end of the \textbf{first} subsequence in the list such that the bit...
Let's assume that we don't have any zeroes in our array. We'll deal with them later. The key observation is that the number of sequences in the decomposition is not more than $3$. To prove this, we can use the fact that each element $3$ will be appended to the first subsequence in the decomposition; so, if the second/t...
[ "binary search", "brute force", "data structures", "divide and conquer", "dp", "two pointers" ]
2,300
#include<bits/stdc++.h> using namespace std; const int N = 300043; int n; int v[N]; map<vector<int>, long long> dp[N]; pair<int, vector<int>> go(vector<int> a, int x) { if(x == 0) return {1, a}; else { bool f = false; for(int i = 0; i < a.size() && !f; i++) if((a[i] &...
1766
F
MCF
You are given a graph consisting of $n$ vertices and $m$ directed arcs. The $i$-th arc goes from the vertex $x_i$ to the vertex $y_i$, has capacity $c_i$ and weight $w_i$. No arc goes into the vertex $1$, and no arc goes from the vertex $n$. There are no cycles of negative weight in the graph (it is impossible to trave...
This problem is solved using minimum cost flows (duh). Suppose all arcs have even capacity. Then we can just divide each arc's capacity by $2$ and solve a usual minimum cost flow problem. However, when we have arcs with odd capacity, it's not that simple. We will deal with them as follows: split an arc with capacity $2...
[ "flows" ]
2,800
#include <bits/stdc++.h> using namespace std; const int N = 243; struct edge { int y, c, w, f; edge() {}; edge(int y, int c, int w, int f) : y(y), c(c), w(w), f(f) {}; }; vector<edge> e; vector<int> g[N]; int rem(int x) { return e[x].c - e[x].f; } void add_edge(int x, int y, int c, int w) { ...
1767
A
Cut the Triangle
You are given a non-degenerate triangle (a non-degenerate triangle is a triangle with positive area). The vertices of the triangle have coordinates $(x_1, y_1)$, $(x_2, y_2)$ and $(x_3, y_3)$. You want to draw a straight line to cut the triangle into \textbf{two non-degenerate triangles}. Furthermore, the line you dra...
The line we draw must go through a triangle's vertex; otherwise, two sides of the triangle are split, and one of the resulting parts becomes a quadrilateral. So we need to check if it is possible to make a horizontal or vertical cut through a vertex. A horizontal cut is possible if all $y$-coordinates are different (we...
[ "implementation" ]
800
t = int(input()) for i in range(t): input() xs = [] ys = [] for j in range(3): x, y = map(int, input().split()) xs.append(x) ys.append(y) print('YES' if len(set(xs)) == 3 or len(set(ys)) == 3 else 'NO')