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 ⌀ |
|---|---|---|---|---|---|---|---|
1972 | A | Contest Proposal | A contest contains $n$ problems and the difficulty of the $i$-th problem is expected to be \textbf{at most} $b_i$. There are already $n$ problem proposals and the difficulty of the $i$-th problem is $a_i$. Initially, both $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$ are sorted in non-decreasing order.
Some of t... | Enumerate through the array $a$, if $a_i > b_i$ at some index $i$, then propose a problem with difficulty $b_i$. Time complexity: $\mathcal O(n^2)$ for each test case. It can also be solved in $\mathcal O(n)$ if we record the problems we've added. | [
"brute force",
"greedy",
"two pointers"
] | 800 | //By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x, y, z) for(int x = (y); x <= (z); ++x)
#define per(x, y, z) for(int x = (y); x >= (z); --x)
#define endl '\n'
using namespace std;
typedef long long ll;
const int N = 105;
int T, n, a[N], b[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0); c... |
1972 | B | Coin Games | There are $n$ coins on the table forming a circle, and each coin is either facing up or facing down. Alice and Bob take turns to play the following game, and Alice goes first.
In each operation, the player chooses a facing-up coin, removes the coin, and flips the two coins that are adjacent to it. If (before the opera... | It can be proved that Alice will win the game if and only if the number of facing-up coins is odd. Time complexity: $\mathcal O(n)$ for each case. Proof: Consider all possible operations: ...UUU... -> ...DD...: The number of U decreases by $3$. ...UUD... -> ...DU...: The number of U decreases by $1$. ...DUU... -> ...UD... | [
"games"
] | 900 | //By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x, y, z) for(int x = (y); x <= (z); ++x)
#define per(x, y, z) for(int x = (y); x >= (z); --x)
#define endl '\n'
using namespace std;
typedef long long ll;
int T, n;
string s;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
for(cin... |
1973 | A | Chess For Three | Three friends gathered to play a few games of chess together.
In every game, two of them play against each other. The winner gets $2$ points while the loser gets $0$, and in case of a draw, both players get $1$ point each. Note that the same pair of players could have played any non-negative number of times (possibly ... | If someone would claim that the number of draws that happened between the three players are $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$, can you check in $O(1)$ whether this can be true? The constraints are very small. The number of draws between any two players is at most $30$. Hint 3: Try all the possibilities for $d_{1, 2... | [
"brute force",
"dp",
"implementation",
"math"
] | 900 | #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <vector>
typedef long long ll;
typedef long double ld;
using namespace std;
i... |
1973 | B | Cat, Fox and the Lonely Array | Today, Cat and Fox found an array $a$ consisting of $n$ non-negative integers.
Define the loneliness of $a$ as the \textbf{smallest} positive integer $k$ ($1 \le k \le n$) such that for any two positive integers $i$ and $j$ ($1 \leq i, j \leq n - k +1$), the following holds: $$a_i | a_{i+1} | \ldots | a_{i+k-1} = a_j ... | We will say that the array is $k$-lonely if $a_i|a_{i+1}| \ldots |a_{i+k-1}=a_j|a_{j+1}| \ldots |a_{j+k-1}$ is true for any two positive integers $1 \leq i,j \leq n-k+1$. Let $A$ be the maximum value an element in array $a$ can have. how to check if the array is $k$-lonely in $O(n \log A)$? if the array is $k$-lonely, ... | [
"binary search",
"bitmasks",
"data structures",
"greedy",
"math",
"two pointers"
] | 1,300 |
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool check(vector<int>& v, int mid,int ori)
{
vector<int>frekbit(31);
for (int i = 0; i < mid; i++)
{
int x = v[i];
for (int j = 30; j >= 0; j--)
{
if (x>=(1<<j))
... |
1973 | C | Cat, Fox and Double Maximum | Fox loves permutations! She came up with the following problem and asked Cat to solve it:
You are given an \textbf{even} positive integer $n$ and a permutation$^\dagger$ $p$ of length $n$.
The score of another permutation $q$ of length $n$ is the number of \textbf{local maximums} in the array $a$ of length $n$, where... | $n$ is even. What is the obvious upper bound on the number of the local maximums? Right, it is ${n \over 2} - 1$. We can actually achieve this value for any permutation. Consider $p_1 = n$. Can you find $q$ such that all other odd positions will be local maximums? We can easily prove that the sequence can have at most ... | [
"constructive algorithms",
"greedy",
"implementation",
"math",
"sortings"
] | 1,700 | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <vector>
typedef long long ll;
typedef long double ld;
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
... |
1973 | D | Cat, Fox and Maximum Array Split | This is an interactive problem.
Fox gave Cat two positive integers $n$ and $k$. She has a hidden array $a_1, \ldots , a_n$ of length $n$, such that $1 \leq a_i \leq n$ for every $i$. Now they are going to play the following game:
For any two integers $l, r$ such that $1 \leq l \leq r \leq n$, define $f(l, r) = (r - l... | Let $m$ be value we want to find. What values can $m$ take? Look at the maximum value in array $a$. Can you find the maximum value in array? Think about the segment containing the maximum value. Can you finish the problem in $n$ queries? Let's denote maximum value in array $a$ as $mx$. Since the element with maximum va... | [
"brute force",
"interactive",
"math"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#pragma GCC target("popcnt")
using ll = long long;
#define int long long
#define forn(i,n) for(int i=0; i<(n); ++i)
#define pb push_back
#define pi pair<int,int>
#define f first
#define s second
#define vii(a,n) vector<int> a(n); forn(i,n) cin>... |
1973 | E | Cat, Fox and Swaps | Fox has found an array $p_1, p_2, \ldots, p_n$, that is a permutation of length $n^\dagger$ of the numbers $1, 2, \ldots, n$. She wants to sort the elements in increasing order. Cat wants to help her — he is able to swap any two numbers $x$ and $y$ in the array, but only if $l \leq x + y \leq r$ (note that the constrai... | Forget about graphs and data structures, there exists a simple $O(n)$ solution. Find the number of pairs with $l = r$ for which you can sort the permutation. Okay now that you have the special case handled, let's proceed to the general case. Find the minimum and maximum number that need to be swapped. Write down the in... | [
"graphs",
"math",
"sortings"
] | 2,500 | #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <vector>
typedef long long ll;
typedef long double ld;
using namespace std;
l... |
1973 | F | Maximum GCD Sum Queries | For $k$ positive integers $x_1, x_2, \ldots, x_k$, the value $\gcd(x_1, x_2, \ldots, x_k)$ is the greatest common divisor of the integers $x_1, x_2, \ldots, x_k$ — the largest integer $z$ such that all the integers $x_1, x_2, \ldots, x_k$ are divisible by $z$.
You are given three arrays $a_1, a_2, \ldots, a_n$, $b_1, ... | What are the possible pairs of $\gcd$'s of the two arrays we can have after some swaps? For every pair $(X, Y)$ such that $X$ divides $a_1$ and $Y$ divides $b_1$, let's calculate the total number of indices $i$ such that we can have $X | a_i$ and $Y | b_i$ (either with or without the swap), and the minimum cost of swap... | [
"bitmasks",
"brute force",
"dp",
"implementation",
"number theory"
] | 3,100 | // O(n log k + sqrt(k) * log(k) + d(k)^2 * p(k)) solution, model solution for the harder version
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <vector>
typedef long long ll;
using namespace std;
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
void upd(int& a, int b) { a = m... |
1974 | A | Phone Desktop | Little Rosie has a phone with a desktop (or launcher, as it is also called). The desktop can consist of several screens. Each screen is represented as a grid of size $5 \times 3$, i.e., five rows and three columns.
There are $x$ applications with an icon size of $1 \times 1$ cells; such an icon occupies only one cell ... | Note that on one screen we can put no more than two $2 \times 2$ icons. Thus, we need at least $Z = \lceil y / 2 \rceil$ screens. Then, we check how many $1 \times 1$ icons we can put on these screens: $15 \cdot Z - 4 \cdot y$. The $1 \times 1$ icons left we need to put on additional screens. | [
"greedy",
"math"
] | 800 | nt = int(input())
for t in range(nt):
line = input()
x, y = [int(q) for q in line.split()]
mm = (y + 1) // 2
x -= (mm * 5 * 3 - y * 2 * 2)
x = max(x, 0)
mm += (x + 5 * 3 - 1) // (5 * 3)
print(mm) |
1974 | B | Symmetric Encoding | Polycarp has a string $s$, which consists of lowercase Latin letters. He encodes this string using the following algorithm:
- first, he constructs a new auxiliary string $r$, which consists of all distinct letters of the string $s$, written in alphabetical order;
- then the encoding happens as follows: each character ... | Let's construct a string $r$ according to the definition from the condition: we write down all the letters from $s$ once in ascending order. After that, we just need to replace all the characters in $s$ with their symmetric characters in the string $r$. The length of string $r$ does not exceed $26$, so the position of ... | [
"implementation",
"sortings",
"strings"
] | 800 | def solve():
n = int(input())
b = input()
cnt = [0] * 26
for c in b:
cnt[ord(c) - ord('a')] = 1
tmp = ''
for i in range(26):
if cnt[i] > 0:
tmp += chr(ord('a') + i)
a = ''
for c in b:
a += tmp[-1 - tmp.find(c)]
print(a)
for _ in range(int(in... |
1974 | C | Beautiful Triple Pairs | Polycarp was given an array $a$ of $n$ integers. He really likes triples of numbers, so for each $j$ ($1 \le j \le n - 2$) he wrote down a triple of elements $[a_j, a_{j + 1}, a_{j + 2}]$.
Polycarp considers a pair of triples $b$ and $c$ beautiful if they differ in exactly one position, that is, one of the following c... | To consider each pair only once, we will go from left to right and while adding a new triplet, we will add to the answer the number of already added triplets that form a beautiful pair with the current one. We will maintain a map with triplets, to denote a triplet with an error, we will place $0$ (or any other value th... | [
"combinatorics",
"data structures"
] | 1,400 | def solve():
n = int(input())
a = [int(x) for x in input().split()]
cnt = dict()
ans = 0
for i in range(n - 2):
triplet = (a[i], a[i + 1], a[i + 2])
mist = [0] * 3
mist[0] = (0, a[i + 1], a[i + 2])
mist[1] = (a[i], 0, a[i + 2])
mist[2] = (a[i], a[i + 1], 0)
... |
1974 | D | Ingenuity-2 | Let's imagine the surface of Mars as an infinite coordinate plane. Initially, the rover Perseverance-2 and the helicopter Ingenuity-2 are located at the point with coordinates $(0, 0)$. A set of instructions $s$ consisting of $n$ instructions of the following types was specially developed for them:
- N: move one meter... | For the string $S$, calculate the 2D-coordinates $(x, y)$ of the point obtained as a result of sequentially executing all instructions (for example, N decreases $y$ by 1, S increases $y$ by 1, E increases $x$ by 1, W decreases $x$ by 1). Consider the following cases: $x \bmod 2 \neq 0$ or $y \bmod 2 \neq 0$. Obviously,... | [
"constructive algorithms",
"greedy",
"implementation"
] | 1,400 | inv = {'N':'S', 'S': 'N',
'E': 'W', 'W': 'E'}
def solve():
n = int(input())
s = input()
x, y = 0, 0
for c in s:
if c == 'N':
y += 1
if c == 'S':
y -= 1
if c == 'E':
x += 1
if c == 'W':
x -= 1
if x % 2 == 1 or y % 2 ... |
1974 | E | Money Buys Happiness | Being a physicist, Charlie likes to plan his life in simple and precise terms.
For the next $m$ months, starting with no money, Charlie will work hard and earn $x$ pounds per month. For the $i$-th month $(1 \le i \le m)$, there'll be a single opportunity of paying cost $c_i$ pounds to obtain happiness $h_i$.
Borrowin... | Let's consider the classic knapsack problem. Let $dp[j]$ be the minimum cost required to achieve happiness $j$. In the $i$-th month, we iterate through $dp[k]$ and check if $dp[k]+c_i \le (i-1) \cdot x$, and if so, we can afford to transition to $dp[k+h_i]$ and accordingly update $dp[k+h_i]$. The complexity is $O(m \cd... | [
"dp"
] | 1,800 | T = int(input())
big = float('inf')
for _ in range(T):
m, x = map(int, input().split())
c = []
h = []
for i in range(m):
ci, hi = map(int, input().split())
c.append(ci)
h.append(hi)
mh = sum(h)
dp = [0] + [big] * mh
for i in range(m):
for j in range(mh, h[i]-1... |
1975 | A | Bazoka and Mocha's Array | Mocha likes arrays, so before her departure, Bazoka gave her an array $a$ consisting of $n$ positive integers as a gift.
Now Mocha wants to know whether array $a$ could become sorted in non-decreasing order after performing the following operation some (possibly, zero) times:
- Split the array into two parts — a pref... | We can't do any insertions by the operation. If the answer is yes, we can make $a$ become non-decreasing in no more than one operation. Read the hints. If $a$ is non-decreasing initially, the answer is yes. If $a$ isn't non-decreasing initially, we can find the smallest $i$ such that $a_i> a_{i+1}$. Then we choose $x=[... | [
"brute force",
"greedy",
"implementation",
"sortings"
] | 800 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int pos=0;
for(int i=1;i<n;i++){
if(a[i]>a[i+1]){
pos... |
1975 | B | 378QAQ and Mocha's Array | Mocha likes arrays, so before her departure, 378QAQ gave her an array $a$ consisting of $n$ positive integers as a gift.
Mocha thinks that $a$ is beautiful if there exist two numbers $i$ and $j$ ($1\leq i,j\leq n$, $i\neq j$) such that for all $k$ ($1 \leq k \leq n$), $a_k$ is divisible$^\dagger$ by either $a_i$ or $a... | How to solve the problem if we only need to find a number $i$($1\leq i\leq n$) such that $a_k$ is divisible by $a_i$ for all $k$($1\leq k\leq n$)? We only need to check whether all elements are divisible by the minimum element of the array. Read the hints. Suppose the minimum element of $a$ is $x$. Then we iterate over... | [
"brute force",
"greedy",
"math",
"sortings"
] | 1,000 | #include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5+10;
int a[N];
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int fl=0;
for(int i=1;i<=n;i++){
cin>>a[i];
if(a[i]==1)fl=1;
}
if(fl)cout<<"Yes\n";
... |
1975 | C | Chamo and Mocha's Array | Mocha likes arrays, so before her departure, Chamo gave her an array $a$ consisting of $n$ positive integers as a gift.
Mocha doesn't like arrays containing different numbers, so Mocha decides to use magic to change the array. Mocha can perform the following three-step operation some (possibly, zero) times:
- Choose ... | If a subarray of length at least $2$ contains only the same elements, we can change all elements of the array to that element by operations. Suppose the answer is $x$, we can perform no more than one operation on the original array $a$ so that there is a subarray of length at least $2$ that contains only $x$. If we can... | [
"binary search",
"brute force",
"greedy"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int main(){
int n,t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
if(n==2)cout<<min(a[1],a[2])<<"\n";
else{
int ans = min(a[1],a[2]);
for(int i=1;... |
1975 | D | Paint the Tree | 378QAQ has a tree with $n$ vertices. Initially, all vertices are white.
There are two chess pieces called $P_A$ and $P_B$ on the tree. $P_A$ and $P_B$ are initially located on vertices $a$ and $b$ respectively. In one step, 378QAQ will do the following in order:
- Move $P_A$ to a neighboring vertex. If the target ver... | If two pieces overlap at the beginning, can you solve the problem? Consider the first time a vertex is painted blue. After this event occurs, what happens next? Read the hints. In subsequent movements after the first time a vertex is painted blue, we can ignore the process of painting vertices red and then painting the... | [
"brute force",
"dfs and similar",
"dp",
"greedy",
"shortest paths",
"trees"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 2e5+10;
vector<int> g[N];
int dep[N],f[N],mx,n,a,b;
void dfs(int x,int fa){
dep[x]=dep[fa]+1;
mx = max(mx,dep[x]);
f[x]=fa;
for(auto i:g[x]){
if(i==fa)continue;
dfs(i,x);
}
}
vector<int> move(int x,int y)... |
1975 | E | Chain Queries | You are given a tree of $n$ vertices numbered from $1$ to $n$. Initially, all vertices are colored white or black.
You are asked to perform $q$ queries:
- "u" — toggle the color of vertex $u$ (if it was white, change it to black and vice versa).
After each query, you should answer whether all the black vertices form... | Suppose the tree is a rooted tree, we only need to care about the number of black child vertices of each vertex. If the black vertices form a chain, there is no black vertex that has three or more black child vertices. And there is at most one black vertex that has two black child vertices. If the black vertices form a... | [
"binary search",
"data structures",
"dfs and similar",
"implementation",
"trees"
] | 2,100 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
int f[N];
vector<int> g[N];
int col[N],num[N];
int faw,sum_two,sum_more,tot_black,xor_two;
int n;
void init(){
sum_two=0;
tot_black=0;
sum_more=0;
faw=0;
xor_two=0;
for(int i=1;i<=n;i++){
g[i].clear();
num[i]=0;
... |
1975 | F | Set | Define the binary encoding of a finite set of natural numbers $T \subseteq \{0,1,2,\ldots\}$ as $f(T) = \sum\limits_{i \in T} 2^i$. For example, $f(\{0,2\}) = 2^0 + 2^2 = 5$ and $f(\{\}) = 0$. Notice that $f$ is a bijection from all such sets to all non-negative integers. As such, $f^{-1}$ is also defined.
You are giv... | Consider enumerating each number from $0$ to $n-1$ whether it is contained by $S$, when we have enumerated the first $x$ numbers, there are only $2^{n-x}$ constraints. Read the hints. Consider enumerating each number from $0$ to $n-1$ whether it is contained by $S$. Suppose that the current enumeration reaches $i$, and... | [
"bitmasks",
"brute force",
"combinatorics",
"dfs and similar",
"divide and conquer",
"dp",
"math"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
const int N = 24, S = (1 << 20) + 5;
int n = 0, f[N][S] = {};
vector<int> ans;
inline void dfs(int s = 0, int i = 0){
if(i < n){
int m = 1 << (n - i - 1);
for(int t = 0 ; t < m ; t ++) f[i + 1][t] = f[i][t] & f[i][m | t];
dfs(s << 1, i + 1);
for(int t = 0 ; t < m... |
1975 | G | Zimpha Fan Club | One day, Zimpha casually came up with a problem. As a member of "Zimpha fan club", you decided to solve that problem.
You are given two strings $s$ and $t$ of length $n$ and $m$, respectively. Both strings only consist of lowercase English letters, - and *.
You need to replace all occurrences of * and -, observing th... | If $s, t$ both have $*$, or both don't have $*$, then it will be a simple problem. Can you try to solve this problem? According to the first hint, we have discussed two cases. In the remaining cases, without loss of generality, we think that only $t$ has $*$. Suppose we write $t$ as $t'_0*t'_1*t'_2* \dots*t'_k$. Where ... | [
"fft",
"greedy",
"math",
"strings"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = (1 << 22) + 5, Mod = 2013265921, G = 31;
inline ll power(ll x, ll y){
ll ret = 1;
while(y){
if(y & 1) ret = ret * x % Mod;
x = x * x % Mod, y >>= 1;
}
return ret;
}
ll p[N] = {}, w[N] = {}, g[N] = {}, iv[N] = {};
inline void df... |
1975 | H | 378QAQ and Core | 378QAQ has a string $s$ of length $n$. Define the core of a string as the substring$^\dagger$ with maximum lexicographic$^\ddagger$ order.
For example, the core of "$\mathtt{bazoka}$" is "$\mathtt{zoka}$", and the core of "$\mathtt{aaa}$" is "$\mathtt{aaa}$".
378QAQ wants to rearrange the string $s$ so that the core ... | Consider the maximum character $m$ of the string $s$. If $m$ only appears once, then obviously the string starting with it is the largest in lexicographical order. To make it the smallest, $m$ should be arranged at the end. Other characters can be arranged arbitrarily. If $m$ appears more than twice, it can be proven t... | [
"greedy",
"strings"
] | 3,500 | #include<bits/stdc++.h>
using namespace std;
struct ch{
string c;
ch(){c = "";}
ch(string cc){c=cc;}
bool operator == (const ch& p)const{
return c==p.c;
}
bool operator != (const ch& p)const{
return c!=p.c;
}
void add(ch& p){
c.append(p.c);
}
};
vector<ch> sol... |
1975 | I | Mind Bloom | \begin{quote}
This is the way it always was.
\end{quote}
\begin{quote}
This is the way it always will be.
\end{quote}
\begin{quote}
All will be forgotten again soon...
\end{quote}
Jellyfish is playing a one-player card game called "Slay the Spire". There are $n$ cards in total numbered from $1$ to $n$. The $i$-th ca... | Play "Slay the Spire". Unfortunately, it doesn't help much. It may be helpful to calculate the probability that your hand becomes empty instead of the probability that the draw pile becomes empty. The intended solution is a $O(n^5)$ DP. The constant factor is small enough to run. If all the cards in your hand is $0$, y... | [
"dp"
] | 3,500 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 120 + 5, Mod = 1e9 + 7;
inline ll power(ll x, ll y){
ll ret = 1;
while(y){
if(y & 1) ret = ret * x % Mod;
x = x * x % Mod, y >>= 1;
}
return ret;
}
inline ll inv(ll x){
return power(x, Mod - 2);
}
ll n = 0, m = 0, w = 0, o = 0... |
1976 | A | Verify Password | Monocarp is working on his new site, and the current challenge is to make the users pick strong passwords.
Monocarp decided that strong passwords should satisfy the following conditions:
- password should consist only of lowercase Latin letters and digits;
- there should be no digit that comes after a letter (so, aft... | There's no real idea in the problem, the main difficulty is the implementation. Many programming languages have functions to check if a character is a digit or if it's a letter. They can be used to check that no digit follows a letter. How does the order check work? Well, most languages allow you to compare characters ... | [
"implementation",
"sortings",
"strings"
] | 800 | for _ in range(int(input())):
n = int(input())
s = input()
print("YES" if list(s) == sorted(s) else "NO") |
1976 | B | Increase/Decrease/Copy | You are given two integer arrays: array $a$ of length $n$ and array $b$ of length $n+1$.
You can perform the following operations any number of times in any order:
- choose any element of the array $a$ and increase it by $1$;
- choose any element of the array $a$ and decrease it by $1$;
- choose any element of the ar... | Let's fix the index of the element to be copied (denote it as $i$). For all other elements of the array, the number of required operations is $|a_j-b_j|$ for all $j \ne i$. Consider the case when $a_i \le b_i$ (similar to the case when $a_i \ge b_i$). There are three possible relative location of the desired element $b... | [
"greedy",
"implementation"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
using li = long long;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<li> a(n), b(n + 1);
for (auto& x : a) cin >> x;
for (auto& x : b) cin >> x;
li sum = 0, ext = 1e18;
for (int i = 0; i < n; ++i) {
sum += a... |
1976 | C | Job Interview | Monocarp is opening his own IT company. He wants to hire $n$ programmers and $m$ testers.
There are $n+m+1$ candidates, numbered from $1$ to $n+m+1$ in chronological order of their arriving time. The $i$-th candidate has programming skill $a_i$ and testing skill $b_i$ (a person's programming skill is different from th... | Let's naively calculate the answer for the $(n+m+1)$-th candidate. While calculating it, let's store two values: $type_i$ - the type of job the $i$-th candidate was hired for; $bad$ - the index of the first candidate who was hired for a suboptimal role. We can show that this first candidate $bad$ who was hired for a su... | [
"binary search",
"dp",
"greedy",
"implementation",
"two pointers"
] | 1,600 | for _ in range(int(input())):
n, m = map(int, input().split())
bounds = [n, m]
a = []
a.append(list(map(int, input().split())))
a.append(list(map(int, input().split())))
bad = -1
badType = -1
cur = [0, 0]
ans = 0
types = [0 for i in range(n + m + 1)]
for i in range(n + m... |
1976 | D | Invertible Bracket Sequences | A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example:
- bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)");
-... | Let's define $bal_i$ as the number of characters '(' minus the number of characters ')' if we consider a prefix of length $i$. The bracket sequence is regular if both of the following conditions holds: there is no index $i$ such that $bal_i < 0$; $bal_n = 0$, where $n$ is the length of the sequence. Using that fact, we... | [
"binary search",
"combinatorics",
"data structures",
"divide and conquer",
"implementation",
"two pointers"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
map<int, int> cnt;
int b = 0;
++cnt[b];
long long ans = 0;
for (auto& c : s) {
b += (c == '(' ? +1 : -1);
ans += cnt[b];
++cnt[b];
while (cnt.begin(... |
1976 | E | Splittable Permutations | Initially, we had one array, which was a permutation of size $n$ (an array of size $n$ where each integer from $1$ to $n$ appears exactly once).
We performed $q$ operations. During the $i$-th operation, we did the following:
- choose any array we have with at least $2$ elements;
- split it into two non-empty arrays (... | First, let's deal with the case $q=n-1$. In this case, after all operations are performed, all arrays have only one element each, and can no longer be split. We can show that the initial order of elements can be restored uniquely in this case. For example, we can start with $n$ arrays consisting of single elements (one... | [
"combinatorics",
"data structures",
"dfs and similar",
"greedy",
"math",
"trees"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
const int N = 300043;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int nxt[N], prv[N];
bool exists[N];
int main()
{
int n, q;
s... |
1976 | F | Remove Bridges | You are given a rooted tree, consisting of $n$ vertices, numbered from $1$ to $n$. Vertex $1$ is the root. Additionally, the root only has one child.
You are asked to add exactly $k$ edges to the tree (possibly, multiple edges and/or edges already existing in the tree).
Recall that a bridge is such an edge that, afte... | What does an extra edge change in the configuration of the bridges? Well, all tree edges on the path between the two vertices that an extra edge connects, stop being bridges. So, the task can be restated as follows: choose $k$ pairs of distinct vertices such that: a root is present in at least one pair; the number of e... | [
"data structures",
"dfs and similar",
"dp",
"greedy",
"sortings",
"trees"
] | 2,800 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
vector<int> h;
vector<vector<int>> g;
void dfs(int v, int p = -1){
for (int u : g[v]) if (u != p){
dfs(u, v);
h[v] = max(h[v], h[u] + 1);
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int t;
... |
1977 | A | Little Nikita | The little boy Nikita was given some cubes as a present. He decided to build a tower out of them.
Initially, the tower doesn't have any cubes. In one move, Nikita either puts exactly $1$ cube on top of the tower or removes exactly $1$ cube from the top of the tower. Is it possible that after $n$ moves, the resulting t... | Note that one action with the cube changes the parity of the number of cubes in the tower. Therefore, if the parities of $n$ and $m$ do not match, it is impossible to build the tower. Also, if $n < m$, the tower cannot be built either. In all other cases, it is possible to build a tower of height $m$ in $m$ operations,... | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n, m;
cin >> n >> m;
cout << (n >= m && (n%2) == (m%2) ? "Yes" : "No") << '\n';
}
} |
1977 | B | Binary Colouring | You are given a positive integer $x$. Find any array of integers $a_0, a_1, \ldots, a_{n-1}$ for which the following holds:
- $1 \le n \le 32$,
- $a_i$ is $1$, $0$, or $-1$ for all $0 \le i \le n - 1$,
- $x = \displaystyle{\sum_{i=0}^{n - 1}{a_i \cdot 2^i}}$,
- There does not exist an index $0 \le i \le n - 2$ such th... | We will iterate over the prefix of $i$ bits and construct a correct answer for the number formed by the prefix bits of the number $x$. We are interested in considering only the one bits, as they are the only ones that affect the value of the number $x$. If we have already placed a one at position $i$ in the answer, we ... | [
"bitmasks",
"constructive algorithms",
"greedy",
"math"
] | 1,100 | #include "bits/stdc++.h"
#define all(a) a.begin(), a.end()
#define pb push_back
typedef long long ll;
using namespace std;
mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());
/// Actual code starts here
const int N = 100005;
void solve() {
ll x;
cin >> x;
vector<int> res(... |
1977 | C | Nikita and LCM | Nikita is a student passionate about number theory and algorithms. He faces an interesting problem related to an array of numbers.
Suppose Nikita has an array of integers $a$ of length $n$. He will call a subsequence$^\dagger$ of the array special if its least common multiple (LCM) is not contained in $a$. The LCM of ... | Try to check if the entire array $a$ can be the answer. First, let's understand if we can take the entire array $a$ as the special subsequence. To do this, find the LCM($a_1, a_2, \dots, a_n$). If it is greater than max($a_1, a_2, \dots, a_n$), then obviously such a number is not in the subsequence, because $LCM \geq m... | [
"brute force",
"data structures",
"dp",
"greedy",
"math",
"number theory",
"sortings"
] | 1,900 | #include "bits/stdc++.h"
#define err(x) cerr << "["#x"] " << (x) << "\n"
#define errv(x) {cerr << "["#x"] ["; for (const auto& ___ : (x)) cerr << ___ << ", "; cerr << "]\n";}
#define errvn(x, n) {cerr << "["#x"] ["; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << ", "; cerr << "]\n";}
#define all(a) a.beg... |
1977 | D | XORificator | You are given a binary (consisting only of 0s and 1s) $n \times m$ matrix. You are also given a XORificator, using which you can invert all the values in a chosen row (i.e. replace 0 with 1 and 1 with 0).
A column in the matrix is considered special if it contains exactly one 1. Your task is to find the maximum number... | Try to fix the specialty of column $i$ and the presence of a one in cell $i, j$. Let's assume that the value in the $i$-th row and $j$-th column is strictly one and it is the only one in the column. Then the entire table is uniquely determined, as well as the XORificator. For each possible state of the XORificator that... | [
"bitmasks",
"brute force",
"greedy",
"hashing"
] | 2,300 | #include "bits/stdc++.h"
using namespace std;
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
void solve() {
int n, m;
cin >> n >> m;
vector<vector<bool>> table(n, vector<bool>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
char c;
... |
1977 | E | Tensor | This is an interactive problem.
You are given an integer $n$.
The jury has hidden from you a directed graph with $n$ vertices (numbered from $1$ to $n$) and some number of edges. You additionally know that:
- The graph only contains edges of the form $i \leftarrow j$, where $1 \le i < j \le n$.
- For any three verti... | First, let's understand why 2 colors are indeed sufficient. Notice that the reachability relation in a graph defines a Partially Ordered Set. According to Dilworth's Theorem, the size of the maximum antichain is equal to the minimum number of chains that cover the Partially Ordered Set. Note that the condition on the r... | [
"constructive algorithms",
"graphs",
"interactive"
] | 2,600 | #include "bits/stdc++.h"
#define err(x) cerr << "["#x"] " << (x) << "\n"
#define errv(x) {cerr << "["#x"] ["; for (const auto& ___ : (x)) cerr << ___ << ", "; cerr << "]\n";}
#define errvn(x, n) {cerr << "["#x"] ["; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << ", "; cerr << "]\n";}
#define all(a) a.beg... |
1978 | A | Alice and Books | Alice has $n$ books. The $1$-st book contains $a_1$ pages, the $2$-nd book contains $a_2$ pages, $\ldots$, the $n$-th book contains $a_n$ pages. Alice does the following:
- She divides all the books into two non-empty piles. Thus, each book ends up in exactly one of the two piles.
- Alice reads one book with the \text... | Note that we will always be required to take a book with the number $n$. Thus, the answer can be all pairs of the form $(k, n)$, where $k < n$. We will find a pair with the maximum sum among these, and it will be the answer. | [
"constructive algorithms",
"greedy",
"sortings"
] | 800 | #include <random>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define ll long long
#define pii pair<int, int>
#define pb emplace_back
int main() {
int t;
cin >> t;
... |
1978 | B | New Bakery | Bob decided to open a bakery. On the opening day, he baked $n$ buns that he can sell. The usual price of a bun is $a$ coins, but to attract customers, Bob organized the following promotion:
- Bob chooses some integer $k$ ($0 \le k \le \min(n, b)$).
- Bob sells the first $k$ buns at a modified price. In this case, the ... | If $b < a$, then the answer is obviously equal to $a \cdot n$. Otherwise, the profit will be maximized when $k = \min(b - a, n)$. Indeed, if we take $k$ larger, then Bob will sell some buns for less than $a$ coins, which is not profitable. If we take $k$ smaller, then he will sell some buns for $a$ coins, although he c... | [
"binary search",
"greedy",
"math",
"ternary search"
] | 800 | #include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long n, a, b;
cin >> n >> a >> b;
if (b <= a) {
cout << n * a << endl;
} else {
long long k = min(b — a + 1, n);
cout << (b — k + 1) * n... |
1978 | C | Manhattan Permutations | Let's call the Manhattan value of a permutation$^{\dagger}$ $p$ the value of the expression $|p_1 - 1| + |p_2 - 2| + \ldots + |p_n - n|$.
For example, for the permutation $[1, 2, 3]$, the Manhattan value is $|1 - 1| + |2 - 2| + |3 - 3| = 0$, and for the permutation $[3, 1, 2]$, the Manhattan value is $|3 - 1| + |1 - 2... | Notice that if $k$ is odd, then there is no solution. Also notice that the maximum $max_k$ is achieved with the permutation $[n, n - 1, n - 2, ..., 1]$, so if $k > max_k$, then there is also no solution. It is claimed that for any other $k$, a solution exists. Let's consider what happens if we swap $x$ and $1$ in the i... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
cin >> T;
while (T--) {
int n;
ll k;
cin >> n >> k;
ll max_s = 0;
for (int i = 0; i < n; i++) max_s += abs(n &mdas... |
1978 | D | Elections | Elections are taking place in Berland. There are $n$ candidates participating in the elections, numbered from $1$ to $n$. The $i$-th candidate has $a_i$ fans who will vote for him. Additionally, there are $c$ people who are undecided about their favorite candidate, let's call them undecided. Undecided people will vote ... | Notice that if candidate $i$ does not win initially (when no one is removed), then for their victory, we must definitely remove all candidates with numbers less than $i$. Because if someone remains unremoved with a number less than $i$, then the votes for candidate $i$ will not increase, and the maximum number of votes... | [
"data structures",
"greedy",
"implementation",
"math"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n, c;
cin >> n >> c;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
if (n == 1) {
cout << "0\n";
return;
}
int mx = *max_element(a.begin() + 1, a.end());
... |
1978 | E | Computing Machine | Sasha has two binary strings $s$ and $t$ of the same length $n$, consisting of the characters 0 and 1.
There is also a computing machine that can perform two types of operations on binary strings $a$ and $b$ of the same length $k$:
- If $a_{i} = a_{i + 2} =$ 0, then you can assign $b_{i + 1} :=$ 1 ($1 \le i \le k - 2... | Notice that it is advantageous to perform only operations of the first type first, and then only operations of the second type. Perform all possible operations of the first type on the string $t$ and save it in $t'$. Perform all possible operations of the second type on the string $s$, using $t'$, and save it in $s'$. ... | [
"brute force",
"data structures",
"dp",
"greedy",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n;
string s, t;
cin >> n >> s >> t;
auto get_range = [&] (int i) {
if (s[i] == '1') return make_pair(i, i);
int l = -1, r = -1;
if (i > 0 &... |
1978 | F | Large Graph | Given an array $a$ of length $n$. Let's construct a square matrix $b$ of size $n \times n$, in which the $i$-th row contains the array $a$ cyclically shifted to the right by $(i - 1)$. For example, for the array $a = [3, 4, 5]$, the obtained matrix is
$$b = \begin{bmatrix} 3 & 4 & 5 \\ 5 & 3 & 4 \\ 4 & 5 & 3 \end{bmat... | Notice that since we have cyclic shifts to the right and k > 1, the diagonals parallel to the main one will be in the same connected component, except for the case with ones. Diagonals consisting of ones will be counted separately and forgotten. After that, we can solve the problem for the one-dimensional case, where e... | [
"data structures",
"dfs and similar",
"dsu",
"graphs",
"number theory",
"two pointers"
] | 2,400 | #include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <cstring>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include <ctime>... |
1979 | A | Guess the Maximum | Alice and Bob came up with a rather strange game. They have an array of integers $a_1, a_2,\ldots, a_n$. Alice chooses a certain integer $k$ and tells it to Bob, then the following happens:
- Bob chooses two integers $i$ and $j$ ($1 \le i < j \le n$), and then finds the maximum among the integers $a_i, a_{i + 1},\ldot... | Let $m$ be the maximum among the numbers $a_i, a_{i + 1},\ldots, a_j$. Notice that there always exists such $k$ that $i \le k < j$ and $a_k = m$ or $a_{k + 1} = m$. Therefore, we can assume that Bob always chooses the pair of numbers $p$ and $p + 1$ ($1 \le p < n$) as $i$ and $j$. Therefore you need to consider the max... | [
"brute force",
"greedy",
"implementation"
] | 800 | #include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n];
for (int& i : a) {
cin >> i;
}
int mini = max(a[0], a[1]);
for (int i = 1; i < n - 1; i++) {
mini = min(mini, max(a... |
1979 | B | XOR Sequences | You are given two distinct non-negative integers $x$ and $y$. Consider two infinite sequences $a_1, a_2, a_3, \ldots$ and $b_1, b_2, b_3, \ldots$, where
- $a_n = n \oplus x$;
- $b_n = n \oplus y$.
Here, $x \oplus y$ denotes the bitwise XOR operation of integers $x$ and $y$.
For example, with $x = 6$, the first $8$ e... | Look at samples. Consider two numbers $v$ and $u$ such that $x \oplus v = y \oplus u$. Then consider the numbers $x \oplus (v + 1)$ and $y \oplus (u + 1)$. Let's look at the last bit of $v$ and $u$. Possible scenarios: Both bits are equal to $0$ - adding one will change the bits at the same positions, therefore $x \opl... | [
"bitmasks",
"greedy"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
for (int i = 0; i < 30; i++) {
if ((a & (1 << i)) != (b & (1 << i))) {
cout << (1ll << i) << "\n";
break;
... |
1979 | C | Earning on Bets | You have been offered to play a game. In this game, there are $n$ possible outcomes, and for each of them, you must bet a certain \textbf{integer} amount of coins. In the event that the $i$-th outcome turns out to be winning, you will receive back the amount of coins equal to your bet on that outcome, multiplied by $k_... | Try to come up with a condition for the existence of an answer. Let $S$ be the total amount of coins placed on all possible outcomes. Then, if the coefficient for winning is $k_i$, we have to place more than $\frac{S}{k_i}$ on this outcome. We can obtain the following inequality: $\sum_{i = 1}^n \frac{S}{k_i} < S.$ Div... | [
"binary search",
"combinatorics",
"constructive algorithms",
"number theory"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
#define int long long
int gcd(int a, int b) {
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
void solve() {
int n;
cin >> n;
vector <int> k(n);
... |
1979 | D | Fixing a Binary String | You are given a binary string $s$ of length $n$, consisting of zeros and ones. You can perform the following operation \textbf{exactly once}:
- Choose an integer $p$ ($1 \le p \le n$).
- Reverse the substring $s_1 s_2 \ldots s_p$. After this step, the string $s_1 s_2 \ldots s_n$ will become $s_p s_{p-1} \ldots s_1 s_{... | Let's consider the block of characters at the end. Notice that their quantity cannot decrease. Let $x$ be the number of identical characters at the end; there are three possible cases: $x = k$ - it is enough to find any block of length greater than $k$ and separate a block of length $k$ from it; $x > k$ - obviously, th... | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"greedy",
"hashing",
"strings"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int x = 0;
for (int i = n - 1; i >= 0; i--) {
if (s[i] == s[n - 1]) {
x++;
... |
1979 | E | Manhattan Triangle | The Manhattan distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is defined as: $$|x_1 - x_2| + |y_1 - y_2|.$$
We call a Manhattan triangle three points on the plane, the Manhattan distances between each pair of which are equal.
You are given a set of pairwise distinct points and an \textbf{even} integer $d$. ... | In every Manhattan triangle there are two points such that $|x_1 - x_2| = |y_1 - y_2|$. Note this fact: in every Manhattan triangle there are two points such that $|x_1 - x_2| = |y_1 - y_2|$. Let's start with distributing all points with their $(x + y)$ value. For each point $(x; y)$ find point $(x + d / 2; y - d / 2)$... | [
"binary search",
"constructive algorithms",
"data structures",
"geometry",
"implementation",
"two pointers"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int MAXC = 1e5;
const int MAXD = 4e5 + 10;
set <pair <int, int>> diag[MAXD];
void solve() {
int n, d;
cin >> n >> d;
vector <int> x(n), y(n);
for (int i = 0; i < n; i++) {
cin >> x[i] >> y[i];
x[i] += MAXC;
y[i] += MAXC;... |
1979 | F | Kostyanych's Theorem | This is an interactive problem.
Kostyanych has chosen a complete undirected graph$^{\dagger}$ with $n$ vertices, and then removed exactly $(n - 2)$ edges from it. You can ask queries of the following type:
- "? $d$" — Kostyanych tells you the number of vertex $v$ with a degree \textbf{at least} $d$. Among all possibl... | Let's consider the following recursive algorithm. We will store the Hamiltonian path as a double-ended queue, maintaining the start and end. In case there are only $1$ or $2$ vertices left in the graph, the problem is solved trivially. Suppose we know that the current graph has $n$ vertices, and there are at most $(n -... | [
"brute force",
"constructive algorithms",
"graphs",
"interactive"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
pair <int, int> ask(int d) {
cout << "? " << d << endl;
int v, u;
cin >> v >> u;
return {v, u};
}
pair <int, int> get(int n, vector <int>& nxt) {
if (n == 1) {
int v = ask(0).first;
return {v, v};
}
if (n == 2) {
int u ... |
1980 | A | Problem Generator | Vlad is planning to hold $m$ rounds next month. Each round should contain one problem of difficulty levels 'A', 'B', 'C', 'D', 'E', 'F', and 'G'.
Vlad already has a bank of $n$ problems, where the $i$-th problem has a difficulty level of $a_i$. There may not be enough of these problems, so he may have to come up with ... | It is necessary to have at least $m$ problems of each difficulty level. If there are already at least $m$ problems of difficulty level $c$, then there is no need to come up with more problems of this difficulty level. Otherwise, it is necessary to come up with $m - cnt_c$ problems, where $cnt_c$ is the number of proble... | [
"math"
] | 800 | def solve():
n, m = map(int, input().split())
a = input()
ans = 0
for ch in range(ord('A'), ord('H')):
ans += max(0, m - a.count(chr(ch)))
print(ans)
for _ in range(int(input())):
solve() |
1980 | B | Choosing Cubes | Dmitry has $n$ cubes, numbered from left to right from $1$ to $n$. The cube with index $f$ is his favorite.
Dmitry threw all the cubes on the table, and the $i$-th cube showed the value $a_i$ ($1 \le a_i \le 100$). After that, he arranged the cubes in non-increasing order of their values, from largest to smallest. If ... | Let $x$ be the value of the cube with the number $f$. Let's sort all the cubes by non-growth. Then let's look at the value of the $k$-th cube in order. Since the cubes are removed by non-growth, all cubes with large values will be removed, some (perhaps not all) cubes with the same value, and cubes with smaller values ... | [
"sortings"
] | 800 | def solve():
n, f, k = map(int, input().split())
f -= 1
k -= 1
a = list(map(int, input().split()))
x = a[f]
a.sort(reverse=True)
if a[k] > x:
print("NO")
elif a[k] < x:
print("YES")
else:
print("YES" if k == n - 1 or a[k + 1] < x else "MAYBE")
t = int(input(... |
1980 | C | Sofia and the Lost Operations | Sofia had an array of $n$ integers $a_1, a_2, \ldots, a_n$. One day she got bored with it, so she decided to \textbf{sequentially} apply $m$ modification operations to it.
Each modification operation is described by a pair of numbers $\langle c_j, d_j \rangle$ and means that the element of the array with index $c_j$ s... | First, in the array $b_1, b_2, \ldots, b_n$, the number $d_m$ must be present. Second, if $a_i = b_i$, we will not apply any operations to $i$. All extra operations can be applied to $a_j$, where $b_j = d_m$, they will be overwritten by the operation $d_m$. For all other $i$ ($a_i \neq b_i$) we must apply the operation... | [
"constructive algorithms",
"greedy"
] | 1,300 | #include <stdio.h>
#include <stdbool.h>
#define MAXN 200200
#define MAXM 200200
int n, m, k;
int arr[MAXN], brr[MAXN], drr[MAXM], buf[MAXN];
int cmp_i32(const void* pa, const void* pb) {
return *(const int*)pa - *(const int*)pb;
}
void build() {
k = 0;
for (int i = 0; i < n; ++i) {
if (arr[i... |
1980 | D | GCD-sequence | GCD (Greatest Common Divisor) of two integers $x$ and $y$ is the maximum integer $z$ by which both $x$ and $y$ are divisible. For example, $GCD(36, 48) = 12$, $GCD(5, 10) = 5$, and $GCD(7,11) = 1$.
Kristina has an array $a$ consisting of exactly $n$ positive integers. She wants to count the GCD of each neighbouring pa... | Let's loop through the initial array $a$, counting the GCD of neighbouring elements. If at some point, the GCD of the previous pair becomes greater than the GCD of the next pair, we remember the index $i$ of the first element of the pair that gave the greater GCD and stop the loop. Then consider the following cases: th... | [
"greedy",
"implementation",
"math",
"number theory"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
bool good(vector<int>&b){
int g = __gcd(b[0], b[1]);
for(int i = 1; i < int(b.size()) - 1; i++){
int cur_gcd = __gcd(b[i], b[i + 1]);
if(g > cur_gcd) return false;
g = cur_gcd;
}
return true;
}
bool solve(){
int n;
cin >> ... |
1980 | E | Permutation of Rows and Columns | You have been given a matrix $a$ of size $n$ by $m$, containing a permutation of integers from $1$ to $n \cdot m$.
A permutation of $n$ integers is an array containing all numbers from $1$ to $n$ exactly once. For example, the arrays $[1]$, $[2, 1, 3]$, $[5, 4, 3, 2, 1]$ are permutations, while the arrays $[1, 1]$, $[... | For each element, you can calculate its positions in both matrices. You can see that the rearrangement of rows does not affect the column positions of the elements being rearranged. Similarly, column rearrangement does not affect row positions. Since the permutation of rows affects the entire rows, for all elements tha... | [
"constructive algorithms",
"data structures",
"greedy",
"hashing",
"implementation",
"math",
"matrices",
"sortings"
] | 1,600 | #include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
vi read_ints(int n) {
vi res(n);
for (int i = 0; i < n; ++i) {
cin >> res[i];
}
return res;
}
vvi read_matrix(int n, int m)... |
1980 | F1 | Field Division (easy version) | \textbf{This is an easy version of the problem; it differs from the hard version only by the question. The easy version only needs you to print whether some values are non-zero or not. The hard version needs you to print the exact values.}
Alice and Bob are dividing the field. The field is a rectangle of size $n \time... | Since Alice can only move down or to the right, if in the $i$-th row $x$ cells belong to her, then in the $(i-1)$-th row she can have no more than $x$ cells. The construction of the maximum plot can be represented as follows: we will go through the rows from bottom to top and keep track of how many cells we have collec... | [
"data structures",
"math",
"sortings"
] | 1,900 | #include <bits/stdc++.h>
#define int long long
#define pb emplace_back
#define mp make_pair
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(time(nullptr));
const ll inf = 1e9 ... |
1980 | F2 | Field Division (hard version) | \textbf{This is a hard version of the problem; it differs from the easy version only by the question. The easy version only needs you to print whether some values are non-zero or not. The hard version needs you to print the exact values.}
Alice and Bob are dividing the field. The field is a rectangle of size $n \times... | First, read the editorial of the easy version. Let's use the solution of the easy version to precalculate the stored information on the prefix. The fountain will stop being a corner only when it is removed, because the leftmost corner on the prefix could not become further left as a result of removal. To calculate the ... | [
"math",
"sortings"
] | 2,400 | #include <bits/stdc++.h>
#define int long long
#define pb emplace_back
#define mp make_pair
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(time(nullptr));
const ll inf = 1e9 ... |
1980 | G | Yasya and the Mysterious Tree | Yasya was walking in the forest and accidentally found a tree with $n$ vertices. A tree is a connected undirected graph with no cycles.
Next to the tree, the girl found an ancient manuscript with $m$ queries written on it. The queries can be of two types.
The first type of query is described by the integer $y$. The w... | We will hang the tree on the vertex $1$ and count for each vertex $d_v$ - xor on the path from it to the root. This can be done by depth-first traversal in $O(n)$. Now let's learn how to solve the problem in $O(n)$ for each query. The first type of query can be executed straightforwardly. Notice that due to the propert... | [
"bitmasks",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"strings",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
struct trie {
int l, c;
vector<array<int, 2>> node;
vector<int> cnt;
trie(int l, int max_members) : l(l), c(0), node((l + 2) * max_members + 3), cnt((l + 2) * max_members + 3) {}
void add(int x) {
int cur = 0;
for (int i = l; i >= 0; --... |
1981 | A | Turtle and Piggy Are Playing a Game | Turtle and Piggy are playing a number game.
First, Turtle will choose an integer $x$, such that $l \le x \le r$, where $l, r$ are given. It's also guaranteed that $2l \le r$.
Then, Piggy will keep doing the following operation until $x$ becomes $1$:
- Choose an integer $p$ such that $p \ge 2$ and $p \mid x$ (i.e. $x... | For a specific $x$, Piggy always chooses $p$ such that $p$ is a prime number, so the score is the number of prime factors of $x$. It is easy to see that the number with at least $t$ prime factors is $2^t$. The largest integer $t$ satisfying $2^t \le r$ is $\left\lfloor\log_2 r\right\rfloor$. Also, because $2l \le r$, t... | [
"brute force",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int T;
scanf("%d", &T);
while (T--) {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", __lg(r));
}
return 0;
} |
1981 | B | Turtle and an Infinite Sequence | There is a sequence $a_0, a_1, a_2, \ldots$ of infinite length. Initially $a_i = i$ for every non-negative integer $i$.
After every second, each element of the sequence will \textbf{simultaneously} change. $a_i$ will change to $a_{i - 1} \mid a_i \mid a_{i + 1}$ for every positive integer $i$. $a_0$ will change to $a_... | Each bit of the answer is independent, so we can calculate the value of each bit of the answer separately. Let's consider the $d$-th bit. Then, $a_i = \left\lfloor\frac{i}{2^d}\right\rfloor \bmod 2$. Every second, a $1$ will "spread" one position to the left and right. If $a_n$ is initially $1$, then the answer for thi... | [
"bitmasks",
"math"
] | 1,300 | #include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;
void solve() {
ll... |
1981 | C | Turtle and an Incomplete Sequence | Turtle was playing with a sequence $a_1, a_2, \ldots, a_n$ consisting of positive integers. Unfortunately, some of the integers went missing while playing.
Now the sequence becomes incomplete. There may exist an arbitrary number of indices $i$ such that $a_i$ becomes $-1$. Let the new sequence be $a'$.
Turtle is sad.... | Handle the special case where all elements are $-1$ first. Consider extracting all positions where the values are not $-1$, denoted as $c_1, c_2, \ldots, c_k$. The segments $[1, c_1 - 1]$ and $[c_k + 1, n]$ with $-1$s are easy to handle by repeatedly multiplying and dividing by $2$. It's easy to see that the constructi... | [
"bitmasks",
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,800 | #include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;
const int maxn = 2... |
1981 | D | Turtle and Multiplication | Turtle just learned how to multiply two integers in his math class, and he was very excited.
Then Piggy gave him an integer $n$, and asked him to construct a sequence $a_1, a_2, \ldots, a_n$ consisting of integers which satisfied the following conditions:
- For all $1 \le i \le n$, $1 \le a_i \le 3 \cdot 10^5$.
- For... | The necessary condition for $a_i \cdot a_{i + 1} = a_j \cdot a_{j + 1}$ is that the unordered pairs $(a_i, a_{i + 1})$ and $(a_j, a_{j + 1})$ are identical. In fact, if $a_i$ are all prime numbers, then this necessary condition becomes sufficient. If we consider $(a_i, a_{i + 1})$ as an edge, then the problem can be tr... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"number theory"
] | 2,400 | #include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<int, int> pii;
const int maxn =... |
1981 | E | Turtle and Intersected Segments | Turtle just received $n$ segments and a sequence $a_1, a_2, \ldots, a_n$. The $i$-th segment is $[l_i, r_i]$.
Turtle will create an undirected graph $G$. If segment $i$ and segment $j$ intersect, then Turtle will add an undirected edge between $i$ and $j$ with a weight of $|a_i - a_j|$, for every $i \ne j$.
Turtle wa... | We observe that for three segments $(l_1, r_1, a_1), (l_2, r_2, a_2), (l_3, r_3, a_3)$ where each pair of segments intersects (assume $a_1 \le a_2 \le a_3$), we only need to keep the edges between $(1, 2)$ and $(2, 3)$, because $a_3 - a_1 = a_2 - a_1 + a_3 - a_2$ and for every cycle in a graph, the edge with the maximu... | [
"data structures",
"dsu",
"graphs",
"greedy"
] | 2,600 | #include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<int, int> pii;
const int maxn =... |
1981 | F | Turtle and Paths on a Tree | \textbf{Note the unusual definition of $\text{MEX}$ in this problem.}
Piggy gave Turtle a \textbf{binary tree}$^{\dagger}$ with $n$ vertices and a sequence $a_1, a_2, \ldots, a_n$ on his birthday. The binary tree is rooted at vertex $1$.
If a set of paths $P = \{(x_i, y_i)\}$ in the tree covers each edge \textbf{exac... | Let's consider dp. Let $f_{u, i}$ denote the path extending upward within the subtree rooted at $u$, with the condition that this path does not include the value $i$. The value of $i$ ranges from $[1, n + 1]$. In this case, we can directly take the MEX of this path as $i$, because if the MEX is not $i$, then the MEX wi... | [
"data structures",
"dp",
"trees"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
namespace my_std{
#define ll long long
#define bl bool
ll my_pow(ll a,ll b,ll mod){
ll res=1;
if(!b) return 1;
while(b){
if(b&1) res=(res*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return res;
}
ll qpow(ll a,ll b){
ll res=1;
if(!b) return 1;
while(b){
if(... |
1982 | A | Soccer | Dima loves watching soccer. In such a game, the score on the scoreboard is represented as $x$ : $y$, where $x$ is the number of goals of the first team, and $y$ is the number of goals of the second team. At any given time, only one team can score a goal, so the score $x$ : $y$ can change to either $(x + 1)$ : $y$, or $... | In all cases where the first team initially led the score, and then the second team, there will be a moment when the score is equal, so it is enough to check only this condition. If it is met, the answer is "NO", otherwise the answer is "YES". Let's demonstrate how events could have unfolded without an equal score, if ... | [
"greedy",
"implementation",
"math",
"sortings"
] | 800 | t = int(input())
for T in range(t):
la, lb = map(int, input().split())
ra, rb = map(int, input().split())
if la > lb:
la, lb, ra, rb = lb, la, rb, ra
if la < lb and rb < ra:
print("NO")
else:
print("YES") |
1982 | B | Collatz Conjecture | Recently, the first-year student Maxim learned about the Collatz conjecture, but he didn't pay much attention during the lecture, so he believes that the following process is mentioned in the conjecture:
There is a variable $x$ and a constant $y$. The following operation is performed $k$ times:
- increase $x$ by $1$,... | Let's write down what happens in the problem and try to speed it up. The first observation: we will perform operations until $x \neq 1$, after which the answer can be found using the formula $ans = 1 + k\,\%\,(y - 1)$. Indeed, after $x$ becomes equal to $1$, if we continue applying operations to it, it will change as f... | [
"brute force",
"implementation",
"math",
"number theory"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
void solve(){
long long x, y, k;
cin >> x >> y >> k;
while (k > 0 && x != 1) {
long long ost = (x / y + 1) * y - x;
ost = max(1ll, ost);
ost = min(ost, k);
x += ost;
while (x % y == 0) {
x /= y;
}
k -= ost;
... |
1982 | C | Boring Day | On another boring day, Egor got bored and decided to do something. But since he has no friends, he came up with a game to play.
Egor has a deck of $n$ cards, the $i$-th card from the top has a number $a_i$ written on it. Egor wants to play a certain number of rounds until the cards run out. In each round, he takes a n... | Solution 1: Let $dp[i]$ - the maximum number of rounds won by Egor for the first $i$ elements (top cards). It is possible to come up with a solution in $O(n^{2})$ right now. For each state of the dynamic programming $i$, you can either skip the next card (not take it in any winning segment), or iterate over the length ... | [
"binary search",
"data structures",
"dp",
"greedy",
"two pointers"
] | 1,200 | t = int(input())
for T in range(t):
n, l, r = map(int, input().split())
a = [int(x) for x in input().split()]
ans = 0
cur = 0
L, R = 0, 0
while L < n:
while R < n and cur < l:
cur += a[R]
R += 1
if l <= cur and cur <= r:
ans += 1
L = R
cur = 0
else:
cur -= a[L]
L += 1
print(ans) |
1982 | D | Beauty of the mountains | Nikita loves mountains and has finally decided to visit the Berlyand mountain range! The range was so beautiful that Nikita decided to capture it on a map. The map is a table of $n$ rows and $m$ columns, with each cell containing a non-negative integer representing the height of the mountain.
He also noticed that moun... | First, let's calculate the current difference between the heights of different types of mountains, denoted as $D$. Then, for each submatrix of size $k \times k$, we will calculate how the difference in the sums of heights of different types of mountains changes. That is, for each submatrix, we will calculate the differ... | [
"brute force",
"data structures",
"implementation",
"math",
"number theory"
] | 1,700 | import math
def solve():
n, m, k = map(int, input().split())
a = [[int(x) for x in input().split()] for j in range(n)]
s = [input() for i in range(n)]
pref = [[0 for i in range(m + 1)] for j in range(n + 1)]
diff = 0
for i in range(n):
cur = 0
for j in range(m):
if ... |
1982 | E | Number of k-good subarrays | Let $bit(x)$ denote the number of ones in the binary representation of a non-negative integer $x$.
A subarray of an array is called $k$-good if it consists only of numbers with no more than $k$ ones in their binary representation, i.e., a subarray $(l, r)$ of array $a$ is good if for any $i$ such that $l \le i \le r$ ... | Let $f(n, k)$ be a function to solve the problem, which will return three values $(l, r, ans)$ such that: $l$ - for the first $l$ numbers (i.e. from $0$ to $l - 1$) $bit(x) \le k$ holds, while $bit(l) > k$ or $l \ge n$; $r$ - for the last $r$ numbers (i.e. from $n - r$ to $n - 1$) $bit(x) \le k$ holds, while $bit(n - r... | [
"bitmasks",
"brute force",
"combinatorics",
"divide and conquer",
"dp",
"math",
"meet-in-the-middle"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
map<pair<long long, int>, tuple<int, long long, long long>> mem;
tuple<int, long long, long long> calc(long long n, int k){
if (k < 0){
return tuple{0, 0ll, 0ll};
}
if (n == 1){
return tuple{1, 1ll, 1ll};
}
int bit = 63 - __built... |
1982 | F | Sorting Problem Again | You have an array $a$ of $n$ elements. There are also $q$ modifications of the array. Before the first modification and after each modification, you would like to know the following:
What is the minimum length subarray that needs to be sorted in non-decreasing order in order for the array $a$ to be completely sorted i... | Let's maintain a set $s$ of positions $i$ such that $a_{i} < a_{i - 1}$, and also a segment tree (or any other data structure that allows changing the value at a position and finding the minimum/maximum on a segment). Recalculating the set and the segment tree is quite simple for each change in the array $a$. To answer... | [
"binary search",
"data structures",
"sortings"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int inf = 1000000007;
struct SegTree{
vector<int> mn, mx;
int n;
SegTree(int _n): n(_n){
mx.assign(2 * n, -inf);
mn.resize(2 * n, inf);
}
void upd(int pos, int val){
mx[pos + n] = val;
mn[pos + n] = val;
pos = (pos + n) >> 1;
for (;pos > 0; po... |
1983 | A | Array Divisibility | An array of integers $a_1,a_2,\cdots,a_n$ is beautiful subject to an integer $k$ if it satisfies the following:
- The sum of $a_{j}$ over all $j$ such that $j$ is a multiple of $k$ and $1 \le j \le n $, itself, is a multiple of $k$.
- More formally, if $\sum_{k | j} a_{j}$ is divisible by $k$ for all $1 \le j \le n$ t... | The construction $a[i] = i$ for all $1 \le i \le n$ satisfies all the required conditions. | [
"constructive algorithms",
"math"
] | 800 | t = int(input())
for _ in range(t):
n = int(input())
for i in range(1, n + 1):
print(i, end=" ")
print() |
1983 | B | Corner Twist | You are given two grids of numbers $a$ and $b$, with $n$ rows and $m$ columns. All the values in the grid are $0$, $1$ or $2$.
You can perform the following operation on $a$ any number of times:
- Pick any subrectangle in the grid with length and width $\ge 2$. You are allowed to choose the entire grid as a subrectan... | Notice how the operations affect each row and column. The problem offers a really simple solution: the sum of each row and each column modulo $3$ needs to remain constant throughout all the operations. It is easy to see that this is a necessary condition. Let's prove that this is sufficient as well. Notice that using t... | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,200 | t = int(input())
while(t):
t -= 1
n, m = list(map(int,input().split(' ')))
grid_a = []
grid_b = []
for i in range(n):
grid_a.append(list(map(int, list(input()))))
for i in range(n):
grid_b.append(list(map(int, list(input()))))
ac = [0] * n
ar = [0] * m
bc = [0] * n
... |
1983 | C | Have Your Cake and Eat It Too | Alice, Bob and Charlie want to share a rectangular cake cut into $n$ pieces. Each person considers every piece to be worth a different value. The $i$-th piece is considered to be of value $a_i$ by Alice, $b_i$ by Bob and $c_i$ by Charlie.
The sum over all $a_i$, all $b_i$ and all $c_i$ individually is the same, equal ... | There can be several correct answers. It is sufficient to find any correct answer. Although it is not necessary to finish the entire cake, we can easily find a way such that the entire cake is given away. We can start by trying to give a prefix to Alice. To determine if it is possible to divide the cake such that Alice... | [
"binary search",
"brute force",
"greedy",
"implementation"
] | 1,400 | from itertools import permutations
t = int(input())
while(t):
t -= 1
n = int(input())
val = [[0],[0],[0]]
pf = [[0],[0],[0]]
for i in range(3):
val[i] += list(map(int,input().split(' ')))
for i in range(3):
for j in range(1,n+1):
pf[i].append(pf[i][j-1] + val[i][j... |
1983 | D | Swap Dilemma | Given two arrays of distinct positive integers $a$ and $b$ of length $n$, we would like to make both the arrays the same. Two arrays $x$ and $y$ of length $k$ are said to be the same when for all $1 \le i \le k$, $x_i = y_i$.
Now in one move, you can choose some index $l$ and $r$ in $a$ ($l \le r$) and swap $a_l$ and ... | If both the arrays don't have the same multiset of elements then trivially the answer is "NO". Otherwise, we can convert any operation of the form $l$, $r$, $p$, $q$ to swapping $l$, $l+1$, $p$, $p+1$ multiple times. For example: swapping $l=1$, $r=3$, $p=2$, $q=4$ can be converted into three steps: swapping $l=1$, $r=... | [
"constructive algorithms",
"data structures",
"divide and conquer",
"greedy",
"math",
"sortings"
] | 1,700 | #include <bits/stdc++.h>
#define int long long
using namespace std;
int inversions(int arr[],int l,int r){
if(r==l)return 0;
//divide and conquer:
int mid=(l+r)/2;
int x=inversions(arr,l,mid);
int y=inversions(arr,mid+1,r);
//simple merging:
int ans[r-l+1];
int curr=0,inv=0;... |
1983 | E | I Love Balls | Alice and Bob are playing a game. There are $n$ balls, out of which $k$ are special. Each ball has a value associated with it.
The players play turn by turn. In each turn, the player randomly picks a ball and adds the value of the ball to their score, which is $0$ at the beginning of the game. The selected ball is rem... | When there are no special balls, Alice and Bob alternately pick balls starting with Alice. This means Alice picks ${\frac{n+1}{2}}$ balls if $n$ is odd or $\frac{n}{2}$ if $n$ is even. The total value of all balls is $\sum v_i$. On average, Alice's score is $\lfloor\frac{n + 1}{2}\rfloor \cdot \frac{\sum v_i}{n}$. With... | [
"combinatorics",
"math",
"probabilities"
] | 2,300 | #include <iostream>
#include <vector>
#define int long long
const int mod = 1e9 + 7;
int power(int a, int b) {
int ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return ans;
}
int inline inv(int x) { return power(x, mod - 2); }
void... |
1983 | F | array-value | You have an array of non-negative integers $a_1, a_2, \ldots, a_n$.
The value of a sub-array of length $\ge 2$, $a[l, r] = [a_l, a_{l+1}, \ldots, a_r]$ is the minimum value of $a_i \oplus a_j$ such that $l \le i < j \le r$, where $\oplus$ is the xor (exclusive-or) operator.
You have to find the $k$-th smallest value ... | We can binary search on the the value of the $k$th-smallest and maintain the number of subarrays with xor-pair less than the value. This way, we can find the $k$th-smallest value easily. In order to maintain the number of subarrays, we can use our popular xor data structure called trie. For a given binary searched valu... | [
"binary search",
"bitmasks",
"data structures",
"greedy",
"two pointers"
] | 2,500 | #include <bits/stdc++.h>
#define endl "\n"
using namespace std;
int ch[3000042][2]{}, mx[3000042]{};
int nc = 1;
void insert(int root,int val,int idx){
int curr=root;
for(int i=29;i>=0;i--){
int lr = ((val&(1<<i)) != 0);
if(!ch[curr][lr]){
nc++;
mx[nc]=idx;
... |
1983 | G | Your Loss | You are given a tree with $n$ nodes numbered from $1$ to $n$, along with an array of size $n$. The value of $i$-th node is $a_{i}$. There are $q$ queries. In each query, you are given 2 nodes numbered as $x$ and $y$.
Consider the path from the node numbered as $x$ to the node numbered as $y$. Let the path be represent... | We'll solve for each bit separately. Observe that the number of nodes contributing to the sum for a fixed bit $j$ is the sum of the bit xor'ed with an alternating pattern of $2^j$ continuous bits over the path, i.e., say for $j=2$, the bits are xor'ed with $0000111100001\ldots$. For the rest of the editorial, we will u... | [
"bitmasks",
"brute force",
"dp",
"trees"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
const int MAX = 5e5+5;
const int MAXL = 20;
const int QMAX = 1e5+5;
int n,q,b[MAX];
vector<int>g[MAX];
vector<array<int,3>>qinfo(QMAX);
vector<long long>ans(QMAX,0);
int up[MAX][MAXL],depth[MAX];
int pf[MAX], dp[MAX];
int u_split[QMAX][MAXL+1], v_split[QMAX][MAXL+1], v_end... |
1984 | A | Strange Splitting | Define the range of a non-empty array to be the maximum value minus the minimum value. For example, the range of $[1,4,2]$ is $4-1=3$.
You are given an array $a_1, a_2, \ldots, a_n$ of length $n \geq 3$. \textbf{It is guaranteed $a$ is sorted}.
You have to color each element of $a$ red or blue so that:
- the range o... | When is it impossible? When $a = [x, x \dots x]$ for some $x$. Only color one element red to make the range $0$. Which one do you pick to make the blue range different? Read the hints. It is impossible to color the array when all the elements are the same, because the range for the red and blue elements will always be ... | [
"constructive algorithms"
] | 800 | #include <iostream>
using namespace std;
int main(){
int T; cin >> T;
while (T--) {
int n; cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
if (a[0] == a[n - 1]) {
cout << "NO" << "\n";
}
else {
... |
1984 | B | Large Addition | A digit is large if it is between $5$ and $9$, inclusive. A positive integer is large if all of its digits are large.
You are given an integer $x$. Can it be the sum of two large positive integers with the \textbf{same number of digits}? | Solution 1 What must the first (largest) digit be? What must the other non-unit digits be? What must the last digit be? Because every digit is large, every two digits being added together will carry to the next digit. The two addends have the same length, so the sum must be one greater in length, with the largest digit... | [
"implementation",
"math"
] | 1,100 |
#include <iostream>
using namespace std;
#define ll long long
void solve() {
ll n; cin >> n;
n = n - n % 10 + (n % 10 + 1) % 10;
while (n > 9) {
if (n % 10 == 0) {
cout << "NO\n";
return;
}
n /= 10;
}
cout << (n == 1 ? "YES\n" : "NO\n");
}
int main() {
ios_base::sync_with_stdi... |
1984 | C2 | Magnitude (Hard Version) | \textbf{The two versions of the problem are different. You may want to read both versions. You can make hacks only if both versions are solved.}
You are given an array $a$ of length $n$. Start with $c = 0$. Then, for each $i$ from $1$ to $n$ (in increasing order) do \textbf{exactly one} of the following:
- Option $1$... | How many times do we need to pick option $2$? We only need to pick it once. How can we calculate the final value for every position we can pick? We only need to pick option $2$ once. Why? Assume we picked option $2$ more than once, and consider the last two times it was picked. Both of these must occur when $c + a_i$ i... | [
"combinatorics",
"dp",
"greedy",
"math"
] | 1,700 |
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
#define ll long long
const ll MAX_N = 400001;
const ll MOD = 998244353;
vector<ll> p2(MAX_N);
void solve() {
int n; cin >> n;
vector<int> arr(n); for (int i = 0; i < n; ++i) cin >> arr[i];
ll sum = 0, mn = 0, ans = 0, abses = 0... |
1984 | D | ''a'' String Problem | You are given a string $s$ consisting of lowercase Latin characters. Count the number of nonempty strings $t \neq$ "$a$" such that it is possible to partition$^{\dagger}$ $s$ into some substrings satisfying the following conditions:
- each substring either equals $t$ or "$a$", and
- at least one substring equals $t$.
... | What does $t$ have to include? Special case: the string consists of only "$\texttt{a}$", then answer is $n - 1$. Otherwise, $t$ has to contain a character that is not "$\texttt{a}$". Let's consider one approach of counting. Let's force all $t$ to start with the first non-a character, and see how many work. To see if on... | [
"brute force",
"hashing",
"implementation",
"math",
"string suffix structures",
"strings"
] | 2,000 |
#include <iostream>
#include <vector>
#include <climits>
#include <set>
using namespace std;
#define ll long long
vector<int> z_function(string s) {
int n = s.size();
vector<int> z(n);
int l = 0, r = 0;
for(int i = 1; i < n; ++i) {
if (i < r) z[i] = min(r - i, z[i - l]);
while (i + z[i] < n && s[z[... |
1984 | E | Shuffle | Two hungry red pandas, Oscar and Lura, have a tree $T$ with $n$ nodes. They are willing to perform the following \textbf{shuffle procedure} on the whole tree $T$ \textbf{exactly once}. With this shuffle procedure, they will create a new tree out of the nodes of the old tree.
- Choose any node $V$ from the original tre... | Excluding the root, the maximum number of leaves we have is the maximum independent set (MIS) of the rest of the tree. Why? First of all, after rooting tree $T_2$, no two adjacent nodes can both be leaves. This is because, no matter which one you choose to add to $T_2$ first, it must be the ancestor of the other one. T... | [
"dp",
"greedy",
"trees"
] | 2,400 |
#include <iostream>
#include <vector>
#include <map>
using namespace std;
#define pii pair<int, int>
int n;
vector<vector<int>> adj;
vector<pii> edges;
map<pii, int> mp;
vector<vector<int>> dp;
vector<vector<int>> from;
vector<int> miss;
void dfs(int e) {
if (dp[0][e] >= 0 || dp[1][e] >= 0) return;
int p =... |
1984 | F | Reconstruction | There is a hidden array $a_1, a_2, \ldots, a_n$ of length $n$ whose elements are integers between $-m$ and $m$, inclusive.
You are given an array $b_1, b_2, \ldots, b_n$ of length $n$ and a string $s$ of length $n$ consisting of the characters $P$, $S$, and $?$.
For each $i$ from $1$ to $n$ inclusive, we must have:
... | Solve for no question marks in the string first. Add a $0$ on both sides of $a$ and $b$, and add a $\texttt{P}$ before the start of the string and a $\texttt{S}$ after the string. Now you are guaranteed to have a $\texttt{PS}$ somewhere in the string. How does this help? You know the sum of the array. Look at adjacent ... | [
"brute force",
"dp",
"math"
] | 2,500 |
#include <iostream>
#include <vector>
#include <cstring>
#include <assert.h>
#include <set>
using namespace std;
#define ll long long
const int INF = 998244353;
// const int BOUND = 1e9;
void solve() {
int n; cin >> n;
int BOUND; cin >> BOUND;
string s; cin >> s;
s = "P" + s + "S";
vector<ll> b(n + 2);... |
1984 | G | Magic Trick II | The secret behind Oscar's first magic trick has been revealed! Because he still wants to impress Lura, he comes up with a new idea: he still wants to sort a permutation $p_1, p_2, \ldots, p_n$ of $[1, 2, \ldots, n]$.
This time, he chooses an integer $k$. He wants to sort the permutation in non-decreasing order using t... | Solve what the maximum $k$ will be for different types of arrays. The maximum is always close to $n$. There exists two trivial cases. If array is already sorted, $k = n$. If array is cyclic shift of sorted array, $k = n - 1$. Now, $k = n - 2$ and $k = n - 3$ is sufficient to sort any array. Let's assume $n$ is odd firs... | [
"constructive algorithms",
"implementation",
"sortings"
] | 3,200 |
#include <iostream>
#include <vector>
using namespace std;
#define pii pair<int, int>
bool sorted(vector<int> arr, int n) {
for (int i = 1; i < n; ++i) if (arr[i] < arr[i - 1]) return false;
return true;
}
bool cyclic(vector<int> arr, int n) {
for (int i = 1; i < n; ++i) if (arr[i] % n != (arr[i - 1] + 1) ... |
1984 | H | Tower Capturing | There are $n$ towers at $n$ distinct points $(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)$, such that no three are collinear and no four are concyclic. Initially, you own towers $(x_1, y_1)$ and $(x_2, y_2)$, and you want to capture all of them. To do this, you can do the following operation any number of times:
- Pick ... | Are there any useless points? Draw all triangles that contain all points inside their circumcircle. What do you notice? Claim. We can't ever pick a tower inside the convex hull. Proof. A circle can only contain all the points if the points on the circle are on the convex hull; otherwise, the circle will necessarily spl... | [
"combinatorics",
"dp",
"geometry"
] | 3,300 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 998244353;
struct bignum {
static constexpr long long B = 1LL<<30;
static constexpr int N = 6;
array<long long, N> b = {};
bignum() {}
bignum(long long a) {
b[2] = (a / B) / B;
b[1] = (a / B) % B... |
1985 | A | Creating Words | Matthew is given two strings $a$ and $b$, both of length $3$. He thinks it's particularly funny to create two new words by swapping the first character of $a$ with the first character of $b$. He wants you to output $a$ and $b$ after the swap.
Note that the new words may not necessarily be different. | To swap the first character of the strings, you can use the built-in method std::swap in C++, or for each string, separate the first character from the rest of the string and concatenate it with the other string. | [
"implementation",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
string a, b; cin >> a >> b;
swap(a[0], b[0]);
cout << a << " " << b << endl;
}
} |
1985 | B | Maximum Multiple Sum | Given an integer $n$, find an integer $x$ such that:
- $2 \leq x \leq n$.
- The sum of multiples of $x$ that are less than or equal to $n$ is maximized. Formally, $x + 2x + 3x + \dots + kx$ where $kx \leq n$ is maximized over all possible values of $x$. | To maximize the number of multiples of $x$ less than $n$, it optimal to choose a small $x$, in this case, $2$. The only exception is $n = 3$, where it is optimal to choose $3$ instead, since both $2$ and $3$ have only one multiple less than $3$. | [
"brute force",
"math",
"number theory"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
int n; cin >> n;
cout << (n == 3 ? 3 : 2) << endl;
}
} |
1985 | C | Good Prefixes | Alex thinks some array is good if there exists some element that can be represented as the sum of all \textbf{other} elements (the sum of all other elements is $0$ if there are no other elements). For example, the array $[1,6,3,2]$ is good since $1+3+2=6$. Furthermore, the array $[0]$ is also good. However, the arrays ... | The only element that can be the sum of all other elements is the maximum element, since all elements are positive. Therefore, for each prefix $i$ from $1$ to $n$, check if $sum(a_1, a_2, ..., a_i) - max(a_1, a_2, ..., a_i) = max(a_1, a_2, ..., a_i)$. The sum and max of prefixes can be tracked with variables outside th... | [
"greedy"
] | 1,000 | #include <iostream>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
int n; cin >> n;
int a[n];
for(int i = 0; i < n; i++)
cin >> a[i];
long long sum = 0;
int mx = 0, ans = 0;;
for(int i = 0; i < n; i++){
sum += a[i];
mx = max(mx, a[i]);
if(sum - mx == mx)
ans++;
}
cout ... |
1985 | D | Manhattan Circle | Given a $n$ by $m$ grid consisting of '.' and '#' characters, there exists a whole manhattan circle on the grid. The top left corner of the grid has coordinates $(1,1)$, and the bottom right corner has coordinates $(n, m)$.
Point ($a, b$) belongs to the manhattan circle centered at ($h, k$) if $|h - a| + |k - b| < r$,... | Note that the manhattan circle is always in a diamond shape, symmetric from the center. Let's take notice of some special characteristics that can help us. One way is to find the top and bottom points of the circle. Note that these points will have columns at the center of the circle, so here we can acquire the value o... | [
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main(){
int t; cin >> t;
while(t--){
int n, m; cin >> n >> m;
vector<vector<char>> g(n, vector<char>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> g[i][j];
}
}
pair<int, int> top = {INF, INF}, bottom = {-... |
1985 | E | Secret Box | Ntarsis has a box $B$ with side lengths $x$, $y$, and $z$. It lies in the 3D coordinate plane, extending from $(0,0,0)$ to $(x,y,z)$.
Ntarsis has a secret box $S$. He wants to choose its dimensions such that all side lengths are positive integers, and the volume of $S$ is $k$. He can place $S$ somewhere within $B$ suc... | Since the side lengths of $S$ has to multiply to $k$, all three side lengths of $S$ has to be divisors of $k$. Let's denote the side lengths of $S$ along the $x$, $y$, and $z$ axes as $a$, $b$, and $c$ respectively. For $S$ to fit in $B$ , $a \leq x$, $b \leq y$, and $c \leq z$ must hold. Because of the low constraints... | [
"brute force",
"combinatorics",
"math"
] | 1,200 | #include <iostream>
using namespace std;
using ll = long long;
int main(){
int t; cin >> t;
while(t--){
ll x, y, z, k; cin >> x >> y >> z >> k;
ll ans = 0;
for(int a = 1; a <= x; a++){
for(int b = 1; b <= y; b++){
if(k % (a * b)) continue;
ll c = k / (a * b);
if(c > z) continue;
ll ways = (l... |
1985 | F | Final Boss | You are facing the final boss in your favorite video game. The boss enemy has $h$ health. Your character has $n$ attacks. The $i$'th attack deals $a_i$ damage to the boss but has a cooldown of $c_i$ turns, meaning the next time you can use this attack is turn $x + c_i$ if your current turn is $x$. Each turn, you can us... | Unfortunately, there was a lot of hacks on this problem, and we're sorry for it. Since our intended solution is not binary search, we didn't really take overflow using binary search seriously. I (cry) prepared this problem and I only took into account about overflow with big cooldown, but I forgot overflow can happen o... | [
"binary search",
"data structures"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
void solve(){
ll h, n;
cin >> h >> n;
vector<ll> A(n), C(n);
for (ll &i : A)
cin >> i;
for (ll &i : C)
cin >> i;
auto chk = [&](ll t){
ll dmg = 0;
for (int i = 0; i < n and dmg < h; i++){
... |
1985 | G | D-Function | Let $D(n)$ represent the sum of digits of $n$. For how many integers $n$ where $10^{l} \leq n < 10^{r}$ satisfy $D(k \cdot n) = k \cdot D(n)$? Output the answer modulo $10^9+7$. | To satisfy $D(k \cdot n) = k \cdot D(n)$, each digit $d$ in $n$ must become $k \cdot d$ after multiplying $n$ by $k$. In other words, none of $n$'s digits can carry over to the next digit upon multiplication. From this, we can deduce that each digit in $n$ must be less than or equal to $\lfloor \frac{9}{k} \rfloor$. On... | [
"combinatorics",
"math",
"number theory"
] | 1,600 | MOD = int(1e9+7)
t = int(input())
for _ in range(t):
l, r, k = map(int, input().split())
print((pow(9 // k + 1, r, MOD) - pow(9 // k + 1, l, MOD) + MOD) % MOD) |
1985 | H1 | Maximize the Largest Component (Easy Version) | \textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. The only difference between the two versions is the operation.}
Alex has a grid with $n$ rows and $m$ columns consisting of '.' and '#' characters. A set of '#' cells forms a connected componen... | Let's first solve the problem if we can only select and fill rows. Columns can be handled in the exact same way. For each row $r$, we need to find the size of the component formed by filling row $r$ (i.e. the size of the component containing row $r$ if we set all cells in row $r$ to be $\texttt{#}$). The size of the co... | [
"brute force",
"data structures",
"dfs and similar",
"dsu",
"graphs",
"implementation"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int n, m, minR, maxR, minC, maxC, sz, ans; vector<int> R, C, freeR, freeC;
vector<vector<bool>> vis; vector<vector<char>> A;
void dfs(int i, int j){
if (i <= 0 or i > n or j <= 0 or j > m or vis[i][j] or A[i][j] == '.')
return;
vis[i][j] = true;
... |
1985 | H2 | Maximize the Largest Component (Hard Version) | \textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. The only difference between the two versions is the operation.}
Alex has a grid with $n$ rows and $m$ columns consisting of '.' and '#' characters. A set of '#' cells forms a connected componen... | For each row $r$ and column $c$, we need to find the size of the component formed by filling both row $r$ and column $c$ (i.e. the size of the component containing row $r$ and column $c$ if we set all cells in both row $r$ and column $c$ to be $\texttt{#}$). Extending the reasoning in H1, for some row $r$ and column $c... | [
"data structures",
"dfs and similar",
"dp",
"dsu",
"implementation"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int n, m, minR, maxR, minC, maxC, sz, ans; vector<int> R, C, freeR, freeC;
vector<vector<int>> RC; vector<vector<bool>> vis; vector<vector<char>> A;
void dfs(int i, int j){
if (i <= 0 or i > n or j <= 0 or j > m or vis[i][j] or A[i][j] == '.')
return;
... |
1986 | A | X Axis | You are given three points with integer coordinates $x_1$, $x_2$, and $x_3$ on the $X$ axis ($1 \leq x_i \leq 10$). You can choose any point with an integer coordinate $a$ on the $X$ axis. Note that the point $a$ may coincide with $x_1$, $x_2$, or $x_3$. Let $f(a)$ be the total distance from the given points to the poi... | Let $x_1 \leq x_2 \leq x_3$. Notice that the answer is at least $x_3 - x_1$, because $|x_3 - a| + |x_1 - a| \geq |x_3 - x_1|$ for any numbers $a$, $x_1$, $x_3$. The answer is equal to $x_3 - x_1$, since we can choose $a = x_2$. | [
"brute force",
"geometry",
"math",
"sortings"
] | 800 | null |
1986 | B | Matrix Stabilization | You are given a matrix of size $n \times m$, where the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The element at the intersection of the $i$-th row and the $j$-th column is denoted by $a_{ij}$.
Consider the algorithm for stabilizing matrix $a$... | Let's consider any two adjacent cells of the matrix. Notice that our algorithm can change at most one value of these two cells. If the values in the cells are equal, then neither of these two adjacent cells will ever change its value. If the values in the cells are not equal, then the value of the larger cell will neve... | [
"brute force",
"data structures",
"greedy",
"sortings"
] | 1,000 | null |
1986 | C | Update Queries | Let's consider the following simple problem. You are given a string $s$ of length $n$, consisting of lowercase Latin letters, as well as an array of indices $ind$ of length $m$ ($1 \leq ind_i \leq n$) and a string $c$ of length $m$, consisting of lowercase Latin letters. Then, in order, you perform the update operation... | Let $i_1 < i_2 < \ldots < i_k$ be the set of indices of the array $ind$. Note that the indices of the string $s$ that are not in this set will simply not change their value. Then we want to place the smallest character of the string $c$ at position $i_1$, the next smallest at position $i_2$, and so on. To achieve this,... | [
"data structures",
"greedy",
"sortings"
] | 1,100 | null |
1986 | D | Mathematical Problem | You are given a string $s$ of length $n > 1$, consisting of digits from $0$ to $9$. You must insert exactly $n - 2$ symbols $+$ (addition) or $\times$ (multiplication) into this string to form a valid arithmetic expression.
In this problem, the symbols cannot be placed before the first or after the last character of t... | First, let's iterate through the position $i$, such that we do not place a mathematical sign between the $i$-th and $(i+1)$-th elements. Next, we have the following task - we have $n - 1$ numbers and we need to place a $+$ or $\times$ sign between each pair of neighboring numbers to minimize the result. There are three... | [
"brute force",
"dp",
"greedy",
"implementation",
"math",
"two pointers"
] | 1,400 | null |
1986 | E | Beautiful Array | You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $k$. You need to make it beautiful with the least amount of operations.
Before applying operations, you can shuffle the array elements as you like. For one operation, you can do the following:
- Choose an index $1 \leq i \leq n$,
- Make $a_i = ... | Notice that we actually want to pair the elements (in the odd case, exactly one element will not have a pair). If numbers $x \leq y$ fall into the same pair, then: These two numbers should have the same remainder when divided by $k$. This is necessary in order to obtain one from the other. To make them equal, we will n... | [
"greedy",
"math",
"number theory",
"sortings"
] | 1,700 | null |
1986 | F | Non-academic Problem | You are given a connected undirected graph, the vertices of which are numbered with integers from $1$ to $n$. Your task is to minimize the number of pairs of vertices $1 \leq u < v \leq n$ between which there exists a path in this graph. To achieve this, you can remove exactly one edge from the graph.
Find the smalles... | Notice that if an edge is not a bridge, then after its removal the graph remains connected and all vertices are reachable from each other. Therefore, we would like to remove some bridge edge (if there are no bridges, the answer is $\frac{n \cdot (n - 1)}{2}$). After its removal, the graph will split into two connected ... | [
"dfs and similar",
"graphs",
"trees"
] | 1,900 | null |
1986 | G2 | Permutation Problem (Hard Version) | \textbf{This is the hard version of the problem. The only difference is that in this version $n \leq 5 \cdot 10^5$ and the sum of $n$ for all sets of input data does not exceed $5 \cdot 10^5$.}
You are given a permutation $p$ of length $n$. Calculate the number of index pairs $1 \leq i < j \leq n$ such that $p_i \cdot... | Let $a_i = \frac{p_i}{\gcd(i, p_i)}$, $b_i = \frac{i}{\gcd(i, p_i)}$. Notice that we want to calculate the number of index pairs $i < j$, such that: $a_j$ is divisible by $b_i$. $a_i$ is divisible by $b_j$. Let's iterate through the values of $b_i$ from $1$ to $n$ (note that we are not fixing the element $i$, but rathe... | [
"brute force",
"data structures",
"hashing",
"math",
"number theory"
] | 2,500 | null |
1987 | A | Upload More RAM | Oh no, the ForceCodes servers are running out of memory! Luckily, you can help them out by uploading some of your RAM!
You want to upload $n$ GBs of RAM. Every second, you will upload either $0$ or $1$ GB of RAM. However, there is a restriction on your network speed: in any $k$ consecutive seconds, you can upload only... | First of all, note that you can upload $n$ GBs of RAM if you upload on the seconds $1, k + 1, 2k + 1, \ldots, (n - 1)k + 1$, taking $(n - 1)k + 1$ seconds in total. Let's show that it's impossible to do better. Suppose there is a solution where you upload on the times $t_1, t_2, \ldots t_n$, taking $t_n$ seconds to upl... | [
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
cout << 1 + (n - 1) * k << nl;
}
int main() {
ios::sync_with_stdio(0)... |
1987 | B | K-Sort | You are given an array of integers $a$ of length $n$.
You can apply the following operation any number of times (maybe, zero):
- First, choose an integer $k$ such that $1 \le k \le n$ and pay $k + 1$ coins.
- Then, choose \textbf{exactly} $k$ indices such that $1 \le i_1 < i_2 < \ldots < i_k \le n$.
- Then, for each ... | Suppose that after all of the operations, the value at index $i$ has been increased by $b_i$. Notice that our cost can be factored into two parts: $k$ is responsible for how many elements we choose, and $1$ is responsible for how many operations we apply. Since we have to apply at least $\max(b_i)$ operations, and over... | [
"greedy"
] | 1,000 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
ll... |
1987 | C | Basil's Garden | There are $n$ flowers in a row, the $i$-th of them initially has a positive height of $h_i$ meters.
Every second, the wind will blow from the left, causing the height of some flowers to decrease.
Specifically, every second, for each $i$ from $1$ to $n$, in this order, the following happens:
- If $i = n$ or $h_i > h_... | First, let's try to find when $h_{n}$ will first be equal to zero. The answer is clearly $h_{n}$. Suppose for some $2 \le i \le n$ we know that $h_{i}$ will first become equal to zero at time $t_{i}$ ($t_n = h_n$). If at some point in time, $h_{i-1}$ was equal to $h_{i}$ (at the start of the second and before they are ... | [
"dp",
"greedy"
] | 1,200 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> h(n);
for (auto &x: h) cin >> x;
int ans = h[n - ... |
1987 | D | World is Mine | Alice and Bob are playing a game. Initially, there are $n$ cakes, with the $i$-th cake having a tastiness value of $a_i$.
Alice and Bob take turns eating them, with Alice starting first:
- In her turn, Alice chooses and eats any remaining cake whose tastiness is \textbf{strictly greater} than the \textbf{maximum} tas... | Let's consider Alice's strategy. Notice that if both players play optimally, Alice eating a cake with a tastiness value of $t$ is equivalent to her eating all remaining cakes with $a_i \le t$. Since it is better for her to have more cakes to choose from later on, she will choose the minimum possible $t$ on each turn. N... | [
"dp",
"games"
] | 1,800 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int inf = 1e9;
void solve() {
vector<int> a;
{
int n;
cin >> n;
map<int, in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.