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
1635
F
Closest Pair
There are $n$ weighted points on the $OX$-axis. The coordinate and the weight of the $i$-th point is $x_i$ and $w_i$, respectively. All points have distinct coordinates and positive weights. Also, $x_i < x_{i + 1}$ holds for any $1 \leq i < n$. The weighted distance between $i$-th point and $j$-th point is defined as ...
First of all, let's solve the problem for the whole array. Define $L_i$ as the biggest $j$ satisfying $j < i$ and $w_j \leq w_i$, and $R_i$ as the smallest $j$ satisfying $j > i$ and $w_j \leq w_i$. Then, we consider $2n$ pairs of points: $(L_i, i)$ and $(i, R_i)$ for each $1 \leq i \leq n$. In conclusion, the closest ...
[ "data structures", "greedy" ]
2,800
#include <bits/stdc++.h> using namespace std; const int N = 300005; const long long INF = 1ll << 62; vector <int> useful_pair[N]; vector <pair <int, int>> queries[N]; long long bit[N]; void modify(int p, long long v) { for (int i = p; i > 0; i -= i & (-i)) { bit[i] = min(bit[i], v); } } long long q...
1637
A
Sorting Parts
You have an array $a$ of length $n$. You can \textbf{exactly} once select an integer $len$ between $1$ and $n - 1$ inclusively, and then sort in non-decreasing order the prefix of the array of length $len$ and the suffix of the array of length $n - len$ independently. For example, if the array is $a = [3, 1, 4, 5, 2]$...
Consider two cases: The array is already sorted. THe array is not sorted. In the first case, sorting any prefix and any suffix does not change the array. So the array will always remain sorted so the answer is "NO". In the second case, there are two elements with indexes $i$ and $j$, such that $i < j$ and $a_i > a_j$. ...
[ "brute force", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n; cin >> n; vector<int> a(n); for (auto& u : a) cin >> u; if (!is_sorted(a.begin(), a.end())) cout << "YES\n"; else ...
1637
B
MEX and Array
Let there be an array $b_1, b_2, \ldots, b_k$. Let there be a partition of this array into segments $[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$, where $l_1 = 1$, $r_c = k$, and for any $2 \leq i \leq c$ holds that $r_{i-1} + 1 = l_i$. In other words, each element of the array belongs to exactly one segment. Let's def...
We show, that replacing a segment of length $k$ ($k > 1$) with segments of length $1$ does not decrease the cost of the partition. Consider two cases: The segment does not contain $0$. The segment contains $0$. In the first case the contribution of the segment equals to $1$ (because $mex = 0$), but the contribution of ...
[ "brute force", "dp", "greedy", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n; cin >> n; vector<int> a(n); for (auto& u : a) cin >> u; int ans = 0; for (int i = 0; i < n; i++) { ans += (i + 1) * (n ...
1637
C
Andrew and Stones
Andrew has $n$ piles with stones. The $i$-th pile contains $a_i$ stones. He wants to make his table clean so he decided to put every stone either to the $1$-st or the $n$-th pile. Andrew can perform the following operation any number of times: choose $3$ indices $1 \le i < j < k \le n$, such that the $j$-th pile conta...
Consider $2$ cases when the answer is $-1$ for sure: For all $1 < i < n$: $a_i = 1$. In this case, it's not possible to make any operation and not all stones are in piles $1$ or $n$. $n = 3$ and $a_2$ is odd. Then after any operation this number will remain odd, so it can never become equal to $0$. Later it will become...
[ "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (auto &x : a) cin >> x; if (*max_element(a.begin() + 1, a.end() - 1) == 1 || (n == 3 && a[1] % 2 == 1)) { cout << "-1\n"; return; } long long answer = 0; for ...
1637
D
Yet Another Minimization Problem
You are given two arrays $a$ and $b$, both of length $n$. You can perform the following operation any number of times (possibly zero): select an index $i$ ($1 \leq i \leq n$) and swap $a_i$ and $b_i$. Let's define the cost of the array $a$ as $\sum_{i=1}^{n} \sum_{j=i + 1}^{n} (a_i + a_j)^2$. Similarly, the cost of t...
The $cost$ of the array $a$ equals to $\sum_{i=1}^{n} \sum_{j=i + 1}^{n} (a_i + a_j)^2 = \sum_{i=1}^{n} \sum_{j=i + 1}^{n} (a_i^2 + a_j^2 + 2a_i a_j)$. Let $s = \sum_{i=1}^{n} a_i$. Then $cost = (n - 1) \cdot \sum_{i=1}^{n} a_i^2 + \sum_{i=1}^n (a_i \cdot (s - a_i)) = (n - 1) \cdot \sum_{i=1}^{n} a_i^2 + s^2 - \sum_{i=...
[ "dp", "greedy", "math" ]
1,800
#include <bits/stdc++.h> using namespace std; constexpr int MAXSUM = 100 * 100 + 10; int sqr(int x) { return x * x; } void solve() { int n; cin >> n; vector<int> a(n), b(n); for (auto& u : a) cin >> u; for (auto& u : b) cin >> u; int sumMin = 0, sumMax = 0, sumSq = ...
1637
E
Best Pair
You are given an array $a$ of length $n$. Let $cnt_x$ be the number of elements from the array which are equal to $x$. Let's also define $f(x, y)$ as $(cnt_x + cnt_y) \cdot (x + y)$. Also you are given $m$ bad pairs $(x_i, y_i)$. Note that if $(x, y)$ is a bad pair, then $(y, x)$ is also bad. Your task is to find the...
Let's fix $x$ and iterate over $cnt_y \le cnt_x$. Then we need to find maximum $y$ over all elements that occurs exactly $cnt_y$ times, such that $x \neq y$ and pair $(x, y)$ is not bad. To do that, we will just iterate over all elements that occurs exactly $cnt_y$ times in not increasing order, while pair $(x, y)$ is ...
[ "binary search", "brute force", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<int> a(n); map<int, int> cnt; for (auto &x : a) { cin >> x; cnt[x]++; } vector<pair<int, int>> bad_pairs; bad_pairs.reserve(2 * m); for (int i = 0; i < m; i++) { i...
1637
F
Towers
You are given a tree with $n$ vertices numbered from $1$ to $n$. The height of the $i$-th vertex is $h_i$. You can place any number of towers into vertices, for each tower you can choose which vertex to put it in, as well as choose its efficiency. Setting up a tower with efficiency $e$ costs $e$ coins, where $e > 0$. ...
Main solution: Let's consider all leaves. If $v$ is a leaf, then all paths, which cover $v$ should start in $v$. Then let's increase heights of all towers in the leaves by $1$ (it's necessary) and decrease all $h_v$ by $1$. Now we should remove all leaves with $h_v = 0$ (they will be already covered). We will repeat th...
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> h(n); for (int i = 0; i < n; ++i) cin >> h[i]; vector<vector<int>> g(n); for (int i = 0; i + 1 < n; ++i) { int u, v; cin >> u >> v; --...
1637
G
Birthday
Vitaly gave Maxim $n$ numbers $1, 2, \ldots, n$ for his $16$-th birthday. Maxim was tired of playing board games during the celebration, so he decided to play with these numbers. In one step Maxim can choose two numbers $x$ and $y$ from the numbers he has, throw them away, and add two numbers $x + y$ and $|x - y|$ inst...
The answer is $-1$ only if $n = 2$. It will become clear later. Let all numbers be equal to $val$ after all steps. Consider the moves in reverse order: numbers $x$ and $y$ are obtained from $\frac{x + y}{2}$ and $\frac{|x - y|}{2}$. If numbers $x$ and $y$ are multiples of an odd number $p > 1$, then numbers $\frac{x + ...
[ "constructive algorithms", "greedy", "math" ]
3,000
#include <bits/stdc++.h> using namespace std; vector<pair<int, int>> ops; vector<int> a; void rec(int n, int coeff) { if (n <= 2) { for (int i = 1; i <= n; i++) a.push_back(i * coeff); return; } int p = 1; while (p * 2 <= n) p *= 2; if (p == n) { a.push_ba...
1637
H
Minimize Inversions Number
You are given a permutation $p$ of length $n$. You can choose any subsequence, remove it from the permutation, and insert it at the beginning of the permutation keeping the same order. For every $k$ from $0$ to $n$, find the minimal possible number of inversions in the permutation after you choose a subsequence of le...
To simplify the explanation, we will represent a permutation as a set of points $(i, p_i)$. $\bf{Lemma}$: Let's consider some selected subsequence. Then there always exists such sequence of the same length, so that if we select it instead, the number of inversions won't increase, for which the following condition is sa...
[ "data structures", "greedy", "math", "sortings" ]
3,500
#include <bits/stdc++.h> using namespace std; struct binary_index_tree { int n; vector<int> bit; binary_index_tree(int n) : n(n), bit(n + 1) {} void increase(int pos) { for (pos++; pos <= n; pos += pos & -pos) bit[pos]++; } int query(int pref) const { int sum ...
1638
A
Reverse
You are given a permutation $p_1, p_2, \ldots, p_n$ of length $n$. You have to choose two integers $l,r$ ($1 \le l \le r \le n$) and reverse the subsegment $[l,r]$ of the permutation. The permutation will become $p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$. Find the lexicographically s...
When is it best for the permutation to remain unchanged? What elements are obviously optimal and should remain as they are? Find the first non-optimal element. What's the best way to fix it? Let $p_i$ be the first element such that $p_i \neq i$. For the prefix of elements $p_1=1,p_2=2, \dots ,p_{i-1}=i-1$ we do not nee...
[ "constructive algorithms", "greedy", "math" ]
800
null
1638
B
Odd Swap Sort
You are given an array $a_1, a_2, \dots, a_n$. You can perform operations on the array. In each operation you can choose an integer $i$ ($1 \le i < n$), and swap elements $a_i$ and $a_{i+1}$ of the array, if $a_i + a_{i+1}$ is odd. Determine whether it can be sorted in non-decreasing order using this operation any num...
Replace the condition "$a_i+a_{i+1}$ is odd" with something easier to work with. The condition means that we only swap elements of different parity. Now, make some observations. What happens if there are some elements $a_i$ and $a_j$ ($i<j$) of the same parity, such that $a_i>a_j$? If such pair exists, the answer is "N...
[ "data structures", "math", "sortings" ]
1,100
null
1638
C
Inversion Graph
You are given a permutation $p_1, p_2, \dots, p_n$. Then, an undirected graph is constructed in the following way: add an edge between vertices $i$, $j$ such that $i < j$ if and only if $p_i > p_j$. Your task is to count the number of connected components in this graph. Two vertices $u$ and $v$ belong to the same conn...
The key idea is to start merging from the beginning using a stack. Assume that the connected components are always segments in the permutation (this solution also proves this by induction). We will iterate the prefix and maintain in our stack the minimum/maximum element of all the segments in order. When we increase th...
[ "data structures", "dsu", "graphs", "math" ]
1,300
null
1638
D
Big Brush
You found a painting on a canvas of size $n \times m$. The canvas can be represented as a grid with $n$ rows and $m$ columns. Each cell has some color. Cell $(i, j)$ has color $c_{i,j}$. Near the painting you also found a brush in the shape of a $2 \times 2$ square, so the canvas was surely painted in the following wa...
Let's try to build the solution from the last operation to the first operation. The last operation can be any $2 \times 2$ square painted in a single color. If there is no such square, it is clearly impossible. Otherwise, this square being the last operation implies that we could previously color its cells in any color...
[ "constructive algorithms", "data structures", "greedy", "implementation" ]
2,000
null
1638
E
Colorful Operations
You have an array $a_1,a_2, \dots, a_n$. Each element initially has value $0$ and color $1$. You are also given $q$ queries to perform: - Color $l$ $r$ $c$: Change the color of elements $a_l,a_{l+1},\cdots,a_r$ to $c$ ($1 \le l \le r \le n$, $1 \le c \le n$). - Add $c$ $x$: Add $x$ to values of all elements $a_i$ ($1 ...
In the first part, let's consider that for all update operations $l=r$. The idea is not to update each element in an Add operation and instead, keeping an array $lazy[color]$ which stores for each color the total sum we must add to it (because we didn't do it when we had to). Lets's discuss each operation: Update $l$ $...
[ "brute force", "data structures", "implementation" ]
2,400
null
1638
F
Two Posters
You want to advertise your new business, so you are going to place two posters on a billboard in the city center. The billboard consists of $n$ vertical panels of width $1$ and varying integer heights, held together by a horizontal bar. The $i$-th of the $n$ panels has height $h_i$. Initially, all panels hang down fro...
There are many ways in which two posters can be positioned, therefore, we split the problem into multiple sub-problems. Consider the following cases. The two posters share no common panel. The two posters share a range of common panels. Here, there are two sub-cases. The second poster does not share all its panels with...
[ "brute force", "data structures", "greedy", "two pointers" ]
3,200
null
1641
A
Great Sequence
A sequence of positive integers is called great for a positive integer $x$, if we can split it into pairs in such a way that in each pair the first number multiplied by $x$ is equal to the second number. More formally, a sequence $a$ of size $n$ is great for a positive integer $x$, if $n$ is even and there exists a per...
Let's look at the minimal integer in our multiset. Since it can be matched with only one integer, we need to create such pair. Thus, we can maintain the current multiset. We need to take the minimal element out of it (and delete it from it), find a pair for it, and delete it from the multiset if such pair exists, or ad...
[ "brute force", "greedy", "sortings" ]
1,200
#include <iostream> #include <vector> #include <algorithm> using namespace std; signed main() { (*cin.tie(0)).sync_with_stdio(0); int t; cin >> t; while (t--) { int n; int64_t x; cin >> n >> x; vector<int64_t> ar(n); for (auto& it : ar) cin >> it; ...
1641
B
Repetitions Decoding
Olya has an array of integers $a_1, a_2, \ldots, a_n$. She wants to split it into tandem repeats. Since it's rarely possible, before that she wants to perform the following operation several (possibly, zero) number of times: insert a pair of equal numbers into an arbitrary position. Help her! More formally: - A tande...
Let's prove that we can turn the array into a concatenation of tandem repeats using the operations given if and only if every letter occurs an even number of times If there is such letter $x$ that it occurs an odd number of times there is no such sequence of operations, since the parity of the number of occurrences if ...
[ "constructive algorithms", "implementation", "sortings" ]
2,000
#define _USE_MATH_DEFINES #include <algorithm> #include <array> #include <bitset> #include <cassert> #include <chrono> #include <cmath> #include <complex> #include <deque> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <map> #include <math.h> #include <numeric...
1641
C
Anonymity Is Important
In the work of a doctor, it is important to maintain the anonymity of clients and the results of tests. The test results are sent to everyone personally by email, but people are very impatient and they want to know the results right away. That's why in the testing lab "De-vitro" doctors came up with an experimental wa...
If $i$-th person is not ill, the following query exists: $0 \ l \ r \ 0$, such that $l \le i \le r$. Otherwise, the person's status is either unknown or they are ill. If $i$-th person is ill, the following query exists:$0 \ l \ r \ 1$, such that $l \le i \le r$, and every person $i$ such that $l \leq j \leq r$ are not ...
[ "binary search", "brute force", "data structures", "dsu", "greedy", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; #define fi first #define se second #define pb push_back #define eb emplace_back #define mp make_pair #define gcd __gcd #define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define rep(i, n) for (int i=0; i<(n); i++) #define rep1(i, n) for (int i=1; i<=(n...
1641
D
Two Arrays
Sam changed his school and on the first biology lesson he got a very interesting task about genes. You are given $n$ arrays, the $i$-th of them contains $m$ different integers — $a_{i,1}, a_{i,2},\ldots,a_{i,m}$. Also you are given an array of integers $w$ of length $n$. Find the minimum value of $w_i + w_j$ among al...
Let's maintain a set of arrays of length $m$, add new arrays there, delete arrays from this set and understand if the set has a suitable pair for some array. To do this, let's consider a pair of sorted arrays $a$ and $b$ of length $m$. Let's write out all subsets of the array $a$. Then we start a counter $count$, and f...
[ "bitmasks", "brute force", "combinatorics", "greedy", "hashing", "math", "two pointers" ]
2,700
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/rope> using namespace std; #define fi first #define se second #define pb push_back #define eb emplace_back #define mp make_pair #define gcd __gcd #define fastio ios_base::sync_with_stdio(0); cin.tie(...
1641
E
Special Positions
You are given an array $a$ of length $n$. Also you are given $m$ distinct positions $p_1, p_2, \ldots, p_m$ ($1 \leq p_i \leq n$). A \textbf{non-empty} subset of these positions $T$ is randomly selected with equal probability and the following value is calculated: $$\sum_{i=1}^{n} (a_i \cdot \min_{j \in T} \left|i - j...
First of all, calculate for each index the total sum of distances among all subsets if the closest selected position is to the left. Let $suf_i = 2^{cnt_i}$, where $cnt_i$ - the number of cpecial positions at $i$ or to the right of $i$ (if $i > n$ then $cnt_i = 0$). Let $special_i = 1$ if position $i$ is special, other...
[ "combinatorics", "divide and conquer", "fft", "math" ]
3,300
#include <bits/stdc++.h> using namespace std; constexpr int MOD = 998244353, ROOT = 3; int add(int a, int b) { a += b; return a - MOD * (a >= MOD); } int sub(int a, int b) { a -= b; return a + MOD * (a < 0); } int mult(int a, int b) { return 1ll * a * b % MOD; } int power(int a, int b) {...
1641
F
Covering Circle
Sam started playing with round buckets in the sandbox, while also scattering pebbles. His mom decided to buy him a new bucket, so she needs to solve the following task. You are given $n$ distinct points with integer coordinates $A_1, A_2, \ldots, A_n$. All points were generated from the square $[-10^8, 10^8] \times [-...
If the answer is $r$ let's consider $n$ circles $C_1, C_2, \ldots, C_n$ with centers $A_1, A_2, \ldots, A_n$ and radius $r$. If a required circle with radius $r$ exists it should be true, that $k$ circles $C_{i_1}, C_{i_2}, \ldots, C_{i_k}$ has non empty intersection for some $i_1 < i_2 < \ldots < i_k$ and $i_k - i_1 <...
[ "geometry" ]
3,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double ld; mt19937 rnd(228); #define TIME (clock() * 1.0 / CLOCKS_PER_SEC) const int M = 5e4 + 239; const int X = (int)(1e8) + 239; const int T = (1 << 17) + 239; const ld pi = acos((ld)-1.0); int n, l, k, bd, x[M], y[M]; int idx[M], sz...
1642
A
Hard Way
Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle: - its vertices have integer coordinates, - the coordinates of vertices are non-negative, and - its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the tria...
If the triangle's side is not parallel with the line $y = 0$, all points on this side are safe because we can intersect it with $y = 0$ and there will be a point from which we can reach any point on this side of our triangle. All points on the side, which is parallel with $y = 0$ line contains are also safe if the thir...
[ "geometry" ]
800
#include <vector> #include <algorithm> #include <iostream> #include <cassert> #include <map> #include <set> #include <cmath> #include <array> using namespace std; signed main() { if (1) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } int t; cin >> t; while ...
1642
B
Power Walking
Sam is a kindergartener, and there are $n$ children in his group. He decided to create a team with some of his children to play "brawl:go 2". Sam has $n$ power-ups, the $i$-th has type $a_i$. A child's strength is equal to the number of \textbf{different} types among power-ups he has. For a team of size $k$, Sam will...
It is quite easy to understand that every multiset's power is at least 1. The final answer is at east the number of distict integers in the multiset. It is possible to proof that the answer to the problem for $k$ is equal to $\max(k, cnt)$, where $cnt$ is the number of distinct integers. $\textbf{Proof.}$ If the number...
[ "greedy" ]
900
#include <vector> #include <algorithm> #include <iostream> #include <cassert> #include <map> #include <set> #include <cmath> #include <array> using namespace std; signed main() { if (1) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } int t; cin >> t; while ...
1644
A
Doors and Keys
The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it. In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the...
The necessary and sufficient condition is the following: for each color the key should appear before the door. Necessary is easy to show: if there is a key after a door, this door can't be opened. Sufficient can be shown the following way. If there are no closed doors left, the knight has reached the princess. Otherwis...
[ "implementation" ]
800
for _ in range(int(input())): s = input() for (d, k) in zip("RGB", "rgb"): if s.find(d) < s.find(k): print("NO") break else: print("YES")
1644
B
Anti-Fibonacci Permutation
Let's call a permutation $p$ of length $n$ \textbf{anti-Fibonacci} if the condition $p_{i-2} + p_{i-1} \ne p_i$ holds for all $i$ ($3 \le i \le n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once. Your task is for a given number $n$ print $n$ \textbf{dis...
Let's consider one of the possible solutions. Let's put the first element in the $x$-th permutation equal to $x$, and sort all the other elements in descending order. Thus, we get permutations of the form: $[1, n, n-1, \dots, 2]$, $[2, n, n-1, \dots, 1]$, ..., $[n, n-1, n-2, \dots, 1]$. In such a construction $p_{i-1} ...
[ "brute force", "constructive algorithms", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 1; i <= n; ++i) { cout << i; for (int j = n; j > 0; --j) if (i != j) cout << ' ' << j; cout << '\n'; } } }
1644
C
Increase Subarray Sums
You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ integers. You are also given an integer value $x$. Let $f(k)$ be the maximum sum of a contiguous subarray of $a$ after applying the following operation: add $x$ to the elements on exactly $k$ \textbf{distinct} positions. An empty subarray should also be ...
Consider the naive solution. Iterate over $k$. Then iterate over the segment that will have the maximum sum. Let its length be $l$. Since $x$ is non-negative, it's always optimal to increase the elements inside the segment. So if $k \le l$, then the sum of the segment increases by $k \cdot x$. Otherwise, only the eleme...
[ "brute force", "dp", "greedy", "implementation" ]
1,400
INF = 10**9 for _ in range(int(input())): n, x = map(int, input().split()) a = list(map(int, input().split())) mx = [-INF for i in range(n + 1)] mx[0] = 0 for l in range(n): s = 0 for r in range(l, n): s += a[r] mx[r - l + 1] = max(mx[r - l + 1], s) ans = [0 for i in range(n + 1)] for k in range(n + 1...
1644
D
Cross Coloring
There is a sheet of paper that can be represented with a grid of size $n \times m$: $n$ rows and $m$ columns of cells. All cells are colored in white initially. $q$ operations have been applied to the sheet. The $i$-th of them can be described as follows: - $x_i$ $y_i$ — choose one of $k$ non-white colors and color t...
Let's take a look at a final coloring. Each cell has some color. There exist cells such that there were no operation in their row and their column. They are left white, and they don't affect the answer. All other cells are colored in one of $k$ colors. For each cell $(x, y)$ there is a query that has been the last one ...
[ "data structures", "implementation", "math" ]
1,700
from sys import stdin, stdout MOD = 998244353 ux = [] uy = [] for _ in range(int(stdin.readline())): n, m, k, q = map(int, stdin.readline().split()) while len(ux) < n: ux.append(False) while len(uy) < m: uy.append(False) xs = [-1 for i in range(q)] ys = [-1 for i in range(q)] for i in range(q): x, y = map...
1644
E
Expand the Path
Consider a grid of size $n \times n$. The rows are numbered top to bottom from $1$ to $n$, the columns are numbered left to right from $1$ to $n$. The robot is positioned in a cell $(1, 1)$. It can perform two types of moves: - D — move one cell down; - R — move one cell right. The robot is not allowed to move outsi...
First, get rid of the corner cases. If the string doesn't contain either of the letters, the answer is $n$. The general solution to the problem is to consider every single way to modify the path, then find the union of them. Well, every single path is too much, let's learn to reduce the number of different sequences of...
[ "brute force", "combinatorics", "data structures", "implementation", "math" ]
1,900
def calc(s, n): ld = s.find('R') res = ld * (n - 1) y = 0 for i in range(len(s) - 1, ld - 1, -1): if s[i] == 'D': res += y else: y += 1 return res for _ in range(int(input())): n = int(input()) s = input() if s.count(s[0]) == len(s): print(n) continue ans = n * n ans -= calc(s, n) ans -= calc(...
1644
F
Basis
For an array of integers $a$, let's define $|a|$ as the number of elements in it. Let's denote two functions: - $F(a, k)$ is a function that takes an array of integers $a$ and a positive integer $k$. The result of this function is the array containing $|a|$ first elements of the array that you get by replacing each e...
First of all, since the second operation changes all occurrences of some number $x$ to other number $y$ and vice versa, then, by using it, we can convert an array into another array if there exists a bijection between elements in the first array and elements in the second array. It can also be shown that $F(G(a, x, y),...
[ "combinatorics", "fft", "math", "number theory" ]
2,900
null
1646
A
Square Counting
Luis has a sequence of $n+1$ integers $a_1, a_2, \ldots, a_{n+1}$. For each $i = 1, 2, \ldots, n+1$ it is guaranteed that $0\leq a_i < n$, or $a_i=n^2$. He has calculated the sum of all the elements of the sequence, and called this value $s$. Luis has lost his sequence, but he remembers the values of $n$ and $s$. Can ...
Let the number of elements in the sequence equal to $n^2$ be $x$ and let the sum of all other numbers be $u$. Then, $s=x\cdot n^2+u$. If an element of the sequence is not equal to $n^2$, then its value is at most is $n-1$. There are $n+1$ numbers in the sequence, so $u\leq (n-1)\times (n+1)=n^2-1$. Thus, $\displaystyle...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; for(int i = 0; i < t; i++){ long long n, s; cin >> n >> s; cout << s / (n * n) << "\n"; } return 0; }
1646
B
Quality vs Quantity
$ \def\myred#1{\textcolor{red}{\underline{\bf{#1}}}} \def\myblue#1{\textcolor{blue}{\overline{\bf{#1}}}} $ $\def\RED{\myred{Red}} \def\BLUE{\myblue{Blue}}$ You are given a sequence of $n$ non-negative integers $a_1, a_2, \ldots, a_n$. Initially, all the elements of the sequence are unpainted. You can paint each number...
$\def\myred#1{\color{red}{\underline{\bf{#1}}}} \def\myblue#1{\color{blue}{\overline{\bf{#1}}}}$ $\def\RED{\myred{Red}} \def\BLUE{\myblue{Blue}}$ Suppose $\text{Count}(\RED)=k$. If a solution exists, then there is one with $\text{Count}(\BLUE)=k+1$, because if there are more than $k+1$ numbers painted blue, we can remo...
[ "brute force", "constructive algorithms", "greedy", "sortings", "two pointers" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t; cin >> t; for(int test_number = 0; test_number < t; test_number++){ int n; cin >> n; vector <long long> a(n); for(int i = 0; i < n; i++){ cin >> a[i]; } sort(a.begin(), a.end()); vector <l...
1646
C
Factorials and Powers of Two
A number is called powerful if it is a power of two or a factorial. In other words, the number $m$ is powerful if there exists a non-negative integer $d$ such that $m=2^d$ or $m=d!$, where $d!=1\cdot 2\cdot \ldots \cdot d$ (in particular, $0! = 1$). For example $1$, $4$, and $6$ are powerful numbers, because $1=1!$, $4...
If the problem asked to represent $n$ as a sum of distinct powers of two only (without the factorials), then there is a unique way to do it, using the binary representation of $n$ and the number of terms will be the number of digits equal to $1$ in this binary representation. Let's denote this number by $\text{ones}(n)...
[ "bitmasks", "brute force", "constructive algorithms", "dp", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; const long long MAXAI = 1000000000000ll; int get_first_bit(long long n){ return 63 - __builtin_clzll(n); } int get_bit_count(long long n){ return __builtin_popcountll(n); } int main(){ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t; cin >> t; for(int test_nu...
1646
D
Weight the Tree
You are given a tree of $n$ vertices numbered from $1$ to $n$. A tree is a connected undirected graph without cycles. For each $i=1,2, \ldots, n$, let $w_i$ be the weight of the $i$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors. Initially, the weights of all ...
If $n=2$, we can assign $w_1=1$ and $w_2=1$ and there is no way to get a better answer because all vertices are good and the sum of weights cannot be smaller because the weights have to be positive. If $n>2$, two vertices sharing an edge cannot be both good. To prove this, we are going to analyze two cases. If the two ...
[ "constructive algorithms", "dfs and similar", "dp", "implementation", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MAXN = 400005; vector<int> g[MAXN]; bool vis[MAXN]; int pa[MAXN]; //DFS to compute the parent of each node //parent of node i is stored at pa[i] void dfs(int v){ vis[v] = 1; for(auto i : g[v]){ if(!vis[i]){ pa[i] = v; dfs(i); } } } pair<int, int>...
1646
E
Power Board
You have a rectangular board of size $n\times m$ ($n$ rows, $m$ columns). The $n$ rows are numbered from $1$ to $n$ from top to bottom, and the $m$ columns are numbered from $1$ to $m$ from left to right. The cell at the intersection of row $i$ and column $j$ contains the number $i^j$ ($i$ raised to the power of $j$)....
It is easy to see that the first row only contains the number $1$ and that this number doesn't appear anywhere else on the board. We say that an integer is a perfect power if it can be represented as $x^a$ where $x$ and $a$ are positive integers and $a>1$. For each positive integer $x$ which is not a perfect power, we ...
[ "brute force", "dp", "math", "number theory" ]
2,200
#include <bits/stdc++.h> #define fore(i,a,b) for(ll i=a,ggdem=b;i<ggdem;++i) using namespace std; typedef long long ll; const int MAXM = 1000006; const int MAXLOGN = 20; bool visited_mul[MAXM * MAXLOGN]; int main(){ ll n, m; cin >> n >> m; vector<ll> mul_quan(MAXLOGN); ll current_vis = 0; fore(i, 1, MAXLOGN){ ...
1646
F
Playing Around the Table
There are $n$ players, numbered from $1$ to $n$ sitting around a round table. The $(i+1)$-th player sits to the right of the $i$-th player for $1 \le i < n$, and the $1$-st player sits to the right of the $n$-th player. There are $n^2$ cards, each of which has an integer between $1$ and $n$ written on it. For each int...
For each player, we say it is diverse if all his cards have different numbers. For each player, we will call a card repeated if this player has two or more cards with that number. Observe that a player is diverse if and only if he has no repeated cards. To construct the answer we are going to divide the process into tw...
[ "constructive algorithms", "greedy", "implementation" ]
2,900
#include <bits/stdc++.h> #define fore(i, a, b) for(int i = a; i < b; ++i) using namespace std; const int MAXN = 1010; //c[i][j] = number of cards player i has, with the number j int c[MAXN][MAXN]; //extras[i] is the stack of repeated cards for player i. vector<int> extras[MAXN]; int main(){ ios::sync_with_stdio...
1647
A
Madoka and Math Dad
Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem. Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $n$. Madoka is too tired...
Since we want to maximize the number we need, we will first find the longest suitable number. Obviously, it is better to use only the numbers $1$ and $2$ for this. Therefore, the answer always looks like $2121\ldots$ or $1212\ldots$. The first option is optimal when $n$ has a remainder of $2$ or $0$ modulo $3$, otherwi...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int type; if (n % 3 == 1) type = 1; else type = 2; int sum = 0; while (sum != n) { cout << type; sum += type; type = 3 - type; } cout << ' '; } int main() { ...
1647
B
Madoka and the Elegant Gift
Madoka's father just reached $1$ million subscribers on Mathub! So the website decided to send him a personalized award — The Mathhub's Bit Button! The Bit Button is a rectangular table with $n$ rows and $m$ columns with $0$ or $1$ in each cell. After exploring the table Madoka found out that: - A subrectangle $A$ is...
Note that the answer to the problem is "YES" if and only if the picture is a certain number of disjoint rectangles. Now, in this case, let's look at all squares of size $2\times 2$, note that there cannot be exactly $3$ filled cells in each of them. It is also clear that if there are $3$ such cells, then there will be ...
[ "brute force", "constructive algorithms", "graphs", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int> (m)); for (int i = 0; i < n; ++i) { string s; cin >> s; for (int j = 0; j < m; ++j) { a[i][j] = s[j] - '0'; } } for (int i = ...
1647
C
Madoka and Childish Pranks
Madoka as a child was an extremely capricious girl, and one of her favorite pranks was drawing on her wall. According to Madoka's memories, the wall was a table of $n$ rows and $m$ columns, consisting only of zeroes and ones. The coordinate of the cell in the $i$-th row and the $j$-th column ($1 \le i \le n$, $1 \le j ...
According to the condition, if the upper left cell is painted black, then we cannot paint it that way. Otherwise it is possible. Let's colour the cells in the following order: $(n,m), (n,m - 1), \ldots, (n, 1), (n - 1, m), \ldots (1, 1)$. Let the cell $(i, j)$ be colored black, then if $j > 1$, then just paint the rect...
[ "constructive algorithms", "greedy" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int> (m)); for (int i = 0; i < n; ++i) { string s; cin >> s; for (int j = 0; j < m; ++j) a[i][j] = s[j] - '0'; } vector<array<int, 4>> ans...
1647
D
Madoka and the Best School in Russia
Madoka is going to enroll in "TSUNS PTU". But she stumbled upon a difficult task during the entrance computer science exam: - A number is called good if it is a multiple of $d$. - A number is called beatiful if it is \textbf{good} and it \textbf{cannot} be represented as a product of two good numbers. Notice that a b...
Let's solve a more complex problem: calculate the number of partitions into such multipliers. This is easily solved by dynamic programming. Let $dp_{n, d}$ be the number of factorizations, if we have a number left to decompose the number $n$, and before that we divided by the number $d$. Let's go through all such beaut...
[ "constructive algorithms", "dp", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; int prime(int x) { for (int i = 2; i * i <= x; ++i) { if (x % i == 0) return i; } return -1; } void solve() { int x, d; cin >> x >> d; int cnt = 0; while (x % d == 0) { ++cnt; x /= d; } if (cnt ==...
1647
E
Madoka and the Sixth-graders
After the most stunning success with the fifth-graders, Madoka has been trusted with teaching the sixth-graders. There's $n$ single-place desks in her classroom. At the very beginning Madoka decided that the student number $b_i$ ($1 \le b_i \le n$) will sit at the desk number $i$. Also there's an infinite line of stud...
After each lesson, the person's number increases from the maximum number by the number of desks where no one goes. Therefore, it is easy to calculate how much time has passed since the very beginning, let it be the number $k$. Then let's imagine that schoolchildren are not expelled, but at any given time we are simply ...
[ "data structures", "dfs and similar", "greedy" ]
2,500
#include <bits/stdc++.h> using namespace std; const int K = 30; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<int> cnt(n); vector<vector<int>> up(n, vector<int> (K)); for (int i = 0; i < n; ++i) { int a; cin >> a; --a; ...
1647
F
Madoka and Laziness
Madoka has become too lazy to write a legend, so let's go straight to the formal description of the problem. An array of integers $a_1, a_2, \ldots, a_n$ is called a hill if it is not empty and there is an index $i$ in it, for which the following is true: $a_1 < a_2 < \ldots < a_i > a_{i + 1} > a_{i + 2} > \ldots > a_...
The inflection of the sequence is the maximum number in the subsequence. Then note that in the first subsequence, the inflection will be the maximum number in our array, let its position in the array be $ind$. Then let's say for convenience that the inflection of the second subsequence will be to the right of the maxim...
[ "dp", "greedy" ]
3,100
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 228; int solve (int n, vector<int> a) { int ind = max_element(a.begin(), a.end()) - a.begin(); vector<int> dp1(n, inf); dp1[0] = -1; for (int i = 1; i <= ind; ++i) { if (a[i] > dp1[i - 1]) dp1[i] = min(dp1[i], ...
1648
A
Weird Sum
Egor has a table of size $n \times m$, with lines numbered from $1$ to $n$ and columns numbered from $1$ to $m$. Each cell has a color that can be presented as an integer from $1$ to $10^5$. Let us denote the cell that lies in the intersection of the $r$-th row and the $c$-th column as $(r, c)$. We define the \underli...
We note that the manhattan distance between cells $(r_1, c_1)$ and $(r_2, c_2)$ is equal to $|r_1-r_2|+|c_1-c_2|$. For each color we will compose a list of all cells $(r_0, c_0), \ldots, (r_{k-1}, c_{k-1})$ of this color, compute the target sum for this color, and sum up the answers for all colors. The sum is equal: $\...
[ "combinatorics", "data structures", "geometry", "math", "matrices", "sortings" ]
1,400
null
1648
B
Integral Array
You are given an array $a$ of $n$ positive integers numbered from $1$ to $n$. Let's call an array integral if for any two, not necessarily different, numbers $x$ and $y$ from this array, $x \ge y$, the number $\left \lfloor \frac{x}{y} \right \rfloor$ ($x$ divided by $y$ with rounding down) is also in this array. You ...
Let's consider $x, y \in a$ and $r \notin a$. If $y \cdot r \le x < y \cdot (r + 1)$ then $\left \lfloor \frac{x}{y} \right \rfloor = r$, but $r$ is not in $a$, so the answer is "No". Let's suggest that $y$ and $r$ are already given. We can check if there exists such $x \in a$ from the mentioned segment in $O(1)$. It i...
[ "brute force", "constructive algorithms", "data structures", "math" ]
1,800
null
1648
C
Tyler and Strings
While looking at the kitchen fridge, the little boy Tyler noticed magnets with symbols, that can be aligned into a string $s$. Tyler likes strings, and especially those that are lexicographically smaller than another string, $t$. After playing with magnets on the fridge, he is wondering, how many distinct strings can ...
Let $K$ be the size of the alphabet, that is, the number of the maximum letter that occurs in it. First, let's calculate how many different strings can be composed if we have $c_1$ letters of the $1$th type, $c_2$ letters of the $2$th type, $\ldots$, $c_K$ letters of the $K$ type. This is the school formula: $P(c_1, c_...
[ "combinatorics", "data structures", "implementation" ]
1,900
null
1648
D
Serious Business
Dima is taking part in a show organized by his friend Peter. In this show Dima is required to cross a $3 \times n$ rectangular field. Rows are numbered from $1$ to $3$ and columns are numbered from $1$ to $n$. The cell in the intersection of the $i$-th row and the $j$-th column of the field contains an integer $a_{i,j...
Let's denote $pref[i][j] := \sum_{k = 0}^{j - 1} a[i][k]$. Then define $s$ and $t$ as follows: $s[i] = pref[0][i + 1] - pref[1][i]$ $f[i] = pref[1][i + 1] - pref[2][i] + pref[2][n]$ Now we can transform the problem to following: compute $\max\limits_{0\leq i\leq j < n} s[i] + f[j] - cost(i, j)$ where $cost(i, j)$ is th...
[ "data structures", "divide and conquer", "dp", "implementation", "shortest paths" ]
2,800
null
1648
E
Air Reform
Berland is a large country with developed airlines. In total, there are $n$ cities in the country that are historically served by the Berlaflot airline. The airline operates bi-directional flights between $m$ pairs of cities, $i$-th of them connects cities with numbers $a_i$ and $b_i$ and has a price $c_i$ for a flight...
The formal statement of this problem is that we have a weighted graph, for which we build it's complement, where the weight of an edge between $A$ and $B$ equals to minimal maximum on path from $A$ to $B$ in initial graph. The same way we calculate edge weights of initial graph, and we have to output them. We can notic...
[ "data structures", "dfs and similar", "divide and conquer", "dsu", "graphs", "implementation", "trees" ]
3,200
null
1648
F
Two Avenues
In order to make the capital of Berland a more attractive place for tourists, the great king came up with the following plan: choose two streets of the city and call them avenues. Certainly, these avenues will be proclaimed extremely important historical places, which should attract tourists from all over the world. T...
Let's consider two edges from the answer $e_1$, $e_2$. At least one of them should lie on dfs tree, otherwise the graph will be connected after removing $e_1$, $e_2$ and the answer will be $0$. Let the answer be $e_1$, $e_2$, where $e_1$ lies on dfs tree. What cases can be for edges $e_1$, $e_2$? The edge $e_2$ should ...
[ "data structures", "dfs and similar", "graphs" ]
3,500
null
1649
A
Game
You are playing a very popular computer game. The next level consists of $n$ consecutive locations, numbered from $1$ to $n$, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also,...
It is easy to see that if there are no water locations, the answer is $0$. Otherwise, we should jump from the last accessible from the start land location to the first land location from which the finish is accessible. In order to find these locations, one can use two consecutive while loops, one increasing $l$ from $1...
[ "implementation" ]
800
null
1649
B
Game of Ball Passing
Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session. The game involves $n$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how m...
If $max(a) \cdot 2 \leq sum(a)$, we can always prove that we can only use one ball. For other cases, the number of balls is determined by $2 \cdot max(a) - sum(a)$.
[ "greedy", "implementation" ]
1,300
null
1650
A
Deletions of Two Adjacent Letters
The string $s$ is given, the string length is \textbf{odd} number. The string consists of lowercase letters of the Latin alphabet. As long as the string length is greater than $1$, the following operation can be performed on it: select any two adjacent letters in the string $s$ and delete them from the string. For exa...
There will be one character left in the end, so we have to delete all the characters going before and after it. That is, delete some prefix and suffix. Since we always delete some substring of length $2$, we can only delete the prefix and suffix of even length, it means the answer is YES in the case when there is an od...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { string s, t; cin >> s >> t; bool yes = false; forn(i, s.length()) if (s[i] == t[0] && i % 2 == 0) yes =...
1650
B
DIV + MOD
Not so long ago, Vlad came up with an interesting function: - $f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a$, where $\left\lfloor\frac{x}{a}\right\rfloor$ is $\frac{x}{a}$, rounded \textbf{down}, $x \bmod a$ — the remainder of the integer division of $x$ by $a$. For example, with $a=3$ and $x=11$, the valu...
Consider $f_a(r)$. Note that $\left\lfloor\frac{r}{a}\right\rfloor$ is maximal over the entire segment from $l$ to $r$, so if there is $x$ in which $f_a$ gives a greater result, then $x \bmod a > r\bmod a$. Note that numbers from $r - r \bmod a$ to $r$ that have an incomplete quotient when divided by $a$ equal to $\lef...
[ "math" ]
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,ss...
1650
C
Weight of the System of Nested Segments
On the number line there are $m$ points, $i$-th of which has integer coordinate $x_i$ and integer weight $w_i$. The coordinates of all points are different, and the points are numbered from $1$ to $m$. A sequence of $n$ segments $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$ is called system of nested segments if for eac...
We create a structure that stores for each point its coordinate, weight, and index in the input data. Sort the $points$ array by increasing weight. The sum of weights of the first $2 \cdot n$ points will be minimal, so we use them to construct a system of $n$ nested segments. We save the weights of the first $2 \cdot n...
[ "greedy", "hashing", "implementation", "sortings" ]
1,200
#include<bits/stdc++.h> using namespace std; using ll = long long; #define forn(i, n) for (int i = 0; i < int(n); i++) struct point{ int weight, position, id; }; void solve(){ int n, m; cin >> n >> m; vector<point>points(m); forn(i, m) { cin >> points[i].position >> points[i].weight; ...
1650
D
Twist the Permutation
Petya got an array $a$ of numbers from $1$ to $n$, where $a[i]=i$. He performed $n$ operations sequentially. In the end, he received a new state of the $a$ array. At the $i$-th operation, Petya chose the first $i$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements wi...
The first thing to notice - the answer always exists. For $n$ numbers $1\cdot2\cdot3 \dots n = n!$ answer choices, as well as $n!$ permutation combinations. It remains only to restore the answer from this permutation. We will restore by performing reverse operations. On the $i$-th ($i = n,~n - 1, ~\dots, ~2, ~1$) opera...
[ "brute force", "constructive algorithms", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define forn(i, n) for (int i = 0; i < int(n); i++) void solve() { int n; cin >> n; int a[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } int ans[n]; for (int i = n; i > 0; --i) { int ind = 0; f...
1650
E
Rescheduling the Exam
Now Dmitry has a session, and he has to pass $n$ exams. The session starts on day $1$ and lasts $d$ days. The $i$th exam will take place on the day of $a_i$ ($1 \le a_i \le d$), all $a_i$ — are different. \begin{center} {\small Sample, where $n=3$, $d=12$, $a=[3,5,9]$. Orange — exam days. Before the first exam Dmitry ...
To begin with, we will learn how to find the optimal place for the exam that we want to move. Let's imagine that it is not in the schedule, in this case we have two options: Put the exam at the end of the session so that there are $d - a_n - 1$ days before it. Put it in the middle of the largest break between exams ((l...
[ "binary search", "data structures", "greedy", "implementation", "math", "sortings" ]
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() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const ll inf = 1e9; const ll M = 998'244'353; cons...
1650
F
Vitaly and Advanced Useless Algorithms
Vitaly enrolled in the course Advanced Useless Algorithms. The course consists of $n$ tasks. Vitaly calculated that he has $a_i$ hours to do the task $i$ from the day he enrolled in the course. That is, the deadline before the $i$-th task is $a_i$ hours. The array $a$ is sorted in ascending order, in other words, the j...
Note that it is always advantageous for us to complete the task that has an earlier deadline first. Only then will we proceed to the next task. Then we can solve each problem independently for each exam. Then it remains to score $100$ percent on the task on the available options. This is a typical knapsack problem with...
[ "dp", "greedy", "implementation" ]
2,200
#include <bits/stdc++.h> using namespace std; template<class T> bool ckmin(T &a, T b) {return a > b ? a=b, true : false;} #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() struct option { int t, p, id; option(int _t,int _p, int _id) : t(_t), p(_...
1650
G
Counting Shortcuts
Given an undirected connected graph with $n$ vertices and $m$ edges. The graph contains no loops (edges from a vertex to itself) and multiple edges (i.e. no more than one edge between each pair of vertices). The vertices of the graph are numbered from $1$ to $n$. Find the number of paths from a vertex $s$ to $t$ whose...
Note that in any shortest path, we cannot return to the previous vertex. Since if the current vertex $v$, the previous $u$. The current distance $d_v = d_u + 1$ (the shortest distance to vertex $v$), the shortest distance to vertex $t$ - $d_t$. Then, if we return to the vertex $u$, the shortest distance from it to $t$ ...
[ "data structures", "dfs and similar", "dp", "graphs", "shortest paths" ]
2,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define eb emplace_back #define mt make_tuple const int INF = INT_MAX >> 1; const int mod = 1e9 + 7; void csum(int &a,int b) { a = (a + b) % mod; } int s, t; vector<int> us; vector<int>...
1651
A
Playoff
Consider a playoff tournament where $2^n$ athletes compete. The athletes are numbered from $1$ to $2^n$. The tournament is held in $n$ stages. In each stage, the athletes are split into pairs in such a way that each athlete belongs exactly to one pair. In each pair, the athletes compete against each other, and exactly...
During the first stage, every player with an even index competes against a player with an odd index, so in each match during the first stage, the player whose index is smaller wins. The pairs are formed in such a way that, in each pair, the player with an odd index has smaller index, so all players with even indices ge...
[ "implementation" ]
800
t = int(input()) for i in range(t): n = int(input()) print(2 ** n - 1)
1651
B
Prove Him Wrong
Recently, your friend discovered one special operation on an integer array $a$: - Choose two indices $i$ and $j$ ($i \neq j$); - Set $a_i = a_j = |a_i - a_j|$. After playing with this operation for a while, he came to the next conclusion: - For every array $a$ of $n$ integers, where $1 \le a_i \le 10^9$, you can fin...
Suppose the initial sum of $a$ is equal to $S$. If we perform the operation, the new sum will be equal to $S' = S - (a_i + a_j) + 2 |a_i - a_j|$. We want the sum not to decrease, or $S' \ge S$. If $a_i \ge a_j$, we will get: $S' \ge S,$ $S - (a_i + a_j) + 2 (a_i - a_j) \ge S,$ $a_i - 3 a_j \ge 0,$ $a_i \ge 3 a_j.$ In o...
[ "constructive algorithms", "greedy" ]
800
for _ in range(int(input())): n = int(input()) if 3**(n-1) > 10**9: print("NO") else: print("YES") print(*[3**x for x in range(n)])
1651
C
Fault-tolerant Network
There is a classroom with two rows of computers. There are $n$ computers in each row and each computer has its own grade. Computers in the first row have grades $a_1, a_2, \dots, a_n$ and in the second row — $b_1, b_2, \dots, b_n$. Initially, all pairs of \textbf{neighboring} computers in each row are connected by wir...
There is a criterion when the given network becomes fault-tolerant: the network becomes fault-tolerant if and only if each of the corner computers (let's name them $A_1$, $A_n$, $B_1$, and $B_n$) is connected to the other row. From one side: if, WLOG, $A_1$ is not connected to the other row then if $A_2$ is broken - $A...
[ "brute force", "data structures", "implementation" ]
1,500
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) typedef long long li; const int INF = int(1e9); int n; vector<int> a, b; inline bool read() { if(!(cin >> n)) return false; a.resize(n); fore (i, 0, n) cin >> a[i]; b.resize(n); fore (i, 0, n) cin >>...
1651
D
Nearest Excluded Points
You are given $n$ distinct points on a plane. The coordinates of the $i$-th point are $(x_i, y_i)$. For each point $i$, find the nearest (in terms of Manhattan distance) point with \textbf{integer coordinates} that is not among the given $n$ points. If there are multiple such points — you can choose any of them. The ...
Firstly, we can find answers for all points that are adjacent to at least one point not from the set. The distance for such points is obviously $1$ (and this is the smallest possible answer we can get). On the next iteration, we can set answers for all points that are adjacent to points with found answers (because they...
[ "binary search", "data structures", "dfs and similar", "graphs", "shortest paths" ]
1,900
#include <bits/stdc++.h> using namespace std; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<pair<int, int>> a(n); for (auto &[x, y] : a) scanf("%d ...
1651
E
Sum of Matchings
Let's denote the size of the maximum matching in a graph $G$ as $\mathit{MM}(G)$. You are given a bipartite graph. The vertices of the first part are numbered from $1$ to $n$, the vertices of the second part are numbered from $n+1$ to $2n$. \textbf{Each vertex's degree is $2$}. For a tuple of four integers $(l, r, L,...
Instead of counting the edges belonging to the maximum matching, it is easier to count the vertices. So, we will calculate the total number of vertices saturated by the maximum matching over all possible tuples $(l, r, L, R)$, and then divide the answer by $2$. Furthermore, it's easier to calculate the number of unsatu...
[ "brute force", "combinatorics", "constructive algorithms", "dfs and similar", "graph matchings", "greedy", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 3043; vector<int> g[2 * N]; int n; int used[2 * N]; int choose2(int n) { return n * (n + 1) / 2; } int count_ways(int L, int R, const vector<int>& forbidden) { if(L > R) { int ml = *min_element(forbidden.begin(), forbidden.end()); ...
1651
F
Tower Defense
Monocarp is playing a tower defense game. A level in the game can be represented as an OX axis, where each lattice point from $1$ to $n$ contains a tower in it. The tower in the $i$-th point has $c_i$ mana capacity and $r_i$ mana regeneration rate. In the beginning, before the $0$-th second, each tower has full mana. ...
Let's start thinking about the problem from the easy cases. How to solve the problem fast if all towers have full mana? We can store prefix sums of their capacities and find the first tower that doesn't get drained completely with a binary search. Let's try the opposite. How to solve the problem fast if all towers were...
[ "binary search", "brute force", "data structures" ]
3,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct node{ node *l, *r; long long sumc, sumr; node() : l(NULL), r(NULL), sumc(0), sumr(0) {} node(node* l, node* r, long long sumc, long long sumr) : l(l), r(r), sumc(sumc), sumr(sumr) {} }; node* build(int l, in...
1654
A
Maximum Cake Tastiness
There are $n$ pieces of cake on a line. The $i$-th piece of cake has weight $a_i$ ($1 \leq i \leq n$). The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., $\max(a_1+a_2,\, a_2+a_3,\, \ldots,\, a_{n-1} + a_{n})$). You want to maximize the tastiness of the cake. You are allowed ...
Suppose you want to choose pieces of cake $i$, $j$. Can you make them adjacent in $1$ move? The answer is the sum of the $2$ maximum weights. You can always pick the $2$ maximum weights: if they are $a_i$ and $a_j$ ($i < j$), you can flip the subsegment $[i, j-1]$ to make them adjacent. The result can't be larger, beca...
[ "brute force", "greedy", "implementation", "sortings" ]
800
#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 i = 0; i < n; i++) cin >> a[i]; int ans = 0; for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) ...
1654
B
Prefix Removals
You are given a string $s$ consisting of lowercase letters of the English alphabet. You must perform the following algorithm on $s$: - Let $x$ be the length of the longest prefix of $s$ which occurs somewhere else in $s$ as a contiguous substring (the other occurrence may also intersect the prefix). If $x = 0$, break....
Are there any characters that you can never remove? You can't remove the rightmost occurrence of each letter. Can you remove the other characters? If you can remove $s_1, s_2, \dots, s_{i-1}$ and $s_i$ is not the rightmost occurrence of a letter, you can also remove $s_i$. Let $a$ be the initial string. For a string $z...
[ "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; map<char, int> frequency; for (char c : s) frequency[c]++; for (int i = 0; i < s.size(); i++) if (--frequency[s[i]] == 0) { ...
1654
C
Alice and the Cake
Alice has a cake, and she is going to cut it. She will perform the following operation $n-1$ times: choose a piece of the cake (initially, the cake is all one piece) with weight $w\ge 2$ and cut it into two smaller pieces of weight $\lfloor\frac{w}{2}\rfloor$ and $\lceil\frac{w}{2}\rceil$ ($\lfloor x \rfloor$ and $\lce...
Can you find the initial weight which results in $a$? The initial weight is the sum of the final weights. Let's simulate the division, starting from a new cake. How to choose fast which splits to do? If the largest piece is not in $a$, you have to split it. How to find the largest piece efficiently? Keep $a$ and the ne...
[ "data structures", "greedy", "implementation", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { ll n; cin >> n; vector<ll> a(n); for (int i = 0; i < n; i++) cin >> a[i]; ll sum = 0; for (int...
1654
D
Potion Brewing Class
Alice's potion making professor gave the following assignment to his students: brew a potion using $n$ ingredients, such that the proportion of ingredient $i$ in the final potion is $r_i > 0$ (and $r_1 + r_2 + \cdots + r_n = 1$). He forgot the recipe, and now all he remembers is a set of $n-1$ facts of the form, "ingr...
The $n-1$ facts make a tree. Assume that the amount of ingredient $1$ is $1$. For each $i$, the amount of ingredient $i$ would be $c_i/d_i$ for some integer $c_i, d_i > 0$. How to make an integer amount of each ingredient? The optimal amount of ingredient $1$ is $\text{lcm}(d_1, d_2, \dots, d_n)$. Can you find the expo...
[ "dfs and similar", "math", "number theory", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; using ll = long long; const int inf = 1e9+10; const ll inf_ll = 1e18+10; #define all(x) (x).begin(), (x).end() #define pb push_back #define cmax(x, y) (x = max(x, y)) #define cmin(x, y) (x = min(x, y)) #ifndef LOCAL #define debug(...) 0 #else #include "../../debug.cpp" ...
1654
E
Arithmetic Operations
You are given an array of integers $a_1, a_2, \ldots, a_n$. You can do the following operation any number of times (possibly zero): - Choose any index $i$ and set $a_i$ to any integer (positive, negative or $0$). What is the minimum number of operations needed to turn $a$ into an arithmetic progression? The array $a...
Consider each element of the array as being a point in the plane $(i, a_i)$. Then all of the elements that don't get affected by an operation lie on a single line in the plane. Find a line that maximizes the number of points on it. Let $m$ be the upper bound on $a_i$. The intended complexity is $O(n \sqrt m)$. Let $m$ ...
[ "brute force", "data structures", "graphs", "math" ]
2,300
#include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; struct splitmix64 { size_t operator()(size_t x) const { static const size_t fixed = chrono::steady_clock::now().time_since_epoch().count(); x += 0x9e3779b97f4a7c15 + fixed; ...
1654
F
Minimal String Xoration
You are given an integer $n$ and a string $s$ consisting of $2^n$ lowercase letters of the English alphabet. The characters of the string $s$ are $s_0s_1s_2\cdots s_{2^n-1}$. A string $t$ of length $2^n$ (whose characters are denoted by $t_0t_1t_2\cdots t_{2^n-1}$) is a xoration of $s$ if there exists an integer $j$ (...
Let $f(s, x)$ be the string $t$ such that $t_i = s_{i\oplus x}$. The intended solution not only finds the $x$ such that $f(s, x)$ is lexicographically minimized, but produces an array of all $0 \leq x < 2^n$ sorted according the comparator $f(s, i) < f(s, j)$. The solution is similar to the standard method to construct...
[ "bitmasks", "data structures", "divide and conquer", "greedy", "hashing", "sortings", "strings" ]
2,800
#include <bits/stdc++.h> using namespace std; const int N = 18; string s; int a[1<<N], v[1<<N], tmp[1<<N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n >> s; assert(s.size() == (1<<n)); iota(a, a+(1<<n), 0); sort(a, a+(1<<n), [&](int i, int j){ return s[i] < s[j]; });...
1654
G
Snowy Mountain
There are $n$ locations on a snowy mountain range (numbered from $1$ to $n$), connected by $n-1$ trails in the shape of a tree. Each trail has length $1$. Some of the locations are base lodges. The height $h_i$ of each location is equal to the distance to the nearest base lodge (a base lodge has height $0$). There is ...
Let's say that a vertex is "flippable" if it has at least one neighbor of the same height. The optimal strategy for a skier is to ski to a flippable vertex with lowest height, flip back and forth between that vertex and its neighbor until all energy is used, and then ski to a base lodge. Assuming the skier starts at ve...
[ "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "trees" ]
2,900
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second #define int long long const ll mod=998244353; const int N=2e5+1; int n; int d[N]; queue<int>q; vector<int>adj[N]; int g[N],h[N],z; bool use[N]; vector<int>ans[N]; vector<int>f[N]; bool vis[N]; void dfs(int id,int p...
1654
H
Three Minimums
Given a list of distinct values, we denote with first minimum, second minimum, and third minimum the three smallest values (in increasing order). A permutation $p_1, p_2, \dots, p_n$ is good if the following statement holds for all pairs $(l,r)$ with $1\le l < l+2 \le r\le n$. - If $\{p_l, p_r\}$ are (not necessarily...
If $p_1,\dots, p_n$ is good and $p_i=1$, what can you say about $p_1,p_2,\dots, p_i$ and $p_i,p_{i+1},\dots, p_n$? Find a quadratic solution ignoring the constraints given by the string $s$. Find an $O(n^2 + nm)$ solution taking care of the constraints given by the string $s$. Optimize the $O(n^2+nm)$ solution using ge...
[ "combinatorics", "constructive algorithms", "divide and conquer", "dp", "fft", "math" ]
3,500
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef unsigned long long ULL; typedef long long LL; #define SZ(x) ((int)((x).size())) template <typename T1, typename T2> string print_iterable(T1 begin_iter, T2 end_iter, int counter) { bool done_something = false; stringstream res; ...
1656
A
Good Pairs
You are given an array $a_1, a_2, \ldots, a_n$ of positive integers. A good pair is a pair of indices $(i, j)$ with $1 \leq i, j \leq n$ such that, for all $1 \leq k \leq n$, the following equality holds: $$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$ where $|x|$ denotes the absolute value of $x$. Find a good pair. N...
By the triangle inequality, for all real numbers $x, y, z$, we have: $|x-y| + |y-z| \geq |x-z|$ with equality if and only if $\min(x, z) \leq y \leq \max(x, z)$. Now, take indices $i$ and $j$ such that $a_i$ and $a_j$ are the maximum and minimum values of the array, respectively. Then, for each index $k$, we have $a_i ...
[ "math", "sortings" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; int minv = 1e9+1; int maxv = -1; int mini; int maxi; for(int i=0; i < n; ++i) { int a; cin >> a; if(a > maxv) { maxi = i+1; maxv = a; } if(a < minv) { mini = i+1; ...
1656
B
Subtract Operation
You are given a list of $n$ integers. You can perform the following operation: you choose an element $x$ from the list, erase $x$ from the list, and subtract the value of $x$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $1$. Given an integer $k$ ($k>0$), find ...
Note that, after deleting element $a_j$, all numbers in the set are of the form $a_i - a_j$, since the previous substractions are cancelled. Therefore, the final element will be the difference between the last element and the previous element which was erased. So we just need to check if $k$ is the difference of two el...
[ "data structures", "greedy", "math", "two pointers" ]
1,100
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int t; cin >> t; while(t--) { int n, a; cin >> n >> a; vector<int> v(n); for(int& x : v) cin >> x; bool ans = false; if(n == 1) ans = (v[0] == a); else { sort(v.begin(), v....
1656
C
Make Equal With Mod
You are given an array of $n$ non-negative integers $a_1, a_2, \ldots, a_n$. You can make the following operation: choose an integer $x \geq 2$ and replace each number of the array by the remainder when dividing that number by $x$, that is, for all $1 \leq i \leq n$ set $a_i$ to $a_i \bmod x$. Determine if it is possi...
Note that, if $1$ is not present in the array, we can always make all elements equal to $0$ by repeatedly applying the operation with $x = \max(a_i)$ until all elements become $0$, as this operation will set the elements equal to the maximum to $0$, while maintaining the others intact. So the answer is YES. If $1$ is p...
[ "constructive algorithms", "math", "number theory", "sortings" ]
1,200
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vi a(n); for(int i=0; i < n; ++i) cin >> a[i]; sort(a.begin(), a.end()); bool one = false; bool consec = false; for(int i=0; i < n; ++i) { if(a[i] == 1) one = tr...
1656
D
K-good
We say that a positive integer $n$ is $k$-good for some positive integer $k$ if $n$ can be expressed as a sum of $k$ positive integers which give $k$ distinct remainders when divided by $k$. Given a positive integer $n$, find some $k \geq 2$ so that $n$ is $k$-good or tell that such a $k$ does not exist.
$n$ is $k$-good if and only if $n \geq 1 + 2 + \ldots + k = \frac{k(k+1)}{2}$. $n \equiv 1 + 2 + \ldots + k \equiv \frac{k(k+1)}{2} \pmod{k}$. It is clear that both conditions are necessary, and it turns out they're sufficient too since $\frac{k(k+1)}{2} + m \cdot k$ is attainable for any integer $m \geq 0$ by repeated...
[ "constructive algorithms", "math", "number theory" ]
1,900
#include<bits/stdc++.h> using namespace std; #define endl '\n' typedef long long ll; int main() { ios::sync_with_stdio(false); int T; cin >> T; while(T--) { ll n; cin >> n; ll x = n; while(x % 2 == 0) x /= 2; if(x == 1) { cout << -1 << endl; } else if(x <= 2e9 && (x*(x+1))/2 <= n) { c...
1656
E
Equal Tree Sums
You are given an undirected unrooted tree, i.e. a connected undirected graph without cycles. You must assign a \textbf{nonzero} integer weight to each vertex so that the following is satisfied: if any vertex of the tree is removed, then each of the remaining connected components has the same sum of weights in its vert...
Bicolor the tree, and put $+\text{deg}(v)$ in vertices of one color and $-\text{deg}(v)$ in vertices of the other color. Consider removing one vertex $u$. In each subtree, for each edge not incident with $u$, $+1$ will be added for one of the endpoints and $-1$ for the other endpoint, so the total contribution is $0$. ...
[ "constructive algorithms", "dfs and similar", "math", "trees" ]
2,200
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; vvi al; vi ans; void dfs(int u, int p, int c) { ans[u] = ((int)al[u].size())*c; for(int v : al[u]) { if(v != p) { dfs(v, u, -c); } } } int main() { int T; cin >> T; while(T--) { int n; cin >> n; al ...
1656
F
Parametric MST
You are given $n$ integers $a_1, a_2, \ldots, a_n$. For any real number $t$, consider the complete weighted graph on $n$ vertices $K_n(t)$ with weight of the edge between vertices $i$ and $j$ equal to $w_{ij}(t) = a_i \cdot a_j + t \cdot (a_i + a_j)$. Let $f(t)$ be the cost of the minimum spanning tree of $K_n(t)$. De...
Assume $a_1 \leq \ldots \leq a_n$. We will try to connect each node $u$ to the neighbour $v$ that minimizes the cost function $c(u, v) = a_u a_v + t(a_u + a_v)$. If by doing this we obtain a tree which is connected, it will clearly be an MST. Let $b_i(t) = a_i + t$. We can rewrite $c(u, v)$ as $c(u, v) = b_u(t)b_v(t) -...
[ "binary search", "constructive algorithms", "graphs", "greedy", "math", "sortings" ]
2,600
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<ll> vi; int main() { int T; cin >> T; while(T--) { ll n; cin >> n; vi a(n); ll tsum = 0; for(int i=0; i < n; ++i) { cin >> a[i]; tsum += a[i]; } sort(a.begin(), a.end()); if(a[n-1]*(n-2) + tsum < 0 || a[0]*(n-2...
1656
G
Cycle Palindrome
We say that a sequence of $n$ integers $a_1, a_2, \ldots, a_n$ is a palindrome if for all $1 \leq i \leq n$, $a_i = a_{n-i+1}$. You are given a sequence of $n$ integers $a_1, a_2, \ldots, a_n$ and you have to find, if it exists, a cycle permutation $\sigma$ so that the sequence $a_{\sigma(1)}, a_{\sigma(2)}, \ldots, a_...
We clearly see that the following two conditions are necessary: Each number must be repeated an even number of time except possibly one of the numbers. (This is necessary to find any permutation that results in a palindrome, not just a cycle). If $n$ is odd, it can not be that the number $a_{(n+1)/2}$ appears only one ...
[ "constructive algorithms", "graphs", "math" ]
3,200
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; vi obtain_p_permutation(const vi& a) { int n = a.size(); vi pp(n, -1); vi p(n); int cp = 0; vi cnt(n); for(int i=0; i < n; ++i) { cnt[a[i]]++; } for(int i=0; i < n; ++i) { if(pp[a[i]] == -1) { if(cnt[a[i]] == ...
1656
H
Equal LCM Subsets
You are given two sets of positive integers $A$ and $B$. You have to find two non-empty subsets $S_A \subseteq A$, $S_B \subseteq B$ so that the least common multiple (LCM) of the elements of $S_A$ is equal to the least common multiple (LCM) of the elements of $S_B$.
First, we see how to check if the two entire sets have the same LCM (without subsets). To do this, for each element $a \in A$ let us compute $f(a, B) = \gcd(a/\gcd(a, b_1), \ldots, a/\gcd(a, b_n))$ If $f(a, B) > 1$, we can simply delete $a$ from $A$ and solve recursively using the remaining sets (similarly if $f(b, A) ...
[ "data structures", "math", "number theory" ]
3,200
#include<bits/stdc++.h> using namespace std; typedef __int128 ll; typedef vector<ll> vi; typedef vector<vi> vvi; ll read_ll() { string s; cin >> s; ll x = 0; for(int i=0; i < (int)s.length(); ++i) { x *= 10; x += ll(s[i]-'0'); } return x; } void print_ll(ll x) { vector<int> p; while(x > 0) { p....
1656
I
Neighbour Ordering
Given an undirected graph $G$, we say that a neighbour ordering is an ordered list of all the neighbours of a vertex for each of the vertices of $G$. Consider a given neighbour ordering of $G$ and three vertices $u$, $v$ and $w$, such that $v$ is a neighbor of $u$ and $w$. We write $u <_{v} w$ if $u$ comes after $w$ in...
First, note that, for each vertex $v$, the relative order between neighbours that belong to different biconnected components (i. e., neighbours $u$ and $w$ so that the edges $vu$ and $vw$ belong to different biconnected components) is irrelevant, since there can not be any (vertex-disjoint) cycle using edges from diffe...
[ "constructive algorithms", "graphs" ]
3,500
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<vii> vvii; struct graph { int n; int m; vvi al; vi morphism; vvi dfs_children; vi dfs_parent; vi dfs_num; vi dfs_low; int dfs_count; bool is_root...
1657
A
Integer Moves
There's a chip in the point $(0, 0)$ of the coordinate plane. In one operation, you can move the chip from some point $(x_1, y_1)$ to some point $(x_2, y_2)$ if the Euclidean distance between these two points is an \textbf{integer} (i.e. $\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$ is integer). Your task is to determine the minim...
Note that the answer does not exceed $2$, because the chip can be moved as follows: $(0, 0) \rightarrow (x, 0) \rightarrow (x, y)$. Obviously, in this case, both operation are valid. It remains to check the cases when the answer is $0$ or $1$. The answer is $0$ only if the destination point is $(0, 0)$, and the answer ...
[ "brute force", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int x, y; cin >> x >> y; int d = x * x + y * y; int r = 0; while (r * r < d) ++r; int ans = 2; if (r * r == d) ans = 1; if (x == 0 && y == 0) ans = 0; cout << ans << '\n'; } }
1657
B
XY Sequence
You are given four integers $n$, $B$, $x$ and $y$. You should build a sequence $a_0, a_1, a_2, \dots, a_n$ where $a_0 = 0$ and for each $i \ge 1$ you can choose: - either $a_i = a_{i - 1} + x$ - or $a_i = a_{i - 1} - y$. Your goal is to build such a sequence $a$ that $a_i \le B$ for all $i$ and $\sum\limits_{i=0}^{n}...
Strategy is quite easy: we go from $a_1$ to $a_n$ and if $a_{i - 1} + x \le B$ we take this variant (we set $a_i = a_{i - 1} + x$); otherwise we set $a_i = a_{i - 1} - y$. Note that all $a_i$ are in range $[-(x + y), B]$ so there won't be any overflow/underflow. It's also not hard to prove that this strategy maximizes ...
[ "greedy" ]
800
fun main() { repeat(readLine()!!.toInt()) { val (n, B, x, y) = readLine()!!.split(' ').map { it.toInt() } var cur = 0L var ans = 0L for (i in 1..n) { cur += if (cur + x <= B) x else -y ans += cur } println(ans) } }
1657
C
Bracket Sequence Deletion
You are given a bracket sequence consisting of $n$ characters '(' and/or )'. You perform several operations with it. During one operation, you choose the \textbf{shortest} prefix of this string (some amount of first characters of the string) that is \textbf{good} and remove it from the string. The prefix is considere...
Consider the first character of the string. If it is '(', then we can remove the first two characters of the string and continue (because the prefix of length $2$ will be either a palindrome or a regular bracket sequence). If the first character of the string is ')' then this is a bad case. Of course, the regular brack...
[ "greedy", "implementation" ]
1,200
#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; string s; cin >> n >> s; int l = 0; int cnt = 0; while (l...
1657
D
For Gamers. By Gamers.
Monocarp is playing a strategy game. In the game, he recruits a squad to fight monsters. Before each battle, Monocarp has $C$ coins to spend on his squad. Before each battle starts, his squad is empty. Monocarp chooses \textbf{one type of units} and recruits no more units of that type than he can recruit with $C$ coin...
Imagine you are fighting the $j$-th monster, and you fixed the type of units $i$ and their amount $x$. What's the win condition? $\frac{H_j}{d_i \cdot x} < \frac{h_i}{D_j}$. Rewrite it as $H_j \cdot D_j < d_i \cdot x \cdot h_i$. Notice how we only care about $d \cdot h$ for both the units and the monster, but not about...
[ "binary search", "brute force", "greedy", "math", "sortings" ]
2,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) int main(){ int n, C; scanf("%d%d", &n, &C); vector<long long> bst(C + 1); forn(i, n){ int c, d, h; scanf("%d%d%d", &c, &d, &h); bst[c] = max(bst[c], d * 1ll * h); } for (int c = 1; c <= C; ++c) for (int xc ...
1657
E
Star MST
In this problem, we will consider \textbf{complete} undirected graphs consisting of $n$ vertices with weighted edges. The weight of each edge is an integer from $1$ to $k$. An undirected graph is considered \textbf{beautiful} if the sum of weights of all edges incident to vertex $1$ is equal to the weight of MST in th...
Let the weight of the edge between the vertex $x$ to the vertex $y$ be $w_{x,y}$. Suppose there exists a pair of vertices $x$ and $y$ (with indices greater than $2$) such that $w_{x,y} < w_{1,x}$ or $w_{x,y} < w_{1,y}$. Then, if we choose the spanning tree with all vertices connected to $1$, it won't be an MST: we can ...
[ "combinatorics", "dp", "graph matchings", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int binpow(int a, int b){ int res = 1; while (b){ if (b & 1) ...
1657
F
Words on Tree
You are given a tree consisting of $n$ vertices, and $q$ triples $(x_i, y_i, s_i)$, where $x_i$ and $y_i$ are integers from $1$ to $n$, and $s_i$ is a string \textbf{with length equal to the number of vertices on the simple path from $x_i$ to $y_i$}. You want to write a lowercase Latin letter on each vertex in such a ...
Let's design a naive solution first. For each of the given triples, we have two options: either write the string on the tree in the order from $x_i$ to $y_i$, or in reverse order. Some options conflict with each other. So, we can treat this problem as an instance of 2-SAT: create a variable for each of the given string...
[ "2-sat", "dfs and similar", "dsu", "graphs", "trees" ]
2,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) vector<vector<int>> t; vector<int> p, h; void init(int v){ for (int u : t[v]) if (u != p[v]){ p[u] = v; h[u] = h[v] + 1; init(u); } } vector<int> get_path(int v, int u){ vector<int> l, r; while (v != u)...
1658
A
Marin and Photoshoot
Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot! For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $2$ cosplayers, the number of males does not exceed the number of females (obviously). Curr...
How will you solve this problem if there are just $2$ male cosplayers? Notice the distance between $2$ consecutive male cosplayers. It is easy to see, in a beautiful picture, there must be at least $2$ female cosplayers between $2$ consecutive male cosplayers. It is also the sufficient condition, as if there are $x$ ma...
[ "constructive algorithms", "implementation", "math" ]
800
t = int(input()) for _ in range(t): n = input() s = input() ans = 0 cnt = 2 for c in s: if c == '1': cnt += 1 else: ans += max(2 - cnt, 0) cnt = 0 print(ans)
1658
B
Marin and Anti-coprime Permutation
Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length $n$ is a permutation that has the following property: $$ \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n) > 1, $$ where $\gcd$ is the greatest common divisor. A permutation is an array consisting of $n$ di...
Let's $g = \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n)$. What is the maximum value of $g$? For each value of $g$, can you construct a satisfying permutation? We can prove that $g \leq 2$. Assuming $g > 2$: If there exists a prime number $p > 2$ that $p \mid g$, there are $\left \lfloor \dfrac{n}{p} \ri...
[ "combinatorics", "math", "number theory" ]
800
MOD = 998244353 t = int(input()) for _ in range(t): n = int(input()) if n & 1: print(0) continue ans = 1 for i in range(1, n // 2 + 1): ans = ans * i % MOD ans = ans * ans % MOD print(ans)
1658
C
Shinju and the Lost Permutation
Shinju loves permutations very much! Today, she has borrowed a permutation $p$ from Juju to play with. The $i$-th cyclic shift of a permutation $p$ is a transformation on the permutation such that $p = [p_1, p_2, \ldots, p_n] $ will now become $ p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}]$. Let's define th...
There is exactly one $1$ in array $c$ (in $(i - 1)$-th cyclic shift, $c_i > 1$ if $p_1 \neq n$, and $c_i = 1$ if $p_1 = n$), so if the number of $1s$ is greater or less than one, the answer is $\texttt{NO}$. We can rotate the array such that $c_1 = 1$ (initial state) because we don't have to construct the permutation, ...
[ "constructive algorithms", "math" ]
1,700
import sys input = sys.stdin.readline t = int(input()) for _ in range (t): n = int(input()) a = list(map(int, input().split())) if a.count(1) != 1: print("NO") continue a.append(a[0]) ok = True for i in range (0, n): if a[i + 1] - a[i] > 1: ok = False ...
1658
D1
388535 (Easy Version)
This is the easy version of the problem. The difference in the constraints between both versions is colored below in red. You can make hacks only if all versions of the problem are solved. Marin and Gojou are playing hide-and-seek with an array. Gojou initially performs the following steps: - First, Gojou chooses $2...
Let's look at the binary representation of numbers from $0$ to $7$: $000$ $001$ $010$ $011$ $100$ $101$ $110$ $111$ Let us look at the $i$-th bit only (maybe $i=2$), we will get a sequence like $[0,0,1,1,0,0,1,1]$. Notice that the number of zeroes equals the number of ones in a prefix only when the length of the prefix...
[ "bitmasks", "math" ]
1,600
import sys input = sys.stdin.readline t = int(input()) for _ in range (t): l, r = map(int, input().split()) a = list(map(int, input().split())) cnt = [[0] * 2 for _ in range (32)] for x in a: for i in range (31): cnt[i][x & 1] += 1 x >>= 1 ans = 0 for i in r...
1658
D2
388535 (Hard Version)
This is the hard version of the problem. The difference in the constraints between both versions are colored below in red. You can make hacks only if all versions of the problem are solved. Marin and Gojou are playing hide-and-seek with an array. Gojou initially perform the following steps: - First, Gojou chooses $2...
If $a \oplus b = 1$, then $(a \oplus x) \oplus (b \oplus x) = 1$. if $l$ is even and $r$ is odd, the last bit of $x$ can be either $0$ or $1$ (we can pair $a_i$ with $a_i \oplus 1$). There are two solutions to this problem. If $l$ is even and $r$ is odd, we can skip the last bit and divide the range by two, then recurs...
[ "bitmasks", "brute force", "data structures", "math" ]
2,300
import sys input = sys.stdin.readline def solve(l: int, r: int, s: set): if l % 2 == 0 and r % 2 == 1: t = set() for v in s: t.add(v >> 1) return solve(l >> 1, r >> 1, t) << 1 else: for v in s: if (v ^ 1) not in s: ok = True ans = v ...
1658
E
Gojou and Matrix Game
Marin feels exhausted after a long day of cosplay, so Gojou invites her to play a game! Marin and Gojou take turns to place one of their tokens on an $n \times n$ grid with Marin starting first. There are some restrictions and allowances on where to place tokens: - Apart from the first move, the token placed by a pla...
What if a player is forced to play in a cell where they get fewer points than the previous move? Rephrase the problem, then solve it with dynamic programming. Suppose that Marin places a token at $(a,b)$. If Gojou places a token at $(c,d)$ where $V_{c,d}<V_{a,b}$, then Gojou would not have any advantage as Marin can pl...
[ "data structures", "dp", "games", "hashing", "implementation", "math", "number theory", "sortings" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 2e3 + 5; bool f[N][N]; int l, r, u, d, n, k; vector<array<int, 5>> v; bool check(int i, int j) { return (abs(i - u) <= k && abs(i - d) <= k && abs(j - l) <= k && abs(j - r) <= k); } void solve(){ cin >> n >> k; for (int i = 1; i <= n; ++i) { ...
1658
F
Juju and Binary String
The cuteness of a binary string is the number of $1$s divided by the length of the string. For example, the cuteness of $01101$ is $\frac{3}{5}$. Juju has a binary string $s$ of length $n$. She wants to choose some non-intersecting subsegments of $s$ such that their concatenation has length $m$ and it has the same cut...
Let $b$ be the number of black balls and $w$ be the number of white balls. The answer will be impossible if $m$ is not a multiple of $\dfrac{b+w}{gcd(b, w)}$. It is easy to show that the cuteness of $s$ is $\dfrac{b}{n}$. What is the number of $\texttt{1}$ in the concatenated string needed so that the answer exists? Th...
[ "brute force", "constructive algorithms", "greedy", "math" ]
2,700
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; string s; cin >> s; int one = count_if(s.begin(), s.end(), [](char c) { return c == '1'; }); if (1LL * ...
1659
A
Red Versus Blue
Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $n$ matches. In the end, it turned out Team Red won $r$ times and Team Blue won $b$ times. Team Blue was less skilled than Team Red, so $b$ was \textbf{strictly less} than $r$. You missed the strea...
We have $b$ B's which divide the string into $b + 1$ regions and we have to place the R's in these regions. By the strong form of the pigeonhole principle, at least one region must have at least $\lceil\frac{r}{b + 1}\rceil$ R's. This gives us a lower bound on the answer. Now, we will construct a string whose answer is...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,000
t = int(input()) for i in range(t): n, r, b = map(int, input().split()) p = r % (b + 1) y = "" for j in range(int(r / (b + 1))): y = y + "R" ans = "" for i in range(b + 1): if i > 0: ans = ans + "B" ans = ans + y if p > 0: ans = ans + "R" ...
1659
B
Bit Flipping
You are given a binary string of length $n$. You have \textbf{exactly} $k$ moves. In one move, you must select a single bit. The state of all bits \textbf{except} that bit will get flipped ($0$ becomes $1$, $1$ becomes $0$). You need to output the lexicographically largest string that you can get after using \textbf{al...
Let's see how many times a given bit will get flipped. Clearly, a bit gets flipped whenever it is not selected in an operation. Therefore, the $i$-th bit gets flipped $k-f_i$ times. We want to select a bit as few times as possible. Now we can handle a few cases. $k$ is even, bit $i$ is $1$ $\Rightarrow$ $f_i=0$ (even n...
[ "bitmasks", "constructive algorithms", "greedy", "strings" ]
1,300
t = int(input()) for i in range(t): n, k = map(int, input().split()) kc = k s = input() f = [0] * n ans = "" for i in range(n): if k == 0: break if kc % 2 == 1 and s[i] == '1': f[i] = f[i] + 1 k = k - 1 elif kc % 2 == 0 and s[i] == '0':...
1659
C
Line Empire
You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers. Consider a number axis. The capital of your empire is initially at $0$. There are $n$ unconquered kingdoms at positions $0<x_1<x_2<\ldots<x_n$. You want to conquer all other kingdoms. The...
Clearly, we should always move from left to right. Also, assume $x_0=0$ for simplicity. Let us analyze what our cost would look like. It will be composed of a part due to moving capitals, and a part due to conquering kingdoms. If we shift our capital from $x_i$ to $x_j$, the cost is $a\cdot(x_j-x_i)$. If we conquer kin...
[ "binary search", "brute force", "dp", "greedy", "implementation", "math" ]
1,500
#include<bits/stdc++.h> using namespace std; using lol=long long int; #define endl "\n" const lol inf=1e18+8; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int _=1; cin>>_; while(_--) { int n; lol a,b; cin>>n>>a>>b; vector<lol> x(n+1),p(n+1); x[0]=0; for(int i=1;i<=n;i++) cin...
1659
D
Reverse Sort Sum
Suppose you had an array $A$ of $n$ elements, each of which is $0$ or $1$. Let us define a function $f(k,A)$ which returns another array $B$, the result of sorting the first $k$ elements of $A$ in non-decreasing order. For example, $f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$. Note that the first $4$ elements were sorted....
The first thing to notice is that any $1$ in the initial array $A$, will contribute to the sum of elements of array $C$ exactly $n$ times. That means, if $S=c_1+c_2+...+c_n$, $S$ must be divisible by $n$. Let $k=\frac{S}{n}$ be the number of $1$s in the initial array $A$. Observation: The $1$s in $B_n$ form a suffix of...
[ "constructive algorithms", "data structures", "greedy", "implementation", "math", "two pointers" ]
1,900
#include<bits/stdc++.h> using namespace std; using lol=long long int; #define endl "\n" int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int _=1; cin>>_; while(_--) { int n; cin>>n; vector<lol> v(n); for(auto& e:v) cin>>e; int k=accumulate(v.begin(),v.end(),0ll)/n; vector<int> b(...
1659
E
AND-MEX Walk
There is an undirected, connected graph with $n$ vertices and $m$ weighted edges. A walk from vertex $u$ to vertex $v$ is defined as a sequence of vertices $p_1,p_2,\ldots,p_k$ (which are not necessarily distinct) starting with $u$ and ending with $v$, such that $p_i$ and $p_{i+1}$ are connected by an edge for $1 \leq ...
Observation: The MEX can only be $0$, $1$, or $2$. Proof: Suppose the MEX is greater than $2$. We know that on using the bitwise AND function, some on bits will turn off and the sequence will be non-increasing. This would imply that we have $2$, $1$ and $0$ in our sequence. However, going from $2$ (10) to $1$ (01) is n...
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs" ]
2,200
#pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx,avx2,fma") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; mt19937_64 rn...
1659
F
Tree and Permutation Game
There is a tree of $n$ vertices and a permutation $p$ of size $n$. A token is present on vertex $x$ of the tree. Alice and Bob are playing a game. Alice is in control of the permutation $p$, and Bob is in control of the token on the tree. In Alice's turn, she \textbf{must} pick two \textbf{distinct} \textbf{numbers} $...
Let us call all such $i$ that satisfy $p_i \neq i$ as marked. If $p_i=i$, it is called unmarked. Also, a notation like $XY$ means "swap $X$ and $Y$ in the permutation". We are going to show that it is always possible for Alice to win if the diameter of the tree is $\geq 3$. First of all, it should be obvious that no ma...
[ "dfs and similar", "games", "graphs", "trees" ]
3,000
#include<bits/stdc++.h> using namespace std; using lol=long long int; #define endl "\n" pair<int,int> dfs(int u,const vector<vector<int>>& g,int p=-1) //returns {node with max dist,max dist} { pair<int,int> res{u,0}; int mx=0; for(auto v:g[u]) { if(v==p) continue; pair<int,int> cur=...
1660
A
Vasya and Coins
Vasya decided to go to the grocery store. He found in his wallet $a$ coins of $1$ burle and $b$ coins of $2$ burles. He does not yet know the total cost of all goods, so help him find out $s$ ($s > 0$): the \textbf{minimum} positive integer amount of money he \textbf{cannot} pay without change or pay at all using only ...
If Vasya has $b$ coins of $2$ burles, then he can collect amounts of $2, 4, \dots, 2 * b$ burls. If Vasya does not have $1$ burles coins, then he cannot collect the amount of $1$ burle. If he has at least one coin in $1$ burl, he can score odd amounts up to $2*b + a$. The following $1$burl coins increase the maximum am...
[ "greedy", "math" ]
800
#include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; int main() { int t; cin >> t; for (int it = 0; it < t; ++it) { int a, b; cin >> a >> b; cout << (a == 0 ? 1 : a + 2 * b + 1) << '\n'; } return 0; }
1660
B
Vlad and Candies
Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $n$ types of candies, there are $a_i$ candies of the type $i$ ($1 \le i \le n$). Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there a...
There will be three cases in total, let's consider them on two types of candies: $a_1 = a_2$, then we will eat candies in this order $[1, 2, 1, 2, \ dots, 1, 2]$ $a_1 = a_2 + 1$, then we will eat a candy of the type $1$, and then we will eat in this order $[2, 1, 2, 1, \dots, 2, 1]$ (almost as in the case above) $a_1 >...
[ "math" ]
800
t = int(input()) for _ in range(t): n = int(input()) a = [int(x) for x in input().split()] a.sort() if n == 1: if a[0] > 1: print("NO") else: print("YES") continue if a[-2] + 1 < a[-1]: print("NO") else: print("YES")