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
1604
A
Era
Shohag has an integer sequence $a_1, a_2, \ldots, a_n$. He can perform the following operation any number of times (possibly, zero): - Select any positive integer $k$ (it can be different in different operations). - Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any t...
If $a_i \gt i$ for some position $i$, then we need to insert at least $a_i - i$ new small elements before this position. Let $m = max(0, \max\limits_{i = 1}^{n}{(a_i - i)})$. So we need at least $m$ operations. But its not hard to see that $m$ operations are enough. For example, you can insert $m$ $1$s at the beginning...
[ "greedy" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans = 0; for (int i = 1; i <= n; i++) { int k; cin >> k; ans = max(ans, k - i); } cout << ans << '\n'; } return 0; }
1604
B
XOR Specia-LIS-t
YouKn0wWho has an integer sequence $a_1, a_2, \ldots a_n$. Now he will split the sequence $a$ into one or more consecutive subarrays so that each element of $a$ belongs to exactly one subarray. Let $k$ be the number of resulting subarrays, and $h_1, h_2, \ldots, h_k$ be the lengths of the longest increasing subsequence...
What happens if we split the sequence into subarrays of length $1$?. Yes, if $n$ is even, the bitwise XOR will be $0$ as there will be an even number of $1$s. If $n$ is odd we can't do the same. But what if there is an index $i$ such that $a_i \ge a_{i + 1}$? What if we use these two indices as a single subarray as it ...
[]
1,100
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n + 1); bool inc = true; for (int i = 1; i <= n; i++) { cin >> a[i]; inc &= a[i] > a[i - 1]; } if (n % 2 == 0 or...
1605
A
A.M. Deviation
A number $a_2$ is said to be the arithmetic mean of two numbers $a_1$ and $a_3$, if the following condition holds: $a_1 + a_3 = 2\cdot a_2$. We define an arithmetic mean deviation of three numbers $a_1$, $a_2$ and $a_3$ as follows: $d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|$. Arithmetic means a lot to Jeevan. He h...
$\rightarrow$ Applying the operation on $a_1$ and $a_3$ (irrespective of which element is incremented and which one is decremented) does not change the value of $a_1 + a_3 - 2 \cdot a_2$. $\rightarrow$ Incrementing $a_1$ (or $a_3$) by $1$ and decrementing $a_2$ by $1$ causes the value of $a_1 + a_3 - 2 \cdot a_2$ to in...
[ "math", "number theory" ]
800
t=int(input()) for i in range(t): a,b,c=[int(x) for x in input().split()] print(0 if ((a+b+c)%3 == 0) else 1)
1605
B
Reverse Sort
Ashish has a binary string $s$ of length $n$ that he wants to sort in non-decreasing order. He can perform the following operation: - Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $k$ such that $1 \leq k \leq n$ and any sequence of $k$ indices $1 \le i_1 \...
Any binary string $s$ can be sorted in at most $1$ operation! Let the number of $0$s in $s$ be $cnt_0$ and the number of $1$s in $s$ be $cnt_1$. The first $cnt_0$ positions of the final sorted string will be $0$ and the remaining $cnt_1$ positions will be $1$ (since it is sorted in non-decreasing order). Key observatio...
[ "greedy", "sortings" ]
1,000
q = int(input()) for tc in range(q): n = int(input()) s = input() t = ''.join(sorted(s)) ans = [] for i in range(len(s)): if s[i] != t[i]: ans.append(i) val = 1 if len(ans) > 0 else 0 print(val) if val > 0: print(len(ans), end = " ") for elem in range(len...
1605
C
Dominant Character
Ashish has a string $s$ of length $n$ containing only characters 'a', 'b' and 'c'. He wants to find the length of the smallest substring, which satisfies the following conditions: - Length of the substring is \textbf{at least} $2$ - 'a' occurs strictly more times in this substring than 'b' - 'a' occurs strictly more ...
Tl;dr: The following are all the possible minimal substrings (there aren't that many) which satisfy the given conditions: "aa", "aba", "aca", "abca", "acba", "abbacca", "accabba". Any other string that satisfies the condition contains at least one of these as a substring, and hence is not the optimal substring for the ...
[ "brute force", "greedy", "implementation", "strings" ]
1,400
fun main(args: Array<String>) { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val s = readLine()!! var ans = 8; for(i in 0..n-1) { val cnt = IntArray(3) {0} for(j in i..Math.min(i + 6, n - 1)) { cnt[s[j] - 'a']++; ...
1605
D
Treelabeling
Eikooc and Sushi play a game. The game is played on a tree having $n$ nodes numbered $1$ to $n$. Recall that a tree having $n$ nodes is an undirected, connected graph with $n-1$ edges. They take turns alternately moving a token on the tree. \textbf{Eikooc makes the first move, placing the token} on any node of her ch...
If the most significant bits (MSBs) of two integers $x$ and $y$ are the same, say $\mathrm{MSB}_x = \mathrm{MSB}_y = b$, then the $b$-th bit will be unset in $x \oplus y$. Since $min(x, y)$ will have this bit set, it will be greater than $x \oplus y$. Thus, if $\mathrm{MSB}_x = \mathrm{MSB}_y$ then $x \oplus y \leq min...
[ "bitmasks", "constructive algorithms", "dfs and similar", "games", "greedy", "implementation", "trees" ]
2,100
fun dfs(x: Int, p: Int, curcol: Int, adj: Array<MutableList<Int>>, col: Array<Int>) { col[x] = curcol adj[x] .filter { it != p } .forEach { dfs(it, x, curcol xor 1, adj, col) } } fun main(args: Array<String>) { val t = readLine()!!.toInt() repeat(t) { val n = readLine()!!.toInt...
1605
E
Array Equalizer
Jeevan has two arrays $a$ and $b$ of size $n$. He is fond of performing weird operations on arrays. This time, he comes up with two types of operations: - Choose any $i$ ($1 \le i \le n$) and increment $a_j$ by $1$ for every $j$ which is a multiple of $i$ and $1 \le j \le n$. - Choose any $i$ ($1 \le i \le n$) and dec...
Firstly let's observe that only the differences $b_i - a_i$ matter, and not the individual values of $a_i$ and $b_i$. So let us create two more arrays $A$ and $B$ where initially $A_i = 0$ and $B_i = b_i - a_i$ for all $i$. The problem reduces to making $A$ equal to $B$. Let's have a few definitions for ease of explana...
[ "binary search", "greedy", "implementation", "math", "number theory", "sortings", "two pointers" ]
2,400
#include <bits/stdc++.h> using namespace std; #define IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define int long long #define endl "\n" #define sz(w) (int)(w.size()) using pii = pair<int, int>; const double EPS = 1e-9; const long long INF = 1e18; const int N = 2e5+5; int n, m, a[N], b[N], c[N],...
1605
F
PalindORme
An integer array $a$ of length $n$ is said to be a PalindORme if ($a_{1}$ $|$ $a_{2} $ $|$ $ \ldots $ $|$ $ a_{i}) = (a_{{n - i + 1}} $ $|$ $ \ldots $ $|$ $ a_{{n - 1}} $ $|$ $ a_{n}) $ \textbf{for all} $ 1 \leq i \leq n$, where $|$ denotes the bitwise OR operation. An integer array $a$ of length $n$ is considered to ...
$\textbf{Solution Outline:}$ For any bad array, there is $\textbf{exactly one}$ maximum even length good subsequence (possibly the empty subsequence). It can be proven that there exists at most one element in the bad array that doesn't belong to this subsequence, but is a submask of its OR. If such an element exists, w...
[ "combinatorics", "dp" ]
2,900
fun mod_expo(base: Int, pow: Int, MOD: Int): Long { if(pow == 0) { return 1; } var res = mod_expo(base, pow / 2, MOD) res = (res * res) % MOD if(pow % 2 == 1) { res = (res * base) % MOD; } return res; } fun mod_inv(base: Int, MOD: Int): Long { return mod_expo(base, MOD ...
1606
A
AB Balance
You are given a string $s$ of length $n$ consisting of characters a and/or b. Let $\operatorname{AB}(s)$ be the number of occurrences of string ab in $s$ as a \textbf{substring}. Analogically, $\operatorname{BA}(s)$ is the number of occurrences of ba in $s$ as a \textbf{substring}. In one step, you can choose any ind...
Let's look at the first and the last characters of $s$. Note that if $s_1 = s_n$ (where $n = |s|$), then $\operatorname{AB}(s)$ is always equal to $\operatorname{BA}(s)$. It can be proved, for example, by induction: if $s$ consists of equal characters then $\operatorname{AB}(s) = \operatorname{BA}(s) = 0$; if $s$ has a...
[ "strings" ]
900
fun main() { repeat(readLine()!!.toInt()) { val s = readLine()!! println(s.last() + s.substring(1)) } }
1606
B
Update Files
Berland State University has received a new update for the operating system. Initially it is installed only on the $1$-st computer. Update files should be copied to all $n$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them ...
Let $cur$ be the current number of computers with the update already installed (initially it is $1$). Then, in $1$ hour, we can increase $cur$ by $\min(cur, k)$. From here we can see that the value of $cur$ will double for the first few hours, and then, when it becomes greater than $k$, it will begin to increase by exa...
[ "greedy", "implementation", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { li n, k; cin >> n >> k; li ans = 0, cur = 1; while (cur < k) { cur *= 2; ++ans; } if (cur < n) ans += (n - cu...
1606
C
Banknotes
In Berland, $n$ different types of banknotes are used. Banknotes of the $i$-th type have denomination $10^{a_i}$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $1$. Let's denote $f(s)$ as the minimum number of banknotes required to represent exactly $s$ bur...
First of all, let's find out how to calculate $f(s)$. This can be done greedily, let's iterate from the higher denominations to the lower ones, the number of banknotes of $i$-th type is equal to $\left\lfloor {\frac{s}{10^{a_i}}} \right\rfloor$ (the value of $s$ here changes to reflect that we have already taken some b...
[ "greedy", "number theory" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; k += 1; vector<int> a(n); for (int& x : a) { cin >> x; int cur = 1; while (x--) cur *= 10; x = cur; } long long res = 0; for (int i = 0; i < ...
1606
D
Red-Blue Matrix
You are given a matrix, consisting of $n$ rows and $m$ columns. The $j$-th cell of the $i$-th row contains an integer $a_{ij}$. First, you have to color each row of the matrix either red or blue in such a way that \textbf{at least one row is colored red} and \textbf{at least one row is colored blue}. Then, you have t...
Imagine you fixed some cut and then colored one row red. Which rows can now be colored red or blue so that the condition on the left matrix is satisfied? If the row has at least one number greater or equal than the numbers in the red row, then the row must be red. Otherwise, it can be either red or blue. However, imagi...
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; int main() { int tc; scanf("%d", &tc); while (tc--){ int n, m; scanf("%d%d", &n, &m); vector<vector<int>> a(n, vector<int>(m)); forn(i, n) forn(j, m) scanf("%d", &a[i][j]); vector<int>...
1606
E
Arena
There are $n$ heroes fighting in the arena. Initially, the $i$-th hero has $a_i$ health points. The fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals $1$ damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than $1$ at th...
Let's calculate the following dynamic programming $dp_{i, j}$ - the number of ways to choose the initial health if there are $i$ heroes still alive, and they already received $j$ damage. Let's iterate over $k$ - the number of heroes that will survive after the next round. Then we have to make a transition to the state ...
[ "combinatorics", "dp", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 505; const int MOD = 998244353; int n, x; int c[N][N], dp[N][N]; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; return x; } int mul(int x, int y) { return x * 1ll * y % MOD; } int main() { cin >> n >> x; for (int i = 0; i <= n; ++i) ...
1606
F
Tree Queries
You are given a tree consisting of $n$ vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex $1$. You have to process $q$ queries. In each query, you are given a vertex of the tree $v$ and an integer $k$. To process a query, you may delete any vertices from the ...
A naive solution to this problem would be to implement a recursive function which answers each query: let $f(v, k)$ be the answer to the query "$v$ $k$", we can calculate it as $\sum\limits_{u \in children(v)} \max(1, f(u, k) - k)$, since for each child $u$ of vertex $v$, we either delete it and change the score by $f(...
[ "brute force", "dp", "trees" ]
2,800
#include <bits/stdc++.h> using namespace std; struct Vertex { int cost; int depth; int idx; Vertex() {}; Vertex(int cost, int depth, int idx) : cost(cost), depth(depth), idx(idx) {}; }; bool operator <(const Vertex& a, const Vertex& b) { if(a.cost != b.cost) return a.cost > b.cost; if(a.depth !...
1607
A
Linear Keyboard
You are given a keyboard that consists of $26$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter. You have to type the word $s$ on this keyboard. It also consists only of lowercase Latin letters. To type a word, you need to type all its let...
Since it does not take time to place your hand over the first letter, you need to calculate the sum of the distances between the keyboard keys corresponding to each pair of adjacent letters of the word, that is $\sum\limits_{i=2}^n |\mathtt{pos}(s_i) - \mathtt{pos}(s_{i-1})|$ In order to calculate this sum, let's just ...
[ "implementation", "strings" ]
800
t = int(input()) for _ in range(t): k, s = input(), input() res = 0 for i in range(1, len(s)): res += abs(k.index(s[i]) - k.index(s[i - 1])) print(res)
1607
B
Odd Grasshopper
The grasshopper is located on the numeric axis at the point with coordinate $x_0$. Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $x$ with a distance $d$ to the left moves the grasshopper to a point with a coordinate $x - d$, while jumping to ...
Consider the first four actions that the grasshopper will perform, starting at a point with coordinate $0$: coordinate $0$ is even, jumping left to $1$ leads to $-1$ coordinate $-1$ is odd, jumping right to $2$ leads to $2$ coordinate $1$ is odd, jumping right to $3$ leads to $4$ coordinate $4$ is even, jumping left to...
[ "math" ]
900
t = int(input()) maps = [ lambda x: 0, lambda x: x, lambda x: -1, lambda x: -x - 1 ] for _ in range(t): x0, n = map(int, input().split()) d = maps[n % 4](n) print(x0 - d if x0 % 2 == 0 else x0 + d)
1607
C
Minimum Extraction
Yelisey has an array $a$ of $n$ integers. If $a$ has length strictly greater than $1$, then Yelisei can apply an operation called minimum extraction to it: - First, Yelisei finds the minimal number $m$ in the array. If there are several identical minima, Yelisey can choose any of them. - Then the selected minimal ele...
Note that the order of numbers in the array does not affect anything. If you swap two elements in the original array, the set of elements at each step will not change in any way. Let's sort the original array $a$ and denote it by $a^0$. We denote by $a^i$ the state of array $a^0$ after applying $i$ operations of minimu...
[ "brute force", "sortings" ]
1,000
t = int(input()) for _ in range(t): n = int(input()) a = sorted(list(map(int, input().split()))) res = a[0] for i in range(n - 1): res = max(res, a[i + 1] - a[i]) print(res)
1607
D
Blue-Red Permutation
You are given an array of integers $a$ of length $n$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step: - either yo...
Note the following fact: if a number $x$ in a permutation was obtained from a blue number and a number $y$ in a permutation was obtained from a red number, and $x > y$, then by decreasing the blue number and increasing the red number exactly $x - y$ times each, we will obtain the same permutation in which the two numbe...
[ "greedy", "math", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; string c; cin >> c; vector<int> l,...
1607
E
Robot on the Board 1
The robot is located on a checkered rectangular board of size $n \times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. Th...
Let's look at the answer $(r, c)$. Let's see how many commands the robot can execute. Since the robot breaks as soon as goes outside the field, if any command causes it to break, it either leads to its total shift relative to $(r, c)$ of exactly $c$ to the left or exactly $m - c + 1$ to the right, or, similarly, of exa...
[ "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; string s; cin >> s; int bx = 0, by = 0; int min_bx = 0, max_bx = 0, min_by = 0, max_by = 0; for (char c: s) { if (c =...
1607
F
Robot on the Board 2
The robot is located on a checkered rectangular board of size $n \times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. Ea...
Let's start moving from an arbitrary cell of the table, for example, from $(1, 1)$. Movement from each cell is specified by the direction given in that cell, so you can run a loop with a stopping condition "exit from the board border or get to the already visited cell". Create a separate array $d[r][c]$ - how many comm...
[ "brute force", "dfs and similar", "graphs", "implementation" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<string> dir(n); for (int i = 0; i < n; i++) cin >> dir[i]; vector<vi> res(n, v...
1607
G
Banquet Preparations 1
A known chef has prepared $n$ dishes: the $i$-th dish consists of $a_i$ grams of fish and $b_i$ grams of meat. The banquet organizers estimate the balance of $n$ dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat. Technically, the ...
Let's find how much meat and fish a taster can eat at most. Note that a taster can eat no more than $\min(a_i, m)$ of fish from the $i$-th dish (since he can't eat more than $m$ or more than there is at all). Similarly, he can eat no more than $\min(b_i, m)$ of meat. Let's sum the obtained values over all $i$ and denot...
[ "greedy" ]
2,200
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; typedef long long ll; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<pii> dishes(n); ll balance = 0; ll max_a = 0, max_b = 0; ll total_eat = static_cast<l...
1607
H
Banquet Preparations 2
The chef has cooked $n$ dishes yet again: the $i$-th dish consists of $a_i$ grams of fish and $b_i$ grams of meat. Banquet organizers consider two dishes $i$ and $j$ equal if $a_i=a_j$ and $b_i=b_j$ at the same time. The banquet organizers estimate the variety of $n$ dishes as follows. The variety of a set of dishes ...
Note that dishes can become equal if and only if they have equal values of $a_i + b_i - m_i$, that is, how much fish and meat remain in them in total after "tasting". Let's calculate this value for each dish and group all the dishes with equal calculated values. The minimum amount of fish that can remain in the $i$-th ...
[ "greedy", "sortings", "two pointers" ]
2,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) struct seg { int a, b, m; int index; }; int n, ans; vector<seg> segments; map<int, vector<seg>> diags; void erase(multiset<pair<pair<int,int>, int>>& lr, int l, int r, int index) { pair<pair<int,int>,int> ...
1608
A
Find Array
Given $n$, find any array $a_1, a_2, \ldots, a_n$ of integers such that all of the following conditions hold: - $1 \le a_i \le 10^9$ for every $i$ from $1$ to $n$. - $a_1 < a_2 < \ldots <a_n$ - For every $i$ from $2$ to $n$, $a_i$ isn't divisible by $a_{i-1}$ It can be shown that such an array always exists under the...
Notice that $x$ is never divisible by $x-1$ for $x \geq 3$, so we can output $2, 3, \dots, n, n+1$.
[ "constructive algorithms", "math" ]
800
null
1608
B
Build the Permutation
You are given three integers $n, a, b$. Determine if there exists a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, such that: - There are exactly $a$ integers $i$ with $2 \le i \le n-1$ such that $p_{i-1} < p_i > p_{i+1}$ (in other words, there are exactly $a$ local maximums). - There are exactly $b$...
First, answer does not exists if $a+b+2 > n$. Second, answer exists if and only if $|a-b| \leq 1$. It happens because between every two consecutive local maximums must be exactly one local minimum. And vice versa, between two consecutive minimums must be exactly one maximum. First case gives $b \geq a-1$, second - $a \...
[ "constructive algorithms", "greedy" ]
1,200
null
1608
C
Game Master
$n$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to org...
Let's look at the fights in the reversed order. If player $x$ is the winner, then he won against some player $y$ in the last fight. In $(n-2)$-th fight either $x$ or $y$ won against some player $z$, and so on. We always expand the set by adding a player that can lose against at least one player in the set, so if we can...
[ "data structures", "dfs and similar", "dp", "graphs", "greedy", "two pointers" ]
1,700
null
1608
D
Dominoes
You are given $n$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet. The coloring is said to be \textbf{valid} if and only if it is possible to rearrange the dominoes in some order such that for each $1 \le i \le n$ ...
If domino coloring is valid we can split cells into $n$ pairs of cells with opposite colors, so there is exactly $n$ cells of each color. Let $C_B$ and $C_W$ be the number of black and the number of white cells in the input, respectively. If $C_B > n$ or $C_W > n$, then the answer is $0$. Otherwise, the number of color...
[ "combinatorics", "fft", "graphs", "math", "number theory" ]
2,400
null
1608
E
The Cells on the Paper
On an endless checkered sheet of paper, $n$ cells are chosen and colored in three colors, where $n$ is divisible by $3$. It turns out that there are exactly $\frac{n}{3}$ marked cells of each of three colors! Find the largest such $k$ that it's possible to choose $\frac{k}{3}$ cells of each color, remove all other mar...
Rectangles in optimal answer always arranged in one of the following ways: horizontally from left to right; divided by <<T>>: first rectangle is upper than second and third, and the second is to the left of the third; rotations of previous ways. Lets consider all four rotations and find best answer for arrangements 1 a...
[ "binary search", "implementation", "sortings" ]
2,800
null
1608
F
MEX counting
For an array $c$ of nonnegative integers, $MEX(c)$ denotes the smallest nonnegative integer that doesn't appear in it. For example, $MEX([0, 1, 3]) = 2$, $MEX([42]) = 0$. You are given integers $n, k$, and an array $[b_1, b_2, \ldots, b_n]$. Find the number of arrays $[a_1, a_2, \ldots, a_n]$, for which the following...
Let's count $dp[pos][mex][big]$ - the number of ways to assign first $pos$ elements in a way that: $|MEX([a_1, a_2, \ldots, a_i]) - b_i| \le k$ for each $i$ from $1$ to $pos$. $|MEX([a_1, a_2, \ldots, a_i]) - b_i| \le k$ for each $i$ from $1$ to $pos$. $MEX([a_1, a_2, \ldots, a_{pos}]) = mex$ $MEX([a_1, a_2, \ldots, a_...
[ "combinatorics", "dp", "implementation" ]
3,200
null
1608
G
Alphabetic Tree
You are given $m$ strings and a tree on $n$ nodes. Each edge has some letter written on it. You have to answer $q$ queries. Each query is described by $4$ integers $u$, $v$, $l$ and $r$. The answer to the query is the total number of occurrences of $str(u,v)$ in strings with indices from $l$ to $r$. $str(u,v)$ is defi...
Let's concatenate the $m$ input strings, separated by some character not in the input, into a string $S$, and build the suffix array over it. If we could lexicographically compare $str(u, v)$ to some suffix of $S$, we could use binary search to find the left and right boundary of suffixes that start with $str(u, v)$ in...
[ "binary search", "data structures", "dfs and similar", "hashing", "string suffix structures", "strings", "trees" ]
3,500
null
1609
A
Divide and Multiply
William has array of $n$ numbers $a_1, a_2, \dots, a_n$. He can perform the following sequence of operations \textbf{any number of times}: - Pick any two items from array $a_i$ and $a_j$, where $a_i$ must be a multiple of $2$ - $a_i = \frac{a_i}{2}$ - $a_j = a_j \cdot 2$ Help William find the maximal sum of array ele...
First we divide all numbers by $2$, while they're divisible and calculate $k$, the number of successful divisions. Next we notice that to maximize the sum we need to multiply $2^k$ by the largest number remaining in the array after the described operations.
[ "greedy", "implementation", "math", "number theory" ]
900
def solve(): n = int(input()) a = list(map(int, input().split(' '))) temp = 1 for i in range(n): while (a[i] % 2 == 0): a[i] //= 2 temp *= 2 a.sort() a[-1] *= temp print(sum(a)) t = int(input()) for i in range(t): solve()
1609
B
William the Vigilant
Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment: You are given a string $s$ of leng...
Notice that the answer to this problem is the number of substrings "abc" Before starting to process queries let's count the number of substrings "abc" in the initial string. Next, notice that changing a character on position $pos$ can only remove one substring "abc" and add only one substring "abc". To check if either ...
[ "implementation", "strings" ]
1,100
def solve(): n, m = map(int, input().split(' ')) a = list(input()) num = 0 for i in range(n - 2): if (''.join(a[i:i + 3]) == 'abc'): num += 1 for i in range(m): index, ch = input().split(' ') index = int(index) - 1 for j in range(max(0, index - 2), index + 1): if (''.join(a[j:j + 3]) == 'abc'):...
1609
C
Complex Market Analysis
While performing complex market analysis William encountered the following problem: For a given array $a$ of size $n$ and a natural number $e$, calculate the number of pairs of natural numbers $(i, k)$ which satisfy the following conditions: - $1 \le i, k$ - $i + e \cdot k \le n$. - Product $a_i \cdot a_{i + e} \cdot...
Note that the product of $n$ natural numbers is a prime number if, and only if, $n - 1$ of these numbers equal to one and one number is prime. Next, let's group all of our numbers into groups which are ones. It's important that these groups are separated by a prime numbers. If the current number is neither a one nor a ...
[ "binary search", "dp", "implementation", "number theory", "schedules", "two pointers" ]
1,400
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4") // #pragma GCC optimize("Ofast") // #pragma GCC optimize("unroll-loops") #include <iostream> #include <vector> #include <set> #include <algorithm> #include <ctime> #include <cmath> #include <map> #include <assert.h> #include <fstream> #include <cstdlib> #include <rand...
1609
D
Social Network
William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies. The conference has $n$ participants, who are initially unfamiliar with each other. William can introduc...
Note that the conditions form a collection of disjoint sets. Consider two situations: The next condition connects two previously unconnected sets: then we will simply unite. The next condition connects two previously connected sets: this case allows us to "postpone" an edge to use it as we like. The second observation ...
[ "dsu", "graphs", "greedy", "implementation", "trees" ]
1,600
#include <iostream> #include <vector> #include <set> #include <algorithm> #include <ctime> #include <cmath> #include <map> #include <assert.h> #include <fstream> #include <cstdlib> #include <random> #include <iomanip> #include <queue> #include <bitset> using namespace std; #define sqr(a) ((a)*(a)) #define all(a) (a...
1609
E
William The Oblivious
Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it: You are given a string $...
To solve this problem we will use a segment tree. Let's maintain the following informaton for each segment: $dp_{node, mask}$ stores the minimal number of characters that have to be replaced to make the string only contain subsequences equal to $mask$. Next let's define what $mask$ is. Let the first bit of the mask cor...
[ "bitmasks", "data structures", "dp", "matrices" ]
2,400
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4") // #pragma GCC optimize("Ofast") // #pragma GCC optimize("unroll-loops") #include <iostream> #include <vector> #include <set> #include <algorithm> #include <ctime> #include <cmath> #include <map> #include <assert.h> #include <fstream> #include <cstdlib> #include <rand...
1609
F
Interesting Sections
William has an array of non-negative numbers $a_1, a_2, \dots, a_n$. He wants you to find out how many segments $l \le r$ pass the check. The check is performed in the following manner: - The minimum and maximum numbers are found on the segment of the array starting at $l$ and ending at $r$. - The check is considered ...
We will use Divide & Conquer algorithm. Let $f(l, r)$ be the answer to the problem on the subsegment $l\ldots r$. Let's notice, that if $l = r$, then $f(l, r) = 1$, otherwise $f(l, r) = f(l, m) + f(m + 1, r) + f'(l, r)$, where $m = \frac{r + l}{2}$ and $f'(l, r)$ equals to the number of subsegments passing the check, w...
[ "data structures", "divide and conquer", "meet-in-the-middle", "two pointers" ]
2,800
null
1609
G
A Stroll Around the Matrix
William has two arrays of numbers $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_m$. The arrays satisfy the conditions of being convex. Formally an array $c$ of length $k$ is considered convex if $c_i - c_{i - 1} < c_{i + 1} - c_i$ for all $i$ from $2$ to $k - 1$ and $c_1 < c_2$. Throughout William's life he observed ...
Let's try to solve the problem without asking for changes. Note that in the matrix constructed in this way for the move from (i, j) it is always profitable to go to the cell with the smallest number. This can be seen more clearly in the matrix of the first test case: This allows you to solve the problem with complexity...
[ "data structures", "greedy", "math" ]
3,000
null
1609
H
Pushing Robots
There're $n$ robots placed on a number line. Initially, $i$-th of them occupies unit segment $[x_i, x_i + 1]$. Each robot has a program, consisting of $k$ instructions numbered from $1$ to $k$. The robot performs instructions in a cycle. Each instruction is described by an integer number. Let's denote the number corres...
First of all, it should be noted, that one iteration of the described algorithm of robots' movements can be implemented in $O(n)$ time. For example, using stack. Let's consider moments of time that are multiple of $k$. And segments of time between such two consecutive moments of time. Consider two adjacent robots. It c...
[]
3,500
null
1610
A
Anti Light's Cell Guessing
You are playing a game on a $n \times m$ grid, in which the computer has selected some cell $(x, y)$ of the grid, and you have to determine which one. To do so, you will choose some $k$ and some $k$ cells $(x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k)$, and give them to the computer. In response, you will get $k$ numbe...
$\mathcal Complete\;\mathcal Solution$: $\textbf{I encourage you to read the Hints and Assumptions before reading this.}$ Let's say the answer is $ans$. If $n == 1$ and $m == 1$, then there's only one cell, so we don't need any more information, and the hidden cell is that single cell. So for this scenario $ans = 0$. I...
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(); cout.tie(); int t; cin >> t; while(t--){ int n, m; cin >> n >> m; if(n == 1 && m == 1){ cout << "0\n"; } else if(min(n, m) == 1){ ...
1610
B
Kalindrome Array
An array $[b_1, b_2, \ldots, b_m]$ is a palindrome, if $b_i = b_{m+1-i}$ for each $i$ from $1$ to $m$. Empty array is also a palindrome. An array is called \textbf{kalindrome}, if the following condition holds: - It's possible to select some integer $x$ and delete some of the elements of the array equal to $x$, so th...
If the array is already a palindrome the answer is Yes. Otherwise, let's find the minimum $i$ that $a_i \neq a_{n + 1 - i}$. We can prove that we have to remove either $a_i$ or $a_{n + 1 - i}$ in order the make the array palindrome. Imagine it's possible to make the array palindrome by removing all appearances of $x$. ...
[ "greedy", "two pointers" ]
1,100
//khodaya khodet komak kon # include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair <int, int> pii; typedef pair <pii, int> p...
1610
C
Keshi Is Throwing a Party
Keshi is throwing a party and he wants everybody in the party to be happy. He has $n$ friends. His $i$-th friend has $i$ dollars. If you invite the $i$-th friend to the party, he will be happy only if at most $a_i$ people in the party are strictly richer than him and at most $b_i$ people are strictly poorer than him....
Take a look at this greedy approach. Let $p_i$ be the $i$-th poorest invited person.($p_i < p_{i + 1}$) Find the poorest person $v$ that $x - 1 - a_v \le 0 \le b_v$. We will invite this person so $p_1 = v$. For each $2 \le i \le x$ find the poorest person $v$ that $v > p_{i - 1}$ and $x - 1 - a_v \le i - 1 \le b_v$ thi...
[ "binary search", "greedy" ]
1,600
//In the name of God #include <bits/stdc++.h> using namespace std; typedef int ll; typedef pair<ll, ll> pll; const ll maxn = 2e5 + 100; const ll mod = 1e9 + 7; const ll inf = 1e9; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define file_io freopen("input.txt", "r+", stdin);freopen("output....
1610
D
Not Quite Lee
Lee couldn't sleep lately, because he had nightmares. In one of his nightmares (which was about an unbalanced global round), he decided to fight back and propose a problem below (which you should solve) to balance the round, hopefully setting him free from the nightmares. A non-empty array $b_1, b_2, \ldots, b_m$ is c...
$\mathcal Complete\;\mathcal Solution$: $\textbf{I encourage you to read the Hints and Assumptions before reading this.}$ Assume we have an array $c$ of length $k$, need to know if it's good or not. We can choose an initial sequence $t_i$ for all $1 \le i \le k$, then slide them (in other words, choose an index $i$ and...
[ "combinatorics", "dp", "math", "number theory" ]
2,000
//In The Name of God //I usually forget about the previous line... #include <bits/stdc++.h> #define IOS ios::sync_with_stdio(0), cin.tie(), cout.tie(); using namespace std; typedef long long ll; const int maxBt = 30; const int mod = 1e9+7; int cnt[maxBt]; int slv(){ int n; cin >> n; int a[n]; fo...
1610
E
AmShZ and G.O.A.T.
Let's call an array of $k$ integers $c_1, c_2, \ldots, c_k$ \textbf{terrible}, if the following condition holds: - Let $AVG$ be the $\frac{c_1 + c_2 + \ldots + c_k}{k}$(the average of all the elements of the array, it doesn't have to be integer). Then the number of elements of the array which are bigger than $AVG$ sho...
We build the longest good subsequence starting with $a_s$ greedily step by step. In each step we add the smallest possible element to the subsequence. If the last element is $a_k$, we have to find the minimum $i$ that $i > k$ and $a_i \ge 2 \cdot a_k - a_s$. (using lower_bound) Assume $b_1 \neq b_2$, then $k < \log(a_n...
[ "binary search", "brute force", "greedy", "implementation", "math" ]
2,300
//khodaya khodet komak kon # include <bits/stdc++.h> using namespace std; const int xn = 2e5 + 10; int qq, n, a[xn], ans, res, ptr; int main(){ ios::sync_with_stdio(0);cin.tie(0); cout.tie(0); cin >> qq; while (qq --){ cin >> n, ans = 0; for (int i = 1; i <= n; ++ i) cin >> a[i]; for (int i = 1; i <= ...
1610
F
Mashtali: a Space Oddysey
Lee was planning to get closer to Mashtali's heart to proceed with his evil plan(which we're not aware of, yet), so he decided to beautify Mashtali's graph. But he made several rules for himself. And also he was too busy with his plans that he didn't have time for such minor tasks, so he asked you for help. Mashtali's...
If there is a vertex $v$ connected to its neighbors $x$ and $y$ with same edge weights, we delete these edges and add a new edge between $x$ and $y$. So the number of edges decreases by 1. Now we solve the problem for our new graph recurrently. Then we check whether the assigned direction is from $x$ to $y$ or from $y$...
[ "constructive algorithms", "dfs and similar", "graphs" ]
3,000
#include <bits/stdc++.h> #pragma GCC optimize ("O2,unroll-loops") using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define all(x) x.begin(), x.end() #define pb push_back #define SZ(x) ((int)x.size()) #define kill(x) return cout<<x<<'\n', 0; con...
1610
G
AmShZ Wins a Bet
Right before the UEFA Euro 2020, AmShZ and Safar placed bets on who'd be the champion, AmShZ betting on Italy, and Safar betting on France. Of course, AmShZ won. Hence, Safar gave him a bracket sequence $S$. Note that a bracket sequence is a string made of '(' and ')' characters. AmShZ can perform the following opera...
Idea: AmShZ, Keshi, Preparation: AmShZ, Keshi, alireza_kaviani, AliShahali1382 We can prove that there exists a way to achieve the lexicographically minimum by removing some balanced substrings. (A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters "+" and "1".)...
[ "data structures", "greedy", "hashing" ]
3,300
//In the name of God #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> pll; const ll maxn = 3e5 + 100; const ll lg = 20; const ll mod = 1e9 + 7; const ll inf = 1e18; #define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define file_io freopen("input.txt", "r+"...
1610
H
Squid Game
After watching the new \sout{over-rated} series Squid Game, Mashtali and Soroush decided to hold their own Squid Games! Soroush agreed to be the host and will provide money for the winner's prize, and Mashtali became the Front Man! $m$ players registered to play in the games to win the great prize, but when Mashtali f...
A player gets eliminated iff $(x_i, y_i)$ is a cross-edge while rooting the tree from where Mashtali sits. we say a vertex is marked if Mashtali choses it in a move. Lets solve the problem in polynomial time. First, lets fix one of the marked vertices and root the tree from it. Then all cross-edges are already covered ...
[ "data structures", "dfs and similar", "greedy", "trees" ]
3,100
#include <bits/stdc++.h> #pragma GCC optimize ("O2,unroll-loops") using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<pii, int> piii; typedef pair<ll, ll> pll; #define debug(x) cerr<<#x<<'='<<(x)<<endl; #define debugp(x) cerr<<#x<<"= {"<<(x.first)<<", "<<(x.seco...
1611
A
Make Even
Polycarp has an integer $n$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: - Reverse the prefix of length $l$ (in other words, $l$ leftmost digits) of $n$. So, the leftmost digit is swapped with the $l$-th digit from the left, the second digit from th...
If the number is already even, then nothing needs to be done, so the answer in this case is 0. Now let's recall the divisibility by $2$: a number is divisible by $2$ if and only if its last digit is divisible by $2$. It follows that if there are no even digits in our number, then the answer is -1. Let's take a look at ...
[ "constructive algorithms", "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { string n; cin >> n; if((n.back() - '0') % 2 == 0) { cout << "0\n"; continue; } if((n[0] - '0') % 2 == 0) { cout << "1\n"; contin...
1611
B
Team Composition: Programmers and Mathematicians
The All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate. There are $a$ programmers and $b$ mathematicians at Berland State University. How many maximum teams can be made if: - each team must consist of exactly $4$ students, - teams of $4$ mathematicians ...
If necessary, change the values of $a$ and $b$ so that $a \le b$ is always true. Consider two cases. 1. Let $a \le \frac{a + b}{4}$. Then: $4a \le a + b$, $3a \le b$. This means that the set $b$ is at least $3$ times larger than $a$, and we can form $a$ teams of the form $(1, 3)$, where one participant will be a progra...
[ "binary search", "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { ll a, b; cin >> a >> b; cout << min(min(a, b), (a + b) / 4) << '\n'; } int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { solve(); } return 0; }
1611
C
Polycarp Recovers the Permutation
Polycarp wrote on a whiteboard an array $p$ of length $n$, which is a permutation of numbers from $1$ to $n$. In other words, in $p$ each number from $1$ to $n$ occurs exactly once. He also prepared a resulting array $a$, which is initially empty (that is, it has a length of $0$). After that, he did exactly $n$ steps...
The maximum element is always added last, so if it is not in the first or last position, then there is no answer. Let us prove that if the permutation has its maximum element in the first or last position, then after $n$ actions we can get an expanded permutation. Indeed, the maximum element will be added last at the d...
[ "constructive algorithms" ]
1,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; if (a[0] != n && a[n - 1] != n) cout ...
1611
D
Weights Assignment For Tree Edges
You are given a rooted tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. Any vertex can be the root of a tree. A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. The tree is specified by an array of ancestors $b$ conta...
Consider the cases when it is impossible to form a given permutation $p$: 1. The first vertex in the permutation is not the root of the tree. For root $u$ it is true that $dist[u]=0$. For any other vertex $i$ the value of $dist[i]$ will be positive, since there is at least one edge of positive weight on the path to it....
[ "constructive algorithms", "trees" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int> b(n + 1), p(n + 1), dist(n + 1, -1); for(int i = 1; i <= n; i++) cin >> b[i]; for(int i = 1; i <= n; i++) cin >> p[i]; if (b[p[1]] != p[1]){ cout << -1 << '\n'; return...
1611
E1
Escape The Maze (easy version)
The only difference with E2 is the question of the problem.. Vlad built a maze out of $n$ rooms and $n-1$ bidirectional corridors. From any room $u$ any other room $v$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree. Vlad invited $k$ friends to play a game with them. Vl...
First, we need to understand when it is not possible to get to some exit $e$. Let's fix a friend who is at the vertex $f$ and try to understand if he can interfere with us. The paths from $1$ to $e$ and from $f$ to $e$ have a common part, let it start at the vertex $v$. Then, if the path from $f$ to $v$ is not more tha...
[ "dfs and similar", "greedy", "shortest paths", "trees", "two pointers" ]
1,700
// // Created by Vlad on 16.11.2021. // #include <bits/stdc++.h> #define int long long #define mp make_pair #define x first #define y second #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); con...
1611
E2
Escape The Maze (hard version)
The only difference with E1 is the question of the problem. Vlad built a maze out of $n$ rooms and $n-1$ bidirectional corridors. From any room $u$ any other room $v$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree. Vlad invited $k$ friends to play a game with them. Vla...
Let's learn how to find an answer for the subtree rooted in vertex $v$. At first, it is obvious from E1 tutorial that if the nearest to $v$ vertex with a friend from this subtree is no further from it than the root of the entire tree from $v$, then the answer for the entire subtree is $1$ since a friend can come to $v$...
[ "dfs and similar", "dp", "greedy", "shortest paths", "trees" ]
1,900
#include <bits/stdc++.h> #define int long long #define mp make_pair #define x first #define y second #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() /*#pragma GCC optimize("Ofast") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,...
1611
F
ATM and Students
Polycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains $s$ rubles. A queue of $n$ students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If $a_i$ is positive, then the student credits that amount of money via ...
At first glance, this is a standard problem for ST (Segment Tree). Let's solve the problem in that way. First, we find the prefix sums of the $a$ array and store them in $p$. Let's build an ST on the prefix array and store the min in it. For each index $l$ $(1 \le l \le n)$, we'll make a query in ST and will find such ...
[ "binary search", "data structures", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) vector<ll> t, a; ll s, tl; const ll MAX = 1'000'000'000'000'000LL; void build(int v, int l, int r) { if (l == r) t[v] = a[l]; else { int m = (l + r) / 2; build (v * 2, l, m); build (v ...
1611
G
Robot and Candies
Polycarp has a rectangular field of $n \times m$ cells (the size of the $n \cdot m$ field does not exceed $10^6$ cells, $m \ge 2$), in each cell of which there can be candy. There are $n$ rows and $m$ columns in the field. Let's denote a cell with coordinates $x$ vertically and $y$ horizontally by $(x, y)$. Then the t...
Note first that we can solve the two subtasks independently if we consider the coloring as on a chessboard, since at any move of the robot the parity of $x + y$ does not change. Now replace the moves $(x+1, y-1)$, $(x+1, y+1)$ with moves $(x+1, y)$, $(x+1, y+1)$ respectively. This can be done because we simply shifted ...
[ "data structures", "graph matchings", "greedy" ]
2,500
#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() const int N = 1e6 + 50; string a[N]; int n,m; int ans; void solve(int sum0) { vector<int> v; for (int sum = sum0, ad = 0, pref = 0; sum < n + m; sum += 2, ad++) { vecto...
1612
A
Distance
Let's denote the Manhattan distance between two points $p_1$ (with coordinates $(x_1, y_1)$) and $p_2$ (with coordinates $(x_2, y_2)$) as $d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$. For example, the distance between two points with coordinates $(1, 3)$ and $(4, 2)$ is $|1 - 4| + |3 - 2| = 4$. You are given two points, ...
There is a solution in $O(1)$, but in fact, a solution that checks all points with $x$-coordinate from $0$ to $50$ and $y$-coordinate from $0$ to $50$ is fast enough. There's no need to check any other points, since $d(A, C) + d(B, C) = d(A, B)$ implies that point $C$ is on one of the shortest paths between $A$ and $B$...
[ "brute force", "constructive algorithms" ]
800
t = int(input()) for i in range(t): x, y = map(int, input().split()) xc = -1 yc = -1 for j in range(0, 51): for k in range(0, 51): if 2 * (j + k) == x + y and 2 * (abs(x - j) + abs(y - k)) == x + y: xc, yc = j, k print(xc, yc)
1612
B
Special Permutation
A permutation of length $n$ is an array $p=[p_1,p_2,\dots, p_n]$ which contains every integer from $1$ to $n$ (inclusive) exactly once. For example, $p=[4, 2, 6, 5, 3, 1]$ is a permutation of length $6$. You are given three integers $n$, $a$ and $b$, where $n$ is an even number. Print any permutation of length $n$ tha...
There are many different constructions that give the correct answer, if it exists. In my opinion, one of the most elegant is the following one. $a$ should always be present in the left half, and $b$ should be present in the right half, but the exact order of elements in each half doesn't matter. So, it will never be wr...
[ "constructive algorithms", "greedy" ]
900
t = int(input()) for i in range(t): n, a, b = map(int, input().split()) p = [a] for j in range(n, 0, -1): if j != a and j != b: p.append(j) p.append(b) if(len(p) == n and min(p[0:n//2]) == a and max(p[n//2:n]) == b): print(*p) else: print(-1)
1612
C
Chat Ban
You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something. More precisely, you want to spam the emote triangle of size $k$. It consists of $2k-1$ messages. The first message consists of one emote, the second one — of two emotes, .....
This is a pretty obvious binary search problem. If we get banned after $y$ messages, we also get banned after $y+1$, $y+2$ and so on messages (and vice versa, if we don't get banned after $y$ messages, we also don't get banned after $y-1$, $y-2$ and so on messages). For simplicity, let's split the problem into two part...
[ "binary search", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; long long get(int x) { return x * 1ll * (x + 1) / 2; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int k; long long x; cin >> k...
1612
D
X-Magic Pair
You are given a pair of integers $(a, b)$ and an integer $x$. You can change the pair in two different ways: - set (assign) $a := |a - b|$; - set (assign) $b := |a - b|$, where $|a - b|$ is the absolute difference between $a$ and $b$.The pair $(a, b)$ is called $x$-magic if $x$ is obtainable either as $a$ or as $b$ ...
This problem has a GCD-based solution. Firstly, lets' try to solve it naively. Always suppose that $a > b$. If this is not true, let's swap $a$ and $b$. Firstly, if $b > a - b$, let's do $b := a - b$. Okay, now let's subtract $b$ from $a$ until $b \ge a - b$ again and repeat this algorithm till $a = 0$ or $b = 0$. If, ...
[ "math", "number theory" ]
1,600
#include <bits/stdc++.h> using namespace std; bool get(long long a, long long b, long long x) { if (a == x || b == x) return true; if (a < b) swap(a, b); if (b > a - b) b = a - b; if (x > max(a, b) || a == 0 || b == 0) return false; long long cnt = max(1ll, (a - max(x, b)) / (2 * b)); return g...
1612
E
Messages
Monocarp is a tutor of a group of $n$ students. He communicates with them using a conference in a popular messenger. Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows th...
First of all, let's rewrite the answer using expectation linearity. The expected number of students who read their respective messages is equal to $F_1 + F_2 + \dots + F_n$, where $F_i$ is a random value which is $1$ if the $i$-th student reads the message $m_i$, and $0$ if the $i$-th student doesn't do it. Let's analy...
[ "brute force", "dp", "greedy", "probabilities", "sortings" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = 200043; const int K = 20; vector<int> idx[N]; int m[N], k[N]; bool frac_greater(pair<int, int> a, pair<int, int> b) { return a.first * b.second > a.second * b.first; } int main() { int n; scanf("%d", &n); for(int i = 0; i < n; i++) ...
1612
F
Armor and Weapons
Monocarp plays a computer game. There are $n$ different sets of armor and $m$ different weapons in this game. If a character equips the $i$-th set of armor and wields the $j$-th weapon, their power is usually equal to $i + j$; but some combinations of armor and weapons synergize well. Formally, there is a list of $q$ o...
Among two armor sets, one with the greater index is always better. The same can be said about two different weapons. So, it is always optimal to use and obtain the best possible weapon or armor. This observation allows us to model this problem with dynamic programming or shortest paths: let $dp_{x,y}$ be the minimum ti...
[ "brute force", "dp", "greedy", "shortest paths" ]
2,800
#include<bits/stdc++.h> using namespace std; int n, m; #define x first #define y second typedef pair<int, int> comb; comb norm(const comb& a) { return make_pair(min(a.x, n), min(a.y, m)); } bool good(const comb& a) { return a.x == n || a.y == m; } bool comp(const comb& a, const comb& b) { if(a.x != b...
1612
G
Max Sum Array
You are given an array $c = [c_1, c_2, \dots, c_m]$. An array $a = [a_1, a_2, \dots, a_n]$ is constructed in such a way that it consists of integers $1, 2, \dots, m$, and for each $i \in [1,m]$, there are exactly $c_i$ occurrences of integer $i$ in $a$. So, the number of elements in $a$ is exactly $\sum\limits_{i=1}^{m...
Firstly, let's prove that at first and last positions of $a$ the most frequent elements should be placed (but not necessary the same). WLOG, let's prove that $c_{a_1} \ge c_{a_i}$ for any $i > 1$. By contradiction, let's $p$ be the smallest index such that $c_{a_1} < c_{a_p}$. What happens if we swap them? Since $p$ is...
[ "combinatorics", "constructive algorithms", "greedy", "sortings" ]
2,500
#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...
1613
A
Long Comparison
Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $x$ with $p$ zeros appended to its end. Now Monocarp asks you to compare these two numbers. Can you help him?
First, let's say that appending the number with $p$ zeros is the same as multiplying it by $10^p$. The given numbers are so large that they can't fit into any reasonable integer type. Even if you use a language with unlimited length integers (python, for example) or store the numbers in strings, you should still face t...
[ "implementation", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--){ long long x1, x2; int p1, p2; cin >> x1 >> p1 >> x2 >> p2; int mn = min(p1, p2); p1 -= mn; p2 -= mn; if (p1 >= 7) cout << ">" << endl; else if (p2 >= 7) cout << "<" << endl; else{ for (int i = 0; i ...
1613
B
Absent Remainder
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ pairwise distinct positive integers. Find $\left\lfloor \frac n 2 \right\rfloor$ different pairs of integers $x$ and $y$ such that: - $x \neq y$; - $x$ and $y$ appear in $a$; - $x~mod~y$ doesn't appear in $a$. Note that some $x$ or $y$ can belong to m...
There is one important observation: $x~mod~y<y$. Thus, you can obtain at least $n-1$ pair by choosing $y$ as the minimum number in the sequence and $x$ as anything else. $n-1 \ge \left\lfloor \frac n 2 \right\rfloor$ for any positive $n$. Overall complexity: $O(n)$ per testcase.
[ "greedy", "implementation", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; int mn = *min_element(a.begin(), a.end()); for (int i = 0, k = 0; k < n / 2; ++i) if (a[i] != mn) { cout << a[i] << ' ' << mn << '...
1613
C
Poisoned Dagger
Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $100^{500}$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $i$-th attack is performed at the beginning of the $a_i$-th second from the battle start. The dagger...
Let's find out the total damage for a fixed value of $k$. Since the effect of the poison from the $i$-th attack deals damage $\min(k, a_{i+1} - a_i)$ seconds for $i < n$ and $k$ seconds for $i = n$, then the total damage is $k +\sum\limits_{i=1}^{n-1}{\min(k, a_{i+1} - a_i)}$. We can see that the higher the value of $k...
[ "binary search" ]
1,200
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { int t; cin >> t; while (t--) { int n; li h; cin >> n >> h; vector<li> a(n); for (li &x : a) cin >> x; li l = 1, r = 1e18; while (l <= r) { li m = (l + r) / 2; li sum = m; for (int i = ...
1613
D
MEX Sequences
Let's call a sequence of integers $x_1, x_2, \dots, x_k$ MEX-correct if for all $i$ ($1 \le i \le k$) $|x_i - \operatorname{MEX}(x_1, x_2, \dots, x_i)| \le 1$ holds. Where $\operatorname{MEX}(x_1, \dots, x_k)$ is the minimum non-negative integer that doesn't belong to the set $x_1, \dots, x_k$. For example, $\operatorn...
Let's understand what MEX-correct sequences look like. It turns out there are only two types: $[\underline{0, \dots, 0}, \underline{1, \dots, 1}, \dots, \underline{x-1, \dots, x-1}, \underline{x, \dots, x}]$ and $[\underline{0, \dots, 0}, \underline{1, \dots, 1}, \dots, \underline{x-1, \dots, x-1}, \underline{x+1, \dot...
[ "dp", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; return x; } int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); vector<int> dp1(n + 2), dp2(n + 2); dp1[0] = 1; while (n--) { ...
1613
E
Crazy Robot
There is a grid, consisting of $n$ rows and $m$ columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked. A crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the ...
One way to think about this problem is in game theory terms. Imagine a following game. Two players alternate moves. The first players chooses a direction. The second player chooses a different direction and moves a robot there. The game ends when the robot reaches the lab, and the first player wins. Otherwise, it's a d...
[ "dfs and similar", "graphs" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct cell{ int x, y; }; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main() { int t; cin >> t; while (t--){ int n, m; cin >> n >> m; vector<string> s(n); int lx = -1, ly = -1; forn(i, n){ ...
1613
F
Tree Coloring
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is the vertex $1$. You have to color all vertices of the tree into $n$ colors (also numbered from $1$ to $n$) so that there is exactly one vertex for each color. Let $c_i$ be the color of vertex $i$, and $p_i$ be the ...
When a problem asks us to calculate the number of combinatorial objects that meet some constraints, we can sometimes use inclusion-exclusion formula. Let's try to apply it in this problem. We could use $n-1$ constraints that should not be violated. The $i$-th constraint is formulated as follows: $c_i \ne c_{p_i} - 1$ (...
[ "combinatorics", "divide and conquer", "fft" ]
2,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define fore(i, l, r) for (int i = int(l); i < int(r); ++i) #define sz(a) int((a).size()) const int MOD = 998244353; struct Mint { int val; bool operator==(const Mint& other) { return val == other.val; } ...
1614
A
Divan and a Store
Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well. The store he came to has $n$ different chocolate bars, an...
To solve this problem, let's use the following greedy algorithm. Let's sort the prices of chocolate bars in increasing order, after which we will go from left to right and take chocolates that have a price not less than $l$, but not more than $r$ until we run out of money. The number of chocolate bars that we took will...
[ "brute force", "constructive algorithms", "greedy" ]
800
null
1614
B
Divan and a New Project
The company "Divan's Sofas" is planning to build $n + 1$ different buildings on a coordinate line so that: - the coordinate of each building is an integer number; - no two buildings stand at the same point. Let $x_i$ be the coordinate of the $i$-th building. To get from the building $i$ to the building $j$, Divan spe...
Obviously, the more often we have to go to the $i$ building, the closer it should be to the main office. This implies a greedy algorithm. Let's put the main office at $0$ and sort the rest by $a_i$. Then we put the most visited building at a point with a coordinate of $1$, the second at $-1$, the third at $2$, etc. The...
[ "constructive algorithms", "sortings" ]
1,000
null
1614
C
Divan and bitwise operations
Once Divan analyzed a sequence $a_1, a_2, \ldots, a_n$ consisting of $n$ non-negative integers as follows. He considered each non-empty subsequence of the sequence $a$, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence $a$. A sequence $c$ is a subsequence of a s...
Let's count for each bit how many times it will be included in the answer. Let us now consider the $i$-th bit. Note that if no number contains the included $i$-th bit, then such a bit will never be included in the answer. Otherwise, each of the subsequences contains $i$-th bit even or odd number of times. If a bit ente...
[ "bitmasks", "combinatorics", "constructive algorithms", "dp", "math" ]
1,500
null
1614
D1
Divan and Kostomuksha (easy version)
\textbf{This is the easy version of the problem. The only difference is maximum value of $a_i$.} Once in Kostomuksha Divan found an array $a$ consisting of positive integers. Now he wants to reorder the elements of $a$ to maximize the value of the following function: $$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \...
Let's solve the dynamic programming problem. Let $dp_i$ be the maximum answer for all arrays, the last element of which is divisible by $i$. Let's calculate the dynamics from $C$ to $1$, where $C$ is the maximum value of $a_i$. Initially, $dp_i = cnt_i \cdot i$, where $cnt_i$ is the amount of $a_i = i$. How do we recal...
[ "dp", "number theory" ]
2,100
null
1614
D2
Divan and Kostomuksha (hard version)
\textbf{This is the hard version of the problem. The only difference is maximum value of $a_i$.} Once in Kostomuksha Divan found an array $a$ consisting of positive integers. Now he wants to reorder the elements of $a$ to maximize the value of the following function: $$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \...
To solve $D2$, we can notice that to recalculate the dynamics, we can iterate over all such $j$ that differ from $i$ by multiplying exactly $1$ prime number. Also, to speed up the solution, we can use the linear sieve of Eratosthenes to find primes and factorization. The resulting asymptotics in time: $\mathcal{O}(C\lo...
[ "dp", "number theory" ]
2,300
null
1614
E
Divan and a Cottage
Divan's new cottage is finally complete! However, after a thorough inspection, it turned out that the workers had installed the insulation incorrectly, and now the temperature in the house directly depends on the temperature outside. More precisely, if the temperature in the house is $P$ in the morning, and the street ...
Let $ans_{temp}$ the current answer for temperature $temp$. Before all days, $ans_{temp}$ is considered equal to $temp$. In order to respond to a request with a temperature of $x$, we will just need to output the value of $ans_x$. But how to maintain $ans$? With the help of an implicit tree of segments, at the vertices...
[ "binary search", "data structures" ]
2,600
null
1615
A
Closing The Gap
There are $n$ block towers in a row, where tower $i$ has a height of $a_i$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: - Choose two indices $i$ and $j$ ($1 \leq i, j \leq n$; $i \neq j$), and move a block from t...
If $\max(a) - \min(a)$ is strictly greater than $1$, you can apply the operation on the max and the min respectively, which brings them both closer to each other. In other words, it either decreases $\max(a) - \min(a)$ or leaves it the same. This implies that the answer is always $\leq 1$. Now what remains is determini...
[ "greedy", "math" ]
800
null
1615
B
And It's Non-Zero
You are given an array consisting of all integers from $[l, r]$ inclusive. For example, if $l = 2$ and $r = 5$, the array would be $[2, 3, 4, 5]$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero? A bitwise AND is a binary operation that takes two equal-length binary r...
Let's solve the complement problem: find the largest subsequence of the array such that their bitwise AND is non-zero. Let $x$ be the bitwise and of the optimal subsequence. Since $x \neq 0$, at least one bit must be set in $x$. Let's iterate over that bit, call it $b$, and in each iteration, calculate the largest subs...
[ "bitmasks", "greedy", "math" ]
1,300
null
1615
C
Menorah
There are $n$ candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string $s$, where the $i$-th candle is lit if and only if $s_i=1$. Initially, the candle lights are described by a string $a$. In an operation, you select a candle that is \textbf...
First, let's define the "type" of a candle $i$ to be the string $a_ib_i$. For example, if a candle is currently unlit and must be lit in the end, its type is $01$. It's useful to think about the number of candles of each type because the position of a candle is irrelevant in this problem. Now, let's consider what happe...
[ "brute force", "graphs", "greedy", "math" ]
1,600
null
1615
D
X(or)-mas Tree
'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are $n$ nodes in the tree, connected by $n-1$ edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation. He has $m$ elves come over and admire his...
Let $\text{count}(x)$ be the number of $1$-bits in an integer $x$. Notice that $\text{count}(x \oplus y)\mod 2$ = $\text{count}(x) \mod 2 \oplus \text{count}(y) \mod 2$. This means that you can replace each integer $x$ on the tree with $\text{count}(x) \mod 2$. Note that you can pretend the initial given edges are also...
[ "bitmasks", "dfs and similar", "dsu", "graphs", "trees" ]
2,200
null
1615
E
Purple Crayon
Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game. The game works as follows: there is a tree of size $n$, rooted at node $1$, where each node is initially white. Red and ...
After expanding the expression given in the statement (by replacing $w$ with $n - r - b$), it reduces to $r \cdot (n - r) - b \cdot (n - b)$. This means that in Blue's turn, his only goal is to maximize $b \cdot (n - b)$. To maximize the value of that function, it's optimal to pick the value of $b$ that is closest to $...
[ "data structures", "dfs and similar", "games", "graphs", "greedy", "math", "sortings", "trees" ]
2,400
null
1615
F
LEGOndary Grandmaster
After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height $1$ and length $n$, some positions of which are occupied by $1$ by $1$ Lego pieces. In one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or ad...
First, let's consider a fixed pair of strings $s$ and $t$, and find a simple way to calculate the amount of time it takes. Key observation: Flip every bit at an even position in both strings $s$ and $t$. Now, the operation is equivalent to swapping two adjacent bits of $s$. This is because the operation is equivalent t...
[ "combinatorics", "dp", "math" ]
2,800
null
1615
G
Maximum Adjacent Pairs
You are given an array $a$ consisting of $n$ non-negative integers. You have to replace each $0$ in $a$ with an integer from $1$ to $n$ (different elements equal to $0$ can be replaced by different integers). The value of the array you obtain is the number of integers $k$ from $1$ to $n$ such that the following condi...
Let's consider each segment of zeroes in our sequence. Each of these segments has either odd or even length. If a segment has length $2m + 1$ (it is odd), then it can be used to create $m$ pairs of neighboring elements, and an additional pair for either the number right before the segment, or for the number right after...
[ "constructive algorithms", "graph matchings" ]
3,300
null
1615
H
Reindeer Games
There are $n$ reindeer at the North Pole, all battling for the highest spot on the "Top Reindeer" leaderboard on the front page of CodeNorses (a popular competitive reindeer gaming website). Interestingly, the "Top Reindeer" title is just a measure of upvotes and has nothing to do with their skill level in the reindeer...
Let's try to find a nice lower bound for the answer. Let's denote a requirement of two nodes $u$ and $v$ by a directed edge $u\to v$. We can observe that if there are two nodes $u$ and $v$ such that there's a requirement $u\to v$ (or a path of requirements from $u$ to $v$), then we will need to do at least $a_u-a_v$ op...
[ "binary search", "constructive algorithms", "data structures", "divide and conquer", "flows", "graphs", "shortest paths" ]
3,000
null
1616
A
Integer Diversity
You are given $n$ integers $a_1, a_2, \ldots, a_n$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $x \to (-x)$). What is the maximum number of different values in the array you can achieve?
At first, let's replace $a_i$ with $|a_i|$. Let $f(x)$ denote the number of vaues in the array equal to $x$ after the replacement (or, equal to $x$ or $-x$ before). Then, for the zero we can only get $\min(1, f(0))$ different values. And for any other number $x > 0$, we can get $\min(2, f(x))$ different numbers in the ...
[ "implementation" ]
800
null
1616
B
Mirror in the String
You have a string $s_1 s_2 \ldots s_n$ and you stand on the left of the string looking right. You want to choose an index $k$ ($1 \le k \le n$) and place a mirror after the $k$-th letter, so that what you see is $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$. What is the lexicographically smallest string you can see? A...
Let's compare $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$ and $s_1 s_2 \ldots s_{k+1} s_{k+1} s_{k} \ldots s_1$. Note that they have a long common prefix $s_1, s_2, \ldots, s_k$. And the next pair of characters to compare is $s_{k+1}$ and $s_k$. So, unless $s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$ is a prefix of ...
[ "greedy", "strings" ]
1,100
null
1616
C
Representative Edges
An array $a_1, a_2, \ldots, a_n$ is good if and only if for every subsegment $1 \leq l \leq r \leq n$, the following holds: $a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1)$. You are given an array of integers $a_1, a_2, \ldots, a_n$. In one operation, you can replace any one element of this ...
Note that if the array is good $a_{k+2}-a_{k+1}=a_{k+1}-a_k$. In other words, the array form an arithmetic progression. We can either fix an arbitrary element and set all other elements equal to it (giving us the lower bound $n-1$ on the answer). Or, to solve the remaining case, we can fix any two elements that are in ...
[ "brute force", "geometry", "implementation", "math" ]
1,500
null
1616
D
Keep the Average High
You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $x$. You need to select the maximum number of elements in the array, such that for every subsegment $a_l, a_{l + 1}, \ldots, a_r$ containing strictly more than one element $(l < r)$, either: - At least one element on this subsegment is \textbf{...
Note that $a_l + a_{l+1} + \ldots + a_r \geq x \cdot (r - l + 1) \Rightarrow (a_l - x) + (a_{l+1} - x) + \ldots + (a_r - x) \geq 0$. After subtracting $x$ from all elements, the problem is reduced to choosing the maximum number of elements with only non-negative sum contiguous elements. Note that there should be a nega...
[ "dp", "greedy", "math" ]
2,000
null
1616
E
Lexicographically Small Enough
You are given two strings $s$ and $t$ of equal length $n$. In one move, you can swap any two adjacent characters of the string $s$. You need to find the minimal number of operations you need to make string $s$ lexicographically smaller than string $t$. A string $a$ is lexicographically smaller than a string $b$ if an...
Let's iterate over characters one by one and see the minimum number of operations required to make the string smaller with the fixed common prefix. Every time, we need to update the answer with the minimum number of moves required to make our prefix equal to some other prefix (iterating over characters smaller than the...
[ "brute force", "data structures", "greedy", "strings" ]
2,200
null
1616
F
Tricolor Triangles
You are given a simple undirected graph with $n$ vertices and $m$ edges. Edge $i$ is colored in the color $c_i$, which is either $1$, $2$, or $3$, or left uncolored (in this case, $c_i = -1$). You need to color all of the uncolored edges in such a way that for any three pairwise adjacent vertices $1 \leq a < b < c \le...
$c_1, c_2, c_3$ form a valid triangle coloring if and only if $c_1 + c_2 + c_3 = 3k$ for some $k \in \mathbb{Z}$ Hence we can solve our problem with the simple Gaussian elemeniation. Complexity depends on your implementation, and you can use bitset to optimize it by $64$ times. Note that the number of triangles is boun...
[ "brute force", "graphs", "math", "matrices" ]
2,900
null
1616
G
Just Add an Edge
You are given a directed acyclic graph with $n$ vertices and $m$ edges. For all edges $a \to b$ in the graph, $a < b$ holds. You need to find the number of pairs of vertices $x$, $y$, such that $x > y$ and after adding the edge $x \to y$ to the graph, it has a Hamiltonian path.
First of all, we have to check whether there is a Hamiltonian path in the original graph. In this case, the number is ${n \choose 2}$ Otherwise, addition of the edge $a \to b$ can only add a Hamiltonian path of the form: $(1 \to \ldots \to a - 1) \to \ldots \to b$ $b \to a$ $a \to \ldots \to (b \to \ldots n)$ And these...
[ "dfs and similar", "dp", "graphs" ]
3,500
null
1616
H
Keep XOR Low
You are given an array $a_1, a_2, \ldots, a_n$ and an integer $x$. Find the number of non-empty subsets of indices of this array $1 \leq b_1 < b_2 < \ldots < b_k \leq n$, such that for all pairs $(i, j)$ where $1 \leq i < j \leq k$, the inequality $a_{b_i} \oplus a_{b_j} \leq x$ is held. Here, $\oplus$ denotes the bit...
First of all, we should divide all elements into groups by the prefix before the leading bit $i$ of $x$, as elements from different groups will definitely yield invalid answers. In one group, we either choose elements only from the group with the same bit $i$, then we can choose an artbirary subset. Or we need to solve...
[ "bitmasks", "combinatorics", "data structures", "divide and conquer", "dp", "math" ]
3,000
null
1617
A
Forbidden Subsequence
You are given strings $S$ and $T$, consisting of lowercase English letters. It is guaranteed that $T$ is a permutation of the string abc. Find string $S'$, the \textbf{lexicographically smallest} permutation of $S$ such that $T$ is \textbf{not} a subsequence of $S'$. String $a$ is a permutation of string $b$ if the n...
When is the lexicographically smallest permutation of $S$ (i.e. the sorted string) not the answer? If there are no occurrences of a, b or c in $S$, sort $S$ and output it. Else, if $T \ne$ abc, sort $S$ and output it. Else, output all a, then all c, then all b, then the rest of the string sorted. Originally, the author...
[ "constructive algorithms", "greedy", "sortings", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define all(x) x.begin(), x.end() int main() { int T; cin >> T; while(T--) { string s, t; cin >> s >> t; sort(all(s)); vector<int> cnt(26, 0); for(auto x: s)cnt[x - 'a']++; if(t != "abc" || !cnt[0] || !cnt[1] || !c...
1617
B
GCD Problem
Given a positive integer $n$. Find three \textbf{distinct} positive integers $a$, $b$, $c$ such that $a + b + c = n$ and $\operatorname{gcd}(a, b) = c$, where $\operatorname{gcd}(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
There must exist a solution for $c=1$ under the given constraints. Key observation: there always exists a solution with $c = 1$ under the given constraints. We set $n \ge 10$ because there is no solution when $1 \le n \le 5$ or $n = 7$. Solution 1: Brute force from $a = 2, 3, 4, \dots$ and calculate the value of $b$ ($...
[ "brute force", "constructive algorithms", "math", "number theory" ]
900
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin>>n; if (n%2==0) cout<<"2 "<<(n-1)-2<<" 1\n"; else { int cur=(n-1)/2; if (cur%2==0) cout<<cur-1<<" "<<cur+1<<" "<<1<<endl; else cout<<cur-2<<" "<<cur+2<<" "<<1<<endl; } } signed main(){ int t; cin>>t; while (t--) solve(); }
1617
C
Paprika and Permutation
Paprika loves permutations. She has an array $a_1, a_2, \dots, a_n$. She wants to make the array a \textbf{permutation} of integers $1$ to $n$. In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers $i$ ($1 \le i \le n$) and $x$ ($x > 0$), then perform $a_...
For any two positive integers $x$, $y$ that satisfy $x \ge y$, what is the maximum value of $x \bmod y$? Consider the following input: $n = 4$, $a = [3, 3, 10, 10]$. Sometimes, we don't need to do anything to some $a_i$. When do we have to make operations, and when do we not have to? Key observation: $x \bmod y < \frac...
[ "binary search", "greedy", "math", "sortings" ]
1,300
#include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t>0){ t--; int n; cin >> n; set<int> st; for(int i=1;i<=n;i++){st.insert(i);} vector<int> rem; for(int i=0;i<n;i++){ ...
1617
D1
Too Many Impostors (easy version)
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions. There are $n$ players labelled from $1$ to $n$. \textbf{It is guaranteed that $n$ is a multiple of $3$.} Among them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is ...
The weird constraint, $\frac{n}{3} < k < \frac{2n}{3}$, is crucial. If you know the index of one crewmate and one impostor, how to find the roles of other $n-2$ players in exactly $n-2$ queries? Query players ($1, 2, 3$), ($2, 3, 4$), $\dots$, ($n-1, n, 1$), ($n, 1, 2$). After that, you can surely find out the index of...
[ "constructive algorithms", "implementation", "interactive" ]
1,800
#include <bits/stdc++.h> using namespace std; void solve() { int N; cin >> N; int res[N]; for(int i=0; i<N; i++) { cout << "? " << i + 1 << " " << (i+1) % N + 1 << " " << (i+2) % N + 1 << endl; cin >> res[i]; } vector<int> imp; for(int i=0; i<N; i++) { if(res[i] != r...
1617
D2
Too Many Impostors (hard version)
This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions. There are $n$ players labelled from $1$ to $n$. \textbf{It is guaranteed that $n$ is a multiple of $3$.} Among them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is ...
Aim to find an impostor and a crewmate's index in $\frac{n}{3} + c$ queries, with $c$ being a small constant. Consider splitting the $n$ players into groups of $3$ (and query each group) in order to reach the goal in Hint 1. What is special about the results of the $\frac{n}{3}$ queries? Firstly query ($1, 2, 3$), ($4,...
[ "constructive algorithms", "implementation", "interactive", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; int query(int a, int b, int c) { cout << "? " << a << ' ' << b << ' ' << c << endl; int r; cin >> r; return r; } void solve(int tc) { int n; cin >> n; int a[n+1], role[n+1]; for(int i=1; i+2<=n; i+=3) a[i] = query(i, i+1, i+2); int imp, crew; ...
1617
E
Christmas Chocolates
Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains $n$ chocolates. The $i$-th chocolate has a non-negative integer type $a_i$. Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all $a_i$ are \textbf{distinct}). Icy want...
Translate the problem into a graph problem. What feature of the graph is it asking about? Draw out the graph, for $a_i \le 10$. What special property does the graph have? Any specific algorithm to solve the problem (in Hint 1)? In graph terms, the problem is as follows: in a graph with infinite nodes, two nodes $x$ and...
[ "dfs and similar", "dp", "games", "graphs", "implementation", "math", "number theory", "shortest paths", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; int f(int x){ for(int i=0;;i++){ if((1<<i)>=x){ return (1<<i)-x; } } } using pi=pair<int,int>; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; map<int,pair<pi,pi>> mp; priority_queue<in...
1618
A
Polycarp and Sums of Subsequences
Polycarp had an array $a$ of $3$ \textbf{positive} integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $b$ of $7$ integers. For example, if $a = \{1, 4, 3\}$, then Polycarp wrote out $1$, $4$, $3$, $1 + 4 = 5$, $1 + 3 = 4$, $4 + 3 = 7$, $1 ...
The order of elements in $a$ doesn't matter. If there is at least one correct array $a$, then we can sort it and get the answer in which $a_1 \le a_2 \le a_3$. Therefore, we can always find a sorted array. Suppose that $a_1 \le a_2 \le a_3$. Then $b_1 = a_1$, $b_2 = a_2$, $b_7 = a_1 + a_2 + a_3$. We can find $a_3$ as $...
[ "math", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) { vector <int> b(7); for(int i = 0; i < 7; i++) cin >> b[i]; cout << b[0] << ' ' << b[1] << ...
1618
B
Missing Bigram
Polycarp has come up with a new game to play with you. He calls it "A missing bigram". A bigram of a word is a sequence of two adjacent letters in it. For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba". The game goes as follows. First, Polycarp comes up with a word, consisting only of...
Consider a full sequence of bigrams for some word. The first bigram consists of letters $1$ and $2$ of the word. The second bigram consists of letters $2$ and $3$. The $i$-th bigram consists of letters $i$ and $i+1$. After one bigram is removed, there becomes two adjacent bigrams such that one consists of letters $i$ a...
[ "implementation" ]
800
for _ in range(int(input())): n = int(input()) s = input().split() for i in range(n - 3): if s[i][1] != s[i + 1][0]: s.insert(i + 1, s[i][1] + s[i + 1][0]) break else: s.append(s[-1][1] + 'a') print(s[0][0], end="") for i in range(n - 1): print(s[i][1], end="") print()
1618
C
Paint the Array
You are given an array $a$ consisting of $n$ positive integers. You have to choose a positive integer $d$ and paint all elements into two colors. All elements which are divisible by $d$ will be painted red, and all other elements will be painted blue. The coloring is called beautiful if there are no pairs of adjacent ...
What does it mean that no pair of adjacent elements should have the same color? It means that either all elements on odd positions are blue and all elements on even positions are red, or vice versa. So, we need to check these two cases. Let's try to solve a case when we have to find a number $d$ such that $a_1, a_3, \d...
[ "math" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<long long> a(n); for(int i = 0; i < n; i++) { cin >> a[i]; } vector<long long> g(a.begin(), a.begin() + 2); for(int i = 0; i < n; i++) { g[i % 2] = __gcd(g[i % 2], a[i]); }...
1618
D
Array and Operations
You are given an array $a$ of $n$ integers, and another integer $k$ such that $2k \le n$. You have to perform \textbf{exactly} $k$ operations with this array. In one operation, you have to choose two elements of the array (let them be $a_i$ and $a_j$; they can be equal or different, but \textbf{their positions in the ...
It's kinda obvious that we have to choose the $k$ greatest elements of the array as the denominators in the operations: suppose we haven't chosen one of them, but have chosen a lesser element as a denominator; if we swap them, the total score won't decrease. It is a bit harder to prove that the numerators of the fracti...
[ "dp", "greedy", "math" ]
1,300
def solve(): n, k = map(int, input().split()) a = list(map(int, input().split())) a = sorted(a) cost = sum(a[0:n-2*k]) + sum(map(lambda x: a[x+n-2*k] // a[x+n-k], range(0, k))) print(cost) t = int(input()) for i in range(t): solve()
1618
E
Singers' Tour
$n$ towns are arranged in a circle sequentially. The towns are numbered from $1$ to $n$ in clockwise order. In the $i$-th town, there lives a singer with a repertoire of $a_i$ minutes for each $i \in [1, n]$. Each singer visited all $n$ towns in clockwise order, starting with the town he lives in, and gave exactly one...
First, $b_i = a_i + 2 \cdot a_{i - 1} + \dots + i \cdot a_1 + (i + 1) \cdot a_n + \dots n \cdot a_{i + 1}$. Consider the sum $b_1 + b_2 + \cdots + b_n$. If we substitute the formula of $b_i$ then for every $i = 1, 2, \dots, n$ the coefficient at $a_i$ will be equal to $\frac{n \cdot (n + 1)}{2}$, so we can find the sum...
[ "constructive algorithms", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; using li = long long; const int N = 50013; int b[N]; int a[N]; void solve() { int n; cin >> n; li sumb = 0; for(int i = 0; i < n; i++) { cin >> b[i]; sumb += b[i]; } li d = n * 1ll * (n + 1) / 2; if(sumb % d != 0) { ...
1618
F
Reverse
You are given two positive integers $x$ and $y$. You can perform the following operation with $x$: write it in its binary form without leading zeros, add $0$ or $1$ to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of $x$. For example: - $34$ can be turne...
There are two main approaches to this problem. Approach $1$. Let's analyze how the binary representation of $x$ changes after the operation. If there are no zeroes at the end of it, appending $0$ just reverses the binary representation; if there are any trailing zeroes, we remove them and reverse the binary representat...
[ "bitmasks", "constructive algorithms", "dfs and similar", "implementation", "math", "strings" ]
2,000
#include<bits/stdc++.h> using namespace std; string go(string t) { while(t.back() == '0') t.pop_back(); reverse(t.begin(), t.end()); return t; } string to_bin(long long x) { if(x == 0) return ""; else { string s = to_bin(x / 2); s.push_back(char('0' + x % 2)); ...