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
1400
G
Mercenaries
Polycarp plays a (yet another!) strategic computer game. In this game, he leads an army of mercenaries. Polycarp wants to gather his army for a quest. There are $n$ mercenaries for hire, and the army should consist of some subset of them. The $i$-th mercenary can be chosen if the \textbf{resulting} number of chosen m...
We will use inclusion-exclusion formula to solve this problem (you may read about it here: https://cp-algorithms.com/combinatorics/inclusion-exclusion.html). To put it simply, we are going to count the number of subsets that meet the restrictions on $[l_i, r_i]$, ignoring the edges (I'll call the pairs of mercenaries t...
[ "bitmasks", "brute force", "combinatorics", "dp", "dsu", "math", "two pointers" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 300043; const int MOD = 998244353; int add(int x, int y) { return ((x + y) % MOD + MOD) % MOD; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y > 0) { if(y % 2 == 1) ...
1401
A
Distance and Axis
We have a point $A$ with coordinate $x = n$ on $OX$-axis. We'd like to find an integer point $B$ (also on $OX$-axis), such that the absolute difference between the distance from $O$ to $B$ and the distance from $A$ to $B$ is equal to $k$. \begin{center} {\small The description of the first test case.} \end{center} Si...
If $n$ is less than $k$, we have to move $A$ to coordinate $k$, and set the coordinate of $B$ as $0$ or $k$. So the answer is $k - n$. If $n$ is not less than $k$, let's define the coordinate of $B$ as $m$($m \times 2 \le n$). By the condition in the problem, the difference between ($m - 0$) and ($n - m$) should be equ...
[ "constructive algorithms", "math" ]
900
#include<bits/stdc++.h> #define endl '\n' using namespace std; main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int k, n, t; cin >> t; for(;t--;) { cin >> n >> k; if(n < k) cout << k - n << endl; else if(n % 2 == k % 2) co...
1401
B
Ternary Sequence
You are given two sequences $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$. Each element of both sequences is either $0$, $1$ or $2$. The number of elements $0$, $1$, $2$ in the sequence $a$ is $x_1$, $y_1$, $z_1$ respectively, and the number of elements $0$, $1$, $2$ in the sequence $b$ is $x_2$, $y_2$, $z_2$ respe...
We can find the kind of the value of $c_i$ is three $\left(-2, 0, 2\right)$. And $c_i$ is $-2$ only if $a_i$ is $1$ and $b_i$ is $2$, and $c_i$ is $2$ only if $a_i$ is $2$ and $b_i$ is $1$. Otherwise $c_i$ is $0$. So we have to make ($a_i, b_i$) pair ($1, 2$) as little as possible, and pair ($2, 1$) as much as possible...
[ "constructive algorithms", "greedy", "math" ]
1,100
#include<bits/stdc++.h> #define endl '\n' using namespace std; main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(;t--;) { int m, sum = 0, x0, x1, x2, y0, y1, y2; cin >> x0 >> x1 >> x2 >> y0 >> y1 >> y2; m = min(x0, y2); x0 -= m; y2 -= m; m = m...
1401
C
Mere Array
You are given an array $a_1, a_2, \dots, a_n$ where all $a_i$ are integers and greater than $0$. In one operation, you can choose two different indices $i$ and $j$ ($1 \le i, j \le n$). If $gcd(a_i, a_j)$ is equal to the minimum element of the \textbf{whole array} $a$, you can swap $a_i$ and $a_j$. $gcd(x, y)$ denotes...
Let's define the minimum element of $a$ as $m$. We can find the position of the elements which is not divisible by $m$ cannot be changed because these elements don't have $m$ as factor. But we can rearrange elements divisible by $m$ whatever we want in the following way: $\bullet$ Let's suppose $m$ = $a_x$, and there i...
[ "constructive algorithms", "math", "number theory", "sortings" ]
1,300
#import<bits/stdc++.h> #define endl '\n' using namespace std; int a[100005], b[100005]; main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(;t--;) { int k = 0, m = 1000000000, n; cin >> n; for(int i = 0; i < n; i++) { cin >> a[i]; b...
1401
D
Maximum Distributed Tree
You are given a tree that consists of $n$ nodes. You should label each of its $n-1$ edges with an integer in such way that satisfies the following conditions: - each integer must be greater than $0$; - the product of all $n-1$ numbers should be equal to $k$; - the number of $1$-s among all $n-1$ integers must be minim...
Let's define $w_i$ as the product of the number of vertices belonging to each of the two components divided when the $i_{th}$ edge is removed from the tree, and $z_i$ as the number on $i_{th}$ edge. Now a distribution index is equal to $\sum_{i=1}^{n-1}(w_i \times z_i)$. Now there are two cases: $A$ : $m \le n-1$ In th...
[ "dfs and similar", "dp", "greedy", "implementation", "math", "number theory", "sortings", "trees" ]
1,800
#include<bits/stdc++.h> #define endl '\n' using namespace std; typedef long long LL; struct H{int x, y;}; int ii, n; const int q = 1e9 + 7; LL p[100005], pv[100005], vi[100005], w[100005]; H e[200040]; int C(H a, H b){return a.x < b.x;} int G(LL a, LL b){return a > b;} LL dfs(int v) { LL d = 1; vi[v] = ...
1401
E
Divide Square
There is a square of size $10^6 \times 10^6$ on the coordinate plane with four points $(0, 0)$, $(0, 10^6)$, $(10^6, 0)$, and $(10^6, 10^6)$ as its vertices. You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square. Now you are wond...
Under given condition, there are only two cases in which the number of pieces increases. $\bullet$ When a segment intersects with two sides (facing each other) of the square, the number of pieces increases by one. $\bullet$ When two segment intersects in the square (not including sides), the number of pieces increases ...
[ "data structures", "geometry", "implementation", "sortings" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long LL; struct H{int k, l, r;}; const int p = 1048576; LL l[2100000], r[2100000], z[2100000]; H h[100005], v[200040]; int C(H a, H b){return a.k < b.k;} int D(H a, H b){return a.l < b.l || a.l == b.l && a.r > b.r;} LL sum(int x, int y, int d) // find th...
1401
F
Reverse and Swap
You are given an array $a$ of length $2^n$. You should process $q$ queries on it. Each query has one of the following $4$ types: - $Replace(x, k)$ — change $a_x$ to $k$; - $Reverse(k)$ — reverse each subarray $[(i-1) \cdot 2^k+1, i \cdot 2^k]$ for all $i$ ($i \ge 1$); - $Swap(k)$ — swap subarrays $[(2i-2) \cdot 2^k+1,...
Let's consider the sequence as $0$-based. Then we can find the following two facts: $\bullet$ If we do $Reverse(k)$ operation once, $a_i$ becomes $a_{i\text{^}(2^k-1)}$. $\bullet$ If we do $Swap(k)$ operation once, $a_i$ becomes $a_{i\text{^}(2^k)}.$ So in any state there is an integer $x$ that makes the current $a_i$ ...
[ "binary search", "bitmasks", "data structures" ]
2,400
#include<bits/stdc++.h> #define endl '\n' using namespace std; typedef long long LL; LL p, a[528000], ll[528000], rr[528000]; LL SUM(LL l, LL r, LL d) { LL x, y, z; x = ll[d]; y = rr[d]; z = b & ~(y - x); x ^= z; y ^= z; if(x > r || y < l) return 0; else if(x < l || y > r) ret...
1402
A
Fancy Fence
Everybody knows that Balázs has the fanciest fence in the whole town. It's built up from $N$ fancy sections. The sections are rectangles standing closely next to each other on the ground. The $i$th section has integer height $h_i$ and integer width $w_i$. We are looking for fancy rectangles on this fancy fence. A recta...
Subtask 2 $N, h_i \leq 50, w_i = 1$ There are at most $50^4$ different rectangles. For all of them, we can check if they are fancy or not. This can be done in constant time with some precomputation. Subtask 3 $h_i = 1$ or $h_i = 2$ for all $i$. Consider a rectangle with height $1$ and width $K$. Lemma: There are $\bino...
[ "*special", "data structures", "dsu", "implementation", "math", "sortings" ]
1,800
null
1402
B
Roads
The government of Treeland wants to build a new road network. There are $2N$ cities in Treeland. The unfinished plan of the road network already contains $N$ road segments, each of which connects two cities with a straight line. No two road segments have a common point (including their endpoints). Your task is to deter...
We assume that for segment $s=(p,q)$ the relation $p.x<q.x$ or $p.x=q.x$ and $p.y<q.y$ holds, therefore we can say that $p$ is the left endpoint of the segment. Consider the sequence of segment endpoints ordered by their x-coordinates. We apply the sweep-line method, the event points of the sweeping are the x-coordinat...
[ "*special", "geometry", "sortings" ]
2,900
null
1402
C
Star Trek
The United Federation of Planets is an alliance of $N$ planets, they are indexed from $1$ to $N$. Some planets are connected by space tunnels. In a space tunnel, a starship can fly both ways really fast. There are exactly $N-1$ space tunnels, and we can travel from any planet to any other planet in the Federation using...
Subtask 2 $N = 2$ The Captain always wins. A possible winning strategy: she uses only tunnels. In this way, Gábor is forced to use only portals. After using a portal they will be in a new universe where the Captain can use the tunnel. So Captain can always move after Gábor, but there is a point where Gábor can't move. ...
[ "*special", "combinatorics", "dfs and similar", "dp", "games", "graphs", "matrices", "trees" ]
2,600
null
1403
A
The Potion of Great Power
Once upon a time, in the Land of the Shamans, everyone lived on the Sky-High Beanstalk. Each shaman had a unique identifying number $i$ between $0$ and $N-1$, and an altitude value $H_i$, representing how high he lived above ground level. The distance between two altitudes is the absolute value of their difference. Al...
We denote the maximum number of edges in the graph by $M$. You can see that $U$ is an upper bound for it. Subtask 2 $Q, U \leq 1000$ We can store each operation, and replay them for each question. We can store all edges in a data structure, or keep neighbours in separate data structures for each node. When answering a ...
[ "*special", "2-sat", "binary search", "data structures", "graphs", "interactive", "sortings", "two pointers" ]
2,400
p1 = 0, p2 = 0 while (p1 < l1.length) and (p2 < l2.length) consider(H[l1[p1]], H[l2[p2]]) if (H[l1[p1]] <= H[l2[p2]]) then p1++ else p2++
1403
B
Spring cleaning
Spring cleanings are probably the most boring parts of our lives, except this year, when Flóra and her mother found a dusty old tree graph under the carpet. This tree has $N$ nodes (numbered from $1$ to $N$), connected by $N-1$ edges. The edges gathered too much dust, so Flóra's mom decided to clean them. Cleaning th...
Cleanable tree It is obvious that a tree is not cleanable if it has an odd number of leaves. Also, every tree with an even number of leaves is cleanable. Subtask 2 $Q = 1$, there is an edge between node $1$ and $i$ for every $i$ $(2 \leq i \leq N)$ Flóra can't add extra leaf to node $1$ If we add 2 extra leaves to an i...
[ "*special", "data structures", "dfs and similar", "graphs", "trees" ]
2,300
null
1403
C
Chess Rush
The mythic world of Chess Land is a rectangular grid of squares with $R$ rows and $C$ columns, $R$ being greater than or equal to $C$. Its rows and columns are numbered from $1$ to $R$ and $1$ to $C$, respectively. The inhabitants of Chess Land are usually mentioned as \underline{pieces} in everyday language, and ther...
Pawns, Rooks and Queens If $c_1=c_R$ then there is a unique shortest path, which takes $1$ step for the rook and the queen, and $R-1$ steps for the pawn. Otherwise, it is impossible getting to the exit square for the pawn, and it takes exactly $2$ steps for both the queen and the rook. It is also obvious that the latte...
[ "*special", "combinatorics", "dp", "implementation", "math" ]
3,200
null
1404
A
Balanced Bitstring
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $k$-\textbf{balanced} if every substring of size $k$ of this bitstring has an equal amount of 0 and 1 characters ($\frac{k}{2}$ of each). You are given an integer $k$ and a string $s$ which is composed only of characters 0, 1, and...
Let's denote the balanced bitstring (if any) deriving from $s$ to be $t$. Also, for the ease of the tutorial, let the strings be $0$-indexed (so the first character has index $0$ and the last character has index $n - 1$). First of all, let's prove a very important observation: for every $i$ such that $0 \leq i < n - k$...
[ "implementation", "strings" ]
1,500
#include <bits/stdc++.h> using namespace std; int n, k, t; string s; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> t; while (t--) { cin >> n >> k >> s; int zer = 0, one = 0; bool chk = true; for (int i = 0; i < k; i++) { int tmp =...
1404
B
Tree Tag
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of $n$ vertices numbered from $1$ to $n$. Recall that a tree on $n$ vertices is an undirected, connected graph with $n-1$ edges. Initially, Alice is located at vertex $a$, and Bob at vertex $b$. They take turns alternately, and Alice makes...
Let's consider several cases independently. Case 1: $\mathrm{dist}(a, b)\le da$ Unsurprisingly, Alice wins in this case by tagging Bob on the first move. Case 2: $2da\ge \mathrm{tree\ diameter}$ Here, the diameter of a tree is defined as the length of the longest simple path. In this case, Alice can move to a center of...
[ "dfs and similar", "dp", "games", "trees" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, a, b, da, db, depth[N]; vector<int> adj[N]; int diam = 0; int dfs(int x, int p) { int len = 0; for(int y : adj[x]) { if(y != p) { depth[y] = depth[x] + 1; int cur = 1 + dfs(y, x); diam =...
1404
C
Fixed Point Removal
Let $a_1, \ldots, a_n$ be an array of $n$ positive integers. In one operation, you can choose an index $i$ such that $a_i = i$, and remove $a_i$ from the array (after the removal, the remaining parts are concatenated). The weight of $a$ is defined as the maximum number of elements you can remove. You must answer $q$ ...
Convenient transformation Replace $a_i$ by $i - a_i$. The new operation becomes: remove a zero, and decrement all elements after by one. For each query, note $l = 1+x$ and $r = n-y$ the endpoints of the non-protected subarray. The main idea of the solution is iterating over $r$, maintaining answers for each $l$ in a BI...
[ "binary search", "constructive algorithms", "data structures", "greedy", "two pointers" ]
2,300
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(0); int n, q; cin >> n >> q; vector<int> a(n+1), ans(q), leftBound(q); vector<vector<int>> endHere(n+1); for (int i = 1; i <= n; ++i) { cin >> a[i]; a[i] = i - a[i]; } for (int i = 0; i < q; ++i) { int x, ...
1404
D
Game of Pairs
\textbf{This is an interactive problem.} Consider a fixed positive integer $n$. Two players, First and Second play a game as follows: - First considers the $2n$ numbers $1, 2, \dots, 2n$, and partitions them as he wants into $n$ disjoint pairs. - Then, Second chooses exactly one element from each of the pairs that Fi...
We split the problem into two cases: $n$ is even We claim that First can guarantee a win by forming the pairs $(1, n + 1), \dots, (n, 2n)$. Note that no matter which elements Second chooses, he will always take one element having each remainder modulo $n$. Thus the total sum is $0 + 1 + 2 + \dots + n - 1 \equiv \frac{n...
[ "constructive algorithms", "dfs and similar", "interactive", "math", "number theory" ]
2,800
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e6 + 10; vector<int> adj[MAXN]; int vi[MAXN], pv[MAXN]; vector<int> choices[2]; void dfs(int s, int x) { vi[s] = 1; choices[x].push_back(s); for(auto v : adj[s]) if(!vi[v]) dfs(v, x ^ 1); } int main() { ios_base::s...
1404
E
Bricks
A brick is defined as a rectangle with integer side lengths with either width $1$ or height $1$ (or both). There is an $n\times m$ grid, and each cell is colored either black or white. A tiling is a way to place bricks onto the grid such that each black cell is covered by exactly one brick, and each white cell is not ...
Instead of placing a minimum number of bricks into the cells, let's imagine that we start out with all $1\times 1$ bricks and delete the maximum number of borders. Of course, we need to make sure that when we delete borders, all the regions are in fact bricks. A region is a brick if and only if it contains no "L" shape...
[ "flows", "graph matchings", "graphs" ]
2,800
#include <bits/stdc++.h> using namespace std; #define SOURCE 0 #define HORZ(i, j) (m * (i) + (j) + 1) #define VERT(i, j) ((n - 1) * m + n * (j) + (i) + 1) #define SINK ((n - 1) * m + n * (m - 1) + 1) const int N = 305, V = 2e5 + 5; struct edge { int u, v, cap, flow; }; struct Dinic { vector<edge> e; ...
1405
A
Permutation Forgery
A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). Let $p$ be any ...
Let $p'=\mathrm{reverse}(p).$ Then $p'$ is a permutation, since every value from $1$ to $n$ appears exactly once. $p'\ne p$ since $p'_1=p_n\ne p_1$. (Here, we use $n\ge 2$.) $F(p')=F(p)$ since any two adjacent values in $p$ remain adjacent in $p'$.
[ "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int te; cin >> te; while(te--) { int n; cin >> n; vector<int> a(n); for(int &x : a) cin >> x; reverse(a.begin(), a.end()); for(int x : a) cout << x ...
1405
B
Array Cancellation
You're given an array $a$ of $n$ integers, such that $a_1 + a_2 + \cdots + a_n = 0$. In one operation, you can choose two \textbf{different} indices $i$ and $j$ ($1 \le i, j \le n$), decrement $a_i$ by one and increment $a_j$ by one. If $i < j$ this operation is free, otherwise it costs one coin. How many coins do yo...
The answer is the maximum suffix sum, which can be computed in $\mathcal{O}(n)$. Formal proof. Define $c_i = a_i + a_{i+1} + \cdots + a_n$ (partial suffix sum). Note $M = \max(c)$. We can observe that $a_1 = \cdots = a_n = 0$ if and only if $c_1 = \cdots = c_n = 0$. (If $c$ is null, $a_i = c_i - c_{i+1} = 0 - 0 = 0$.) ...
[ "constructive algorithms", "implementation" ]
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; cin >> n; long long cur = 0; for (int i = 0; i < n; ++i) { long long x; cin >> x; cur = max(0LL, cur + x); } cout << cur << "\n"; } }
1406
A
Subset Mex
Given a set of integers (it can contain equal elements). You have to split it into two subsets $A$ and $B$ (both of them can contain equal elements or be empty). You have to maximize the value of $mex(A)+mex(B)$. Here $mex$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:...
Let us store the count of each number from $0$ to $100$ in array $cnt$. Now $mex(A)$ would be the smallest $i$ for which $cnt_i=0$.Let this $i$ be $x$. $mex(B)$ would be smallest $i$ for which $cnt_i\leq 1$. This is because one count of each number less than $x$ would go to $A$ therefore the element which was present i...
[ "greedy", "implementation", "math" ]
900
#include<bits/stdc++.h> #define re register using namespace std; inline int read(){ re int t=0;re char v=getchar(); while(v<'0')v=getchar(); while(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar(); return t; } int n,a[102],vis[2][102],ansa,ansb; int main(){ re int t=read(); while(t--){ n=read(); for(re int i=1;i<=n;++i)a...
1406
B
Maximum Product
You are given an array of integers $a_1,a_2,\ldots,a_n$. Find the maximum possible value of $a_ia_ja_ka_la_t$ among all five indices $(i, j, k, l, t)$ ($i<j<k<l<t$).
First, if all numbers are less than $0$, then you should print the product of the five biggest numbers of them. Otherwise, the maximum product must be non-negative. Sort the numbers by their absolute value from big to small. If the first five numbers' product is positive then print it. Then we can always change one of ...
[ "brute force", "dp", "greedy", "implementation", "sortings" ]
1,200
#include<bits/stdc++.h> using namespace std; long long ans,a[100005]; int main() { int t; scanf("%d",&t); while(t--){ int n; long long mx=-1e9; scanf("%d",&n); for(int i=1;i<=n;i++)scanf("%lld",&a[i]),mx=max(mx,a[i]); sort(a+1,a+n+1,[](long long x,long long y){return abs(x)>abs(y);}); if(mx<0){ cou...
1406
C
Link Cut Centroids
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a \textbf{centroid} of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph i...
Let vertex $1$ be the root of the tree. If there is only one centroid, just cut any edge and link it back. Otherwise there are two centroids. Let them be $x$ and $y$, then there must be an edge connecting $x$ and $y$. (If not, choose any other vertex on the path from $x$ to $y$ and the size of the largest connected com...
[ "constructive algorithms", "dfs and similar", "graphs", "trees" ]
1,700
#include<iostream> #include<cstdio> #include<algorithm> #include<vector> using namespace std; int n,size[100005],fa[100005],minn=1e9,cent1,cent2; vector<int> g[100005]; void dfs(int x,int f){ fa[x]=f,size[x]=1; int mx=0; for(int y:g[x]){ if(y==f)continue; dfs(y,x); size[x]+=size[y]; mx=max(mx,size[y]); } m...
1406
D
Three Sequences
You are given a sequence of $n$ integers $a_1, a_2, \ldots, a_n$. You have to construct two sequences of integers $b$ and $c$ with length $n$ that satisfy: - for every $i$ ($1\leq i\leq n$) $b_i+c_i=a_i$ - $b$ is non-decreasing, which means that for every $1<i\leq n$, $b_i\geq b_{i-1}$ must hold - $c$ is non-increasi...
Since sequence $b$ is non-decreasing and sequence $c$ is non-increasing, we need to mimimize $\max(c_1,b_n)$. Now observe that if $a_i>a_{i-1}$ then $b_i=b_{i-1}+a_i-a_{i-1}$ and $c_i=c_{i-1}$.Else if $a_i<a_{i-1}$ then $b_i=b_{i-1}$ but $c_i=c_{i-1}+a_i-a_{i-1}$. Now we calculate $\sum\limits_{i=2}^{n}\max(0,a_i-a_{i-...
[ "constructive algorithms", "data structures", "greedy", "math" ]
2,200
#include<cstdio> #include<cmath> #define re register #define int long long using namespace std; inline int read(){ re int t=0,f=0;re char v=getchar(); while(v<'0')f|=(v=='-'),v=getchar(); while(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar(); return f?-t:t; } int n,a[100002],sumg,suml,a1,A,B,C,q; inline int check(){ retur...
1406
E
Deleting Numbers
\textbf{This is an interactive problem.} There is an unknown integer $x$ ($1\le x\le n$). You want to find $x$. At first, you have a set of integers $\{1, 2, \ldots, n\}$. You can perform the following operations no more than $10000$ times: - A $a$: find how many numbers are multiples of $a$ in the current set. - B ...
If we know what prime factors x has, we can find $x$ just using bruteforce. To find the prime factors, we can just do $B~p$ for every prime $p$ in ascending order, meanwhile calculate the numbers there supposed to be without $x$, if it differs with the number the interactor gives, then $x$ contains the prime factor $p$...
[ "interactive", "math", "number theory" ]
2,600
#include<bits/stdc++.h> #define re register #define int long long using namespace std; bool vis[100002]; int pri[100002],tot,n,x,sum,ans,ia; signed main(){ srand(19260817); scanf("%lld",&n); for(re int i=2; i<=n; ++i) { if(!vis[i]) { pri[++tot]=i; if(i<=sqrt(n)) for(re int j=i*i; j<=n; j+=i)vis[j]=1; ...
1407
A
Ahahahahahahahaha
Alexandra has an even-length array $a$, consisting of $0$s and $1$s. The elements of the array are enumerated from $1$ to $n$. She wants to remove \textbf{at most} $\frac{n}{2}$ elements (where $n$ — length of array) in the way that alternating sum of the array will be equal $0$ (i.e. $a_1 - a_2 + a_3 - a_4 + \dotsc = ...
Let $cnt_0$ be the count of zeroes in the array, $cnt_1$ - count of ones. Then if $cnt_1 \leq \frac{n}{2}$, we remove all ones and alternating sum, obliously, equals $0$. Otherwise, $cnt_0 < \frac{n}{2}$, we remove all zeroes and if $cnt_1$ is odd - plus another $1$. In this case, alternating sum equals $1 - 1 + 1 - \l...
[ "constructive algorithms", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int>a(n), ans; int cnt0 = 0; for (int i = 0; i < n; i++) { cin >> a[i]; if (!a[i]) cnt0++; } int cnt1 = n - cnt0;...
1407
B
Big Vova
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro...
We'll describe several constructive solutions for this task, differing by the time complexity: 1. $O(n^2log A)$ Let $b$ be an empty sequence in the beginning. We'll consequently transfer elements from $a$ to $b$ in a certain order. Let's notice that if we've already transfered $(k-1)$ elements then we can always choose...
[ "brute force", "greedy", "math", "number theory" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int a[n]; int mi = 0; for (int i = 0; i < n; i++) { cin >> a[i]; mi = (a[i] > a[mi] ? i : mi); } vector<int> b(n); b[0] = a[mi]; a[mi] = 0; int cg = b[0]; for (int i = 1; i < n; i++) {...
1407
C
Chocolate Bunny
\textbf{This is an interactive problem.} We hid from you a permutation $p$ of length $n$, consisting of the elements from $1$ to $n$. You want to guess it. To do that, you can give us 2 different indices $i$ and $j$, and we will reply with $p_{i} \bmod p_{j}$ (remainder of division $p_{i}$ by $p_{j}$). We have enough...
Observation: $(a \bmod b > b \bmod a) \Leftrightarrow (a < b)$. Proof: if $a > b$, then $(a \bmod b) < b = (b \bmod a$). If $a = b$, then $(a \bmod b) = (b \bmod a) = 0$. Let's maintain index $mx$ of maximal number on the reviewed prefix (initially $mx = 1$). Let's consider index $i$. Ask two queries: ? i mx and ? mx i...
[ "constructive algorithms", "interactive", "math", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; int ask(int x, int y) { cout << "? " << x + 1 << ' ' << y + 1 << endl; int z; cin >> z; return z; } int main() { int n; cin >> n; vector<int>ans(n, -1); int mx = 0; for (int i = 1; i < n; i++) { int a = ask(mx, i); int b =...
1407
D
Discrete Centrifugal Jumps
There are $n$ beautiful skyscrapers in New York, the height of the $i$-th one is $h_i$. Today some villains have set on fire first $n - 1$ of them, and now the only safety building is $n$-th skyscraper. Let's call a jump from $i$-th skyscraper to $j$-th ($i < j$) \textbf{discrete}, if all skyscrapers between are stric...
Consider such a jump, when all of the skyscrapers between are smaller than initial and final (another case is similar). Let's stand on the skyscraper with index $x$. We want to find out whether $y$-th skyscraper satisfies our conditions. We have two cases: $h_x \leq h_y$. Then, obviously, $y$ is the first skyscraper th...
[ "data structures", "dp", "graphs" ]
2,200
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 1; const int maxn = 3e5 + 1; int h[maxn], dp[maxn], lge[maxn], lle[maxn], rge[maxn], rle[maxn]; vector<int>jumps[maxn]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> h[i]; dp[i] = INF; } dp[0] = ...
1407
E
Egor in the Republic of Dagestan
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan. There are $n$ cities in the republic, some of them are connected by $m$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitra...
**This task has a simple intuitive proof, but I wanted to describe it formally so it's pretty complicated.** We'll show a constructive algorithm for this task and proof it's correctness. We also provide a realisation with $O(n+m)$ time complexity. Let's change each edge's direction to the opposite. Then for vertex of c...
[ "constructive algorithms", "dfs and similar", "dp", "graphs", "greedy", "shortest paths" ]
2,500
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 1; vector<int> bg[maxn], rg[maxn]; int b[maxn], r[maxn], d[maxn], col[maxn]; int n, m; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for (int i = 0; i < m; i++) { int u, v, t; ci...
1408
A
Circle Coloring
You are given three sequences: $a_1, a_2, \ldots, a_n$; $b_1, b_2, \ldots, b_n$; $c_1, c_2, \ldots, c_n$. For each $i$, $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$. Find a sequence $p_1, p_2, \ldots, p_n$, that satisfy the following conditions: - $p_i \in \{a_i, b_i, c_i\}$ - $p_i \neq p_{(i \mod n) + 1}$. In ot...
At first, set $p_1 = a_1$. Then for $i \in \{2, \ldots, n-1\}$ if $a_i = p_{i-1}$, then set $p_i = b_i$. Otherwise, set $p_i = a_i$. In the end, set $p_n$ to one of $\{a_n, b_n, c_n\}$, which is not equal to $p_1$ or $p_{n-1}$.
[ "constructive algorithms" ]
800
null
1408
B
Arrays Sum
You are given a \textbf{non-decreasing} array of \textbf{non-negative} integers $a_1, a_2, \ldots, a_n$. Also you are given a positive integer $k$. You want to find $m$ \textbf{non-decreasing} arrays of \textbf{non-negative} integers $b_1, b_2, \ldots, b_m$, such that: - The size of $b_i$ is equal to $n$ for all $1 \...
Case $k = 1$: If all $a_i$ are equal the answer is $1$. Otherwise the answer is $-1$. Case $k > 1$: Let's consider an array $a' = (a_2 - a_1, a_3 - a_2, \ldots, a_n - a_{n-1})$ and arrays $b_i' = (b_{i, 2} - b_{i, 1}, b_{i, 3} - b_{i, 2}, \ldots, b_{i, n} - b_{i, n-1})$. The number of non-zero elements in $b_i'$ is at ...
[ "constructive algorithms", "greedy", "math" ]
1,400
null
1408
C
Discrete Acceleration
There is a road with length $l$ meters. The start of the road has coordinate $0$, the end of the road has coordinate $l$. There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to th...
Solution $1$: Let's make a binary search on the answer. If we have some time $t$ we can calculate the coordinate of each car after $t$ seconds. Let's define them as $x_1$ and $x_2$. If $x_1 \leq x_2$ let's move the left bound of the binary search, otherwise, let's move the right bound. Time complexity: $O(n \log{\frac{...
[ "binary search", "dp", "implementation", "math", "two pointers" ]
1,500
null
1408
D
Searchlights
There are $n$ robbers at coordinates $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ and $m$ searchlight at coordinates $(c_1, d_1)$, $(c_2, d_2)$, ..., $(c_m, d_m)$. In one move you can move each robber to the right (increase $a_i$ of each robber by one) or move each robber up (increase $b_i$ of each robber by one). No...
Let's define as $x$ our move to the right and as $y$ our move to the up. For all pairs $(i, j)$ of (robber, searchlight) at least one of this should be true: $x + a_i > c_j$, $y + b_i > d_j$. So if $x \leq c_j - a_i$ then $y \geq d_j - b_i + 1$. Let's make an array $r$ of length $C = 10^6$ and write on each position of...
[ "binary search", "brute force", "data structures", "dp", "implementation", "sortings", "two pointers" ]
2,000
null
1408
E
Avoid Rainbow Cycles
You are given $m$ sets of integers $A_1, A_2, \ldots, A_m$; elements of these sets are integers between $1$ and $n$, inclusive. There are two arrays of positive integers $a_1, a_2, \ldots, a_m$ and $b_1, b_2, \ldots, b_n$. In one operation you can delete an element $j$ from the set $A_i$ and pay $a_i + b_j$ coins for...
Let's make a bipartite graph with $m$ vertices on the left side and $n$ vertices on the right side. We will connect vertex $i$ from the left side with all elements of $A_i$. It can be proven, that the graph, which we create using our sets don't have rainbow cycles if and only if our bipartite graph don't have cycles. S...
[ "data structures", "dsu", "graphs", "greedy", "sortings", "trees" ]
2,400
null
1408
F
Two Different
You are given an integer $n$. You should find a list of pairs $(x_1, y_1)$, $(x_2, y_2)$, ..., $(x_q, y_q)$ ($1 \leq x_i, y_i \leq n$) satisfying the following condition. Let's consider some function $f: \mathbb{N} \times \mathbb{N} \to \mathbb{N}$ (we define $\mathbb{N}$ as the set of positive integers). In other wo...
Claim: for each $k$, we can perform operations on $2^k$ elements to make all numbers the same. You can prove this fact with induction by $k$. For $k=0$ this fact is obvious, For $k>0$, at first change first $2^{k-1}$ and last $2^{k-1}$ points to the same value (assume that those values are $x$ and $y$, respectively). A...
[ "constructive algorithms", "divide and conquer" ]
2,300
null
1408
G
Clusterization Counting
There are $n$ computers in the company network. They are numbered from $1$ to $n$. For each pair of two computers $1 \leq i < j \leq n$ you know the value $a_{i,j}$: the difficulty of sending data between computers $i$ and $j$. All values $a_{i,j}$ for $i<j$ are different. You want to separate all computers into $k$ ...
Sort all edges by their weights. In this order, maintain the DSU. For each connected component, let's maintain $dp_k$: the number of ways to divide this component into $k$ groups. When you merge two connected clusters, you have to recalculate the DP as in the multiplication of two polynomials (of course, if you bound $...
[ "combinatorics", "dp", "dsu", "fft", "graphs", "trees" ]
2,700
null
1408
H
Rainbow Triples
You are given a sequence $a_1, a_2, \ldots, a_n$ of non-negative integers. You need to find the largest number $m$ of triples $(i_1, j_1, k_1)$, $(i_2, j_2, k_2)$, ..., $(i_m, j_m, k_m)$ such that: - $1 \leq i_p < j_p < k_p \leq n$ for each $p$ in $1, 2, \ldots, m$; - $a_{i_p} = a_{k_p} = 0$, $a_{j_p} \neq 0$; - all ...
Let's reformulate this problem: you should choose different $i$ with different $a_i > 0$, and for each of them choose one zero to the left and one zero to the right (i.e. for each chosen guy we can assume that we have two vertices in the bipartite graph, and we want to match the left of them with some zero to the left,...
[ "binary search", "data structures", "flows", "greedy" ]
3,300
null
1408
I
Bitwise Magic
You are given a positive integer $k$ and an array $a_1, a_2, \ldots, a_n$ of non-negative distinct integers not smaller than $k$ and not greater than $2^c-1$. In each of the next $k$ seconds, one element is chosen randomly equiprobably out of all $n$ elements and decreased by $1$. For each integer $x$, $0 \leq x \leq...
There are several solutions to this problem, with various complexities. Some of our solutions work in less than half a second. The constraints were set to allow most non-naive solutions. Solution 1, DP on Trie Let's look at the bitwise trie. Each node corresponds to some segment $[l, r]$ of possible numbers. Let's note...
[ "dp", "math" ]
3,200
null
1409
A
Yet Another Two Integers Problem
You are given two integers $a$ and $b$. In one move, you can choose some \textbf{integer} $k$ from $1$ to $10$ and add it to $a$ or subtract it from $a$. In other words, you choose an integer $k \in [1; 10]$ and perform $a := a + k$ or $a := a - k$. You may use \textbf{different} values of $k$ in different moves. You...
We can add or subtract $10$ until the difference between $a$ and $b$ becomes less than $10$. And if it is not $0$ after all such moves, we need one additional move. Let $d = |a - b|$ is the absolute difference between $a$ and $b$. The final answer is $\left\lfloor\frac{d}{10}\right\rfloor$ plus one if $d \mod 10 > 0$. ...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b; cin >> a >> b; cout << (abs(a - b) + 9) / 10 << endl; } return 0; }
1409
B
Minimum Product
You are given four integers $a$, $b$, $x$ and $y$. Initially, $a \ge x$ and $b \ge y$. You can do the following operation \textbf{no more than} $n$ times: - Choose either $a$ or $b$ and decrease it by one. However, as a result of this operation, value of $a$ cannot become less than $x$, and value of $b$ cannot become ...
The only fact required to solve the problem: if we start decreasing the number, we are better to end decreasing it and only then decrease the other number. So, we can just consider two cases: when we decrease $a$ first, and $b$ after that and vice versa, and just take the minimum product of these two results. The rest ...
[ "brute force", "greedy", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b, x, y, n; cin >> a >> b >> x >> y >> n; long long ans = 1e18; for (int i = 0; i < 2; ++i) { int da = min(n, ...
1409
C
Yet Another Array Restoration
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: - The array consists of $n$ \textbf{distinct positive} (greater than $0$) integers. - The array contains two elements $x$ and $y$ (these elements are \textbf{known} for you) such that $x < y$. -...
The only fact required to solve this problem is just to notice that the answer array is just an arithmetic progression. After that, we can fix the first element $start$, fix the difference $d$, construct the array $[start, start + d, start + 2d, \dots, start + d \cdot (n-1)]$, check if $x$ and $y$ are in this array and...
[ "brute force", "math", "number theory" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int tcs; cin >> tcs; while (tcs--) { int n, x, y; cin >> n >> x >> y; int diff = y - x; for (int delta = 1; delta <= diff; ++delta) { if (diff % delta) continue; if (diff / delta + 1 > n) co...
1409
D
Decrease the Sum of Digits
You are given a positive integer $n$. In one move, you can increase $n$ by one (i.e. make $n := n + 1$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $n$ be less than or equal to $s$. You have to answer $t$ independent test cases.
Firstly, let's check if the initial $n$ fits the conditions. If it is, print $0$ and continue. Otherwise, let's solve the problem greedily. At first, let's try to set the last digit to zero. Let $dig = n \mod 10$. We need exactly $(10 - dig) \mod 10$ moves to do that. Let's add this number to $n$ and to the answer and ...
[ "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; int sum(long long n) { int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { long long n; int s; c...
1409
E
Two Platforms
There are $n$ points on a plane. The $i$-th point has coordinates $(x_i, y_i)$. You have two horizontal platforms, both of length $k$. Each platform can be placed anywhere on a plane but it should be placed \textbf{horizontally} (on the same $y$-coordinate) and have \textbf{integer borders}. If the left border of the p...
Firstly, we obviously don't need $y$-coordinates at all because we can place both platforms at $y=-\infty$. Let's sort all $x$-coordinates in non-decreasing order. Calculate for each point $i$ two values $l_i$ and $r_i$, where $l_i$ is the number of points to the left from the point $i$ (including $i$) that are not fur...
[ "binary search", "dp", "sortings", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> x(n), y(n); for (auto &it : x) cin >> it; for (auto &it : y) cin >> it; sort(x....
1409
F
Subsequences of Length Two
You are given two strings $s$ and $t$ consisting of lowercase Latin letters. The length of $t$ is $2$ (i.e. this string consists only of two characters). In one move, you can choose \textbf{any} character of $s$ and replace it with \textbf{any} lowercase Latin letter. More formally, you choose some $i$ and replace $s_...
I'm almost sure this problem can be solved faster and with greater constraints but this version is fine for the last problem. Consider both strings $0$-indexed and let's do the dynamic programming $dp_{i, j, cnt_0}$. It means the maximum number of occurrences of $t$ if we considered first $i$ characters of $s$, did $j$...
[ "dp", "strings" ]
2,100
// Author: Ivan Kazmenko (gassa@mail.ru) module solution; import std.algorithm; import std.conv; import std.range; import std.stdio; import std.string; void main () { int n, k; while (readf !(" %s %s") (n, k) > 0) { readln; auto s0 = readln.strip; auto t = readln.strip; auto s = s0.dup; int res = 0; for...
1411
A
In-game Chat
You have been assigned to develop a filter for bad messages in the in-game chat. A message is a string $S$ of length $n$, consisting of lowercase English letters and characters ')'. The message is bad if the number of characters ')' at the end of the string strictly greater than the number of remaining characters. For ...
You should count the number of parentheses at the end of the string, suppose there are $x$ such parentheses. Then if $x > \frac{n}{2}$, message is bad. Note that you should divide $n$ by $2$ without rounding. Or you can compare $2 \cdot x$ and $n$ instead. If $2 \cdot x > n$, the message is bad.
[ "implementation" ]
800
null
1411
B
Fair Numbers
We call a positive integer number fair if it is divisible by each of its nonzero digits. For example, $102$ is fair (because it is divisible by $1$ and $2$), but $282$ is not, because it isn't divisible by $8$. Given a positive integer $n$. Find the minimum integer $x$, such that $n \leq x$ and $x$ is fair.
Let's call a number super-fair if it is divisible by each of the numbers $1..9$. It is fair to say that super-fair numbers are also divisible by $LCM(1..9)$ which is equal to $2520$. The answer isn't larger than the nearest super-fair number, which means that you can increase the original $n$ by one until it becomes fa...
[ "brute force", "number theory" ]
1,000
null
1411
C
Peaceful Rooks
You are given a $n \times n$ chessboard. Rows and columns of the board are numbered from $1$ to $n$. Cell $(x, y)$ lies on the intersection of column number $x$ and row number $y$. Rook is a chess piece, that can in one turn move any number of cells vertically or horizontally. There are $m$ rooks ($m < n$) placed on t...
Consider rooks as edges in a graph. The position $(x, y)$ will correspond to an edge $(x \to y)$. From the condition that there're at most one edge exits leading from each vertex and at most one edge leading to each vertex, it follows that the graph decomposes into cycles, paths, and loops (edges of type $v \to v$). Wh...
[ "dfs and similar", "dsu", "graphs" ]
1,700
null
1411
D
Grime Zoo
Currently, XXOC's rap is a string consisting of zeroes, ones, and question marks. Unfortunately, haters gonna hate. They will write $x$ angry comments for every occurrence of \textbf{subsequence} 01 and $y$ angry comments for every occurrence of \textbf{subsequence} 10. You should replace all the question marks with 0 ...
Consider two adjacent question marks at positions $l$ and $r$ ($l < r$). Let $c_0$ zeros and $c_1$ ones be on the interval $(l, r)$. In case $s_l = 0$, $s_r = 1$ there will be written $(c_1 + 1) \cdot x + c_0 \cdot x + out = (c_0 + c_1 + 1) \cdot x + out = (r - l) \cdot x + out$ comments, where $out$ is the number of c...
[ "brute force", "greedy", "implementation", "strings" ]
2,100
null
1411
E
Poman Numbers
You've got a string $S$ consisting of $n$ lowercase English letters from your friend. It turned out that this is a number written in poman numerals. The poman numeral system is long forgotten. All that's left is the algorithm to transform number from poman numerals to the numeral system familiar to us. Characters of $S...
First, note that the last digit will always be taken with a plus sign, and the one before the last - with a minus sign. It turns out that all other digits may be taken with any sign. Let's prove it. Suppose we want to get the mask $---++--++---+$. All minuses on the left can be obtained by simply splitting one characte...
[ "bitmasks", "greedy", "math", "strings" ]
2,300
null
1411
F
The Thorny Path
According to a legend the Hanoi Temple holds a permutation of integers from $1$ to $n$. There are $n$ stones of distinct colors lying in one line in front of the temple. Monks can perform the following operation on stones: choose a position $i$ ($1 \le i \le n$) and cyclically shift stones at positions $i$, $p[i]$, $p[...
The problem boils down to getting an array consisting of threes and a remainder (2 or 2+2 or 4) using split and merge operations. It helps to think that all merge operations are done before split operations. To solve the problem, you can brute which elements of the array the remainder is subtracted from, then the rest ...
[ "greedy", "math" ]
3,000
null
1411
G
No Game No Life
Let's consider the following game of Alice and Bob on a directed acyclic graph. Each vertex may contain an arbitrary number of chips. Alice and Bob make turns alternating. Alice goes first. In one turn player can move exactly one chip along any edge outgoing from the vertex that contains this chip to the end of this ed...
The winner of the game is determined by xor of Grundy values for all chips' vertices. Notice that every Grundy value $\leq\sqrt m$ so xor doesn't exceed 512. Let $P_v$ be a probability of Alice's victory if the current xor is $v$. $P_v = \sum P_{to}\cdot prob(v \rightarrow to) + [v\neq 0] \cdot\frac{1}{n + 1}$ In the s...
[ "bitmasks", "games", "math", "matrices" ]
2,700
null
1413
A
Finding Sasuke
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are $T$ rooms there. Every room has a door into it, each door can be described by the number $n$ of seals on it and their integer energies $a_1$, $a_2$, ..., $a_n$. All energies $a_i$ are \textbf{nonzero} and do not exceed $100$ by absol...
The following is always a valid answer: $-a_2, a_1, -a_4, a_3, ..., -a_n, a_{n-1}$.
[ "constructive algorithms", "math" ]
800
null
1413
B
A New Technique
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $n\cdot m$ different seals, denoted by distinct numbers. All of them were written in an $n\times m$ table. The table is lost now. Naruto managed to remember elements of each row from left to rig...
To solve this problem it's sufficient to find the position of each row in the table. If we consider the first number of each row and find a column containing it, we will automatically obtain the position of the row. Since all numbers are distinct, the positions will be determined uniquely.
[ "implementation" ]
1,100
null
1413
C
Perform Easily
After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has $6$ strings and an infinite number of frets numbered from $1$. Fretting the fret number $j$ on the $i$-th string produces the note $a_{i} + j$. Tayuya wants to play a melody of $n$ notes. Each note...
Consider all possible frets we may need to use. To do this we sort all the pairs $(b_j - a_i, j)$ lexicographically. Now we need to find a subsegment with the minimal range containing the first fields and also so that all numbers from $1$ to $n$ occur among the second fields (so it will mean that for each note there is...
[ "binary search", "brute force", "dp", "implementation", "sortings", "two pointers" ]
1,900
null
1413
D
Shurikens
Tenten runs a weapon shop for ninjas. Today she is willing to sell $n$ shurikens which cost $1$, $2$, ..., $n$ ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the a...
Let's note that if a shuriken of price $x$ is being bought right now, then the only information we obtain about all the remaining shurikens is that they are of prices $\geq x$. It's also clear that if we consider two shurikens on the showcase then the one which was placed earlier has the stronger constraints (as writte...
[ "data structures", "greedy", "implementation" ]
1,700
null
1413
E
Solo mid Oracle
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal $a$ instant damage to him, and then heal that enemy $b$ health points at the end of every second, for exactly $c$ seconds, starting one second after the ability is used. That means that if the ability is used at time $...
It will be easier to explain using illustrations. We will use timelines, where each cast spell instance will occupy a separate row; and each second will be represented as a column. First of all, if $a > b\cdot c$ then the answer is $-1$. Indeed, after time $t$ the total amount of damage dealt is $(a - bc)$ for each spe...
[ "greedy", "math", "ternary search" ]
2,100
null
1413
F
Roads and Ramen
In the Land of Fire there are $n$ villages and $n-1$ bidirectional road, and there is a path between any pair of villages by roads. There are only two types of roads: stone ones and sand ones. Since the Land of Fire is constantly renovating, every morning workers choose a single road and flip its type (so it becomes a ...
Fix any diameter of the tree. One of the optimal paths always starts at one of the diameter's endpoints. Proof: Let $AB$ be a diameter of the tree, and the optimal answer be $EF$. Then the parity of the number of stone roads on $DE$ is the same as on $DF$, and also the same holds for $CE$ and $CF$. Since a diameter has...
[ "data structures", "trees" ]
2,800
null
1415
A
Prison Break
There is a prison that can be represented as a rectangular matrix with $n$ rows and $m$ columns. Therefore, there are $n \cdot m$ prison cells. There are also $n \cdot m$ prisoners, one in each prison cell. Let's denote the cell in the $i$-th row and the $j$-th column as $(i, j)$. There's a secret tunnel in the cell $...
The problem is equivalent to finding the farthest cell from $( x , y )$. It is easy to see that, if they move optimally, $( i , j )$ can reach $( x , y )$ just by moving in an L shape, and this is equivalent to the Manhattan distance between the two points. The longest distance a prisoner will move on rows is $max( x -...
[ "brute force", "math" ]
800
null
1415
B
Repainting Street
There is a street with $n$ houses in a line, numbered from $1$ to $n$. The house $i$ is initially painted in color $c_i$. The street is considered beautiful if all houses are painted in the same color. Tom, the painter, is in charge of making the street beautiful. Tom's painting capacity is defined by an integer, let's...
If we want to paint every house on the street with color $x$, it is easy to see that we need to change every house with color different from $x$, and not necessarily repaint houses already painted in color $x$. We can do the following greedy algorithm to minimize the number of days: Find leftmost house not painted in c...
[ "brute force", "greedy" ]
1,100
null
1415
C
Bouncing Ball
You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $1$, and in each cell you can either put a platform or leave it empty. In order to pass a level, a player must throw a ball from the ...
Note that instead of deletion of the first cell we can increase the value of $p$ by one, these operations are equivalent. Now let's loop through the possible final values of $p$, let it be $q$ ($p \le q \le n$). Then we need to add missing platforms in cells $q$, $(q + k)$, $(q + 2k)$, and so on. Let's compute the arra...
[ "brute force", "dp", "implementation" ]
1,400
null
1415
D
XOR-gun
Arkady owns a \textbf{non-decreasing} array $a_1, a_2, \ldots, a_n$. You are jealous of its beauty and want to destroy this property. You have a so-called XOR-gun that you can use one or more times. In one step you can select two \textbf{consecutive} elements of the array, let's say $x$ and $y$, remove them from the a...
First let's compute array $b_1, b_2, \ldots, b_n$, where $b_i$ is the index of the highest bit equal to $1$ in the binary notation of $a_i$. The statement says $b_i \le b_{i + 1}$. These values can be computed by dividing the given numbers by $2$ until they are zero. Note that if for a given $i$ the equality $b_{i - 1}...
[ "bitmasks", "brute force", "constructive algorithms" ]
2,000
null
1415
E
New Game Plus!
Wabbit is playing a game with $n$ bosses numbered from $1$ to $n$. The bosses can be fought in any order. Each boss needs to be defeated \textbf{exactly once}. There is a parameter called \textbf{boss bonus} which is initially $0$. When the $i$-th boss is defeated, the current \textbf{boss bonus} is added to Wabbit's ...
We see that each playthrough (whether it is the first one or any of the playthroughs after the reset) is completely independent of any other playthrough. Thus, we should instead think of the problem as partitioning the $n$ bosses into $k+1$ playthroughs. Consider a playthrough with $x$ bosses which have point increment...
[ "constructive algorithms", "greedy", "math" ]
2,200
null
1415
F
Cakes for Clones
You live on a number line. You are initially (at time moment $t = 0$) located at point $x = 0$. There are $n$ events of the following type: at time $t_i$ a small cake appears at coordinate $x_i$. To collect this cake, you have to be at this coordinate at this point, otherwise the cake spoils immediately. No two cakes a...
Let $mintime_i$ be the minimum time we can get to coordinate $x_i$ given that all previous cakes are collected and the latest created clone is already useless. Also let $dp_{i, j}$ be a boolean being true if we can reach a situation where we just collected the $i$-th cake, and our clone is currently waiting for the cak...
[ "dp" ]
2,900
null
1416
A
k-Amazing Numbers
You are given an array $a$ consisting of $n$ integers numbered from $1$ to $n$. Let's define the $k$-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length $k$ (recall that a subsegment of $a$ of length $k$ is a contiguous part of $a$ containing exactly $k$ e...
Let's fix some arbitrary number $x$ and calculate the minimum value of $k$ such that $x$ occurs in all segments of length $k$. Let $p_1 < p_2 < \dots < p_m$ be the indices of entries of $x$ in the array. Then, for each $1 \le i < m$ it is clear that $k$ should be at least the value of $p_{i+1}-p_i$. Also, $k \ge p_1$ a...
[ "binary search", "data structures", "implementation", "two pointers" ]
1,500
// chrono::system_clock::now().time_since_epoch().count() #include<bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define debug(x) cerr << #x << " = " << x << endl; using namespace std; typedef long long ll; ty...
1416
B
Make Them Equal
You are given an array $a$ consisting of $n$ \textbf{positive} integers, numbered from $1$ to $n$. You can perform the following operation no more than $3n$ times: - choose three integers $i$, $j$ and $x$ ($1 \le i, j \le n$; $0 \le x \le 10^9$); - assign $a_i := a_i - x \cdot i$, $a_j := a_j + x \cdot i$. After each...
Let $S$ be the sum of the array. If $S$ is not divisible by $n$, then the answer is obviously $-1$. Otherwise, there always exists a solution which uses no more than $3n$ queries. We will solve this problem in two phases. First phase: gather the sum in $a_1$. Let's iterate over $2 \le i \le n$ in increasing order. If $...
[ "constructive algorithms", "greedy", "math" ]
2,000
// chrono::system_clock::now().time_since_epoch().count() #include<bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define debug(x) cerr << #x << " = " << x << endl; using namespace std; typedef long long ll; ty...
1416
C
XOR Inverse
You are given an array $a$ consisting of $n$ non-negative integers. You have to choose a non-negative integer $x$ and form a new array $b$ of size $n$ according to the following rule: for all $i$ from $1$ to $n$, $b_i = a_i \oplus x$ ($\oplus$ denotes the operation bitwise XOR). An inversion in the $b$ array is a pair...
Note: the integer $x$ from the statement is marked as an uppercase $X$ for clarity. Take any arbitrary integers $x$ and $y$. It is a well-known fact that whether $x < y$ or $x > y$ depends only on one bit - the highest bit which differs in both. So, let's construct a trie on our array integers. Represent each number as...
[ "bitmasks", "data structures", "divide and conquer", "dp", "greedy", "math", "sortings", "strings", "trees" ]
2,000
#include <bits/stdc++.h> #define mp make_pair #define pb push_back #define f first #define s second #define ll long long #define forn(i, a, b) for(int i = (a); i <= (b); ++i) #define forev(i, b, a) for(int i = (b); i >= (a); --i) #define VAR(v, i) __typeof( i) v=(i) #define forit(i, c) for(VAR(i, (c).begin()); i != (...
1416
D
Graph and Queries
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Initially there is a single integer written on every vertex: the vertex $i$ has $p_i$ written on it. All $p_i$ are distinct integers from $1$ to $n$. You have to process $q$ queries of two types: - $1$ $v$ — among all vertices reachable from ...
Basically, we want to transform each "connected component maximum" query into "segment maximum" query. It can be efficiently done using DSU and processing all queries in reversed order. For simplicity, let's assume all edges will eventually get deleted in the process. If not, you can always add some extra queries at th...
[ "data structures", "dsu", "graphs", "implementation", "trees" ]
2,600
// chrono::system_clock::now().time_since_epoch().count() #include<bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define debug(x) cerr << #x << " = " << x << endl; using namespace std; typedef long long ll; ty...
1416
E
Split
One day, BThero decided to play around with arrays and came up with the following problem: You are given an array $a$, which consists of $n$ positive integers. The array is numerated $1$ through $n$. You execute the following procedure \textbf{exactly once}: - You create a new array $b$ which consists of $2n$ \textbf...
Note that minimizing $|b|$ is the same as maximizing the number of consecutive equal pairs. We will focus on the second version. Let's forget about constraints and consider the most naive solution with dynamic programming. $DP[i][j]$ will store the answer if we have already considered ($a_1$, ..., $a_i$) and our last e...
[ "binary search", "data structures", "dp", "greedy" ]
3,200
// chrono::system_clock::now().time_since_epoch().count() #include<bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define debug(x) cerr << #x << " = " << x << endl; using namespace std; typedef long long ll; ty...
1417
A
Copy-paste
\begin{quote} — Hey folks, how do you like this problem?— That'll do it. \end{quote} BThero is a powerful magician. He has got $n$ piles of candies, the $i$-th pile initially contains $a_i$ candies. BThero can cast a copy-paste spell as follows: - He chooses two piles $(i, j)$ such that $1 \le i, j \le n$ and $i \ne ...
If we do our operation on two arbitrary integers $x \le y$, it is always better to copy $x$ into $y$ rather than to copy $y$ into $x$ (since a resulting pair $(x, x + y)$ is better than $(y, x + y)$). Now, let's assume that we do our operation on two integers $x \le y$ such that $x$ is not the minimum element of our ar...
[ "greedy", "math" ]
800
// chrono::system_clock::now().time_since_epoch().count() #include<bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define debug(x) cerr << #x << " = " << x << endl; using namespace std; typedef long long ll; ty...
1417
B
Two Arrays
RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$. Let's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \le i < j \le m$ and $b_i + b_j = T$. RedDreamer has to paint each element of $a$ into one of two...
Let us partition the array into three sets $X$, $Y$, $Z$ such that $X$ contains all numbers less than $T/2$, $Y$ contains all numbers equal to $T/2$ and $Z$ contains all numbers greater than $T/2$. It is clear that $f(X) = f(Z) = 0$. Now, since each pair in $Y$ makes a sum of $T$, the best solution is to distribute all...
[ "greedy", "math", "sortings" ]
1,100
#include <bits/stdc++.h> #define len(v) ((int)((v).size())) #define all(v) (v).begin(), (v).end() #define rall(v) (v).rbegin(), (v).rend() #define chmax(x, v) x = max((x), (v)) #define chmin(x, v) x = min((x), (v)) using namespace std; using ll = long long; void solve() { int n, tar; cin >> n >> tar; int curMid = 0...
1418
A
Buying Torches
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $k$ torches. One torch can be crafted using \textbf{one stick and one coal}. Hopefully, you've met a very handsome wandering trader who has two trade offers: - exchange $1$ stick for $x$ sticks (you lose $1$ stick an...
You need $s = yk + k - 1$ additional sticks to get $k$ torches ($yk$ sticks for $y$ units of coal and also $k$ sticks required to craft torches) and you get $x-1$ sticks per one trade. To buy this number of sticks, you need $\left\lceil\frac{s}{x-1}\right\rceil$ trades. And also, you need $k$ additional trades to turn ...
[ "math" ]
1,000
for i in range(int(input())): x, y, k = map(int, input().split()) print(((y + 1) * k - 1 + x - 2) // (x - 1) + k)
1418
B
Negative Prefixes
You are given an array $a$, consisting of $n$ integers. Each position $i$ ($1 \le i \le n$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new on...
Let's collect the prefix sums of the initial array $a$. How do they change if you swap two values in the array? Let's swap values on positions $l$ and $r$ ($l < r$). Prefix sums from $1$ to $l-1$ aren't changed. Prefix sums from $l$ to $r-1$ are increased by $a_r-a_l$ (note that if $a_l>a_r$ then these sums become smal...
[ "greedy", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) void solve() { int n; cin >> n; vector<int> a(n), b(n), c; forn(i, n) cin >> a[i]; forn(i, n) cin >> b[i]; forn(i, n) if (!b[i]) c.push_back(a[i]); sort(...
1418
C
Mortal Kombat Tower
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $n$ bosses in this tower, numbered from $1$ to $n$. The type of the $i$-th boss is $a_i$. If the $i$-th boss is easy then its type is $a_i = 0$, otherwise this boss is hard and its type is $a_i = 1$. During o...
If $a_1 = 1$ then our friend always needs one skip point because he always has to kill the first boss. Let's just remove this boss from our consideration and increase the answer if needed. What about other skip points? Firstly, let's understand that we can always do our moves in such a way that the first hard boss will...
[ "dp", "graphs", "greedy", "shortest paths" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto &it : a) cin >> it; int ans...
1418
D
Trash Problem
Vova decided to clean his room. The room can be represented as the coordinate axis $OX$. There are $n$ piles of trash in the room, coordinate of the $i$-th pile is the integer $p_i$. All piles have \textbf{different} coordinates. Let's define a total cleanup as the following process. The goal of this process is to col...
First, let's understand that if we choose some subset of points $x_1, x_2, \dots, x_k$, then it does not matter to which point we move it (inside the segment [$\min(x_1, x_2, \dots, x_k); \max(x_1, x_2, \dots, x_k)]$) because the minimum number of moves will always be the same and it is equal to $\max(x_1, x_2, \dots, ...
[ "data structures", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; int get(const set<int> &x, const multiset<int> &len) { if (len.empty()) return 0; return *x.rbegin() - *x.begin() - *len.rbegin(); } void add(int p, set<int> &x, multiset<int> &len) { x.insert(p); auto it = x.find(p); int prv = -1, nxt = -1; if (i...
1418
E
Expected Damage
You are playing a computer game. In this game, you have to fight $n$ monsters. To defend from monsters, you need a shield. Each shield has two parameters: its current durability $a$ and its defence rating $b$. Each monster has only one parameter: its strength $d$. When you fight a monster with strength $d$ while havi...
First of all, let's find a solution in $O(nm)$. We will use the lineriality of expectation: the answer for some shield $j$ is equal to $\sum\limits_{i = 1}^{n} d_i P(i, j)$, where $P(i, j)$ is the probability that the monster $i$ will deal damage if we use the $j$-th shield. Let's see how to calculate $P(i, j)$. Consid...
[ "binary search", "combinatorics", "probabilities" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; const int MOD = 998244353; int mul(int a, int b) { return (a * 1LL * b) % MOD; } int bp(int a, int n) { int res = 1; for (; n > 0; n /= 2) { if (n & 1) res = mul(res, a); a = mul(a, a); } return res; }...
1418
F
Equal Product
You are given four integers $n$, $m$, $l$ and $r$. Let's name a tuple $(x_1, y_1, x_2, y_2)$ as good if: - $1 \le x_1 < x_2 \le n$; - $1 \le y_2 < y_1 \le m$; - $x_1 \cdot y_1 = x_2 \cdot y_2$; - $l \le x_1 \cdot y_1 \le r$. Find any good tuple \textbf{for each $x_1$ from $1$ to $n$ inclusive}.
Let's look at $x_1 y_1 = x_2 y_2$ where $x_1 < x_2$. It can be proven that there always exists such pair $(a, b)$ ($a \mid x_1$, $b \mid y_1$ and $a < b$) that $x_2 = \frac{x_1}{a} b$ and $y_2 = \frac{y_1}{b} a$. Brief proof is following: calculate $g = \gcd(x_1, x_2)$, then let $a = \frac{x_1}{g}$ and $b = \frac{x_2}{...
[ "data structures", "math", "number theory", "two pointers" ]
3,000
#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; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out...
1418
G
Three Occurrences
You are given an array $a$ consisting of $n$ integers. We denote the subarray $a[l..r]$ as the array $[a_l, a_{l + 1}, \dots, a_r]$ ($1 \le l \le r \le n$). A subarray is considered good if every integer that occurs in this subarray occurs there \textbf{exactly thrice}. For example, the array $[1, 2, 2, 2, 1, 1, 2, 2,...
Let's consider two solutions: a non-deterministic and a deterministic one. The random solution goes like that. Let's assign a random integer to each value from $1$ to $n$ (to value, not to a position). Let the value of the subarray be the trit-wise sum of the assigned integers of all values on it. Trit-wise is the anal...
[ "data structures", "divide and conquer", "hashing", "two pointers" ]
2,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) typedef unsigned long long uli; vector<int> a; vector<pair<int, int>> t; vector<int> ps; pair<int, int> merge(const pair<int, int> &a, const pair<int, int> &b){ if (a.first != b.first) return min(a, b); ...
1419
A
Digit Game
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $t$ matches of a digit game... In each of $t$ matches of the digit game, a positive integer is generated. It consists of $n$ digits. The digits of this integer are numer...
Let's say that digits on odd positions are blue and digits on even positions are red. If $n$ is even the remaining digit will be red. If there is at least one even red digit then Breach wins (he can mark all digits except the one that will remain in the end). In other case Raze wins, because any digit that may remain i...
[ "games", "greedy", "implementation" ]
900
"#include <bits/stdc++.h>\nusing namespace std;\n\nsigned main() {\n\tint T;\n\tcin >> T;\n\twhile (T --> 0) {\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\tbool odd = false, even = false;\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tif (i % 2 == 1) {\n\t\t\t\todd |= ((s[i - 1] - '0') % 2 == 1);\n\t\t\t} else {\n\t...
1419
B
Stairs
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases. A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase ha...
Let's prove, that the minimal amount of squares needed to cover the staircase is not less than $n$, where $n$ is the height of a staircase. To highest cell of each stair is the top left cell of some square. That's why we need at least $n$ squares. You need exactly $n$ squares if and only if the top left cell of each st...
[ "brute force", "constructive algorithms", "greedy", "implementation", "math" ]
1,200
"#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define ll long long\nconst int INF = 2e9 + 1;\n \nll getS(ll x) {\n\treturn x * (x + 1) / 2;\t\n}\n \nint main() {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n int T;\n cin >> T;\n while (T --> 0) {\n ll x;\n cin >...
1419
C
Killjoy
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by \textbf{an integer} (it can possibly be negative or very large). Killjoy's account is already infected and has a rating equal to $x$. Its rating is constant. There are $n$ accounts except...
If all $n$ accounts have the rating equal to $x$ then the answer is $0$. Now let's consider other cases. Let's try to make all ratings equal to $x$ in a single contest. It's possible only in two cases: 1. If at least one account is already infected we can infect all other accounts in a single contest. Let's say that so...
[ "greedy", "implementation", "math" ]
1,500
"#include <bits/stdc++.h>\nusing namespace std;\n\nsigned main() {\n int T;\n cin >> T;\n while (T --> 0) {\n int n, x;\n cin >> n >> x;\n int cnt = 0;\n int sum = 0;\n for (int i = 0; i < n; ++i) {\n int val;\n cin >> val;\n cnt += (val == x)...
1419
D2
Sage's Birthday (hard version)
\textbf{This is the hard version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem.} Today is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are pla...
Let's learn how to check whether it's possible to buy $x$ ice spheres. Let's sort the array $a$ in the non-decreasing order and then take $x$ smallest elements of it. We will suppose that these $x$ ice spheres will be cheap. To make these ice spheres cheap, we need $x+1$ ice spheres more, so let's take $x+1$ most expen...
[ "binary search", "brute force", "constructive algorithms", "greedy", "sortings", "two pointers" ]
1,500
"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n int n;\n cin >> n;\n vector<int> a(n);\n for (int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n sort(a.begin(), a.end());\n int l = 0, r = n + 1;\n ...
1419
E
Decryption
An agent called Cypher is decrypting a message, that contains a composite number $n$. All divisors of $n$, which are greater than $1$, are placed in a circle. Cypher can choose the initial order of numbers in the circle. In one move Cypher can choose two adjacent numbers in a circle and insert their least common multi...
Let's factorize $n$: $n = p_1^{q_1} \cdot p_2^{q_2} \cdot \dots \cdot p_k^{q_k}$ If $k = 2$ and $q_1 = q_2 = 1$ (i.e. $n$ is the product of two different prime numbers)Divisors $p_1$ and $p_2$ will definately be adjacent and they are coprime so we should make one operation to insert their lcm between them. After that t...
[ "constructive algorithms", "implementation", "math", "number theory" ]
2,100
"#include <bits/stdc++.h>\nusing namespace std;\n\nbool prime(int x) {\n\tif (x == 2 || x == 3) return true;\n\tfor (int i = 2; i * i <= x; ++i) {\n\t\tif (x % i == 0) return false;\n\t}\n\treturn true;\n}\n\nsigned main() {\n\tint T;\n\tcin >> T;\n\twhile (T --> 0) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> d;\n\t\...
1419
F
Rain of Fire
There are $n$ detachments on the surface, numbered from $1$ to $n$, the $i$-th detachment is placed in a point with coordinates $(x_i, y_i)$. All detachments are placed in different points. Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts. To move from one det...
We can consider a graph where vertices are the points (detachments), and there is an edge between two points, if it's possible to move from one point to another. It is possible if these points are on the same line ($x_i = x_j$ or $y_i = y_j$) and the distance between them is $\le T$. Now we can check, whether current $...
[ "binary search", "data structures", "dfs and similar", "dsu", "graphs", "implementation" ]
2,800
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define pb emplace_back\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define ll long long\n#define pii pair<int, int>\n\nconst int INF = 2e9 + 1;\n\nvector<vector<int>> g;\nvector<int> usd;\n\nvoid dfs(int v, int col) {\n usd[v] = co...
1420
A
Cubes Sorting
\begin{quote} {{\small For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're ...
It is not difficult to see that the answer <<NO>> in this task is possible when and only when all $a_i$ are different and sorted in descending order. In this case we need $\frac{n \cdot (n-1)}{2}$ operations. Otherwise the answer is always <<YES>>. Why does this solution work? Let's define number of inversions as the n...
[ "math", "sortings" ]
900
#include<iostream> using namespace std; int a[1000000+5]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin>>t; while (t--) { int n; cin>>n; for (int i=0; i<n; i++) { cin>>a[i]; } bool can=false; ...
1420
B
Rock and Lever
\begin{quote} {{\small "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you."}} \end{quote} Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them. Hermit Lizard agreed to give D...
Let's take a pair $(a_i, a_j)$ and see in which case $a_i\ \&\ a_j \ge a_i \oplus a_j$ will hold. For this we will follow the bits $a_i$ and $a_j$ from highest to lowest. If we meet two zero bits, the values of $a_i\ \&\ a_j$ and $a_i \oplus a_j$ will match in this bit, so we move on. If we meet a zero bit in $a_i$ and...
[ "bitmasks", "math" ]
1,200
#include<iostream> #include<vector> #include<algorithm> #include<ctime> #include<random> using namespace std; mt19937 rnd(time(NULL)); int a[1000000+5]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin>>t; while (t--) { int n; cin>>n; ...
1420
C1
Pokémon Army (easy version)
\textbf{This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.} Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamo...
The easy version of the task can be solved in different ways. For example, you can use the dynamic programming method. Let $d1_i$ - be the maximum possible sum of a subsequence on a prefix from the first $i$ elements, provided that the length of the subsequence is odd. Similarly enter $d2_i$, only for subsequences of e...
[ "constructive algorithms", "dp", "greedy" ]
1,300
#include <iostream> #include <vector> using namespace std; inline int64_t calc(const vector<int> &a) { int n = a.size(); vector<int64_t> d1(n+1), d2(n+1); d1[0] = -static_cast<int64_t>(1e18); d2[0] = 0; for (int i = 0; i < n; ++i) { d1[i+1] = max(d1[i], d2[i] + a[i]); d2[i+1] = max(d2[i], d1[i] - a[i]); } ...
1420
C2
Pokémon Army (hard version)
\textbf{This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.} Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamo...
Let's give a solution for a fixed array and then prove its optimality. Let us name the element $a_i$ a local maximum if $a_i > a_{i-1}$ and $a_i > a_{i+1}$. Similarly let's call the element $a_i$ a local minimum if $a_i < a_{i-1}$ and $a_i < a_{i+1}$. If any of the $a_{i-1}$ or $a_{i+1}$ does not exist in the definitio...
[ "data structures", "divide and conquer", "dp", "greedy", "implementation" ]
2,100
#include<iostream> using namespace std; #define int long long int a[1000000+5]; int n; int ans=0; inline void insert(int i) { if (i==0||i==n+1) return; if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i]; if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i]; } inline void erase(int i) { if (i==0||i==n+1) return; if (...
1420
D
Rescue Nibel!
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened. Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional de...
In this task, we need to find the number of sets of $k$ segments such that these $k$ segments intersect at least in one point. Let's look at the starting point of the intersection. This point will always be the beginning of a segment. Let us find the number of sets of segments that their intersection begins at the poin...
[ "combinatorics", "data structures", "sortings" ]
1,800
import java.io.*; import java.util.*; public class D_Java { public static final int MOD = 998244353; public static int mul(int a, int b) { return (int)((long)a * (long)b % MOD); } int[] f; int[] rf; public int C(int n, int k) { return (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k])); } public ...
1420
E
Battle Lemmings
A lighthouse keeper Peter commands an army of $n$ battle lemmings. He ordered his army to stand in a line and numbered the lemmings from $1$ to $n$ from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield. The more protected Peter's army is, the better. To calculate the prot...
First, let us denote $f(A)$ as a conversion of the original sequence of $A$. In the beginning, we will write down the number of zeros before the the first one. Then, we write down the number of zeros standing between the first and second ones, then - between the second and third ones, and so on. For example, $f(0110001...
[ "dp", "greedy" ]
2,500
#include <cassert> #include <climits> #include <iostream> #include <vector> #include <numeric> using namespace std; template<typename T> inline void umin(T &a, const T &b) { a = min(a, b); } template<typename T> inline void umax(T &a, const T &b) { a = max(a, b); } int main() { ios_base::sync_with_stdio(false); ...
1421
A
XORwice
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers $a$ and $b$ and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of ($a \oplus x$) + ($b \oplus x$) for any given $x$, where $\oplus$ denotes the b...
Think about addition in base two. Say $a$ = $10101$ and $b$ = $1001$. What your operation does is it modifies the bits in your numbers, so if the first bit in $a$ is $1$ and the first bit in $b$ is $1$ (as is the case above) you can make both $0$ by making that bit $1$ in $x$. This is actually the only way you can decr...
[ "bitmasks", "greedy", "math" ]
800
null
1421
B
Putting Bricks in the Wall
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size $n\times n$ and he wants to traverse his grid from the upper left ($1,1$) corner to the...
It's hard to use the two valuable switches somewhere in the middle of the matrix, a much wiser choice would be to somehow block the $S$ cell or the $F$ cell. Perhaps you can set both neighbours of $S$ to $1$ to force Roger to pick $1$. If we pick the neighbours of $S$ to be $1$ we can make the neighbours of $F$ $0$ and...
[ "constructive algorithms", "implementation" ]
1,100
null
1421
C
Palindromifier
Ringo found a string $s$ of length $n$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $s$ into a palindrome by applying two types of operations to the string. The first operation allows him to ch...
You're not allowed to just pick the whole string and append its reversed result to the front, but what's the next best thing? We're very close to the answer if we take the whole string except for a letter (so for $abcde$ we make $dcbabcde$). The operation above which transformed $abcde$ into $dcbabcde$ is very close, i...
[ "constructive algorithms", "strings" ]
1,400
null
1421
D
Hexagons
Lindsey Buckingham told Stevie Nicks "Go your own way". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world. Consider a hexagonal tiling of the plane as on the picture below. Nicks wishes to go from the cell marked $(0, 0)$ to a certain cell given by the coordinates. Sh...
Using too many edges in the solution feels wasteful, the solution surely has some neat line as straight as possible. Perhaps we can prove only two edges are required? Indeed two edges are required in the solution, so one approach would be picking all combinations of edges and do linear algebra so see how many times eac...
[ "brute force", "constructive algorithms", "greedy", "implementation", "math", "shortest paths" ]
1,900
null
1421
E
Swedish Heroes
While playing yet another strategy game, Mans has recruited $n$ Swedish heroes, whose powers which can be represented as an array $a$. Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consec...
The problem gives us an array and we have to come up with an achievable sequence of pluses and minuses such that summing the numbers after applying the signs we get the largest sum. Intuitively we can probably assign $+$ to most positive numbers and - to most negative numbers somehow, but we should investigate exactly ...
[ "brute force", "dp", "implementation" ]
2,700
null
1422
A
Fence
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $a$, $b$, and $c$. Now he needs to find out some possible integer length $d$ of the fourth straight fence segment so that he can build the fence using th...
A quadrilateral can be built when $max (a, b, c, d) < a + b + c + d - max (a, b, c, d)$, that is, the sum of the minimum three numbers is greater than the maximum. To do this, you could choose $max (a, b, c)$ or $a + b + c - 1$ as $d$.
[ "geometry", "math" ]
800
#include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define a...
1422
B
Nice Matrix
A matrix of size $n \times m$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $(a_1, a_2, \dots , a_k)$ is a palindrome, if for any integer $i$ ($1 \le i \le k$) the equality $a_i = a_{k - i + 1}$ holds. Sasha owns a matrix $a$ of size $n \times m$. In one operation he can...
Note, that if the value of $a_{1, 1}$ is equal to some number $x$, then values of $a_{n, 1}$, $a_{1, m}$ and $a_{n, m}$ must also be equal to this number $x$ by the palindrome property. A similar property holds for all of the following elements $a_{x, y}$ ($a_{x, y}=a_{n - x + 1, y}=a_{1,m - y + 1}=a_{n - x + 1, m - y ...
[ "greedy", "implementation", "math" ]
1,300
#include <bits/stdc++.h> #define fi first #define se second #define m_p make_pair #define endl '\n' #define fast_io ios_base::sync_with_stdio(0); cin.tie(0) using namespace std; typedef long long ll; const int MAXN = 412345; const int MAXINT = 2047483098; const ll MOD = 1e9 + 7; const int MAX = 1e4; const lon...
1422
C
Bargain
Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price $n$, Vova removes a non-empty substring of (co...
Let's count for each digit how many times it will be included in the final sum and in what place. Let's denote $m$ as the length of the number $n$. Consider the digit $a_i$ at the position $i$ in the number $n$ ($1 \le i \le m$). If some part of the number to the left of the digit is removed, then the current digit wil...
[ "combinatorics", "dp", "math" ]
1,700
#include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define a...
1422
D
Returning Home
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city. Let's represent the city as an area of $n \times n$ square blocks. Yura needs to move from the block with coordinates $(s_x,s_y)...
You can build a graph with vertices at the start point and all fast travel points. The distance between the vertices $(x_1, y_1)$ and $(x_2, y_2)$ is calculated as $min (|x_1 - x_2|, |y_1 - y_2|)$. To avoid drawing all $m * (m + 1) / 2$ edges in the graph, note that for a pair of points $(x_1, y_1)$ and $(x_2, y_2)$ su...
[ "graphs", "shortest paths", "sortings" ]
2,300
#include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define a...
1422
E
Minlexes
Some time ago Lesha found an entertaining string $s$ consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows. Lesha chooses an arbitrary (possibly zero) number of pairs on positions $(i, i + 1)$ in such a way that the ...
Let's find the answer $ans_i$ for all suffixes, starting with the smallest in length. $ans_n$ is equal to an empty string. Then if $s_i = s_{i + 1}$ ($0 \le i + 1 < n$), then $ans_i = min (s_i + ans_{i + 1}, ans_{i + 2})$, and otherwise $ans_i = s_i + ans_{i + 1}$. To quickly find minimum of two strings, they can be st...
[ "dp", "greedy", "implementation", "strings" ]
2,700
#include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <vector> using namespace std; #define a...