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 ⌀ |
|---|---|---|---|---|---|---|---|
1840 | G2 | In Search of Truth (Hard Version) | \textbf{The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $1000$ queries.}
This is an interactive problem.
You are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in t... | Let's sample $n$ by making $k$ random queries "+ x" where we pick $x$ each time randomly between $1$ and $10^6$ and get $k$ random integers $n_1, n_2, \dots, n_k$ in the range $[1, n]$ as the answers to the queries. Then, we can sample $n$ with $n_0 = max(n_1, n_2, \dots, n_k)$. Now, we can assume that $n_0 \le n \le n... | [
"constructive algorithms",
"interactive",
"math",
"meet-in-the-middle",
"probabilities"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define int long long
const int MAXN = 1e6 + 7;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int pos[MAXN];
const int K = 400;
const int T = 300;
int get() {
return rng() % MAXN;
}
int32_t main() {
int num;
cin >> num;
... |
1841 | A | Game with Board | Alice and Bob play a game. They have a blackboard; initially, there are $n$ integers written on it, and each integer is equal to $1$.
Alice and Bob take turns; Alice goes first. On their turn, the player has to choose several (\textbf{at least two}) \textbf{equal} integers on the board, wipe them and write a new integ... | Let's try to find a winning strategy for Alice. We can force Bob into a situation where his only action will be to make a move that leaves Alice without any legal moves, so she will win. For example, Alice can start by merging $n-2$ ones, so the board will be $\{1, 1, n-2\}$ after her move. The only possible move for B... | [
"constructive algorithms",
"games"
] | 800 | t = int(input())
for i in range(t):
n = int(input())
print('Alice' if n >= 5 else 'Bob') |
1841 | B | Keep it Beautiful | The array $[a_1, a_2, \dots, a_k]$ is called beautiful if it is possible to remove several (maybe zero) elements from the beginning of the array and insert all these elements to the back of the array in the same order in such a way that the resulting array is sorted in non-descending order.
In other words, the array $... | First, notice that the given operation is a cyclic shift of the array. So we can treat the array as cyclic, meaning element $n$ is a neighbor of element $1$. Let's try to rephrase the condition for the beautiful array. What does it mean for the array to be sorted? For all $j$ from $1$ to $n-1$, $a_j \le a_{j+1}$ should... | [
"implementation"
] | 1,000 | for _ in range(int(input())):
q = int(input())
a = []
cnt = 0
for x in map(int, input().split()):
nw_cnt = cnt + (len(a) > 0 and a[-1] > x)
if nw_cnt == 0 or (nw_cnt == 1 and x <= a[0]):
a.append(x)
cnt = nw_cnt
print('1', end="")
else:
print('0', end="")
print() |
1841 | C | Ranom Numbers | No, not "random" numbers.
Ranom digits are denoted by uppercase Latin letters from A to E. Moreover, the value of the letter A is $1$, B is $10$, C is $100$, D is $1000$, E is $10000$.
A Ranom number is a sequence of Ranom digits. The value of the Ranom number is calculated as follows: the values of all digits are su... | There are two main solutions to this problem: dynamic programming and greedy. DP approach Reverse the string we were given, so that the sign of each digit depends on the maximum digit to the left of it (not to the right). Then, run the following dynamic programming: $dp_{i,j,k}$ is the maximum value of the number if we... | [
"brute force",
"dp",
"greedy",
"math",
"strings"
] | 1,800 | def replace_char(s, i, c):
return s[:i] + c + s[i + 1:]
def id(c):
return ord(c) - ord('A')
def evaluate(s):
t = s[::-1]
ans = 0
max_id = -1
for x in t:
i = id(x)
if max_id > i:
ans -= 10 ** i
else:
ans += 10 ** i
max_id = max(max... |
1841 | D | Pairs of Segments | Two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if there exists at least one $x$ such that $l_1 \le x \le r_1$ and $l_2 \le x \le r_2$.
An array of segments $[[l_1, r_1], [l_2, r_2], \dots, [l_k, r_k]]$ is called \textbf{beautiful} if $k$ is even, and is possible to split the elements of this array into $\frac{k}... | The resulting array should consist of pairs of intersecting segments, and no segments from different pairs should intersect. Let's suppose that segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect, and segments $[l_3, r_3]$ and $[l_4, r_4]$ intersect. How to check that no other pair of these four segments intersects? Inste... | [
"data structures",
"greedy",
"sortings",
"two pointers"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
bool comp(const pair<int, int>& a, const pair<int, int>& b)
{
return a.second < b.second;
}
void solve()
{
int n;
scanf("%d", &n);
vector<pair<int, int>> s(n);
for(int i = 0; i < n; i++)
scanf("%d %d", &s[i].first, &s[i].second);
vector<pair<int, int>> pairs;
f... |
1841 | E | Fill the Matrix | There is a square matrix, consisting of $n$ rows and $n$ columns of cells, both numbered from $1$ to $n$. The cells are colored white or black. Cells from $1$ to $a_i$ are black, and cells from $a_i+1$ to $n$ are white, in the $i$-th column.
You want to place $m$ integers in the matrix, from $1$ to $m$. There are two ... | Notice that the rows of the matrix are basically independent. When we fill the matrix with integers, the values from the rows are just added together. Moreover, in a single row, the segments of white cells separated by black cells are also independent in the same way. And how to solve the problem for one segment of whi... | [
"data structures",
"greedy",
"math"
] | 2,200 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct seg{
int l, r;
};
bool operator <(const seg &a, const seg &b){
return a.l < b.l;
}
int main() {
int t;
scanf("%d", &t);
while (t--){
int n;
scanf("%d", &n);
vector<int> a(n);
forn(i, n) scanf("%d",... |
1841 | F | Monocarp and a Strategic Game | Monocarp plays a strategic computer game in which he develops a city. The city is inhabited by creatures of four different races — humans, elves, orcs, and dwarves.
Each inhabitant of the city has a happiness value, which is an integer. It depends on how many creatures of different races inhabit the city. Specifically... | Let's denote $a, b, c, d$ as the total number of humans, orcs, elves, and dwarves taken respectively. We calculate the contribution of humans and orcs to the final score. It will be $a(a-1) + b(b-1) - 2ab + a + b$, where $a(a-1) + b(b-1)$ is the contribution to the total happiness (and thus to the final score) for an i... | [
"geometry",
"sortings",
"two pointers"
] | 2,700 | #include <iostream>
#include <algorithm>
using namespace std;
#define int long long
#define x first
#define y second
const int MAXN = 2e6 + 16;
int a[MAXN], b[MAXN];
pair<int, int> v[MAXN];
int section(pair<int, int> a) {
if (a.x > 0 && a.y >= 0)
return 0;
else if (a.x <= 0 && a.y > 0)
return 1;... |
1842 | A | Tenzing and Tsondu | \begin{quote}
Tsondu always runs first! ! !
\end{quote}
Tsondu and Tenzing are playing a card game. Tsondu has $n$ monsters with ability values $a_1, a_2, \ldots, a_n$ while Tenzing has $m$ monsters with ability values $b_1, b_2, \ldots, b_m$.
Tsondu and Tenzing take turns making moves, with Tsondu going first. In ea... | Let's view it as when monsters $x$ and $y$ fight, their health changes into $\max(x-y,0)$ and $\max(y-x,0)$ respectively. So any monster with $0$ health is considered dead. Therefore, a player loses when the health of his monsters are all $0$. Notice that $\max(x-y,0)=x-\min(x,y)$ and $\max(y-x,0)=y-\min(x,y)$. Therefo... | [
"games",
"math"
] | 800 | #include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
int n, m, a[50], b[50];
long long sumA = 0, sumB = 0;
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> a[i], sumA += a[i];
... |
1842 | B | Tenzing and Books | Tenzing received $3n$ books from his fans. The books are arranged in $3$ stacks with $n$ books in each stack. Each book has a non-negative integer difficulty rating.
Tenzing wants to read some (possibly zero) books. At first, his knowledge is $0$.
To read the books, Tenzing will choose a non-empty stack, read the boo... | Observe the bitwise OR: if a bit of the knowledge changes to $1$, it will never become $0$. It tells us, if a book has difficulty rating $y$, and $x|y \neq x$, Tenzing will never read this book because it will change a $0$ bit in $x$ to $1$. We called a number $y$ valid if $x|y=x$. For each sequence, we can find a long... | [
"bitmasks",
"greedy",
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
int n, x, ai;
cin >> n >> x;
vector<int> pre[3];
for (int i = 0; i < 3; i++) {
int s = 0;
pre[i].push_back(s)... |
1842 | C | Tenzing and Balls | \begin{quote}
Enjoy erasing Tenzing, identified as Accepted!
\end{quote}
Tenzing has $n$ balls arranged in a line. The color of the $i$-th ball from the left is $a_i$.
Tenzing can do the following operation any number of times:
- select $i$ and $j$ such that $1\leq i < j \leq |a|$ and $a_i=a_j$,
- remove $a_i,a_{i+1... | Let us write down the original index of each range we delete. Firstly, it is impossible to delete ranges $(a,c)$ and $(b,d)$ where $a<b<c<d$. Secondly, if we delete ranges $(a,d)$ and $(b,c)$ where $a<b<c<d$, we must have deleted range $(b,c)$ before deleting range $(a,d)$. Yet, the effect of deleting range $(b,c)$ and... | [
"dp"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
const int N = 200000 + 5;
int n, a[N], dp[N], buc[N];
cin >> n;
dp[0] = 0;
for (int i = 1; i <= n; i++) buc[i] = 0x3f3f3f3f;
... |
1842 | D | Tenzing and His Animal Friends | \begin{quote}
Tell a story about me and my animal friends.
\end{quote}
Tenzing has $n$ animal friends. He numbers them from $1$ to $n$.
One day Tenzing wants to play with his animal friends. To do so, Tenzing will host several games.
In one game, he will choose a set $S$ which is a subset of $\{1,2,3,...,n\}$ and ch... | Consider the restrictions on $u$, $v$, and $y$ as a weighted edge between $u$ and $v$ with weight $y$. Obviously, the final answer will not exceed the shortest path from $1$ to $n$. One possible approach to construct the solution is to start with the set ${1}$ and add vertices one by one. If $i$ is added to the set at ... | [
"constructive algorithms",
"graphs",
"greedy"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
int n, m;
long long dis[100][100];
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
cin >> n >> m;
memset(dis, 0x3f, sizeof dis);
while (m--) {
int u, v, w;
cin >> u >> v >> w, u--, v--;
dis[u][v] = dis[v][u] = w;
}
... |
1842 | E | Tenzing and Triangle | There are $n$ \textbf{pairwise-distinct} points and a line $x+y=k$ on a two-dimensional plane. The $i$-th point is at $(x_i,y_i)$. All points have non-negative coordinates and are strictly below the line. Alternatively, $0 \leq x_i,y_i, x_i+y_i < k$.
Tenzing wants to erase all the points. He can perform the following ... | Observe that all triangles will be disjoint, if two triangle were not disjoint, we can merge them together to such that the cost used is less. Therefore, we can consider doing DP. The oblique side of the triangle is a segment on the line $y=k-x$. Therefore, we use the interval $[L,R]$ to represent the triangle with the... | [
"data structures",
"dp",
"geometry",
"greedy",
"math"
] | 2,300 | #include <bits/stdc++.h>
struct IO {
static const int inSZ = 1 << 17;
char inBuf[inSZ], *in1, *in2;
inline __attribute((always_inline))
int read() {
if(__builtin_expect(in1 > inBuf + inSZ - 32, 0)) {
auto len = in2 - in1;
memcpy(inBuf, in1, len);
in1 = inBuf,... |
1842 | F | Tenzing and Tree | Tenzing has an undirected tree of $n$ vertices.
Define the value of a tree with black and white vertices in the following way. The value of an edge is the absolute difference between the number of black nodes in the two components of the tree after deleting the edge. The value of the tree is the sum of values over all... | Let $root$ be the centroid of all black vertices and $size_i$ be the number of black vertices in the subtree of node $i$. Then the value is $\sum_{i\neq root} k-2\cdot size_i=(n-1)\cdot k-2\cdot\sum_{i\neq root} size_i$. Consider painting node $i$ black, the total contributio to all of its ancestors is $2\cdot depth_i$... | [
"dfs and similar",
"greedy",
"shortest paths",
"sortings",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
const int N = 5000 + 8;
int n, ans[N];
vector<int> G[N];
void bfs(int u) {
static int q[N], dis[N];
memset(dis, -1, sizeof dis);
q[1] = u, dis[u] = 0;
for (int l = 1, r = 2; l < r; l++) {
u = q[l];
for (int v : G[u]) if (dis[v] < 0)
... |
1842 | G | Tenzing and Random Operations | \begin{quote}
Yet another random problem.
\end{quote}
Tenzing has an array $a$ of length $n$ and an integer $v$.
Tenzing will perform the following operation $m$ times:
- Choose an integer $i$ such that $1 \leq i \leq n$ uniformly at random.
- For all $j$ such that $i \leq j \leq n$, set $a_j := a_j + v$.
Tenzing w... | Before starting to solve this problem, let's establish two basic properties: For two completely independent random variables $x_1,x_2$, we have $E(x_1x_2) = E(x_1)E(x_2)$. For $(a+b)\times (c+d)$, we have $E((a+b)\times (c+d)) = E(ac) + E(ad) + E(bc) + E(bd)$. Returning to this problem, let $x_{i,j}$ be a random variab... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
const int N = 5000 + 8, P = 1e9 + 7;
int n, m, v, a[N], coef[N], dp[N][N];
long long Pow(long long a, int n) {
long long r = 1;
while (n) {
if (n & 1) r = r * a % P;
a = a * a % P, n >>= 1;
}
return r;
}
int main() {
ios::sync_with_s... |
1842 | H | Tenzing and Random Real Numbers | There are $n$ uniform random real variables between 0 and 1, inclusive, which are denoted as $x_1, x_2, \ldots, x_n$.
Tenzing has $m$ conditions. Each condition has the form of $x_i+x_j\le 1$ or $x_i+x_j\ge 1$.
Tenzing wants to know the probability that all the conditions are satisfied, modulo $998~244~353$.
Formall... | Ignoring time complexity for now, how do we calculate the answer? The first step is to enumerate which variables are $<0.5$ and which variables are $>0.5$. Sort all variables $x_i$ by $\min(x_i,1-x_i)$ and enumerate the sorted result (referring to the permutation). Suppose no variable equals $0.5$, because the probabil... | [
"bitmasks",
"dp",
"graphs",
"math",
"probabilities"
] | 3,000 | #include <iostream>
const int P = 998244353;
long long Pow(long long a, int n) {
long long r = 1;
while (n) {
if (n & 1) r = r * a % P;
a = a * a % P, n >>= 1;
}
return r;
}
inline void inc(int& a, int b) {
if((a += b) >= P) a -= P;
}
int n, m, G[20][2], f[1 << 20];
int main(... |
1842 | I | Tenzing and Necklace | \begin{quote}
bright, sunny and innocent......
\end{quote}
Tenzing has a beautiful necklace. The necklace consists of $n$ pearls numbered from $1$ to $n$ with a string connecting pearls $i$ and $(i \text{ mod } n)+1$ for all $1 \leq i \leq n$.
One day Tenzing wants to cut the necklace into several parts by cutting so... | How to solve it if you want to cut exactly $m$ edges ? DP+divide and conquer Add a constraint: "you must cut off $m$ edges". Consider enumerating the minimum cut edges from small to large. Suppose the minimum cut edge chosen is $a_1$, and the subsequent optimal solution is $a_2, a_3, ..., a_m$. If another minimum cut e... | [
"divide and conquer",
"dp",
"greedy"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 8;
int n, K, a[N], pre[N * 2];
long long dp[N * 2], ans;
vector<int> trim(vector<int> a, int L, int R) {
return vector(a.begin() + L, a.end() - R);
}
vector<int> init() {
static int q[N];
q[1] = 0;
for (int i = 1, l = 1, r = 1; i <= n... |
1843 | A | Sasha and Array Coloring | Sasha found an array $a$ consisting of $n$ integers and asked you to paint elements.
You have to paint each element of the array. You can use as many colors as you want, but each element should be painted into exactly one color, and for each color, there should be at least one element of that color.
The cost of one c... | First, there exists an optimal answer, in which there are no more than two elements of each color. Proof: let there exist an optimal answer, in which there are more elements of some color than 2. Then, take the median among the elements of this color and paint in another new color in which no other elements are painted... | [
"greedy",
"sortings",
"two pointers"
] | 800 | def solve():
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
ans = 0
for i in range(n // 2):
ans += a[-i-1] - a[i]
print(ans)
t = int(input())
for _ in range(t):
solve() |
1843 | B | Long Long | Today Alex was brought array $a_1, a_2, \dots, a_n$ of length $n$. He can apply as many operations as he wants (including zero operations) to change the array elements.
In $1$ operation Alex can choose any $l$ and $r$ such that $1 \leq l \leq r \leq n$, and multiply all elements of the array from $l$ to $r$ inclusive ... | We can delete all zeros from the array, and it won't affect on answer. Maximum sum is $\sum_{i=1}^n |a_i|$. Minimum number of operations we should do - number of continuous subsequences with negative values of elements. Total complexity: $O(n)$ | [
"greedy",
"math",
"two pointers"
] | 800 | T = int(input())
for _ in range(T):
n = int(input())
a = list(map(int, input().split()))
sum = 0
cnt = 0
open = False
for x in a:
sum += abs(x)
if x < 0 and not open:
open = True
cnt += 1
if x > 0:
open = False
print(sum, cnt... |
1843 | C | Sum in Binary Tree | Vanya really likes math. One day when he was solving another math problem, he came up with an interesting tree. This tree is built as follows.
Initially, the tree has only one vertex with the number $1$ — the root of the tree. Then, Vanya adds two children to it, assigning them consecutive numbers — $2$ and $3$, respe... | It is easy to notice that the children of the vertex with number $u$ have numbers $2 \cdot u$ and $2 \cdot u + 1$. So, the ancestor of the vertex $u$ has the number $\lfloor \frac{u}{2} \rfloor$. Note that based on this formula, the size of the path from the root to the vertex with number $n$ equals $\lfloor \log_2 n \... | [
"bitmasks",
"combinatorics",
"math",
"trees"
] | 800 | t = int(input())
for _ in range(t):
n = int(input())
s = 0
while n >= 1:
s += n
n //= 2
print(s) |
1843 | D | Apple Tree | Timofey has an apple tree growing in his garden; it is a rooted tree of $n$ vertices with the root in vertex $1$ (the vertices are numbered from $1$ to $n$). A tree is a connected graph without loops and multiple edges.
This tree is very unusual — it grows with its root upwards. However, it's quite normal for programm... | Let $cnt_v$ be the number of vertices from which an apple can fall if it is in the vertex $v$. Then the answer to the query is $cnt_v \cdot cnt_u$. Note that the value of $cnt_v$ is equal to the number of leaves in the subtree of vertex $v$. Then, these values can be computed using the DFS or BFS. The value $cnt$ for a... | [
"combinatorics",
"dfs and similar",
"dp",
"math",
"trees"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<vector<int>> g;
vector<ll> cnt;
void dfs(int v, int p) {
if (g[v].size() == 1 && g[v][0] == p) {
cnt[v] = 1;
} else {
for (auto u : g[v]) {
if (u != p) {
dfs(u, v);
cnt[v] +... |
1843 | E | Tracking Segments | You are given an array $a$ consisting of $n$ zeros. You are also given a set of $m$ not necessarily different segments. Each segment is defined by two numbers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$) and represents a subarray $a_{l_i}, a_{l_i+1}, \dots, a_{r_i}$ of the array $a$.
Let's call the segment $l_i, r_i$ b... | Let's use a binary search for an answer. It will work, because if some segment was good, then after one more change it will not be no longer good, and if all segments were bad, then if you remove the last change, they will remain bad. To check if there is a good segment for the prefix of changes, you can build the arra... | [
"binary search",
"brute force",
"data structures",
"two pointers"
] | 1,600 | def solve():
n, m = map(int, input().split())
segs = []
for i in range(m):
l, r = map(int, input().split())
l -= 1
segs.append([l, r])
q = int(input())
ord = [0] * q
for i in range(q):
ord[i] = int(input())
ord[i] -= 1
l = 0
r = q + 1
while r -... |
1843 | F1 | Omsk Metro (simple version) | \textbf{This is the simple version of the problem. The only difference between the simple and hard versions is that in this version $u = 1$.}
As is known, Omsk is the capital of Berland. Like any capital, Omsk has a well-developed metro system. The Omsk metro consists of a certain number of stations connected by tunne... | Let $\mathrm{mx}$ be the maximal sum on the path subsegment, $\mathrm{mn}$ - the minimal sum on the path subsegment. Then it is said that a subsegment with sum $x$ exists if and only if $\mathrm{mn} \leq x \leq \mathrm{mx}$. Proof: Let us fix the subsegment with the minimum sum and the subsegment with the maximum sum. ... | [
"data structures",
"dfs and similar",
"dp",
"graphs",
"greedy",
"math",
"trees"
] | 1,800 | class info:
mn_suf = 0
mx_suf = 0
mn_ans = 0
mx_ans = 0
def solve():
n = int(input())
start = info()
start.mx_suf = start.mx_ans = 1
st = [start]
for i in range(n):
com = input().split()
if (com[0] == '+'):
v = int(com[1]) - 1
x = i... |
1843 | F2 | Omsk Metro (hard version) | \textbf{This is the hard version of the problem. The only difference between the simple and hard versions is that in this version $u$ can take any possible value.}
As is known, Omsk is the capital of Berland. Like any capital, Omsk has a well-developed metro system. The Omsk metro consists of a certain number of stati... | Similarly to the problem F1, we need to be able to find a subsegment with maximum and minimum sum, but on an arbitrary path in the tree. To do this, we will use the technique of binary lifts. For each lift, we will store the maximum/minimum sum on the prefix and suffix, the sum of the subsegment and the maximum sum on ... | [
"data structures",
"dfs and similar",
"divide and conquer",
"dp",
"math",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct info {
int sum, minPrefL, maxPrefL, minPrefR, maxPrefR, minSeg, maxSeg;
info(int el = 0) {
sum = el;
minSeg = minPrefL = minPrefR = min(el, 0);
maxSeg = maxPrefL = maxPrefR = max(el, 0);
}
};
struct ... |
1844 | A | Subtraction Game | You are given two positive integers, $a$ and $b$ ($a < b$).
For some positive integer $n$, two players will play a game starting with a pile of $n$ stones. They take turns removing exactly $a$ or exactly $b$ stones from the pile. The player who is unable to make a move loses.
Find a positive integer $n$ such that the... | We present two approaches. Approach 1 If $a \ge 2$, then $n = 1$ works. Else if $a = 1$ and $b \ge 3$, $n = 2$ works. Otherwise, $a = 1$ and $b = 2$, so $n = 3$ works. Approach 2 Printing $a+b$ works because no matter what move the first player makes, the second player can respond with the opposite move. The time compl... | [
"constructive algorithms",
"games"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t,a,b;
scanf("%d",&t);
while (t--) {
scanf("%d %d",&a,&b);
printf("%d\n",a+b);
}
return 0;
} |
1844 | B | Permutations & Primes | You are given a positive integer $n$.
In this problem, the $\operatorname{MEX}$ of a collection of integers $c_1,c_2,\dots,c_k$ is defined as the smallest \textbf{positive} integer $x$ which does not occur in the collection $c$.
The primality of an array $a_1,\dots,a_n$ is defined as the number of pairs $(l,r)$ such ... | The cases $n \le 2$ can be handled separately. For $n \ge 3$, any construction with $a_1 = 2, a_{\lfloor (n+1)/2 \rfloor} = 1, a_n = 3$ is optimal. We can prove this as follows: Note that since $2$ and $3$ are both prime, any $(l,r)$ with $l \le \left\lfloor \frac{n+1}{2} \right\rfloor \le r$ has a prime $\operatorname... | [
"constructive algorithms",
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int a[200000];
int main() {
int i;
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
if (n == 1) printf("1\n");
else if (n == 2) printf("1 2\n");
else {
int c = 4;
fill(a,a+n,0);
a[0] ... |
1844 | C | Particles | You have discovered $n$ mysterious particles on a line with integer charges of $c_1,\dots,c_n$. You have a device that allows you to perform the following operation:
- Choose a particle and remove it from the line. The remaining particles will shift to fill in the gap that is created. If there were particles with char... | Consider the set of even-indexed particles and the set of odd-indexed particles. Observe that particles can only ever combine with other particles from the same set. It follows that the answer is at most $\max\left(\sum_{\text{odd }i} \max(c_i,0),\sum_{\text{even }i} \max(c_i,0)\right).$ On the other hand, this bound i... | [
"dp",
"greedy",
"implementation",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
int c[200000];
int main() {
int i;
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
for (i = 0; i < n; i++) scanf("%d",&c[i]);
int allneg = 1;
for (i = 0; i < n; i++) allneg &= (c[i] < 0);
... |
1844 | D | Row Major | The row-major order of an $r \times c$ grid of characters $A$ is the string obtained by concatenating all the rows, i.e. $$ A_{11}A_{12} \dots A_{1c}A_{21}A_{22} \dots A_{2c} \dots A_{r1}A_{r2} \dots A_{rc}. $$
A grid of characters $A$ is bad if there are some two adjacent cells (cells sharing an edge) with the same c... | The condition is equivalent to a graph of pairs of characters in $s$ that need to be different. In graph-theoretic language, we need to find the chromatic number of this graph. By considering the $1 \times n$ and $n \times 1$ grids, there is an edge between character $u$ and $u+1$ for all $1 \le u \le n-1$. By consider... | [
"constructive algorithms",
"greedy",
"math",
"number theory",
"strings"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
char s[1000001];
int main() {
int i;
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
int c = 1;
while ((n % c) == 0) c++;
for (i = 0; i < n; i++) s[i] = 'a'+(i % c);
s[n] = '\0';
printf("%s\n",s);
}... |
1844 | E | Great Grids | An $n \times m$ grid of characters is called great if it satisfies these three conditions:
- Each character is either 'A', 'B', or 'C'.
- Every $2 \times 2$ contiguous subgrid contains all three different letters.
- Any two cells that share a common edge contain different letters.
Let $(x,y)$ denote the cell in the $... | We present two approaches. Approach 1 Let the letters 'A', 'B', and 'C' correspond to the numbers $0$, $1$, and $2$ modulo $3$ respectively. Consider drawing an arrow between any two adjacent cells in a great grid pointing to the right or down, and label this arrow with the difference of the two cells modulo $3$. The c... | [
"2-sat",
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef vector<pair<int,int> > vpii;
#define mp make_pair
#define pb push_back
vpii adjList[4000];
int colour[4000],bad = 0;
int doDFS(int u,int c) {
if (colour[u] != -1) {
if (colour[u] != c) bad = 1;
return 0;
}
colour[u] = c;
for (auto [v... |
1844 | F1 | Min Cost Permutation (Easy Version) | \textbf{The only difference between this problem and the hard version is the constraints on $t$ and $n$.}
You are given an array of $n$ positive integers $a_1,\dots,a_n$, and a (possibly negative) integer $c$.
Across all permutations $b_1,\dots,b_n$ of the array $a_1,\dots,a_n$, consider the minimum possible value of... | Let the cost of a permutation $b$ of $a$ be the value $\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$. When $c \ge 0$, it can be proven that the minimum cost can be obtained by sorting $a$ in nondecreasing order. As sorting $a$ in nondecreasing order is also the lexicographically smallest array, this is the answer. Similarly, when ... | [
"brute force",
"constructive algorithms",
"greedy",
"math"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
int a[200000];
int main() {
int i,j;
int t,n,c;
scanf("%d",&t);
while (t--) {
scanf("%d %d",&n,&c);
for (i = 0; i < n; i++) scanf("%d",&a[i]);
if (c >= 0) {
sort(a,a+n);
for (i = 0; ... |
1844 | F2 | Min Cost Permutation (Hard Version) | \textbf{The only difference between this problem and the easy version is the constraints on $t$ and $n$.}
You are given an array of $n$ positive integers $a_1,\dots,a_n$, and a (possibly negative) integer $c$.
Across all permutations $b_1,\dots,b_n$ of the array $a_1,\dots,a_n$, consider the minimum possible value of... | Let $c < 0$. We now simplify condition $(*)$, which involves considering a few cases depending on the sign of the terms. It turns out that the condition is equivalent to ($a_{i-1}-a_{i+1} \le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$) and ($b_{k-1}-a_i \le |c|$) (for full details, see the overall proof below). Sort $a... | [
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"math",
"sortings"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
#define mp make_pair
int a[200000],b[200000],l[200000],r[200000];
set<pii> S;
int main() {
int i;
int t,n,c;
scanf("%d",&t);
while (t--) {
scanf("%d %d",&n,&c);
for (i = 0; i < n; i++) scanf("%d",&a[i]);
if... |
1844 | G | Tree Weights | You are given a tree with $n$ nodes labelled $1,2,\dots,n$. The $i$-th edge connects nodes $u_i$ and $v_i$ and has an unknown positive integer weight $w_i$. To help you figure out these weights, you are also given the distance $d_i$ between the nodes $i$ and $i+1$ for all $1 \le i \le n-1$ (the sum of the weights of th... | Let $x_u$ be the sum of the weights of the edges on the path from node $1$ to node $u$. We know that $x_1 = 0$ and $x_i + x_{i+1} - 2x_{\text{lca}(i,i+1)} = d_i$ for all $1 \le i \le n-1$. This is a system of $n$ linear equations in $n$ variables. As $x_u$ should be integers, let's first solve this system modulo $2$. T... | [
"bitmasks",
"constructive algorithms",
"data structures",
"dfs and similar",
"implementation",
"math",
"matrices",
"number theory",
"trees"
] | 3,000 | #include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
typedef vector<pair<int,int> > vpii;
#define mp make_pair
#define pb push_back
vpii adjList[100000];
LLI d[100000];
int parent[100000][17],parenti[100000],depth[100000];
int doDFS(int u,int p,int d) {
parent[u][0] = p,depth[u] = d;
for (a... |
1844 | H | Multiple of Three Cycles | An array $a_1,\dots,a_n$ of length $n$ is initially all blank. There are $n$ updates where one entry of $a$ is updated to some number, such that $a$ becomes a permutation of $1,2,\dots,n$ after all the updates.
After each update, find the number of ways (modulo $998\,244\,353$) to fill in the remaining blank entries o... | The partially formed permutation is composed of several paths and cycles, and only the length of each path/cycle modulo $3$ matters. We can use a DSU to track the number of paths/cycles of each length $\pmod 3$. If at any point a cycle whose length is not $\equiv 0 \pmod 3$ is formed, the answer is $0$. Thus, the probl... | [
"combinatorics",
"data structures",
"dp",
"dsu",
"math"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
#define MOD 998244353
int parent[300000],siz[300000];
int find(int n) {
if (parent[n] != n) parent[n] = find(parent[n]);
return parent[n];
}
int queries[600000][3],ans[600000];
int fact[300000],invfact[300000],invn[300000];
int inv(int n)... |
1845 | A | Forbidden Integer | You are given an integer $n$, which you want to obtain. You have an unlimited supply of every integer from $1$ to $k$, except integer $x$ (there are no integer $x$ at all).
You are allowed to take an arbitrary amount of each of these integers (possibly, zero). Can you make the sum of taken integers equal to $n$?
If t... | The problem is about considering the least amount of cases possible. I propose the following options. If $x \neq 1$, then you can always print $n$ ones. So the answer is YES. If $k = 1$, then no integer is available, so the answer is NO. If $k = 2$, then only $2$ is available, so you can only collect even $n$. So if it... | [
"constructive algorithms",
"implementation",
"math",
"number theory"
] | 800 | for _ in range(int(input())):
n, k, x = map(int, input().split())
if x != 1:
print("YES")
print(n)
print(*([1] * n))
elif k == 1 or (k == 2 and n % 2 == 1):
print("NO")
else:
print("YES")
print(n // 2)
print(*([3 if n % 2 == 1 else 2] + [2] * (n // 2 - 1))) |
1845 | B | Come Together | Bob and Carol hanged out with Alice the whole day, but now it's time to go home. Alice, Bob and Carol live on an infinite 2D grid in cells $A$, $B$, and $C$ respectively. Right now, all of them are in cell $A$.
If Bob (or Carol) is in some cell, he (she) can move to one of the neighboring cells. Two cells are called n... | Let $d(P_1, P_2)$ be the Manhattan distance between points $P_1 = (x_1, y_1)$ and $P_2 = (x_2, y_2)$. Then $d(P_1, P_2) = |x_1 - x_2| + |y_1 - y_2|$. Note that if you are going from $A$ to $B$ (or to $C$) along the shortest path, the Manhattan distance will be decreasing with each move. So Bob and Carol can walk togeth... | [
"geometry",
"implementation",
"math"
] | 900 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
pt A, B, C;
inline bool read() {
if(!(cin >> A.x >> A.y))
return false;
cin >> B.x >> B.y;
ci... |
1845 | C | Strong Password | Monocarp finally got the courage to register on ForceCoders. He came up with a handle but is still thinking about the password.
He wants his password to be as strong as possible, so he came up with the following criteria:
- the length of the password should be exactly $m$;
- the password should only consist of digits... | Consider the naive solution. You iterate over all password options that fit the criteria on $l$ and $r$ and check if they appear in $s$ as a subsequence. That check can be performed greedily: find the first occurrence of the first digit of the password, then find the first occurrence after it of the second digit of the... | [
"binary search",
"dp",
"greedy",
"strings"
] | 1,400 | import sys
for _ in range(int(sys.stdin.readline())):
s = [int(c) for c in sys.stdin.readline().strip()]
n = len(s)
m = int(sys.stdin.readline())
l = sys.stdin.readline()
r = sys.stdin.readline()
mx = 0
for i in range(m):
li = int(l[i])
ri = int(r[i])
nmx = mx
for c in range(li, ri + 1):
cur = mx
w... |
1845 | D | Rating System | You are developing a rating system for an online game. Every time a player participates in a match, the player's rating changes depending on the results.
Initially, the player's rating is $0$. There are $n$ matches; after the $i$-th match, the rating change is equal to $a_i$ (the rating increases by $a_i$ if $a_i$ is ... | Let's fix some $k$ and look at the first and the last moment when the rating should fall below $k$, but doesn't. After such moments, the rating is equal to $k$. So we can "delete" all changes (array elements) between those moments. And the remaining changes (to the left from the first moment and to the right from the l... | [
"binary search",
"brute force",
"data structures",
"dp",
"dsu",
"greedy",
"math",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using li = long long;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
li delta = 0, ans = 0;
li sum = 0, mx = 0;
for (int i = 0; i < n; ++i) {
li x; cin >> x;
sum += x;
mx... |
1845 | E | Boxes and Balls | There are $n$ boxes placed in a line. The boxes are numbered from $1$ to $n$. Some boxes contain one ball inside of them, the rest are empty. At least one box contains a ball and at least one box is empty.
In one move, you \textbf{have to} choose a box with a ball inside and an adjacent empty box and move the ball fro... | Consider a harder problem. For each $k'$ from $0$ to $k$, what's the number of arrangements that have $k'$ as the smallest number of operations needed that obtain them? That would help us solve the full problem. You just have to sum up the answer for $k'$ such that they have the same parity as $k$ (since, once the arra... | [
"dp",
"implementation",
"math"
] | 2,500 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = int(1e9) + 7;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
return a;
}
int main() {
int n, k;
scanf("%d%d", &n, &k);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
int lim = 1;
w... |
1845 | F | Swimmers in the Pool | There is a pool of length $l$ where $n$ swimmers plan to swim. People start swimming at the same time (at the time moment $0$), but you can assume that they take different lanes, so they don't interfere with each other.
Each person swims along the following route: they start at point $0$ and swim to point $l$ with con... | Firstly, note that there are two different situations when some two swimmers meet: they either move in the same direction, or in opposite directions. Suppose, swimmers $i$ and $j$ meet while moving in the same direction. We can write some easy system of equation and get that they will meet each $\frac{2l}{|v_i - v_j|}$... | [
"dp",
"fft",
"math",
"number theory"
] | 2,800 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(... |
1846 | A | Rudolph and Cut the Rope | There are $n$ nails driven into the wall, the $i$-th nail is driven $a_i$ meters above the ground, one end of the $b_i$ meters long rope is tied to it. All nails hang at different heights one above the other. One candy is tied to all ropes at once. Candy is tied to end of a rope that is not tied to a nail.
To take the... | In order for the candy to be on the ground, it is necessary that all the ropes touch the ground. This means that the length of all ropes must be greater than or equal to the height of the nails to which they are attached. That is, you need to cut all the ropes, the length of which is less than the height of their nail.... | [
"implementation",
"math"
] | 800 | #include <iostream>
using namespace std;
int main() {
int test_cases;
cin >> test_cases;
for (int test_case = 0; test_case < test_cases; test_case++) {
int n;
cin >> n;
int ans = 0;
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
if (a > b)
ans++;
}
cout << ans << endl;
}
retur... |
1846 | B | Rudolph and Tic-Tac-Toe | Rudolph invented the game of tic-tac-toe for three players. It has classic rules, except for the third player who plays with pluses. Rudolf has a $3 \times 3$ field — the result of the completed game. Each field cell contains either a cross, or a nought, or a plus sign, or nothing. The game is won by the player who ma... | To solve this problem, it is enough to check the equality of elements on each row, column and diagonal of three elements. If all three elements are equal and are not ".", then the value of these elements is the answer. Note that a row of "." does not give you answer ".". Statement does not say that the players have equ... | [
"brute force",
"implementation",
"strings"
] | 800 | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int test_cases;
cin >> test_cases;
for (int test_case = 0; test_case < test_cases; test_case++) {
vector<string> v(3);
for (int i = 0; i < 3; i++)
cin >> v[i];
string ans = "DRAW";
for(int i = 0; i < 3; i++) {
... |
1846 | C | Rudolf and the Another Competition | Rudolf has registered for a programming competition that will follow the rules of ICPC. The rules imply that for each solved problem, a participant gets $1$ point, and also incurs a penalty equal to the number of minutes passed from the beginning of the competition to the moment of solving the problem. In the final tab... | First of all, it is necessary to determine the optimal order of solving problems for each participant. It is claimed that it is most optimal to solve problems in ascending order of their solution time. Let's prove this: Firstly, it is obvious that this strategy will allow solving the maximum number of problems. Secondl... | [
"constructive algorithms",
"data structures",
"dp",
"greedy",
"sortings"
] | 1,200 | #include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int ttt;
cin >> ttt;
while(ttt--){
int n, m, h;
cin >> n >> m >> h;
pair<int, long long> rud;
int ans = 1;
... |
1846 | D | Rudolph and Christmas Tree | Rudolph drew a beautiful Christmas tree and decided to print the picture. However, the ink in the cartridge often runs out at the most inconvenient moment. Therefore, Rudolph wants to calculate in advance how much green ink he will need.
The tree is a vertical trunk with \textbf{identical} triangular branches at diffe... | Let's consider the triangles in ascending order of $y_i$. Let the current triangle have index $i$. There are two cases: The triangle does not intersect with the $(i+1)$-th triangle $(y_{i + 1} - y_i \ge h)$. In this case, we simply add the area of the triangle to the answer. The area will be $\frac{d \cdot h}{2}$. The ... | [
"constructive algorithms",
"geometry",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout.precision(10); cout.setf(ios::fixed);
int ttt;
cin >> ttt;
while (ttt--) {
int n, d, h;
cin >> n >> d >> h;
vector<int> y(n);
fo... |
1846 | E1 | Rudolf and Snowflakes (simple version) | \textbf{This is a simple version of the problem. The only difference is that in this version $n \le 10^6$.}
One winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician, R... | For the current given constraint you can precalculate whether it is possible to obtain each $n$ for some $k$. To do this, we can iterate through all possible $2 \le k \le 10^6$ and for each of them calculate the values $1 + k + k^2$, $1 + k + k^2 + k^3$, ..., $1 + k + k^2 + k^3 + ... + k^p$, where $p$ is such that $1 \... | [
"brute force",
"implementation",
"math"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
using LL = long long;
set<long long> nums;
int main() {
for (long long k = 2; k <= 1000; ++k) {
long long val = 1 + k;
long long p = k*k;
for (int cnt = 2; cnt <= 20; ++cnt) {
val += p;
if (val > 1e6) break;
... |
1846 | E2 | Rudolf and Snowflakes (hard version) | \textbf{This is the hard version of the problem. The only difference is that in this version $n \le 10^{18}$.}
One winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician... | On these constraints, it is also possible to precalculate whether it is possible to obtain certain values of $n$ for some $k$. To do this, we can iterate through all possible $2 \le k \le 10^6$ and for each of them calculate the values $1 + k + k^2$, $1 + k + k^2 + k^3$, ..., $1 + k + k^2 + k^3 + ... + k^p$, where $p$ ... | [
"binary search",
"brute force",
"implementation",
"math"
] | 1,800 | #include<bits/stdc++.h>
using namespace std;
using LL = long long;
set<long long> nums;
int main() {
for (long long k = 2; k <= 1000000; ++k) {
long long val = 1 + k;
long long p = k*k;
for (int cnt = 3; cnt <= 63; ++cnt) {
val += p;
if (val > 1e18) break;
... |
1846 | F | Rudolph and Mimic | \textbf{This is an interactive task.}
Rudolph is a scientist who studies alien life forms. There is a room in front of Rudolph with $n$ different objects scattered around. Among the objects there is \textbf{exactly one} amazing creature — a mimic that can turn into any object. He has already disguised himself in this ... | The strategy is to keep track of the number of objects of each type. When the number of objects of a certain type increases, that means the mimic has turned into an object of that type. Then you can delete all other objects. After the first such removal, all objects will become equal. Then, after maximum two stages, th... | [
"constructive algorithms",
"implementation",
"interactive"
] | 1,800 | #include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
int test_cases;
cin >> test_cases;
for (int test_case = 0; test_case < test_cases; test_case++) {
int n;
cin >> n;
vector<int> v(n);
map<int, int> m;
for (int i = 0; i < n; i++) {
cin >> v[i];
m[v[i]]++;
}
ve... |
1846 | G | Rudolf and CodeVid-23 | A new virus called "CodeVid-23" has spread among programmers. Rudolf, being a programmer, was not able to avoid it.
There are $n$ symptoms numbered from $1$ to $n$ that can appear when infected. Initially, Rudolf has some of them. He went to the pharmacy and bought $m$ medicines.
For each medicine, the number of days... | Let's denote Rudolf's state as a binary mask of length $n$ consisting of $0$ and $1$, similar to how it is given in the input data. Then each medicine transforms Rudolf from one state to another. Let's construct a weighted directed graph, where the vertices will represent all possible states of Rudolf. There will be $2... | [
"bitmasks",
"dp",
"graphs",
"greedy",
"shortest paths"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int ttt;
cin >> ttt;
while (ttt--) {
int n, m;
cin >> n >> m;
bitset<10> tmp;
cin >> tmp;
int s = (int) tmp.to_ulong();
v... |
1847 | A | The Man who became a God | Kars is tired and resentful of the narrow mindset of his village since they are content with staying where they are and are not trying to become the perfect life form. Being a top-notch inventor, Kars wishes to enhance his body and become the perfect life form. Unfortunately, $n$ of the villagers have become suspicious... | Let us find $f(1,n)$. Now, you need to divide the array into more $K-1$ parts. When you split an array $b$ of size $m$ into two parts, the suspicion changes from $f(1,m)$ to $f(1,i)+f(i+1,m)$ ($1 \leq i < m$). Also, $f(1,m) = f(1,i) + |b_i - b_{i+1}| + f(i+1,m)$. Substituting this in previous change, we get $f(1,i) + |... | [
"greedy",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define all(x) x.begin(),x.end()
void solve(){
int n , k;
cin >> n >> k;
ll arr[n];
for(int ... |
1847 | B | Hamon Odyssey | Jonathan is fighting against DIO's Vampire minions. There are $n$ of them with strengths $a_1, a_2, \dots, a_n$. $\def\and {{\,&\,}}$
Denote $(l, r)$ as the group consisting of the vampires with indices from $l$ to $r$. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise ... | There are two cases in this problem. First, if $f(1,n) > 0$, then maximum number of groups becomes $1$. This is because there are some bits set in all the elements. Now, if we divide the array in more than one group, then these bits are taken more than once which will not give smallest AND. Second case is when $f(1,n) ... | [
"bitmasks",
"greedy",
"two pointers"
] | 1,000 | #include <iostream>
#include <vector>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define all(x) x.begin(),x.end()
void solve(){
int n;
cin >> n;
int arr[n];
for... |
1847 | C | Vampiric Powers, anyone? | DIO knows that the Stardust Crusaders have determined his location and will be coming to fight him. To foil their plans he decides to send out some Stand users to fight them. Initially, he summoned $n$ Stand users with him, the $i$-th one having a strength of $a_i$. Using his vampiric powers, he can do the following as... | At the end of the array, you can only achieve xor of any subarray of the original array. Lets denote $f(u,v) =$ xor of all $a_i$ such that $min(u,v) \leq i < max(u,v)$. In the first operation you add $f(n,i)$. I.e. $[u_1,v_1)=[n,i)$. It can be proven that $f(u_k,v_k) = f(v_{k-1},v_k)$ in the $k$-th operation which is a... | [
"bitmasks",
"brute force",
"dp",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int ntest;
cin >> ntest;
while (ntest--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &i : a)
cin >> i;
int const max_value = 1 << 8;
vector<char> ... |
1847 | D | Professor Higashikata | Josuke is tired of his peaceful life in Morioh. Following in his nephew Jotaro's footsteps, he decides to study hard and become a professor of computer science. While looking up competitive programming problems online, he comes across the following one:
Let $s$ be a binary string of length $n$. An operation on $s$ is ... | Lets assume you know string $t$. String $t$ is made by positions in $s$. Lets denote $f(i) =$ position in $s$ from which $t_i$ is made. For maximising $t$ you need to make the starting elements in $t$ as large as possible. Now, to make $t$ lexicographically as large as possible, we need to swap positions in $s$. We can... | [
"data structures",
"dsu",
"greedy",
"implementation",
"strings"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define vf first
#define vs second
#define all(x) x.begin(),x.end()
void solve(){
int n , m , ... |
1847 | E | Triangle Platinum? | This is an interactive problem.
Made in Heaven is a rather curious Stand. Of course, it is (arguably) the strongest Stand in existence, but it is also an ardent puzzle enjoyer. For example, it gave Qtaro the following problem recently:
Made in Heaven has $n$ hidden integers $a_1, a_2, \dots, a_n$ ($3 \le n \le 5000$,... | First, notice that we can uniquely determine the multiset of numbers any three $a_i, a_j, a_k$ except for the collision between triples $(1, 4, 4)$ and $(2, 2, 3)$. The issue is that even if we know the multiset we cannot always uniquely determine $a_i, a_j, a_k$. But what if all the elements of the multiset are equal?... | [
"brute force",
"combinatorics",
"implementation",
"interactive",
"math",
"probabilities"
] | 2,900 | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18
#define f first
#define s second
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
const int N = 5005;
int ans[N];
int n;
int dp[5][5][5];
int holy[11][11][11];
int area(int a, int b, int c){
if (a >=... |
1847 | F | The Boss's Identity | While tracking Diavolo's origins, Giorno receives a secret code from Polnareff. The code can be represented as an infinite sequence of positive integers: $a_1, a_2, \dots $. Giorno immediately sees the pattern behind the code. The first $n$ numbers $a_1, a_2, \dots, a_n$ are \textbf{given}. For $i > n$ the value of $a_... | Lets start with an example of $n=5$. Let $a = [a,b,c,d,e]$ where $a$,$b$,$c$,$d$ and $e$ are variables. First $20$ elements of $a$ will be [$a$,$b$,$c$,$d$,$e$,$ab$,$bc$,$cd$,$de$,$abe$,$abc$,$bcd$,$cde$,$abde$,$abce$,$abcd$,$bcde$,$abcde$,$abcde$,$abcde$]. By removing and rearranging some elements we can get $b$$c$$d$... | [
"binary search",
"bitmasks",
"data structures",
"dfs and similar",
"greedy",
"math",
"sortings"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define vf first
#define vs second
#define all(x) x.begin(),x.end()
const int B = 31;
struct it... |
1848 | A | Vika and Her Friends | Vika and her friends went shopping in a mall, which can be represented as a rectangular grid of rooms with sides of length $n$ and $m$. Each room has coordinates $(a, b)$, where $1 \le a \le n, 1 \le b \le m$. Thus we call a hall with coordinates $(c, d)$ a neighbouring for it if $|a - c| + |b - d| = 1$.
Tired of empt... | Let's color the halls of a rectangle in a chess coloring. Then Vika will be able to escape from her friends infinitely only if none of her friends is on a cell of the same color as Vika. This observation seems intuitively clear, but let's formalize it. $\Leftarrow)$ It is true, because if initially Vika and her friend ... | [
"games",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int t;
cin >> t;
while (t--) {
int n, m, k;
cin >> n >> m >> k;
int x, y;
cin >> x >> y;
string ans = "YES\n";
for (int i = 0; i < k; ++i) {
int xx, yy;
... |
1848 | B | Vika and the Bridge | In the summer, Vika likes to visit her country house. There is everything for relaxation: comfortable swings, bicycles, and a river.
There is a wooden bridge over the river, consisting of $n$ planks. It is quite old and unattractive, so Vika decided to paint it. And in the shed, they just found cans of paint of $k$ co... | In a single linear pass through the array, let's calculate, for each color, the lengths of the two maximum steps between planks of that color. To do this, we will maintain when we last encountered that color. Now we need to consider that we can repaint one of the planks. Let's say we repaint a plank in color $c$. It is... | [
"binary search",
"data structures",
"greedy",
"implementation",
"math",
"sortings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> c(n);
for (int i = 0; i < n; ++i) {
cin >> c[i];
}
vector<int> last(k, -1);
vector<int> max_step(k), max2_ste... |
1848 | C | Vika and Price Tags | Vika came to her favorite cosmetics store "Golden Pear". She noticed that the prices of $n$ items have changed since her last visit.
She decided to analyze how much the prices have changed and calculated the difference between the old and new prices for each of the $n$ items.
Vika enjoyed calculating the price differ... | First of all, if $a_i$ and $b_i$ are both zero, then all numbers in the sequence will be zero. Otherwise, if one of the numbers $a_i, b_i$ is not zero, then if $a_i \ge b_i$, after one operation, the sum $a_i - b_i + b_i = a_i$ will decrease relative to the original value, or if $b_i > a_i$, after two operations, the s... | [
"math",
"number theory"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#define int long long
int gcd(int a, int b) {
if (a == 0) {
return 0;
}
if (b == 0) {
return 1;
}
if (a >= b) {
int r = a % b;
int k = a / b;
if (k % 2 == 1) {
return gcd(b, r) + k + k / 2;
... |
1848 | D | Vika and Bonuses | A new bonus system has been introduced at Vika's favorite cosmetics store, "Golden Pear"!
The system works as follows: suppose a customer has $b$ bonuses. Before paying for the purchase, the customer can choose one of two options:
- Get a discount equal to the current number of bonuses, while the bonuses are not dedu... | First, let's note that the optimal strategy for Vika will be to accumulate bonuses first and then only get the discount. This simple observation is proved by greedy considerations. Next, let's note that the last digit of the bonus number will either become zero after a few actions (in which case it makes no sense for V... | [
"binary search",
"brute force",
"math",
"ternary search"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
#define int long long
int f(int s, int k) {
// (s + 20x) * (k - 4x)
// (-80)x^2 + (20k - 4s)x + (sk)
// -b/2a = (5k-s)/40
int x = (5 * k - s) / 40;
x = min(x, k / 4);
int res = s * k;
if (x > 0) {
res = max(res, (s + 20 * x) * (k - ... |
1848 | E | Vika and Stone Skipping | In Vika's hometown, Vladivostok, there is a beautiful sea.
Often you can see kids skimming stones. This is the process of throwing a stone into the sea at a small angle, causing it to fly far and bounce several times off the water surface.
Vika has skimmed stones many times and knows that if you throw a stone from th... | The key observation is that the answer for coordinate $x$ is the number of odd divisors of $x$. Let's prove this. Let's see how far a pebble will fly with force $f$, which touches the water $cnt$ times: $f + (f - 1) + \ldots + (f - cnt + 1) = x$. If $cnt$ is even, then $x = (cnt / 2) \cdot (2 \cdot f - cnt + 1) = (p) \... | [
"brute force",
"implementation",
"math",
"number theory"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int K = 1e6;
#define int long long
int mod;
int dp[K + 1];
int cnt[K + 1];
const int MM = 3e6 + 7;
int inv[MM];
int cc = 0;
int mul(int a, int b) {
int bb = b;
while (bb % mod == 0) {
++cc;
bb /= mod;
}
return (a * (bb... |
1848 | F | Vika and Wiki | Recently, Vika was studying her favorite internet resource - Wikipedia.
On the expanses of Wikipedia, she read about an interesting mathematical operation bitwise XOR, denoted by $\oplus$.
Vika began to study the properties of this mysterious operation. To do this, she took an array $a$ consisting of $n$ non-negative... | Let's denote $next(i, delta) = (i + delta \bmod n) + 1$, and $a[cnt][i]$ represents the value of $a_i$ after $cnt$ operations. First, let's observe that if the array becomes all zeros, it will always remain all zeros. Therefore, we need to find the first moment in time when the array becomes all zeros. Furthermore, let... | [
"binary search",
"bitmasks",
"combinatorics",
"divide and conquer",
"dp",
"math"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (1 << 20);
int a[MAXN];
int solve(int n) {
if (n == 1) {
if (a[0] == 0) {
return 0;
} else {
return 1;
}
}
int fl = true;
for (int i = 0; i < n / 2; ++i) {
if (a[i] != a[i + n /... |
1849 | A | Morning Sandwich | Monocarp always starts his morning with a good ol' sandwich. Sandwiches Monocarp makes always consist of bread, cheese and/or ham.
A sandwich always follows the formula:
- a piece of bread
- a slice of cheese or ham
- a piece of bread
- $\dots$
- a slice of cheese or ham
- a piece of bread
So it always has bread on ... | Notice that the type of filling doesn't matter. We can treat both cheese and ham together as one filling, with quantity $c + h$. Then let's start building a sandwich layer by layer. Put a piece of bread. Then put a layer of filling and a piece of bread. Then another layer of filling and a piece of bread. Observe that y... | [
"implementation",
"math"
] | 800 |
fun main() = repeat(readLine()!!.toInt()) {
val (b, c, h) = readLine()!!.split(' ').map { it.toInt() }
println(minOf(b - 1, c + h) * 2 + 1)
}
|
1849 | B | Monsters | Monocarp is playing yet another computer game. And yet again, his character is killing some monsters. There are $n$ monsters, numbered from $1$ to $n$, and the $i$-th of them has $a_i$ health points initially.
Monocarp's character has an ability that deals $k$ damage to the monster with the \textbf{highest current hea... | Let's simulate the game process until the number of health points of each monster becomes $k$ or less. Then we can consider that the $i$-th monster has $a_i \bmod k$ health instead of $a_i$ (except for the case when $a_i$ is divisible by $k$, then the remaining health is $k$, not $0$). Now, the health points of all mon... | [
"greedy",
"math",
"sortings"
] | 1,000 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto &x : a) {
cin >> x;
x %= k;
if (!x) x = k;
}
vector<int> ord(n);
iota(ord.begi... |
1849 | C | Binary String Copying | You are given a string $s$ consisting of $n$ characters 0 and/or 1.
You make $m$ copies of this string, let the $i$-th copy be the string $t_i$. Then you perform exactly one operation on each of the copies: for the $i$-th copy, you sort its substring $[l_i; r_i]$ (the substring from the $l_i$-th character to the $r_i$... | We can see that each modified copy is determined by only two integers $lb$ and $rb$ - the first position at which the character has changed and the last such position. If we can find such numbers for each of the copies, the number of different pairs will be the answer to the problem. Let $lf_i$ be the position of the n... | [
"binary search",
"brute force",
"data structures",
"hashing",
"strings"
] | 1,600 |
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m;
string s;
cin >> n >> m >> s;
vector<int> lf(n), rg(n);
lf[0] = -1;
for (int i = 0; i < n; ++i) {
if (i > 0) lf[i] = lf[i - 1];
if (s[i] == '0') lf[i] = i;
}
rg[n - 1] = n;
for (int i = n -... |
1849 | D | Array Painting | You are given an array of $n$ integers, where each integer is either $0$, $1$, or $2$. Initially, each element of the array is blue.
Your goal is to paint each element of the array red. In order to do so, you can perform operations of two types:
- pay one coin to choose a blue element and paint it red;
- choose a red... | Suppose we used a second operation as follows: we decreased a red element $x$, and painted another element $y$ red. Let's then say that $x$ is the parent of $y$. Furthermore, let's say that the element $x$ controls the element $y$ if one of the two conditions applies: $x$ is the parent of $y$; $x$ controls the parent o... | [
"constructive algorithms",
"greedy",
"two pointers"
] | 1,700 |
n = int(input())
a = list(map(int, input().split()))
ans = 0
l = 0
while l < n:
r = l + 1
hasTwo = (a[l] == 2)
hasMiddleZero = False
while r < n:
if r - 1 > l and a[r - 1] == 0:
hasMiddleZero = True
if a[r] == 2:
hasTwo = True
good = (not hasMiddleZero) ... |
1849 | E | Max to the Right of Min | You are given a permutation $p$ of length $n$ — an array, consisting of integers from $1$ to $n$, all distinct.
Let $p_{l,r}$ denote a subarray — an array formed by writing down elements from index $l$ to index $r$, inclusive.
Let $\mathit{maxpos}_{l,r}$ denote the \textbf{index} of the maximum element on $p_{l,r}$. ... | The problem was originally prepared as part of the lecture on a monotonic stack. Thus, I will omit its explanation. First, recall a common technique of counting all segments satisfying some property. You can count the segments that have the same right border at the same time. Consider all segments $[l, r]$ with a fixed... | [
"binary search",
"data structures",
"divide and conquer",
"dp",
"dsu",
"two pointers"
] | 2,300 |
#include <bits/stdc++.h>
using namespace std;
bool comp(const pair<int, int> &a, const pair<int, int> &b){
return a.second < b.second;
}
int main(){
int n;
scanf("%d", &n);
vector<pair<int, int>> stmn, stmx;
stmn.push_back({-1, -1});
stmx.push_back({n, -1});
long long ans = 0;
int le... |
1849 | F | XOR Partition | For a set of integers $S$, let's define its cost as the minimum value of $x \oplus y$ among all pairs of \textbf{different} integers from the set (here, $\oplus$ denotes bitwise XOR). If there are less than two elements in the set, its cost is equal to $2^{30}$.
You are given a set of integers $\{a_1, a_2, \dots, a_n\... | Disclaimer: the model solution to this problem is a bit more complicated than most of the solutions written by participants, but I will still use it for the editorial so that I can explain some of the classical techniques appearing in it. Suppose we have built a graph on $n$ vertices, where each pair of vertices is con... | [
"binary search",
"bitmasks",
"data structures",
"divide and conquer",
"greedy",
"trees"
] | 2,700 |
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
typedef long long LL;
typedef pair<int, int> PII;
const int N = 200000;
const int NODES = 32 * N;
const int INF = int(2e9);
int n;
int a[N];
int nx[NODES][2], cnt[NODES], fn... |
1850 | A | To My Critics | Suneet has three digits $a$, $b$, and $c$.
Since math isn't his strongest point, he asks you to determine if you can choose any two digits to make a sum greater or equal to $10$.
Output "YES" if there is such a pair, and "NO" otherwise. | One way to solve the problem is to check if $a + b + c - min(a, b, c) \geq 10$ using an if statement. | [
"implementation",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
void solve()
{
int a, b, c;
cin >> a >> b >> c;
cout << (a+b+c-min({a,b,c}) >= 10 ? "YES\n" : "NO\n");
}
int main()
{
int t;
cin >> t;
while(t--)
{
solve();
}
}
|
1850 | B | Ten Words of Wisdom | In the game show "Ten Words of Wisdom", there are $n$ participants numbered from $1$ to $n$, each of whom submits one response. The $i$-th response is $a_i$ words long and has quality $b_i$. No two responses have the same quality, and at least one response has length at most $10$.
The winner of the show is the respons... | Let's iterate through all responses: if it has $> 10$ words, ignore it. Otherwise, keep track of the maximum quality and its index, and update it as we go along. Then output the index with maximum quality. The time complexity is $\mathcal{O}(n)$. | [
"implementation",
"sortings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
int winner = -1, best_score = 0;
for (int i = 1; i <= n; i++) {
int a, b;
cin >> a >> b;
if (b > best_score && a <= 10) {winner = i; best_score = b;}
}
cout << winner << '\... |
1850 | C | Word on the Paper | On an $8 \times 8$ grid of dots, a word consisting of lowercase Latin letters is written vertically in one column, from top to bottom. What is it? | You can iterate through the grid and then once you find a letter, iterate downwards until you get the whole word. However there is an approach that is even faster to code: just input each character, and output it if it is not a dot. This works because we will input the characters in the same order from top to bottom. T... | [
"implementation",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
char x;
cin >> x;
if (x != '.') {cout << x;}
}
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullp... |
1850 | D | Balanced Round | You are the author of a Codeforces round and have prepared $n$ problems you are going to set, problem $i$ having difficulty $a_i$. You will do the following process:
- remove some (possibly zero) problems from the list;
- rearrange the remaining problems in any order you wish.
A round is considered balanced if and on... | Let's calculate the maximum number of problems we can take, and the answer will be $n$ subtracted by that count. An arrangement that always minimizes the absolute difference between adjacent pairs is the array in sorted order. What we notice, is that if the array is sorted, we will always take a subarray (all taken ele... | [
"brute force",
"greedy",
"implementation",
"sortings"
] | 900 | #include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
void solve() {
int n, k; cin >... |
1850 | E | Cardboard for Pictures | Mircea has $n$ pictures. The $i$-th picture is a square with a side length of $s_i$ centimeters.
He mounted each picture on a square piece of cardboard so that each picture has a border of $w$ centimeters of cardboard on all sides. In total, he used $c$ square centimeters of cardboard. Given the picture sizes and the ... | The key idea is to binary search on the answer. If you don't know what that is, you should read this Codeforces EDU article. Let's make a function $f(x)$, which tells us the total area of cardboard if we use a width of $x$. Then you can see that we can calculate $f(x)$ in $\mathcal{O}(n)$ time as $(a_1 + 2x)^2 + (a_2 +... | [
"binary search",
"geometry",
"implementation",
"math"
] | 1,100 | #include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
#define int long long
void solve... |
1850 | F | We Were Both Children | Mihai and Slavic were looking at a group of $n$ frogs, numbered from $1$ to $n$, all initially located at point $0$. Frog $i$ has a hop length of $a_i$.
Each second, frog $i$ hops $a_i$ units forward. Before any frogs start hopping, Slavic and Mihai can place \textbf{exactly one} trap in a coordinate in order to catch... | We disregard any $a_i$ larger than $n$ since we can't catch them anyway. We keep in $cnt_i$ how many frogs we have for each hop distance. We go through each $i$ from $1$ to $n$ and add $cnt_i$ to every multiple of $i$ smaller or equal to $n$. This action is a harmonic series and takes $O(nlogn)$ time. We go through all... | [
"brute force",
"implementation",
"math",
"number theory"
] | 1,300 | #include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
void solve() {
int n; cin >> n... |
1850 | G | The Morning Star | A compass points directly toward the morning star. It can only point in one of eight directions: the four cardinal directions (N, S, E, W) or some combination (NW, NE, SW, SE). Otherwise, it will break.
\begin{center}
{\small The directions the compass can point.}
\end{center}
There are $n$ distinct points with integ... | Let's look at four directions of the line connecting the compass and morning star: vertical, horizontal, with slope $1$ (looks like /), and with slope $-1$ (looks like \). vertical: the two points need to have the same $y$-coordinate. If there are $k$ points with the same $y$-coordinate, then how many pairs are possibl... | [
"combinatorics",
"data structures",
"geometry",
"implementation",
"math",
"sortings"
] | 1,500 | #include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
using namespace std;
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define int long long
void solve()
{
int n;
cin >> n;
map<int, int> up, side, diag1, diag2;
int ans = 0;
for(i... |
1850 | H | The Third Letter | In order to win his toughest battle, Mircea came up with a great strategy for his army. He has $n$ soldiers and decided to arrange them in a certain way in camps. Each soldier has to belong to exactly one camp, and there is one camp at each integer point on the $x$-axis (at points $\cdots, -2, -1, 0, 1, 2, \cdots$).
T... | We can view the conditions and soldiers as a directed graph. The soldiers represent nodes and the conditions represent directed edges. Saying $a_i$ should be $d_i$ meters in front of $b_i$ is equivalent to adding two weighted directed edges: An edge from $a_i$ to $b_i$ with weight $d_i$. An edge from $b_i$ to $a_i$ wit... | [
"dfs and similar",
"dsu",
"graphs",
"greedy",
"implementation"
] | 1,700 | #include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
#define int long long
const int N ... |
1851 | A | Escalator Conversations | One day, Vlad became curious about who he can have a conversation with on the escalator in the subway. There are a total of $n$ passengers. The escalator has a total of $m$ steps, all steps indexed from $1$ to $m$ and $i$-th step has height $i \cdot k$.
Vlad's height is $H$ centimeters. Two people with heights $a$ and... | For each person in the array $h$, we will check the conditions. First, the height should not be the same as Vlad's height, then their difference should be divisible by $k$, and finally, the difference between the extreme steps should not exceed the difference in height. If these requirements are met, there will be step... | [
"brute force",
"constructive algorithms",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define sz(v) (int)v.size()
#define all(v) v.begin(),v.end()
#define eb emplace_back
void solve() {
int n,m,k,H; cin >> n >> m >> k >> H;
int ans = 0;
forn(i, n) {
int x; cin >> x;
ans += (... |
1851 | B | Parity Sort | You have an array of integers $a$ of length $n$. You can apply the following operation to the given array:
- Swap two elements $a_i$ and $a_j$ such that $i \neq j$, $a_i$ and $a_j$ are either \textbf{both} even or \textbf{both} odd.
Determine whether it is possible to sort the array in non-decreasing order by perform... | Let's copy array $a$ to array $b$. Then sort array $b$. Let's check that for each $1 \le i \le n$ it is satisfied that $(a_i \bmod 2) = (b_i \bmod 2)$, where $\bmod$ is the operation of taking the remainder from division. In other words, we need to check that in the sorted array $b$, the element at the $i$-th position ... | [
"greedy",
"sortings",
"two pointers"
] | 800 | #include<bits/stdc++.h>
using namespace std;
bool solve(){
int n;
cin >> n;
vector<int>a(n), b(n);
for(int i = 0; i < n; i++){
cin >> a[i];
b[i] = a[i];
}
sort(b.begin(), b.end());
for(int i = 0; i < n; i++){
if((a[i] % 2) != (b[i] % 2)) return false;
}
retur... |
1851 | C | Tiles Comeback | Vlad remembered that he had a series of $n$ tiles and a number $k$. The tiles were numbered from left to right, and the $i$-th tile had colour $c_i$.
If you stand on the \textbf{first} tile and start jumping any number of tiles \textbf{right}, you can get a path of length $p$. The length of the path is the number of t... | Since the path must start in the first tile and end in the last tile, it is enough to construct a path consisting of $1$ or $2$ blocks of length $k$ to solve the problem. If $c_1 = c_n$, then we need to check that there are $k-2$ tiles of colour $c_0$ between the first and the last tile. If this condition is satisfied,... | [
"greedy"
] | 1,000 | #include "bits/stdc++.h"
using namespace std;
bool solve(){
int n, k;
cin >> n >> k;
vector<int>c(n);
for(int i = 0; i < n; i++) cin >> c[i];
int left = 0, right = 0, i = 0, j = n - 1;
int k_left = k, k_right = k;
if (c[0] == c[n - 1]){
k_left = k / 2;
k_right = k - k_left;... |
1851 | D | Prefix Permutation Sums | Your friends have an array of $n$ elements, calculated its array of prefix sums and passed it to you, accidentally losing one element during the transfer. Your task is to find out if the given array can matches \textbf{permutation}.
A permutation of $n$ elements is an array of $n$ numbers from $1$ to $n$ such that eac... | To begin with, let's learn how to reconstruct an array from its prefix sum array. This can be done by calculating the differences between adjacent elements. If the element $\frac{n * (n + 1)}{2}$ is missing from the array, we will add it and check if the array corresponds to some permutation. Otherwise, there is a miss... | [
"implementation",
"math"
] | 1,300 | #include <iostream>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
ll n;
bool isPermutation(vector<ll> a) {
for (int i = 0; i < n; ++i) {
if (a[i] <= 0 || a[i] > n) {
return false;
}
}
set<ll> s(a.begin(), a.end());
return s.siz... |
1851 | E | Nastya and Potions | Alchemist Nastya loves mixing potions. There are a total of $n$ types of potions, and one potion of type $i$ can be bought for $c_i$ coins.
Any kind of potions can be obtained in no more than one way, by mixing from several others. The potions used in the mixing process will be \textbf{consumed}. Moreover, no potion c... | To begin with, let's note that potions of types $p1, p2, \dots, p_k$ are essentially free, so we can replace their costs with $0$. Let $ans[i]$ be the answer for the $i$-th potion. Each potion can be obtained in one of two ways: by buying it or by mixing it from other potions. For mixing, we obtain all the required pot... | [
"dfs and similar",
"dp",
"graphs",
"sortings"
] | 1,500 | #include <bits/stdc++.h>
#define int long long
using namespace std;
vector<int> dp;
vector<bool> used;
vector<vector<int>> sl;
int get(int v){
if(used[v]){
return dp[v];
}
used[v] = true;
int s = 0;
for(int u: sl[v]){
s += get(u);
}
if(!sl[v].empty()) dp[v] = min(dp[v], s... |
1851 | F | Lisa and the Martians | Lisa was kidnapped by martians! It okay, because she has watched a lot of TV shows about aliens, so she knows what awaits her. Let's call integer martian if it is \textbf{a non-negative integer} and \textbf{strictly less than} $2^k$, for example, when $k = 12$, the numbers $51$, $1960$, $0$ are martian, and the numbers... | Solution 1. Let's use the data structure called a bitwise trie. Fix some $a_i$, where all $a_j$ for $j < i$ have already been added to the trie. We will iterate over the bits in $a_i$ from the $(k - 1)$-th bit to the $0$-th bit. Since $2^t > 2^{t - 1} + 2^{t - 2} + \ldots + 2 + 1$, if there exists $a_j$ with the same b... | [
"bitmasks",
"greedy",
"math",
"strings",
"trees"
] | 1,800 | #include <bits/stdc++.h>
#define all(arr) arr.begin(), arr.end()
using namespace std;
const int MAXN = 200200;
const int MAXK = 30;
const int MAXMEM = MAXN * MAXK;
mt19937 rng(07062006);
struct node {
node *chi[2] {nullptr};
int sz = 0, id = -1;
};
int n, k;
int arr[MAXN];
node *mem = new node[MAXMEM];
node *roo... |
1851 | G | Vlad and the Mountains | Vlad decided to go on a trip to the mountains. He plans to move between $n$ mountains, some of which are connected by roads. The $i$-th mountain has a height of $h_i$.
If there is a road between mountains $i$ and $j$, Vlad can move from mountain $i$ to mountain $j$ by spending $h_j - h_i$ units of energy. If his energ... | Let's consider the change in energy when traveling from $i \rightarrow j \rightarrow k$, $h_i - h_j + h_j - h_k = h_i - h_k$, it can be seen that this is the difference between the heights of the first and last mountains on the path. In other words, from vertex $a$, it is possible to reach any vertex for which there is... | [
"binary search",
"data structures",
"dsu",
"graphs",
"implementation",
"sortings",
"trees",
"two pointers"
] | 2,000 | #include <bits/stdc++.h>
#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;
struct dsu{
vector<int> p, lvl;
dsu(int n){
p.resize(n);
lvl.assign(n, 0);
iota(all(p),... |
1852 | A | Ntarsis' Set | Ntarsis has been given a set $S$, initially containing integers $1, 2, 3, \ldots, 10^{1000}$ in sorted order. Every day, he will remove the $a_1$-th, $a_2$-th, $\ldots$, $a_n$-th smallest numbers in $S$ \textbf{simultaneously}.
What is the smallest element in $S$ after $k$ days? | Suppose that the numbers are arranged in a line in increasing order. Take a look at each number $x$ before some day. If it isn't deleted on that day, what new position does it occupy, and how is that impacted by its previous position? If $x$ is between $a_i$ and $a_{i+1}$, it will move to a new position of $x-i$, since... | [
"binary search",
"math",
"number theory"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int inf = 1e9+10;
const ll inf_ll = 1e18+10;
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define cmax(x, y) (x = max(x, y))
#define cmin(x, y) (x = min(x, y))
#ifndef LOCAL
#define debug(...) 0
#else
#include "../../debug.cpp"
#e... |
1852 | B | Imbalanced Arrays | Ntarsis has come up with an array $a$ of $n$ non-negative integers.
Call an array $b$ of $n$ integers imbalanced if it satisfies the following:
- $-n\le b_i\le n$, $b_i \ne 0$,
- there are no two indices $(i, j)$ ($1 \le i, j \le n$) such that $b_i + b_j = 0$,
- for each $1 \leq i \leq n$, there are \textbf{exactly} ... | You can solve the problem by picking one number from each pair $(n, -n)$, $(n - 1, -n + 1) \dots$, $(1, -1)$. $b_i > b_j$ implies $a_i > a_j$. First, try to determine one index in $O(n)$, or determine if that's impossible. Sort the array $a$ to optimize the $O(n^2)$ solution. At the start, let $x$ be an index such that... | [
"constructive algorithms",
"graphs",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
int n, ans[100010];
vector<pair<int,int>> arr;
void solve() {
cin >> n;
arr.resize(n);
for (int i = 0; i < n; i++) {
cin >> arr[i].first;
arr[i].second = i;
}
sort(arr.begin(), arr.end());
int l = 0, r = n - 1, sz = n;
while (l ... |
1852 | C | Ina of the Mountain | To prepare her "Takodachi" dumbo octopuses for world domination, Ninomae Ina'nis, a.k.a. Ina of the Mountain, orders Hoshimachi Suisei to throw boulders at them. Ina asks you, Kiryu Coco, to help choose where the boulders are thrown.
There are $n$ octopuses on a single-file trail on Ina's mountain, numbered $1, 2, \ld... | Suppose you knew in advance how many times each octopus will regenerate. Could you solve the problem then? To make things easier, replace health values of $k$ with health values of $0$, so the goal is to reach $0$ health. Regeneration is now from $0$, which was formerly $k$, to $k-1$, instead of $1$ to $k$, which is no... | [
"data structures",
"dp",
"greedy",
"math"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
int n, k;
cin >> n >> k;
priority_queue<int, vector<int>, greater<int>> differences;
int previous = 0;
ll ans = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
x %= k;
if (x > previous) {
differences.push(x - previous... |
1852 | D | Miriany and Matchstick | Miriany's matchstick is a $2 \times n$ grid that needs to be filled with characters A or B.
He has already filled in the first row of the grid and would like you to fill in the second row. You must do so in a way such that the number of adjacent pairs of cells with different characters$^\dagger$ is equal to $k$. If it... | Solve the samples for all values of $k$. What does constructing a second row from left to right look like? How does knowing the possible $k$ for any first row help you construct a second row? Apply dynamic programming to calculate the possible $k$, and use the information in the DP to construct a solution. Call the num... | [
"constructive algorithms",
"dp",
"greedy"
] | 2,800 | #include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
struct state {
// represents a set of integers compressed as a vector
// of non-overlapping intervals [l, r]
basic_string<array<int, 2>> a;
// add d to everything in the set
friend state add(state x, int d) {
... |
1852 | E | Rivalries | Ntarsis has an array $a$ of length $n$.
The power of a subarray $a_l \dots a_r$ ($1 \leq l \leq r \leq n$) is defined as:
- The largest value $x$ such that $a_l \dots a_r$ contains $x$ and neither $a_1 \dots a_{l-1}$ nor $a_{r+1} \dots a_n$ contains $x$.
- If no such $x$ exists, the power is $0$.
Call an array $b$ a... | For each distinct value, only the leftmost and rightmost positions actually have an effect on the power. Think of each distinct value as an interval corresponding to its leftmost and rightmost positions, and let that distinct value be the value of its interval. If interval $x$ strictly contains an interval $y$ with gre... | [
"constructive algorithms",
"data structures",
"greedy"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9 + 1;
void setIO() {
ios_base::sync_with_stdio(0); cin.tie(0);
}
pii seg[400005];
int n;
void build(int l = 0, in... |
1852 | F | Panda Meetups | The red pandas are in town to meet their relatives, the blue pandas! The town is modeled by a number line.
The pandas have already planned their meetup, but the schedule keeps changing. You are given $q$ updates of the form x t c.
- If $c < 0$, it means $|c|$ more \textbf{red} pandas enter the number line at position... | If we want to answer one of the questions (say, the question involving all the events) in polynomial time, how do we do it? Construct a network with edges from the source to each of the red panda events with capacities equal to the number of red pandas, edges from red panda events to blue panda events with innite capac... | [
"data structures",
"dp",
"flows"
] | 3,500 | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9 + 1;
void setIO() {
ios_base::sync_with_stdio(0); cin.tie(0);
}
struct node {
//mnpos - leftmost negative
... |
1853 | A | Desorting | Call an array $a$ of length $n$ sorted if $a_1 \leq a_2 \leq \ldots \leq a_{n-1} \leq a_n$.
Ntarsis has an array $a$ of length $n$.
He is allowed to perform one type of operation on it (zero or more times):
- Choose an index $i$ ($1 \leq i \leq n-1$).
- Add $1$ to $a_1, a_2, \ldots, a_i$.
- Subtract $1$ from $a_{i+1... | To make $a$ not sorted, we just need to pick one index $i$ so $a_i > a_{i + 1}$. How do we do this? To make $a$ not sorted, we just have to make $a_i > a_{i + 1}$ for one $i$. In one operation, we can reduce the gap between two adjacent elements $i, i + 1$ by $2$ by adding $1$ to $1 \dots i$ and subtracting $1$ from ${... | [
"brute force",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
#include <numeric>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int T; cin >> T;
while (T--) {
int n; cin >> n;
vector<int> nums(n);
int diff = 1e9;
bool sorted = true;
for (int i = 0; i < n; i++) {
... |
1853 | B | Fibonaccharsis | Ntarsis has received two integers $n$ and $k$ for his birthday. He wonders how many fibonacci-like sequences of length $k$ can be formed with \textbf{$n$ as the $k$-th element} of the sequence.
A sequence of \textbf{non-decreasing non-negative} integers is considered fibonacci-like if $f_i = f_{i-1} + f_{i-2}$ for all... | Can a sequence involving $n$, which is up to $10^5$, really have up to $10^9$ terms? The terms of the fibonacci sequence will increase exponentially. This is quite intuitive, but mathematically, fibonnaci-like sequences will increase at a rate of phi to the power of $n$, where phi (the golden ratio) is about $1.618$. T... | [
"binary search",
"brute force",
"math"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int T; cin >> T;
while (T--) {
int n; int k;
cin >> n >> k;
int ans = 0;
for (int i = 1; i <= n; i++) {
int second = n; //xth element ... |
1854 | A1 | Dual (Easy Version) | \begin{quote}
Popskyy & tiasu - Dual
\hfill ⠀
\end{quote}
\textbf{The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.}
You are given an array $a_1, a_2,\dots, a_n$ of integers (positive, ... | There are several solutions to the easy version. In any case, how to get $a_i \leq a_{i+1}$? For example, you can try making $a_{i+1}$ bigger using a positive element. What to do if all the elements are negative? If all the elements are negative, you can win in $n-1$ moves. If there is a positive element, you can try t... | [
"constructive algorithms",
"math"
] | 1,400 | null |
1854 | A2 | Dual (Hard Version) | \begin{quote}
Popskyy & tiasu - Dual
\hfill ⠀
\end{quote}
\textbf{The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.}
You are given an array $a_1, a_2,\dots, a_n$ of integers (positive, ... | The hints and the solution continue from the easy version. You can win in $n-1$ moves if all the elements are negative, but also if all the elements are positive. Again, make a big positive / negative element, then use it to make everything positive / negative. In how many moves can you either make everything positive ... | [
"constructive algorithms",
"math"
] | 1,900 | null |
1854 | B | Earn or Unlock | Andrea is playing the game Tanto Cuore.
He has a deck of $n$ cards with values $a_1, \ldots, a_n$ from top to bottom. Each card can be either locked or unlocked. Initially, only the topmost card is unlocked.
The game proceeds in turns. In each turn, Andrea chooses an unlocked card in the deck — the value written on t... | The order of used cards doesn't matter. So, you can assume you always use the card on the top. Suppose that you unlock $x$ cards in total. How many points can you get? If you unlock $x$ cards, it means you end up making moves with the first $x$ cards. So, you know the total number of (cards + points) that you get. If y... | [
"bitmasks",
"brute force",
"dp"
] | 2,200 | null |
1854 | C | Expected Destruction | You have a set $S$ of $n$ distinct integers between $1$ and $m$.
Each second you do the following steps:
- Pick an element $x$ in $S$ uniformly at random.
- Remove $x$ from $S$.
- If $x+1 \leq m$ and $x+1$ is not in $S$, add $x+1$ to $S$.
What is the expected number of seconds until $S$ is empty?
Output the answer ... | Consider $n$ blocks in positions $S_1, S_2, \dots, S_n$. After how much time does block $x$ disappear? It may be convenient to put a fake "static" block in position $m+1$. Block $x$ disappears when it reaches block $x+1$. But what if block $x+1$ disappears before block $x$? From the perspective of block $x$, it's conve... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,500 | null |
1854 | D | Michael and Hotel | Michael and Brian are stuck in a hotel with $n$ rooms, numbered from $1$ to $n$, and need to find each other. But this hotel's doors are all locked and the only way of getting around is by using the teleporters in each room. Room $i$ has a teleporter that will take you to room $a_i$ (it might be that $a_i = i$). But th... | You can find any $a_i$ in $9$ queries. Find the nodes in the cycle in the component with node $1$. What happens if you know the whole cycle? Suppose you already know some nodes in the cycle. Can you find other nodes faster? Can you "double" the number of nodes in the cycle? The component with node $1$ contains a cycle.... | [
"binary search",
"interactive",
"trees"
] | 3,000 | null |
1854 | E | Game Bundles | Rishi is developing games in the 2D metaverse and wants to offer game bundles to his customers. Each game has an associated enjoyment value. A game bundle consists of a subset of games whose total enjoyment value adds up to $60$.
Your task is to choose $k$ games, where $1 \leq k \leq 60$, along with their respective e... | Go for a randomized approach. Many ones are useful. Either you go for a greedy or for a backpack. We describe a randomized solution that solves the problem for $m$ up to $10^{11}$ (and, with some additional care, may be able to solve also $m$ up to $10^{12}$). We decided to give the problem with the smaller constraint ... | [
"brute force",
"constructive algorithms",
"dp",
"greedy",
"math"
] | 3,000 | null |
1854 | F | Mark and Spaceship | Mark loves to move fast. So he made a spaceship that works in $4$-dimensional space.
He wants to use the spaceship to complete missions as fast as possible. In each mission, the spaceship starts at $(0, 0, 0, 0)$ and needs to end up at $(a, b, c, d)$. To do this, he instructs the spaceship's computer to execute a seri... | Solve the 2d version first. The 4d version is not too different from the 2d one. Find all the points such that the expected number of necessary moves is wrong. Let us begin by cpnsidering the $2$-dimensional version of the problem. The solution to this simpler version provides the idea of the approach for the $4$-dimen... | [
"brute force",
"dp"
] | 3,500 | null |
1855 | A | Dalton the Teacher | Dalton is the teacher of a class with $n$ students, numbered from $1$ to $n$. The classroom contains $n$ chairs, also numbered from $1$ to $n$. Initially student $i$ is seated on chair $p_i$. It is guaranteed that $p_1,p_2,\dots, p_n$ is a permutation of length $n$.
A student is happy if his/her number is different fr... | What's the most efficient way to make the sad students happy? In most cases, you can make $2$ sad students happy in $1$ move. Let $s$ be the number of sad students at the beginning. The answer is $\lceil \frac{s}{2} \rceil$. In one move, you can make at most $2$ sad students happy (because you can change the position o... | [
"greedy",
"math"
] | 800 | null |
1855 | B | Longest Divisors Interval | Given a positive integer $n$, find the maximum size of an interval $[l, r]$ of positive integers such that, for every $i$ in the interval (i.e., $l \leq i \leq r$), $n$ is a multiple of $i$.
Given two integers $l\le r$, the size of the interval $[l, r]$ is $r-l+1$ (i.e., it coincides with the number of integers belong... | What's the answer if $n$ is odd? Try to generalize Hint 1. What's the answer if $n$ is not a multiple of $3$? If the answer is not a multiple of $x$, the answer is $< x$. If the answer is a multiple of $1, \dots, x$, the answer is $\geq x$. Suppose you find a valid interval $[l, r]$. Note that the interval $[l, r]$ con... | [
"brute force",
"combinatorics",
"greedy",
"math",
"number theory"
] | 900 | null |
1856 | A | Tales of a Sort | Alphen has an array of positive integers $a$ of length $n$.
Alphen can perform the following operation:
- For \textbf{all} $i$ from $1$ to $n$, replace $a_i$ with $\max(0, a_i - 1)$.
Alphen will perform the above operation until $a$ is sorted, that is $a$ satisfies $a_1 \leq a_2 \leq \ldots \leq a_n$. How many opera... | Suppose we have performed $k$ operations and have gotten the array $b$. Then $b_i := \max(0, a_i - k)$ for all $i$ from $1$ to $n$. If $b$ is sorted, then $b_i \le b_{i + 1}$ for all $i$ from $1$ to $n - 1$. In other words, $\max(0, a_i - k) \le \max(0, a_{i + 1} - k)$. Let's find for which $k$ this inequality holds. S... | [
"implementation"
] | 800 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i... |
1856 | B | Good Arrays | You are given an array of \textbf{positive} integers $a$ of length $n$.
Let's call an array of \textbf{positive} integers $b$ of length $n$ good if:
- $a_i \neq b_i$ for \textbf{all} $i$ from $1$ to $n$,
- $a_1 + a_2 +\ldots + a_n = b_1 + b_2 + \ldots + b_n$.
Does a good array exist? | Suppose $b$ didn't have to consist of only positive integers. Then, one simple strategy would be to to decrease each of $a_2, a_3, \ldots a_n$ by $1$ and increase $a_1$ by $n - 1$. Except for $n = 1$, when it is impossible to get a good array. When $b$ has to consist of only positive integers, we can't decrease element... | [
"implementation",
"math"
] | 900 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i... |
1856 | C | To Become Max | You are given an array of integers $a$ of length $n$.
In one operation you:
- Choose an index $i$ such that $1 \le i \le n - 1$ and $a_i \le a_{i + 1}$.
- Increase $a_i$ by $1$.
Find the maximum possible value of $\max(a_1, a_2, \ldots a_n)$ that you can get after performing this operation at most $k$ times. | We will do binary search on the answer. The lower bound can be set to $0$, while $\max(a_1, \ldots a_n) + k$ is clearly enough for the upper bound. Let $b$ be some resulting array after performing at most $k$ operations. Suppose for some $x$ we want to check if we can get $\max(b_1, \ldots b_n) \ge x$ in at most $k$ op... | [
"binary search",
"brute force",
"data structures",
"dp"
] | 1,600 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
ll n, k;
cin >> n >> k;
vector<ll> a(n);
for (in... |
1856 | D | More Wrong | \textbf{This is an interactive problem.}
The jury has hidden a permutation$^\dagger$ $p$ of length $n$.
In one query, you can pick two integers $l$ and $r$ ($1 \le l < r \le n$) by paying $(r - l)^2$ coins. In return, you will be given the number of inversions$^\ddagger$ in the subarray $[p_l, p_{l + 1}, \ldots p_r]$... | Let $q(l, r)$ be be the number of inversions in the subarray $[p_l, p_{l + 1}, \ldots p_r]$. If $l = r$, we have $q(l, r) = 0$, otherwise, $q(l, r) =$ is equal to the result of the query "? l r". Let $f(l, r)$ calculate the index of the maximum value in $p_l, p_{l+1}, \ldots, p_r$. If $l = r$, we have $f(l, r) = l$. Su... | [
"divide and conquer",
"interactive"
] | 2,100 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
int query(int l, int r) {
if (l == r) return 0;
cout << "? " << l << ' ' << r <<... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.