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 ⌀ |
|---|---|---|---|---|---|---|---|
1575 | D | Divisible by Twenty-Five | Mr. Chanek has an integer represented by a string $s$. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.
Mr. Chanek wants to count the number of possible integer $s$, where $s$ is divisible by $25$. Of ... | There are no dirty tricks to solve this problem. Brute force all possible number between $i \in [10^{|s| - 1}, 10^{|s|} - 1]$, with step $i := i + 25$. You might want to handle when $|s| = 1$, because $0$ is a valid $s$, if possible. For easier implementation, you can use the std::to_string(s) in C++. It is also possib... | [
"brute force",
"dfs and similar",
"dp"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
#define sz(x) (int)(x).size()
typedef long long LL;
LL expo(LL a, LL b){
// a %= MOD; // USE THIS WHEN N IS REALLY BIG!
LL ret = 1;
while(b > 0){
if(b&1) ret = (ret*a);
a = (a*a); b >>= 1;
}
return ret;
}
int main(){
ios_base::sync_with_stdio(0);
cin... |
1575 | E | Eye-Pleasing City Park Tour | There is a city park represented as a tree with $n$ attractions as its vertices and $n - 1$ rails as its edges. The $i$-th attraction has happiness value $a_i$.
Each rail has a color. It is either black if $t_i = 0$, or white if $t_i = 1$. Black trains only operate on a black rail track, and white trains only operate ... | We can use centroid decomposition to solve this problem. Suppose we find the centroid $cen$ of the tree, and root the tree at $cen$. We consider each subtree of the children of $cen$ as different groups of vertices. We want to find the sum of $f(u,v)$ for all valid tours, such that $u$ and $v$ are from different groups... | [
"data structures",
"trees"
] | 2,600 | null |
1575 | F | Finding Expected Value | Mr. Chanek opened a letter from his fellow, who is currently studying at Singanesia. Here is what it says.
Define an array $b$ ($0 \leq b_i < k$) with $n$ integers. While there exists a pair $(i, j)$ such that $b_i \ne b_j$, do the following operation:
- Randomly pick a number $i$ satisfying $0 \leq i < n$. Note that... | We can use this trick, which is also explained below. Suppose $a_i \neq -1$ for now. We want to find a function $F(a)$ such that $\mathbb{E}(F_{t + 1} - F_t | F_t) = -1$, where $F_t$ is the value of $F(a)$ at time $t$. If we can find such a function, then the expected stopping time is equal to $F(a_0) - F(a_T)$, where ... | [
"math"
] | 2,900 | null |
1575 | G | GCD Festival | Mr. Chanek has an array $a$ of $n$ integers. The prettiness value of $a$ is denoted as:
$$\sum_{i=1}^{n} {\sum_{j=1}^{n} {\gcd(a_i, a_j) \cdot \gcd(i, j)}}$$
where $\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
In other words, the prettiness value of an array $a$ is the total sum of ... | Define: $d(n)$ as the set of all divisors of $n$; $\phi(x)$ as the euler totient function of $x$; and $d(a, b)$ as the set of all divisors of both $a$ and $b$; or equivalently, $d(\gcd(a, b))$. Observe that $\sum_{x \in d(n)}\phi(x) = n$. This implies $\sum_{x \in d(a, b)}\phi(x) = \gcd(a,b)$ $\sum_{i = 1}^n \sum_{j = ... | [
"math",
"number theory"
] | 2,200 | null |
1575 | H | Holiday Wall Ornaments | The Winter holiday will be here soon. Mr. Chanek wants to decorate his house's wall with ornaments. The wall can be represented as a binary string $a$ of length $n$. His favorite nephew has another binary string $b$ of length $m$ ($m \leq n$).
Mr. Chanek's nephew loves the non-negative integer $k$. His nephew wants ex... | Do a dynamic programming with three states: Position in $s$ Position in $t$ How many matches left. define the dynamic programming of $dp[a][b][rem]$ as the minimum cost of having the string $p = s[1..a]$, $rem$ matches left, and the longest prefix match between $s$ and $t$ is at $b$. The answer will be at $dp[n][c][0]$... | [
"dp",
"strings"
] | 2,200 | null |
1575 | I | Illusions of the Desert | Chanek Jones is back, helping his long-lost relative Indiana Jones, to find a secret treasure in a maze buried below a desert full of illusions.
The map of the labyrinth forms a tree with $n$ rooms numbered from $1$ to $n$ and $n - 1$ tunnels connecting them such that it is possible to travel between each pair of room... | Note that $\max(|a_x + a_y|, |a_x - a_y|) = |a_x| + |a_y|$. Now the problem can be reduced to updating a vertex's value and querying the sum of values of vertices in a path. This can be done in several ways. One can use euler tour tree flattening method, as described in Euler Tour Magic by brdy blog, or use heavy-light... | [
"data structures",
"trees"
] | 2,300 | null |
1575 | J | Jeopardy of Dropped Balls | Mr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid $a$ of size $n \times m$
Each cell $(x,y)$ contains an integer $a_{x,y}$ denoting the direction of how the ball will move.
- $a_{x,y}=1$ — the ball will move to the right (the next cell is $(x, y + 1)$);
- $a_{x,y}=2$ — the ball will mo... | Naively simulating the ball's path is enough, and runs in $O(nm + nk)$. Note that if we visit a non-$2$ cell, then the path length of the current ball is increased by $1$, and then the cell turns into $2$. So the total length of all paths can be increased by at most $O(nm)$ times. In addition, each ball needs at least ... | [
"binary search",
"brute force",
"dsu",
"implementation"
] | 1,500 | null |
1575 | K | Knitting Batik | Mr. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid $a$ with size $n \times m$. There are $k$ colors, and each cell in the grid can be one of the $k$ colors.
\textbf{Define} a sub-rectangle as an ordered pair of two cells $((x_1, y_1), (x_2, y_2))$, denoting the top-left cell a... | October the 2nd is the National Batik Day of Indonesia Observe that only some several non-intersecting part of $nm - rc$ that is independent in the grid. Simple casework shows that the answer is $k^{nm}$ if $a = b$, and $k^{nm - rc}$ otherwise. Time complexity: $O(\log nm)$ | [
"implementation",
"math"
] | 2,200 | null |
1575 | L | Longest Array Deconstruction | Mr. Chanek gives you a sequence $a$ indexed from $1$ to $n$. Define $f(a)$ as the number of indices where $a_i = i$.
You can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the $3$-rd element from the sequence $[4, 2, 3, 1]$, the res... | Define $a'$ as the array we get after removing some elements in $a$ and valid element as $a'_i$ that satisfy $a'_i = i$. We can try to find combination of indices ${c_1, c_2, \dots c_m}$ such that $a_{c_i} = a'_{p_i} = p_i$ for a certain set ${p_1, p_2, \dots p_m}$. In other words, we want to find all indices ${c_1, c_... | [
"data structures",
"divide and conquer",
"dp",
"sortings"
] | 2,100 | null |
1575 | M | Managing Telephone Poles | Mr. Chanek's city can be represented as a plane. He wants to build a housing complex in the city.
There are some telephone poles on the plane, which is represented by a grid $a$ of size $(n + 1) \times (m + 1)$. There is a telephone pole at $(x, y)$ if $a_{x, y} = 1$.
For each point $(x, y)$, define $S(x, y)$ as the ... | Interestingly, if you generate the Voronoi Diagram and transcribe it to a grid, then the same connected area in the Voronoi Diagram is not necessarily in the same 8-connected component in the grid. This is why most Dijkstra solutions will get WA. We can use convex hull trick to solve this problem. Suppose that we only ... | [
"data structures",
"geometry"
] | 2,400 | null |
1579 | A | Casimir's String Solitaire | Casimir has a string $s$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions:
- he can either erase exactly one letter 'A' \textbf{and} exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent);
- or h... | Note that no matter which action is chosen, after this action is performed exactly one letter 'B' is erased from the string exactly two letters in total are erased from the string Let's denote the length of the string $s$ by $n$. If $n$ is odd, then described turns can not erase all the characters from the strings, bec... | [
"math",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
cout << (count(s.begin(), s.end(), 'B') * 2 == s.size() ?
"YES\n" : "NO\n");
}
} |
1579 | B | Shifting Sort | The new generation external memory contains an array of integers $a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$.
This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back in... | In this problem, it was enough to implement an analogue of standard selection sort or insertion sort. Here is an example of a solution based on selection sort. Let's find the minimum element in the array by simply iterating over it. Let's denote its index in the array by $p_1$. If we apply a shift "$1$ $p_1$ $(p_1 - 1)... | [
"implementation",
"sortings"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
vector<pii> actions;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n - 1; i+... |
1579 | C | Ticks | Casimir has a rectangular piece of paper with a checkered field of size $n \times m$. Initially, all cells of the field are white.
Let us denote the cell with coordinates $i$ vertically and $j$ horizontally by $(i, j)$. The upper left cell will be referred to as $(1, 1)$ and the lower right cell as $(n, m)$.
Casimir ... | For each painted cell, we will determine whether it can be part of some tick of the allowed size. If some of the cells cannot be a part of any tick, the answer is obviously NO. Otherwise, let's match each colored cell with an arbitrary valid (entirely contained in the field under consideration and of size $\ge k$) tick... | [
"greedy",
"implementation"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, m, k;
cin >> n >> m >> k;
vector<vector<int>> status(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0;... |
1579 | D | Productive Meeting | An important meeting is to be held and there are exactly $n$ people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.
Each person has limited sociability. The sociability of the $i$-th person is a non-negative intege... | For the first conversation let's choose two people $i$ and $j$ with maximal values of sociability. Note that after this conversation takes place, we move on to a similar problem, but in which $a_i$ and $a_j$ are decreased by $1$. After decreasing $a_i$ and $a_j$ by $1$, we repeat the choice of the two people with the m... | [
"constructive algorithms",
"graphs",
"greedy"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
auto cmp = [](pii const &x, pii const &y) {
return x > y;
};
set<pii, decltype(cmp)> a(cmp);
vector<pii> answe... |
1579 | E1 | Permutation Minimization by Deque | In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.
A permutation $p$ of size $n$ is given. A permutation of size $n$ is an array of size $n$ in which each integer from $1$ to $n$ occurs exactly once. For example, $[1, 4, 3, 2]$ and $[4, 2, 1, 3]$ are... | We'll process the permutation elements one by one. For the first element, it doesn't matter which side of the deque we add it to, the result of its addition will be the same - there will be a sequence of one element (equal to the first permutation element) in the deque. Now let's consider adding the $i$-th element of a... | [
"constructive algorithms",
"greedy",
"math"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, a;
cin >> n;
deque<int> d;
for (int i = 0; i < n; i++) {
cin >> a;
if (d.empty() || a < d[0])
d.push_front(a);
else
... |
1579 | E2 | Array Optimization by Deque | In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.
You are given an integer array $a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$.
Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the b... | Let's process the array elements one by one. For the first element, it doesn't matter which side of the deque we add it to, the result of its addition will be the same - there will be a sequence of one element (equal to the first array element) in the deque. Now let's consider adding the $i$th element of an array into ... | [
"data structures",
"greedy"
] | 1,700 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef pair<int, int> node;
typedef tree<node, null_type, less<node>,
rb_tree_tag, tree_order_statistics_node_update> ordered_set;
int main() {
int t;
cin >> t;
while (t--) {
... |
1579 | F | Array Stabilization (AND version) | You are given an array $a[0 \ldots n - 1] = [a_0, a_1, \ldots, a_{n - 1}]$ of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.
In one step, the array $a$ is replaced by another array of length $n$ according to the following rules:
- First, a n... | We'll consider an arbitrary index of the array $i$ and see what changes happen to $a_i$ during several steps of the described algorithm. Let's denote by $a^k$ the value of the array after $k$ steps of the algorithm and prove by induction that $a^k_i$ is the logical "AND" of $k + 1$ elements of the array $a$, starting f... | [
"brute force",
"graphs",
"math",
"number theory",
"shortest paths"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, d;
cin >> n >> d;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
vector<bool> used(n, false);
bool fail = false;
int res = 0;
... |
1579 | G | Minimal Coverage | You are given $n$ lengths of segments that need to be placed on an infinite axis with coordinates.
The first segment is placed on the axis so that one of its endpoints lies at the point with coordinate $0$. Let's call this endpoint the "start" of the first segment and let's call its "end" as that endpoint that is not ... | One possible solution involves the method of dynamic programming. As a state of DP we will use the number of already placed segments $i$, and the distance $l$ from the "end" of the last segment to the current left boundary of the coverage, and in the DP we will store the minimal possible distance from the "end" of the ... | [
"dp"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
int maxl = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
maxl = max(maxl, a[i]);
... |
1580 | A | Portal | CQXYM found a rectangle $A$ of size $n \times m$. There are $n$ rows and $m$ columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation.
A rectangle $M$ size of $a \times b$ is called a porta... | We can enumerate the two corner of the submatrix, calculate the answer by precalculating the prefix sums. The time complexity is $O(\sum n^2m^2)$. When we enumerated the upper edge and the lower edge of the submatrix, we can calculate the answer by prefix sum. Assume the left edge of the submatrix is $l$, and the right... | [
"brute force",
"data structures",
"dp",
"greedy",
"implementation"
] | 1,700 | #include<stdio.h>
char s[402];
int sum[401][401],f[401];
inline int GetSum(int lx,int ly,int rx,int ry){
return sum[rx][ry]-sum[rx][ly-1]-sum[lx-1][ry]+sum[lx-1][ly-1];
}
inline void Solve(){
int n,m,i,j,k,ans=999999,cur;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++){
scanf("%s",s+1);
for(j=1;j<=m;j++){
sum[i][j]=s... |
1580 | B | Mathematics Curriculum | Let $c_1, c_2, \ldots, c_n$ be a permutation of integers $1, 2, \ldots, n$. Consider all subsegments of this permutation containing an integer $x$. Given an integer $m$, we call the integer $x$ good if there are exactly $m$ different values of maximum on these subsegments.
Cirno is studying mathematics, and the teache... | Define the dp state $f_{l,s,d}$ as the number of the permutaion length of $l$ with exactly $d$ such numbers that all the subsegments containing them have exactly $s$ different maxima in total. We enumerate the position of the bigest number in the permutaion. We call the position is $a$. The numbers before $a$ and after... | [
"brute force",
"combinatorics",
"dp",
"trees"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100 + 5;
int n, m, k, P;
int fac[MAX_N], c[MAX_N][MAX_N], f[MAX_N][MAX_N][MAX_N];
int add(int a, int b) {
return a + b < P ? a + b : a + b - P;
}
void dp(int sz, int cnt, int dep) {
if (f[dep][sz][cnt] != -1) return ;
register int &F = f[d... |
1580 | C | Train Maintenance | Kawasiro Nitori is excellent in engineering. Thus she has been appointed to help maintain trains.
There are $n$ models of trains, and Nitori's department will only have at most one train of each model at any moment. In the beginning, there are no trains, at each of the following $m$ days, one train will be added, or o... | Let's distinguish the trains according to $x_i + y_i$. If $x_i + y_i > \sqrt{m}$, the total times of maintenance and running don't exceed $\frac{m}{\sqrt{m}}=\sqrt{m}$. So we can find every date that the train of model $i$ begin or end maintenance in $O(\sqrt{m})$, and we can maintain a differential sequence. We can ad... | [
"brute force",
"data structures",
"implementation"
] | 2,200 | #include <bits/stdc++.h>
char BUF_R[1 << 22], *csy1, *csy2;
#define GC (csy1 == csy2 && (csy2 = (csy1 = BUF_R) + fread(BUF_R, 1, 1 << 22, stdin), csy1 == csy2) ? EOF : *csy1 ++)
template <typename Ty>
inline void RI(Ty &t) {
char c = GC;
for (t = 0; c < 48 || c > 57; c = GC);
for (; c > 47 && c < 58; c = ... |
1580 | D | Subsequence | Alice has an integer sequence $a$ of length $n$ and \textbf{all elements are different}. She will choose a subsequence of $a$ of length $m$, and defines the value of a subsequence $a_{b_1},a_{b_2},\ldots,a_{b_m}$ as $$\sum_{i = 1}^m (m \cdot a_{b_i}) - \sum_{i = 1}^m \sum_{j = 1}^m f(\min(b_i, b_j), \max(b_i, b_j)),$$ ... | First we can change the way we calculate the value of a subsequence. We can easily see the value of a subsequence $a_{b_1},a_{b_2},\ldots ,a_{b_m}$ is also $\sum_{i = 1}^m \sum_{j = i + 1}^m a_{b_i} + a_{b_j} - 2 \times f(b_i, b_j)$, which is very similar to the distance of two node on a tree. Thus we can build the car... | [
"brute force",
"divide and conquer",
"dp",
"greedy",
"trees"
] | 2,900 | #include <cstdio>
#include <algorithm>
typedef long long ll;
const int MAX_N = 4000 + 5;
int N, M, a[MAX_N], ls[MAX_N], rs[MAX_N], lw[MAX_N], rw[MAX_N], sz[MAX_N];
ll f[MAX_N][MAX_N];
inline void umax(ll &a, ll b) {
a = a < b ? b : a;
}
void dfs(int u) {
sz[u] = 1;
if (ls[u]) {
dfs(ls[u]);
... |
1580 | E | Railway Construction | Because the railway system in Gensokyo is often congested, as an enthusiastic engineer, Kawasiro Nitori plans to construct more railway to ease the congestion.
There are $n$ stations numbered from $1$ to $n$ and $m$ two-way railways in Gensokyo. Every two-way railway connects two different stations and has a positive ... | For convenience, we first define $dis[u]$ as the length of the shortest path between node 1 and node $u$ and "distance" of node $u$ as $dis[u]$, and call node $u$ is "deeper" than node $v$ if and only if $dis[u] > dis[v]$. Similarly, we call node $u$ is "lower" than node $v$ if and only if $dis[u] < dis[v]$. We will us... | [
"brute force",
"constructive algorithms",
"data structures",
"graphs",
"shortest paths"
] | 3,400 | #include <cstdio>
#include <algorithm>
#include <queue>
#include <set>
using std::set;
typedef long long ll;
char BUF_R[1 << 22], *csy1, *csy2;
#define GC (csy1 == csy2 && (csy2 = (csy1 = BUF_R) + fread(BUF_R, 1, 1 << 22, stdin), csy1 == csy2) ? EOF : *csy1 ++)
template <class T>
inline void RI(T &t) {
char c = GC... |
1580 | F | Problems for Codeforces | XYMXYM and CQXYM will prepare $n$ problems for Codeforces. The difficulty of the problem $i$ will be an integer $a_i$, where $a_i \geq 0$. The difficulty of the problems must satisfy $a_i+a_{i+1}<m$ ($1 \leq i < n$), and $a_1+a_n<m$, where $m$ is a fixed integer. XYMXYM wants to know how many plans of the difficulty of... | If two numbers $a,b$ satisfying $a+b<m$, there can only be one number not less than $\lceil \frac{m}{2} \rceil$. Consider that cut the cycle to a sequence at the first position $p$ satisfying $\max(a_p,a_{p+1})<\lceil \frac{m}{2} \rceil$. When we minus all the numbers that are not less than $\lceil \frac{m}{2} \rceil$ ... | [
"combinatorics",
"fft",
"math"
] | 3,300 | #include<stdio.h>
#include<memory.h>
#define mod 998244353
unsigned long long tmp[131073],invn;
int a_[131072];
inline int ksm(unsigned long long a,int b){int ans=1;while(b)(b&1)&&(ans=a*ans%mod),a=a*a%mod,b>>=1;return ans;}
void init(int n){
for(int i=1;i<n;i++)a_[i]=i&1?a_[i^1]|n>>1:a_[i>>1]>>1;
for(int i=tmp[0]=... |
1581 | A | CQXYM Count Permutations | CQXYM is counting permutations length of $2n$.
A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $... | Assume a permutation $p$, and $\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\forall 1 \leqslant i \leqslant 2n, q_i=2n-p_i$. We can know that $\forall 2 \leqslant i \leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ s... | [
"combinatorics",
"math",
"number theory"
] | 800 | #include<stdio.h>
int f[100001];
int main(){
f[1]=1;
for(register int i=2;i!=100001;i++){
f[i]=((i<<1)-1ll)*f[i-1]%1000000007*(i<<1)%1000000007;
}
int n;
scanf("%d",&n);
for(register int i=n;i!=0;i--){
scanf("%d",&n);
printf("%d\n",f[n]);
}
return 0;
} |
1581 | B | Diameter of Graph | CQXYM wants to create a connected undirected graph with $n$ nodes and $m$ edges, and the diameter of the graph must be strictly less than $k-1$. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most ... | If $m < n-1$, the graph can't be connected, so the answer should be No. If $m > \frac{n(n-1)}{2}$, the graph must contaion multiedges, so the answer should be No. If $m=\frac{n(n-1)}{2}$, the graph must be a complete graph. The diameter of the graph is $1$. If $k>2$ the answer is YES, otherwise the answer is NO. If $n=... | [
"constructive algorithms",
"graphs",
"greedy",
"math"
] | 1,200 | #include<stdio.h>
inline void Solve(){
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
if((n-1ll)*n>>1<m||m<n-1){
puts("NO");
return;
}
if(n==1){
if(k>1){
puts("YES");
}else{
puts("NO");
}
}else if(m<(n-1ll)*n>>1){
if(k>3){
puts("YES");
}else{
puts("NO");
}
}else if(k>2){
puts("YES");
}else{
... |
1582 | A | Luntik and Concerts | Luntik has decided to try singing. He has $a$ one-minute songs, $b$ two-minute songs and $c$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.
He wants to make the absolute difference of durations of the concerts as small as possible.... | Let $S$ be the sum of durations of all songs, that is $S = a + 2 \cdot b + 3 \cdot c$. Let's notice that since $a, b, c \ge 1$, it is possible to make a concert of any duration from $0$ to $S$ (indeed, if we just execute a greedy algorithm and take three-minute songs while possible, then take two-minute songs, and then... | [
"math"
] | 800 | #include<bits/stdc++.h>
using namespace std;
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t, a, b, c;
cin >> t;
while (t--) {
cin >> a >> b >> c;
cout << (a + c) % 2 << '\n';
}
return 0;
} |
1582 | B | Luntik and Subsequences | Luntik came out for a morning stroll and found an array $a$ of length $n$. He calculated the sum $s$ of the elements of the array ($s= \sum_{i=1}^{n} a_i$). Luntik calls a subsequence of the array $a$ nearly full if the sum of the numbers in that subsequence is equal to $s-1$.
Luntik really wants to know the number of... | It can be noticed that all subsequences with sum $s-1$ appear if we erase some $0$-es from the array and also erase exactly one $1$. We can independently calculate the number of ways to erase some $0$-es from the array (that way the sum will remain the same), then calculate the number of ways to erase exactly one $1$ f... | [
"combinatorics",
"math"
] | 900 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t, n, x;
cin >> t;
while (t--) {
cin >> n;
int cnt0 = 0, cnt1 = 0;
for (int i = 1; i <= n; ++i) {
cin >> x;
... |
1582 | C | Grandma Capa Knits a Scarf | Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $s$ of length $n$.
Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that... | Let's iterate over the letter that we will erase from the string (from 'a' to 'z'), and for each letter independently find the minimal number of erased symbols required to make the string a palindrome. Let's say we are currently considering a letter $c$. Let's use the two pointers method: we will maintain two pointers ... | [
"brute force",
"data structures",
"greedy",
"strings",
"two pointers"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t, n;
cin >> t;
while (t--) {
string s;
cin >> n >> s;
int ans = n + 1;
for (int c = 0; c < 26; ++c) {
int l = 0, r = n - 1, cnt = 0;... |
1582 | D | Vupsen, Pupsen and 0 | Vupsen and Pupsen were gifted an integer array. Since Vupsen doesn't like the number $0$, he threw away all numbers equal to $0$ from the array. As a result, he got an array $a$ of length $n$.
Pupsen, on the contrary, likes the number $0$ and he got upset when he saw the array without zeroes. To cheer Pupsen up, Vupse... | Let's consider two cases: when $n$ is even, and when $n$ is odd. If $n$ is even, let's split all numbers into pairs: let $a_1$ and $a_2$ be in one pair, $a_3$ and $a_4$ in one pair as well and so on. In the pair $a_i$, $a_{i+1}$, let $b_i=a_{i+1}$ and $b_{i+1}=-a_i$, then the sum $a_i \cdot b_i + a_{i+1} \cdot b_{i+1}$... | [
"constructive algorithms",
"math"
] | 1,600 | ttt = int(input())
for t in range(ttt):
n = int(input())
a = [int(x) for x in input().split()]
start = 0
if n % 2 == 1:
if (a[0] + a[1] != 0):
print(-a[2], -a[2], a[0] + a[1], end = " ")
elif (a[1] + a[2] != 0):
print(a[2] + a[1], -a[0], -a[0], end = " ")
else:
print(-a[1], a[0] + a[2], -a[1], end = ... |
1582 | E | Pchelyonok and Segments | Pchelyonok decided to give Mila a gift. Pchelenok has already bought an array $a$ of length $n$, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array!
Pchelyonok wants his gift to be beautiful, so he decided to choose $k$ non-overlapping segments of the array $[l_1,r_... | Let's notice that $k$ can be the answer, only if the sum of lengths of the segments does not exceed the number of elements in the array, that is $\frac{k \cdot (k + 1)}{2} \le n$. From this inequation we can get that $k$ is less than $\sqrt{2n}$, and when $n$ hits its maximal value, it does not exceed $447$. Let $dp_{i... | [
"binary search",
"data structures",
"dp",
"greedy",
"math"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int const maxn = 1e5 + 5, maxk = 450;
int a[maxn], dp[maxn][maxk];
int inf = 1e9 + 7;
ll pref[maxn];
main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t, n;
cin >> t;
while (t--) {
cin >> n;
f... |
1582 | F2 | Korney Korneevich and XOR (hard version) | \textbf{This is a harder version of the problem with bigger constraints.}
Korney Korneevich dag up an array $a$ of length $n$. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers $x \ge 0$ such that there exists an \... | Let's iterate over all numbers of the array and for each number $t$ maintain a list $g_t$ of all numbers $y$, such that it's possible to choose an increasing subsequence on the current prefix, in which $xor$ of numbers is equal to $y$, and the last number of that increasing subsequence is less than $t$. Let us currentl... | [
"binary search",
"brute force",
"dp",
"greedy",
"two pointers"
] | 2,400 | #include<bits/stdc++.h>
using namespace std;
int const max_value = (1 << 13);
vector < int > g[max_value];
int ans[max_value], r[max_value];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, x;
cin >> n;
ans[0] = 1;
for (int i = 0; i < max_value; ++i) {
g[... |
1582 | G | Kuzya and Homework | Kuzya started going to school. He was given math homework in which he was given an array $a$ of length $n$ and an array of symbols $b$ of length $n$, consisting of symbols '*' and '/'.
Let's denote a path of calculations for a segment $[l; r]$ ($1 \le l \le r \le n$) in the following way:
- Let $x=1$ initially. For e... | Notice that the segment is simple, if for any prime number we will get a bracket sequence, which has the minimal balance greater of equal to $0$. The bracket sequence is formed the following way: we will iterate over the segment and add an opening bracket if we multiply by that number, and a closing bracket, if we divi... | [
"data structures",
"number theory"
] | 2,600 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int const maxn = 1e6 + 5;
int a[maxn];
int prime[maxn];
int L[maxn];
vector < int > pos[maxn];
inline void add(int x, int l) {
L[l] = l;
while (x > 1) {
pos[prime[x]].push_back(l);
x /= prime[x];
}
}
inline void del(int ... |
1583 | A | Windblume Ode | A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.
You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $n$ ($n \ge 3$) positive \textbf{distinct} integers (i.e. different, no duplicates are allowed).
Find the largest subset ... | Let $s$ be equal to the sum of array $a$. If $s$ is composite then $a$ is the largest composite subset of itself. Otherwise, since $n \geq 3$, $s$ must be a prime number greater than $2$, meaning $s$ must be odd. Now notice that because all elements of $a$ are distinct, if we remove any one number from $a$, the remaini... | [
"math",
"number theory"
] | 800 | //make sure to make new file!
import java.io.*;
import java.util.*;
public class OmkarAndHeavenlyTreeSolution{
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
... |
1583 | B | Omkar and Heavenly Tree | Lord Omkar would like to have a tree with $n$ nodes ($3 \le n \le 10^5$) and has asked his disciples to construct the tree. However, Lord Omkar has created $m$ ($\mathbf{1 \le m < n}$) restrictions to ensure that the tree will be as heavenly as possible.
A tree with $n$ nodes is an connected undirected graph with $n$ ... | Because the number of restrictions is less than $n$, there is guaranteed to be at least one value from $1$ to $n$ that is not a value of $b$ for any of the restrictions. Find a value that is not $b$ for all of the restrictions and construct a tree that is a "star" with that value in the middle. An easy way to do this i... | [
"constructive algorithms",
"trees"
] | 1,200 | //Praise our lord and saviour qlf9
//DecimalFormat f = new DecimalFormat("##.00");
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.*;
public class CCorrect{
public static void main(String[] omkar) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in))... |
1583 | C | Omkar and Determination | The problem statement looms below, filling you with determination.
Consider a grid in which some cells are empty and some cells are filled. Call a cell in this grid \textbf{exitable} if, starting at that cell, you can exit the grid by moving up and left through only empty cells. This includes the cell itself, so all f... | First notice that in a determinable grid, for any cell, it can't be that both the cell above it and the cell to its left are filled. If that were the case, then the cell wouldn't be exitable regardless of whether it was filled or not, and so we couldn't determine whether it was filled. Now notice that in any grid with ... | [
"data structures",
"dp"
] | 1,700 | /*
“I just don't have any patience for people who would rather hurt others instead of facing their own reality.”
– Mikoto Misaka.
*/
import static java.lang.Math.*;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class MeaningOfMikotoMisaka
{
public static... |
1583 | D | Omkar and the Meaning of Life | It turns out that the meaning of life is a permutation $p_1, p_2, \ldots, p_n$ of the integers $1, 2, \ldots, n$ ($2 \leq n \leq 100$). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries.
A query consists of an array $a_1, a_2, \ldots, a_n$ of integers betwee... | Solution 1 We will determine for each $j$, the index $\text{next}_j$ such that $p_{\text{next}_j} = p_j + 1$. For each index $j$, perform a query with all $1$s except that $a_j = 2$. If the result $k$ exists, then we should set $\text{next}_k = j$. Also, for each index $j$, perform a query with all $2$s except that $a_... | [
"constructive algorithms",
"greedy",
"interactive"
] | 1,800 | //stan hu tao
//come to K-expo!!!
//watch me get carried in nct ridin
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class MomentOfBloomModel
{
static ArrayDe... |
1583 | E | Moment of Bloom | She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.
Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of $n$ nodes with $m$ edges. You also have $q$ queries. Each query co... | Let $f_v$ be the number of times $v$ appears in the $q$ queries. If $f_v$ is odd for any $1 \leq v \leq n$, then there does not exist an assignment of paths that will force all even edge weights. To see why, notice that one query will correspond to exactly one edge adjacent to $v$. If an odd number of paths are adjacen... | [
"constructive algorithms",
"dfs and similar",
"graph matchings",
"graphs",
"greedy",
"trees"
] | 2,200 | //stan hu tao
//come to K-expo!!!
//watch me get carried in nct ridin
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class DefenderModel
{
public static void ... |
1583 | F | Defender of Childhood Dreams | Even if you just leave them be, they will fall to pieces all by themselves. So, someone has to protect them, right?
You find yourself playing with Teucer again in the city of Liyue. As you take the eccentric little kid around, you notice something interesting about the structure of the city.
Liyue can be represented ... | The minimum number of colors that you need is $\lceil \log_k n \rceil$. To achieve this, you can divide the nodes into $k$ contiguous subsegments of equal size (or as close as possible). Any edge between nodes in different subsegments, you color with $1$ for example. Then you recursively solve those subsegments excludi... | [
"bitmasks",
"constructive algorithms",
"divide and conquer"
] | 2,500 | //khodaya khodet komak kon
# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <pii, int> p... |
1583 | G | Omkar and Time Travel | El Psy Kongroo.
Omkar is watching Steins;Gate.
In Steins;Gate, Okabe Rintarou needs to complete $n$ tasks ($1 \leq n \leq 2 \cdot 10^5$). Unfortunately, he doesn't know when he needs to complete the tasks.
Initially, the time is $0$. Time travel will now happen according to the following rules:
- For each $k = 1, 2... | Each time travel that Okabe performs creates a new set of completed tasks. We will take this as given, but it can be proven using ideas from the rest of the proof. It thus suffices to count the number of distinct sets of task that come before the first one that contains $s$ as a subset. We should first figure out what ... | [
"data structures",
"math"
] | 3,000 | //
// Created by Danny Mittal on 4/11/21.
//
#define ll int
#define MAXN 200000
#define LGMAXN 18
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct edge {
int from;
int to;
ll capacity;
ll toll;
};
bool compareEdges(edge e, edge f) {
return f.capacity... |
1583 | H | Omkar and Tours | Omkar is hosting tours of his country, Omkarland! There are $n$ cities in Omkarland, and, rather curiously, there are exactly $n-1$ bidirectional roads connecting the cities to each other. It is guaranteed that you can reach any city from any other city through the road network.
Every city has an enjoyment value $e$. ... | First, note that we can process all the queries offline. We can sort the queries by the number of vehicles in the tour group and process them in decreasing order. Now, consider solving a version of the problem with distinct enjoyment values. Then, there will always be exactly one reachable city with the maximum enjoyme... | [
"data structures",
"divide and conquer",
"sortings",
"trees"
] | 3,300 | #ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
//#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
typedef long long ll;
int n;
const int maxN = 2005;
int a[maxN][maxN];
int b[maxN][maxN];
vector<pair<int,int>> by[maxN];
const int dx[3] = {-1, 0, 0};
const int dy[3] = {0, -1... |
1584 | A | Mathematical Addition | Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:
- You are given two positive integers $u$ and $v$, find any pair of integers (\textbf{not necessarily positive}) $x$, $y$, such that: $$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$
- ... | We have the equation: $\frac{x}{u} + \frac{y}{v} =\frac{x +y}{u+ v}.$ Let's multiply the left and right parts by $u*v*(u + v)$. Received: $x * v * (u + v) + y * u * (u + v) = (x + y) * u * v$. After opening the brackets and simplifying, we have: $x *v^2 + y*u^2 = 0$. One of the solutions to this equation is $x = -u^2$,... | [
"math"
] | 800 | null |
1584 | B | Coloring Rectangles | David was given a \textbf{red} checkered rectangle of size $n \times m$. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.
As a result, he will get a set of rectangles... | Rectangles after cutting will be painted in a chess coloring. So, if the area is even, then the number of cells of different colors is the same, and if it is odd, then it differs by exactly $1$. Let's find out what part the colored cells occupy in relation to all of them. For an even area, this ratio is always $\frac{1... | [
"greedy",
"math"
] | 1,000 | null |
1584 | C | Two Arrays | You are given two arrays of integers $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$.
Let's define a transformation of the array $a$:
- Choose any non-negative integer $k$ such that $0 \le k \le n$.
- Choose $k$ distinct array indices $1 \le i_1 < i_2 < \ldots < i_k \le n$.
- Add $1$ to each of $a_{i_1}, a_{i_2},... | Let's sort the arrays first. Let's check the two smallest elements in the arrays and investigate their behavior. First, obviously, if $a_1 + 1 < b_1$ (as nothing can be matched with $a_1$) or $a_1 > b_1$ (as nothing can be matched with $b_1$) the answer is No. Then, it's possible that $a_1 = b_1 = x$. In this case, we ... | [
"greedy",
"math",
"sortings"
] | 900 | null |
1584 | D | Guess the Permutation | \textbf{This is an interactive problem.}
Jury initially had a sequence $a$ of length $n$, such that $a_i = i$.
The jury chose three integers $i$, $j$, $k$, such that $1 \leq i < j < k \leq n$, $j - i > 1$. After that, Jury reversed subsegments $[i, j - 1]$ and $[j, k]$ of the sequence $a$.
Reversing a subsegment $[l... | Note that the number of inversions on decreasing sequence of length $l$ is $(_2^l)$. As we reversed two non-overlaping subsegments, the number of inversions on each subsegment is equal to sum of number of inversions of parts of reversed subsegments, which are decreasing. First of all, let's find $A := (_2^{k-j+1}) + (_... | [
"binary search",
"combinatorics",
"interactive",
"math"
] | 2,000 | null |
1584 | E | Game with Stones | Bob decided to take a break from calculus homework and designed a game for himself.
The game is played on a sequence of piles of stones, which can be described with a sequence of integers $s_1, \ldots, s_k$, where $s_i$ is the number of stones in the $i$-th pile. On each turn, Bob picks a pair of non-empty adjacent pi... | This game has greedy strategy: look at first pile, all its stones have to be matched with stones from next pile, because it is its only adjacent pile. If pile is non-empty and there are no next pile, or next pile is smaller than current, Bob loses. Otherwise, Bob makes current pile empty, and remove corresponding numbe... | [
"binary search",
"data structures",
"games",
"greedy"
] | 2,300 | null |
1584 | F | Strange LCS | You are given $n$ strings $s_1, s_2, \ldots, s_n$, each consisting of lowercase and uppercase English letters. In addition, it's guaranteed that each character occurs in each string \textbf{at most twice}. Find the longest common subsequence of these strings.
A string $t$ is a subsequence of a string $s$ if $t$ can be... | Let's define efinegraph with vertexes ($c$, $msk$), where $chr$ denoting some character, ans $mask$ is $n$-bit mask of occasions ($i$-th bit is set to $1$ if and only if we consider second occasion of $c$ in $i$-th string). Not all $mask$ are possible for some $c$ since there could be less than $2$ occasions. Note: ver... | [
"bitmasks",
"dp",
"graphs",
"greedy",
"strings"
] | 2,600 | null |
1584 | G | Eligible Segments | You are given $n$ \textbf{distinct} points $p_1, p_2, \ldots, p_n$ on the plane and a positive integer $R$.
Find the number of pairs of indices $(i, j)$ such that $1 \le i < j \le n$, and for every possible $k$ ($1 \le k \le n$) the distance from the point $p_k$ to the \textbf{segment} between points $p_i$ and $p_j$ i... | The distance from point $P$ to segment $[AB]$ is equal to the maximum of the distance from point $P$ to ray $[AB)$ and the distance from point $P$ to ray $[BA)$. Let's fix a point $P_i$. Now we have to find all points $P_j$ such that distance from every point $P_k (1 \le k \le n)$ to the ray $[P_i, P_j)$ is less than $... | [
"geometry"
] | 3,200 | null |
1585 | A | Life of a Flower | Petya has got an interesting flower. Petya is a busy person, so he sometimes forgets to water it. You are given $n$ days from Petya's live and you have to determine what happened with his flower in the end.
The flower grows as follows:
- If the flower isn't watered for two days in a row, it dies.
- If the flower is w... | Iterating through array and looking on our element and previous element, there is possible 4 variants: $a_i == 1$ and $a_{i - 1} == 1$ - k += 5 $a_i == 1$ and $a_{i - 1} == 0$ - k += 1 $a_i == 0$ and $a_{i - 1} == 1$ - k += 0 $a_i == 0$ and $a_{i - 1} == 0$ - k = -1, break | [
"implementation"
] | 800 | null |
1585 | B | Array Eversion | You are given an array $a$ of length $n$.
Let's define the eversion operation. Let $x = a_n$. Then array $a$ is partitioned into two parts: left and right. The left part contains the elements of $a$ that are not greater than $x$ ($\le x$). The right part contains the elements of $a$ that are strictly greater than $x$ ... | Lemma: If $x$ is max element of the array then eversion doesn't change the array. Proof: In spite of the fact that division is stable, all elements will be passed to the left part. Their order won't be changed. Lemma: The lastest element after eversion is the rightest element of the array which is greater than $x$ and ... | [
"greedy"
] | 900 | null |
1585 | C | Minimize Distance | A total of $n$ depots are located on a number line. Depot $i$ lies at the point $x_i$ for $1 \le i \le n$.
You are a salesman with $n$ bags of goods, attempting to deliver one bag to each of the $n$ depots. You and the $n$ bags are initially at the origin $0$. You can carry up to $k$ bags at a time. You must collect t... | This problem can be solved with a greedy approach. First, we note that it makes sense to solve positive points $x^p$ and negative points $x^n$ separately since we would like the minimize the number of times we move across the origin. Second, when we move to the farthest depot to which we haven't delivered a bag yet, we... | [
"greedy"
] | 1,300 | null |
1585 | D | Yet Another Sorting Problem | Petya has an array of integers $a_1, a_2, \ldots, a_n$. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only $3$-cycles. More formally, in one operation he can pick $3$ \textbf{pairwise distinct... | Set of all $3$-cycles generates a group of even permuations $A_n$. So the answer is "YES" if and only if there is an even permutation that sorts array $a$. If all elements of $a$ are distinct, then there is unique sorting permutation that has the same parity as $a$. If there are identic elements in $a$, let's look at a... | [
"data structures",
"math"
] | 1,900 | null |
1585 | E | Frequency Queries | Petya has a rooted tree with an integer written on each vertex. The vertex $1$ is the root. You are to answer some questions about the tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node $v$ is the next vertex on the shortest path from $v$ to the r... | Let's traverse through the tree with depth-first-search from the root and maintain counting array ($cnt_x$ := "number of occasions of x in the sequence"). When dfs enters vertex $v$, it increases $cnt_{a_v}$ by $1$, then it proceeds all queries correspondent to $v$. When dfs leaves the vertex, it decreases $cnt_{a_v}$ ... | [
"data structures",
"dfs and similar",
"trees"
] | 2,400 | null |
1585 | F | Non-equal Neighbours | You are given an array of $n$ positive integers $a_1, a_2, \ldots, a_n$. Your task is to calculate the number of arrays of $n$ positive integers $b_1, b_2, \ldots, b_n$ such that:
- $1 \le b_i \le a_i$ for every $i$ ($1 \le i \le n$), and
- $b_i \neq b_{i+1}$ for every $i$ ($1 \le i \le n - 1$).
The number of such ar... | Let's solve the problem using the inclusion-exclusion formula. Let the $i$-th property mean that the elements $b_i$ and $b_{i+1}$ are the same. Then for each $k=1, \ldots, n - 1$ the array is divided into $n-k$ consecutive segments, where all the numbers in each of the segments are equal. Next, we will use the dynamic ... | [
"combinatorics",
"dp",
"math"
] | 2,400 | null |
1585 | G | Poachers | Alice and Bob are two poachers who cut trees in a forest.
A forest is a set of zero or more trees. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node $v$ is the next vertex on the shortest path from $v$ to the root. Children of vertex $v$ are all nodes ... | Solution below uses Sprague-Grundy theory. Make sure you understand this concept before reading the editorial. We can note that every position that appears in the game is subtree of one of initial trees or their combinations. This shows that it's sufficient to find grundy-values for all subtrees of initial trees. Dynam... | [
"dp",
"games",
"graphs",
"trees"
] | 2,500 | null |
1586 | I | Omkar and Mosaic | Omkar is creating a mosaic using colored square tiles, which he places in an $n \times n$ grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells.
A completed mosaic will be a \textbf{mastapeece} if and only if each... | The first main observation to make is that the possible mastapeeces don't just have square "loops" of the same color. A counterexample to this is shown below: Instead, observe that, in a mastapeece: a) The two cells adjacent to corner cells must be the same color as the corner. b) Any cell not on the border must be adj... | [
"combinatorics",
"constructive algorithms",
"math"
] | 3,500 | null |
1588 | F | Jumping Through the Array | You are given an array of integers $a$ of size $n$ and a permutation $p$ of size $n$. There are $q$ queries of three types coming to you:
- For given numbers $l$ and $r$, calculate the sum in array $a$ on the segment from $l$ to $r$: $\sum\limits_{i=l}^{r} a_i$.
- You are given two numbers $v$ and $x$. Let's build a d... | Let's call $B = \lfloor \sqrt{n} \rfloor$. Let's divide an array $a$ into consecutive blocks of size $B$. To answer the query we will have to sum $O(B)$ $a_i$ near the segment's bounds and $O(\frac{n}{B})$ sums on blocks. Let's try to calculate them fast. There are two types of cycles: small: with length $< B$ big: wit... | [
"binary search",
"data structures",
"graphs",
"two pointers"
] | 3,500 | null |
1592 | A | Gamer Hemose | One day, Ahmed_Hossam went to Hemose and said "Let's solve a gym contest!". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?
There is an Agent in Valorant, and he has $n$ weapons. The $i$-th ... | It's always optimal to use two weapons with the highest damage value and switch between them. Let $x$ be the highest damage value of a weapon, and $y$ be the second-highest damage value of a weapon. we will decrease monster health by $x$ in the first move, and by $y$ in the second move and so on. $ans=\begin{cases} 2 \... | [
"binary search",
"greedy",
"math",
"sortings"
] | 800 | null |
1592 | B | Hemose Shopping | Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.
Hemose has an array of $n$ integers. He wants Samez to sort the array in the non-decr... | The answer is always "YES" If $n \geq 2*x$ because you can reorder the array as you want. Otherwise, You can swap the first $n-x$ elements and the last $n-x$ elements, so you can reorder them as you want but the rest have to stay in their positions in the sorted array. So if elements in the subarray $[n-x+1, x]$ in the... | [
"constructive algorithms",
"dsu",
"math",
"sortings"
] | 1,200 | null |
1592 | C | Bakry and Partitioning | Bakry faced a problem, but since he's lazy to solve it, he asks for your help.
You are given a tree of $n$ nodes, the $i$-th node has value $a_i$ assigned to it for each $i$ from $1$ to $n$. As a reminder, a tree on $n$ nodes is a connected graph with $n-1$ edges.
You want to delete \textbf{at least $1$, but at most ... | The most important observation is: If you can partition the tree into $m$ components such that the xor of every component is $x$, Then you can partition the tree into $m-2$ components by merging any 3 adjacent components into 1 component, and the xor of the new component will equal $x$, since $x$ xor $x$ xor $x$ = $x$.... | [
"bitmasks",
"constructive algorithms",
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,700 | null |
1592 | D | Hemose in ICPC ? | \textbf{This is an interactive problem!}
{In the last regional contest Hemose, ZeyadKhattab and YahiaSherif — members of the team Carpe Diem — did not qualify to ICPC because of some \sout{un}known reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very wel... | The maximum gcd of a path equals the maximum weight of an edge in the tree. Let $x$ be the value of the maximum weight of an edge in the tree, We need to find $u$, $v$ such that there's an edge between $u$ and $v$ with weight equals $x$. Let's find $x$ by putting all the $n$ nodes in the same query, Now we need to find... | [
"binary search",
"dfs and similar",
"implementation",
"interactive",
"math",
"number theory",
"trees"
] | 2,300 | null |
1592 | E | Bored Bakry | Bakry got bored of solving problems related to xor, so he asked you to solve this problem for him.
You are given an array $a$ of $n$ integers $[a_1, a_2, \ldots, a_n]$.
Let's call a subarray $a_{l}, a_{l+1}, a_{l+2}, \ldots, a_r$ \textbf{good} if $a_l \, \& \, a_{l+1} \, \& \, a_{l+2} \, \ldots \, \& \, a_r > a_l \op... | Let $And(l, r)$ denotes the bitwise and of the elements in subarray $[L, R]$ in the array and $Xor(l, r)$ denotes the bitwise xor of the elements in subarray $[L, R]$ in the array. If subarray $[L, R]$ length is odd then it can't be a good subarray because $And(l, r)$ is a submask of $Xor(l, r)$ since every bit in $And... | [
"bitmasks",
"greedy",
"math",
"two pointers"
] | 2,400 | null |
1592 | F1 | Alice and Recoloring 1 | \textbf{The difference between the versions is in the costs of operations. Solution for one version won't work for another!}
Alice has a grid of size $n \times m$, \textbf{initially all its cells are colored white}. The cell on the intersection of $i$-th row and $j$-th column is denoted as $(i, j)$. Alice can do the f... | We will transform favorite coloring to the all-white coloring instead. Let's denote W by $0$ and B by $1$. First observation is that it doesn't make sense to do operations of type $2$ and $3$ at all. Indeed, each of them can be replaced with $2$ operations of type $1$: Instead of flipping subrectangle $[x, n]\times[1, ... | [
"constructive algorithms",
"greedy"
] | 2,600 | null |
1592 | F2 | Alice and Recoloring 2 | \textbf{The difference between the versions is in the costs of operations. Solution for one version won't work for another!}
Alice has a grid of size $n \times m$, \textbf{initially all its cells are colored white}. The cell on the intersection of $i$-th row and $j$-th column is denoted as $(i, j)$. Alice can do the f... | Everything from the editorial of the first part of the problem stays the same, except one thing: now the second operation on the modified grid costs only $2$ coins. Sadly, now it's not true that it's not optimal to use the second operation more than once. Let's denote the second operation on $a$ by $op(x, y)$ (meaning ... | [
"constructive algorithms",
"flows",
"graph matchings",
"greedy"
] | 2,800 | null |
1593 | A | Elections | The elections in which three candidates participated have recently ended. The first candidate received $a$ votes, the second one received $b$ votes, the third one received $c$ votes. For each candidate, solve the following problem: how many votes should be added to this candidate so that he wins the election (i.e. the ... | Let's solve the problem for the first candidate. To win the election, he needs to get at least $1$ more votes than every other candidate. Therefore, the first candidate needs to get at least $\max(b, c) + 1$ votes. If $a$ is already greater than this value, then you don't need to add any votes, otherwise, you need to a... | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int solveSingle(int best, int other1, int other2)
{
return max(0, max(other1, other2) + 1 - best);
}
int main()
{
int t;
cin >> t;
while (t--)
{
int a, b, c;
cin >> a >> b >> c;
cout << solveSingle(a, b, c) << ' ' << solveSingle(b, a, c) << ' ' << solveSingl... |
1593 | B | Make it Divisible by 25 | It is given a positive integer $n$. In $1$ move, one can select any single digit and remove it (i.e. one selects some position in the number and removes the digit located at this position). The operation cannot be performed if only one digit remains. If the resulting number contains leading zeroes, they are automatical... | A number is divisible by $25$ if and only if its last two digits represent one of the following strings: "00", "25", "50", "75". Let's solve for each string the following subtask: what is the minimum number of characters to be deleted so that the string becomes a suffix of the number. Then, choosing the minimum of the ... | [
"dfs and similar",
"dp",
"greedy",
"math"
] | 900 | #include <bits/stdc++.h>
using namespace std;
const string subseqs[] = { "00", "25", "50", "75" };
const int INF = 100;
int solve(string& s, string& t)
{
int sptr = s.length() - 1;
int ans = 0;
while (sptr >= 0 && s[sptr] != t[1])
{
sptr--;
ans++;
}
if (sptr < 0) return INF;
sptr--;
while (sptr >= 0... |
1593 | C | Save More Mice | There are one cat, $k$ mice, and one hole on a coordinate line. The cat is located at the point $0$, the hole is located at the point $n$. All mice are located between the cat and the hole: the $i$-th mouse is located at the point $x_i$ ($0 < x_i < n$). At each point, many mice can be located.
In one second, the follo... | Let's solve the problem using a linear search. Let $m$ be the number of mice we are trying to save. Then it is more efficient to save $m$ mice such that they are the closest ones to the hole. Let $r_i$ be the distance from the $i$-th mouse to the hole ($r_i = n - x_i$). Denote $R := \sum\limits_{i = 1}^m r_i$. Let's pr... | [
"binary search",
"greedy"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
vector<int> x(k);
for (int i = 0; i < k; i++) cin >> x[i];
sort(x.rbegin(), x.rend());
int cnt = 0;
long long sum = 0;
while (cnt < x.size() && sum + n - x[cnt] < n)
{
sum +=... |
1593 | D1 | All are Same | This problem is a simplified version of D2, but it has significant differences, so read the whole statement.
Polycarp has an array of $n$ ($n$ is even) integers $a_1, a_2, \dots, a_n$. Polycarp conceived of a positive integer $k$. After that, Polycarp began performing the following operations on the array: take an ind... | $k$ can be arbitrarily large if and only if all numbers in the array are the same. In this case, we can choose any number $k$ and subtract it from all the numbers, for example, exactly once. Suppose we fix some $k$. Let $q_i$ be the number of subtractions of the number $k$ from the number $a_i$. In this case, all numbe... | [
"math",
"number theory"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
bool inf = true;
int minval = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] != a[0])
{
inf = false;
break;
}
... |
1593 | D2 | Half of Same | This problem is a complicated version of D1, but it has significant differences, so read the whole statement.
Polycarp has an array of $n$ ($n$ is even) integers $a_1, a_2, \dots, a_n$. Polycarp conceived of a positive integer $k$. After that, Polycarp began performing the following operations on the array: take an in... | $k$ can be arbitrarily large if and only if at least half of the numbers in the array are the same. In this case, we can choose any number $k$ and subtract it from all numbers, for example, exactly once. Let's iterate over the element $a_{i_0}$, it will be the minimum among the numbers that we want to make the same. Le... | [
"brute force",
"math",
"number theory"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
set<int> divs(int n) {
set<int> d;
for (int dd = 1; dd * dd <= n; dd++)
if (n % dd == 0) {
d.insert(n / dd);
d.insert(dd);
}
return d;
}
int main() {
int t;
... |
1593 | E | Gardener and Tree | A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to \textbf{at most one} vertex.
The gardener Vitaly grew a tree from $n$ vertices. He decided to trim the tree. To do this, he performs a number of operations. In... | Let's create two arrays of length $n$. The element of the array $layer$ will contain the operation number at which the vertex which is the index of the array will be deleted. The $rem$ array will contain the number of neighbors of a given vertex at a certain time. This array must be initialized with the number of neigh... | [
"brute force",
"data structures",
"dfs and similar",
"greedy",
"implementation",
"trees"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
vector<vector<int>> g(n, vector<int>());
vector<int> rem(n, 0);
vector<int> layer(n, 0);
for (int i = 1; i < n; i++)
{
int x, y;
cin >> x >> y;
x--;
y--;
g[x].push_bac... |
1593 | F | Red-Black Number | It is given a non-negative integer $x$, the decimal representation of which contains $n$ digits. You need to color \textbf{each} its digit in red or black, so that the number formed by the red digits is divisible by $A$, and the number formed by the black digits is divisible by $B$.
\textbf{At least one} digit must be... | The number $x$ is divisible by the number $y$ if and only if $x \equiv 0$ modulo $y$. To solve this problem, let's use the concept of dynamic programming. There will be four states: the number of considered digits of the number $x$, the number of such considered digits that we have colored red, the remainder from divid... | [
"dfs and similar",
"dp",
"implementation",
"math",
"meet-in-the-middle"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 64;
bool dp[MAX_N][MAX_N][MAX_N][MAX_N]; // (taken, red, mod A, mod B) -> may be
pair<bool, int> sert[MAX_N][MAX_N][MAX_N][MAX_N]; // the same -> (true (red) | false(black), prev red/black)
int main()
{
int t;
cin >> t;
while (t--)
{
int n, a, b... |
1593 | G | Changing Brackets | A sequence of round and square brackets is given. You can change the sequence by performing the following operations:
- change the direction of a bracket from opening to closing and vice versa without changing the form of the bracket: i.e. you can change '(' to ')' and ')' to '('; you can change '[' to ']' and ']' to ... | Consider a substring $t = s[l \dots r]$. Let's call square brackets located in odd positions in the substring odd brackets, and square brackets located in even positions even brackets. Let $cnt_{odd}$ be the number of odd brackets, $cnt_{even}$ be the number of even brackets, $cnt_{all} = cnt_{odd} + cnt_{even}$ be the... | [
"constructive algorithms",
"data structures",
"dp",
"greedy"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1'000'000;
int psumOdd[MAX_N + 1];
int psumEven[MAX_N + 1];
void solve()
{
string s;
int q;
cin >> s >> q;
int n = s.length();
psumOdd[0] = psumEven[0] = 0;
for (int i = 0; i < n; i++)
{
psumOdd[i + 1] = psumOdd[i];
psumEven[i + 1] = psumEv... |
1594 | A | Consecutive Sum Riddle | Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).
You are given an integer $n$. You need to find two integers $l$ and $r$ such that $-10^{18} \le l < r \le 10^{18}$ and $l + (l + 1) + \ldots + (r - 1) + r = n$. | You can take $(-n + 1) + (-n + 2) + \ldots + (n - 1) + n$, so the sum will be $n$. Thus, $l = -n + 1$ and $r = n$. | [
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(void){
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--){
ll n;
cin>>n;
cout<<-n+1<<" "<<n<<endl;
}
} |
1594 | B | Special Numbers | Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.
Let's call a positive number special if it can be written as a sum of \textbf{different} non-negative powers of $n$. For example, for $n = 4$ number $17$ is s... | The problem is the same as finding the $k$-th number that in base $n$ has only zeros and ones. So you can write $k$ in binary system and instead of powers of $2$ add powers of $n$. | [
"bitmasks",
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9+7;
const ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ll,ii>
#define f(i,a,b) for(ll i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()
... |
1594 | C | Make Them Equal | Theofanis has a string $s_1 s_2 \dots s_n$ and a character $c$. He wants to make all characters of the string equal to $c$ using the minimum number of operations.
In one operation he can choose a number $x$ ($1 \le x \le n$) and \textbf{for every position $i$}, where $i$ is \textbf{not} divisible by $x$, replace $s_i$... | If the whole string is equal to $c$ then you don't need to make any operations. In order to find if it is possible with exactly $1$ operation, we can pass through every $x$ and count all the letters $c$ that are divisible by $x$. This takes $O(|s| log |s|)$ time complexity. If for some $x$ all its multiples are $c$ the... | [
"brute force",
"greedy",
"math",
"strings"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9+7;
const ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ll,ii>
#define f(i,a,b) for(int i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()... |
1594 | D | The Number of Imposters | Theofanis started playing the new online game called "Among them". However, he always plays with Cypriot players, and they all have the same name: "Andreas" (the most common name in Cyprus).
In each game, Theofanis plays with $n$ other players. Since they all have the same name, they are numbered from $1$ to $n$.
The... | If person $A$ said in a comment that person $B$ is a $crewmate$ then $A$ and $B$ belong to the same team (either imposters or crewmates). If person $A$ said in a comment that person $B$ is an $imposter$ then $A$ and $B$ belong to different teams. Solution $1$: You can build a graph and check if all its components are b... | [
"constructive algorithms",
"dfs and similar",
"dp",
"dsu",
"graphs"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9+7;
const ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ll,ii>
#define f(i,a,b) for(int i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()... |
1594 | E1 | Rubik's Cube Coloring (easy version) | \textbf{It is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors.}
Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?
You have a perfect binary tr... | You have $6$ choices for the first node and $4$ for each other node. Thus, the answer is $6 \cdot 4 ^{2 ^ k - 2}$. | [
"combinatorics",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9+7;
const ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ii,ll>
#define f(i,a,b) for(ll i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()
... |
1594 | E2 | Rubik's Cube Coloring (hard version) | \textbf{It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.}
Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?
You have a perfect binary tree ... | Let's define a node as marked if it has a predefined node in its subtree. There is always at least $1$ marked node since all predefined nodes are definitely marked. You can see that marked nodes form a path for the root to any predefined node. Thus there are at most $n \cdot k$ marked nodes and we can run a standard $d... | [
"brute force",
"dp",
"implementation",
"math",
"trees"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e9+7;
const ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ii,ll>
#define f(i,a,b) for(ll i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()
... |
1594 | F | Ideal Farm | Theofanis decided to visit his uncle's farm. There are $s$ animals and $n$ animal pens on the farm. For utility purpose, animal pens are constructed in one row.
Uncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one c... | The problem is the same as: We have an array $a$ of length $n$ where every element of it is a positive integer and the sum of the whole array is $s$. If no matter how we construct the array $a$, we can find a non-zero length subarray which has sum equal to $k$ print "YES" else print "NO". If $s = k$ then the answer is ... | [
"constructive algorithms",
"math"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll INF = 1e9+7;
ll MOD = 998244353;
typedef pair<ll,ll> ii;
#define iii pair<ii,ll>
#define f(i,a,b) for(int i = a;i < b;i++)
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define all(x) (x).begin(), (x).end()
int main(vo... |
1598 | A | Computer Game | Monocarp is playing a computer game. Now he wants to complete the first level of this game.
A level is a rectangular grid of $2$ rows and $n$ columns. Monocarp controls a character, which starts in cell $(1, 1)$ — at the intersection of the $1$-st row and the $1$-st column.
Monocarp's character can move from one cell... | At first glance, it seems like a graph problem. And indeed, this problem can be solved by explicitly building a graph considering cells as the vertices and checking that there is a safe path from start to finish via DFS/BFS/DSU/any other graph algorithm or data structure you know. But there's a much simpler solution. S... | [
"brute force",
"dfs and similar",
"dp",
"implementation"
] | 800 | def solve():
n = int(input())
s1 = input()
s2 = input()
bad = False
for i in range(n):
bad |= s1[i] == '1' and s2[i] == '1'
if bad:
print('NO')
else:
print('YES')
t = int(input())
for i in range(t):
solve() |
1598 | B | Groups | $n$ students attended the first meeting of the Berland SU programming course ($n$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups mu... | Since there are only five days, we can iterate over the two of them that will be the answer. Now we have fixed a pair of days $a$ and $b$ and want to check if it can be the answer. All students can be divided into four groups: marked neither of days $a$ and $b$, marked only day $a$, marked only day $b$ and marked both ... | [
"brute force",
"implementation"
] | 1,000 | t = int(input())
for i in range(t):
n = int(input())
a = [[] for i in range(n)]
for j in range(n):
a[j] = list(map(int, input().split()))
ans = False
for j in range(5):
for k in range(5):
if k != j:
cnt1 = 0
cnt2 = 0
cntno =... |
1598 | C | Delete Two Elements | Monocarp has got an array $a$ consisting of $n$ integers. Let's denote $k$ as the mathematic mean of these elements (note that it's possible that $k$ is not an integer).
The mathematic mean of an array of $n$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $n$).
Monocarp ... | First of all, instead of the mathematic mean, let's consider the sum of elements. If the mathematic mean is $k$, then the sum of elements of the array is $k \cdot n$. Let's denote the sum of elements in the original array as $s$. Note $s$ is always an integer. If we remove two elements from the array, the resulting sum... | [
"data structures",
"dp",
"implementation",
"math",
"two pointers"
] | 1,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
vector<int> a(n);
map<int, int> cnt;
for (auto &x : a) {
scanf("%d", &x);
cnt[x] += 1;
}
long long sum = accumulate(a.begin(), a.end(), 0LL);
if ((... |
1598 | D | Training Session | Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.
Monocarp has $n$ problems that none of his students have seen yet. The $i$-th problem has a topic $a_i$ (an integer from $1$ to $n$) and a difficulty $b_i$ (an integer from ... | There are many different ways to solve this problem, but, in my opinion, the easiest one is to count all possible triples and subtract the number of bad triples. The first part is easy - the number of ways to choose $3$ elements out of $n$ is just $\frac{n \cdot (n - 1) \cdot (n - 2)}{6}$. The second part is a bit tric... | [
"combinatorics",
"data structures",
"geometry",
"implementation",
"math"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n), b(n), ca(n + 1), cb(n + 1);
for (int i = 0; i < n; ++i) {
cin >> a[i] >> b[i];
ca[a[i]]++; cb[b[i]]++;
... |
1598 | E | Staircases | You are given a matrix, consisting of $n$ rows and $m$ columns. The rows are numbered top to bottom, the columns are numbered left to right.
Each cell of the matrix can be either free or locked.
Let's call a path in the matrix a staircase if it:
- starts and ends in the free cell;
- visits only free cells;
- has one... | The solution consist of two main parts: calculate the initial number of staircases and recalculate the number of staircases on query. The constraints were pretty loose, so we'll do the first part in $O(nm)$ and the second part in $O(n + m)$ per query. However, it's worth mentioning that faster is possible. The first pa... | [
"brute force",
"combinatorics",
"data structures",
"dfs and similar",
"dp",
"implementation",
"math"
] | 2,100 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int n, m, q;
scanf("%d%d%d", &n, &m, &q);
vector<vector<int>> a(n, vector<int>(m, 1));
long long ans = 0;
forn(x, n) forn(y, m){
if (x == 0){
for (int k = 1;; ++k){
int nx = x + k / 2;
int... |
1598 | F | RBS | A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example:
- bracket sequence... | The constraint $n \le 20$ is a clear hint that we need some exponential solution. Of course, we cannot try all $n!$ permutations. Let's instead try to design a solution with bitmask dynamic programming. A string is an RBS if its balance (the difference between the number of opening and closing brackets) is $0$, and the... | [
"binary search",
"bitmasks",
"brute force",
"data structures",
"dp"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
const int INF = int(1e9);
const int N = 20;
const int M = (1 << N);
struct BracketSeqn
{
int balance;
int lowestBalance;
vector<int> queryAns;
pair<int, bool> go(int x, bool f)
{
if(f)
return make_pair(0, true);
else
return ... |
1598 | G | The Sum of Good Numbers | Let's call a positive integer good if there is no digit 0 in its decimal representation.
For an array of a good numbers $a$, one found out that the sum of some two neighboring elements is equal to $x$ (i.e. $x = a_i + a_{i + 1}$ for some $i$). $x$ had turned out to be a good number as well.
Then the elements of the a... | Let's denote $a$ as the largest of the terms of the sum, and $b$ is the smaller one. Consider $2$ cases: $|a| =|x| - 1$ or $|a|=|x|$. If $|a| =|x| - 1$, then $|b| =|x| - 1$. So we need to find two consecutive substrings of length $|x| - 1$ such that if we convert these substrings into integers, their sum is equal to $x... | [
"hashing",
"math",
"string suffix structures",
"strings"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int MOD[] = { 597804841, 618557587, 998244353 };
const int N = 500 * 1000 + 13;
const int K = 3;
using hs = array<int, K>;
int add(int x, int y, int mod) {
x += y;
if (x >= mod) x -= mod;
if (x < 0) x += m... |
1601 | A | Array Elimination | You are given array $a_1, a_2, \ldots, a_n$, consisting of non-negative integers.
Let's define operation of "elimination" with integer parameter $k$ ($1 \leq k \leq n$) as follows:
- Choose $k$ distinct array indices $1 \leq i_1 < i_2 < \ldots < i_k \le n$.
- Calculate $x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ \ldots ~ \& ~... | Let's note, that in one destruction for any bit $i$ ($0 \leq i < 30$) we either change all $k$-th non-zero bits into zero bits, or nothing changes. So, the number of $i$-th non-zero bits in the array either decreases by $k$ or doesn't change. In the end, all these numbers will be equal to $0$. So, to be able to destruc... | [
"bitmasks",
"greedy",
"math",
"number theory"
] | 1,300 | null |
1601 | B | Frog Traveler | Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of $n$ meters depth. Now Gorf is on the bottom of the well and has a long way up.
The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Go... | Let's denote sequence of moves $i \Rightarrow i - a_i \dashrightarrow i - a_i + b_{i-a_i}$ as jump. We will use $dp_i$ - minimal number of moves needed to travel from $i$ to $0$. It can be calculated $dp_i = 1 + \min (dp_j + b_j)$, with $i - a_i \le j \le i$. We expected calculations to use bfs-style order. So, if ther... | [
"data structures",
"dfs and similar",
"dp",
"graphs",
"shortest paths",
"two pointers"
] | 1,900 | null |
1601 | C | Optimal Insertion | You are given two arrays of integers $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_m$.
You need to insert all elements of $b$ into $a$ in an arbitrary way. As a result you will get an array $c_1, c_2, \ldots, c_{n+m}$ of size $n + m$.
Note that you are not allowed to change the order of elements in $a$, while you ... | Let's sort array $b$. Let's define $p_i$ as the index of the array $a$, before which we should insert $b_i$. If $b_i$ should be inserted at the end of the array $a$, let's make $p_i = n + 1$. Let's note, that all inserted elements should go in the sorted order in the optimal answer. If it is false and there exists $p_i... | [
"data structures",
"divide and conquer",
"dp",
"greedy",
"sortings"
] | 2,300 | null |
1601 | D | Difficult Mountain | A group of $n$ alpinists has just reached the foot of the mountain. The initial difficulty of climbing this mountain can be described as an integer $d$.
Each alpinist can be described by two integers $s$ and $a$, where $s$ is his skill of climbing mountains and $a$ is his neatness.
An alpinist of skill level $s$ is a... | First, discard all $i$ such that $s_i < d$ Instead of climbers, we will consider pairs $(s_i, a_i)$, and also say that the set of pairs is correct if there is a permutation $p_1 \ldots p_n$ such that for every $i : \max (d, a_ {p_1}, \ldots a_ {p_ {i-1}}) \le s_ {p_i}$, which means that there is an order in which all c... | [
"data structures",
"dp",
"greedy",
"sortings"
] | 2,700 | null |
1601 | E | Phys Ed Online | Students of one unknown college don't have PE courses. That's why $q$ of them decided to visit a gym nearby by themselves. The gym is open for $n$ days and has a ticket system. At the $i$-th day, the cost of one ticket is equal to $a_i$. You are free to buy more than one ticket per day.
You can activate a ticket purch... | Observe that we need to buy a subscription at day one, then we need to buy the cheapest subscricption among first $k + 1$ days, $...$, then the cheapest among the first $tk + 1$ days. Let's denote $b_i$ as a minimum on a segment $[i - k, i - k + 1, ..., i]$, $b_i$ can be calculated in a linear time using monotonic queu... | [
"data structures",
"dp",
"greedy"
] | 2,900 | null |
1601 | F | Two Sorts | Integers from $1$ to $n$ (inclusive) were sorted lexicographically (considering integers as strings). As a result, array $a_1, a_2, \dots, a_n$ was obtained.
Calculate value of $(\sum_{i = 1}^n ((i - a_i) \mod 998244353)) \mod 10^9 + 7$.
$x \mod y$ here means the remainder after division $x$ by $y$. This remainder is... | Suppose $b$ is an inverse permutation of $a$, that is $a_{b_{i}} = b_{a_i} = i$, that is $b_i$ is an index of $i$ in the lexicographical sorting. Rewrite desired sum replacing $i \to b_i$: $\sum_{i=1 \ldots n} ((i - a_i) \bmod p) = \sum_{i=1 \ldots n} ((b_i - a_{b_i}) \bmod p) = \sum_{i=1 \ldots n} ((b_i - i) \bmod p)$... | [
"binary search",
"dfs and similar",
"math",
"meet-in-the-middle"
] | 3,400 | null |
1602 | A | Two Subsequences | You are given a string $s$. You need to find two non-empty strings $a$ and $b$ such that the following conditions are satisfied:
- Strings $a$ and $b$ are both \textbf{subsequences} of $s$.
- For each index $i$, character $s_i$ of string $s$ must belong to \textbf{exactly one} of strings $a$ or $b$.
- String $a$ is le... | Note that taking $a$ as minimum character in $s$ is always optimal ($a$ starts with minimum possible character and is prefix of any other longer string). In such case, $b$ is just all characters from $s$ except character from $a$. | [
"implementation"
] | 800 | null |
1602 | B | Divine Array | Black is gifted with a Divine array $a$ consisting of $n$ ($1 \le n \le 2000$) integers. Each position in $a$ has an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable transformation.
The transformation consists of infinite steps. Array $a$ changes at the $i$-th step in th... | It can be shown that after at most $n$ steps of transformation, array $a$ becomes repetitive. There is even a better lower bound: it can be shown that after at most $\log(n)$ steps $a$ becomes repetitive, so we use either of these two facts to simulate the process and answer the queries. | [
"constructive algorithms",
"implementation"
] | 1,100 | null |
1603 | A | Di-visible Confusion | YouKn0wWho has an integer sequence $a_1, a_2, \ldots, a_n$. He will perform the following operation until the sequence becomes empty: select an index $i$ such that $1 \le i \le |a|$ and $a_i$ is \textbf{not} divisible by $(i + 1)$, and erase this element from the sequence. Here $|a|$ is the length of sequence $a$ at th... | Notice that we can erase $a_i$ at positions from $1$ to $i$. So for each $i$, there should be at least one integer from $2$ to $i + 1$ such that $a_i$ is not divisible by that integer. If it is not satisfied for some integer $i$, then there is no solution for sure. Otherwise, it turns out that a solution always exists.... | [
"constructive algorithms",
"math",
"number theory"
] | 1,300 | #include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t; cin >> t;
while (t--) {
int n; cin >> n;
bool ok = true;
for (int i = 1; i <= n; i++) {
int x; cin >> x;
bool found = false;
for (int j = i + 1; j >= 2; j--) { // this loop ... |
1603 | B | Moderate Modular Mode | YouKn0wWho has two \textbf{even} integers $x$ and $y$. Help him to find an integer $n$ such that $1 \le n \le 2 \cdot 10^{18}$ and $n \bmod x = y \bmod n$. Here, $a \bmod b$ denotes the remainder of $a$ after division by $b$. If there are multiple such integers, output any. It can be shown that such an integer always e... | If $x \gt y$, then $x + y$ works, as $(x + y) \bmod x = y \bmod x = y$ and $y \bmod (x + y) = y$. The challenge arrives when $x \le y$. The later part of the editorial assumes that $x \le y$. Claim $1$: $n$ can't be less than $x$. Proof: Assume that for some $n \lt x$, $n \bmod x = y \bmod n$ is satisfied. Then $n \bmo... | [
"constructive algorithms",
"math",
"number theory"
] | 1,600 | #include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t; cin >> t;
while (t--) {
int x, y; cin >> x >> y;
if (x <= y) {
cout << y - y % x / 2 << '\n';
}
else {
cout << x + y << '\n';
}
}
return 0;
} |
1603 | C | Extreme Extension | For an array $b$ of $n$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $b$ \textbf{non-decreasing}:
- Select an index $i$ such that $1 \le i \le |b|$, where $|b|$ is the current length of $b$.
- Replace $b_i$ with two elemen... | Let's find out how to calculate the extreme value of an array $a$ of $n$ integers. It turns out that a greedy solution exists! Consider the rightmost index $i$ such that $a_i \gt a_{i + 1}$. So we must split $a_i$ into new (let's say $k$) elements $1 \le b_1 \le b_2 \le \ldots \le b_k \le a_{i+1}$ such that $b_1 + b_2 ... | [
"dp",
"greedy",
"math",
"number theory"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9, mod = 998244353;
vector<int> v[2];
int dp[2][N];
int a[N];
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t; cin >> t;
while (t--) {
int n; cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
long lon... |
1603 | D | Artistic Partition | For two positive integers $l$ and $r$ ($l \le r$) let $c(l, r)$ denote the number of integer pairs $(i, j)$ such that $l \le i \le j \le r$ and $\operatorname{gcd}(i, j) \ge l$. Here, $\operatorname{gcd}(i, j)$ is the greatest common divisor (GCD) of integers $i$ and $j$.
YouKn0wWho has two integers $n$ and $k$ where ... | For now, let $c(l, r)$ denote the number of integer pairs $(i, j)$ such that $l \le i \lt j \le r$ (instead of $i \le j$) and $\operatorname{gcd}(i, j) \ge l$. So we can add $n$ to $f(n, k)$ in the end. We can construct a straightforward dp where $f(n, k) = \min\limits_{i = 1}^{n}{(f(i - 1, k - 1)+c(i, n))}$. As a stra... | [
"divide and conquer",
"dp",
"number theory"
] | 3,000 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
const long long inf = 1e12;
using ll = long long;
int phi[N];
void totient() {
for (int i = 1; i < N; i++) phi[i] = i;
for (int i = 2; i < N; i++) {
if (phi[i] == i) {
for (int j = i; j < N; j += i) phi[j] -= phi[j] / i;
}
}
}
ll ... |
1603 | E | A Perfect Problem | A sequence of integers $b_1, b_2, \ldots, b_m$ is called good if $max(b_1, b_2, \ldots, b_m) \cdot min(b_1, b_2, \ldots, b_m) \ge b_1 + b_2 + \ldots + b_m$.
A sequence of integers $a_1, a_2, \ldots, a_n$ is called perfect if every non-empty subsequence of $a$ is good.
YouKn0wWho has two integers $n$ and $M$, $M$ is p... | Let's go deeper into the properties of perfect sequences. Observation $1$: If a sorted sequence $a_1, a_2, \ldots, a_n$ is perfect then all its permutations are also perfect. Actually, it's very easy to see that as the order doesn't matter. So we will work on the sorted version of the sequence. Observation $2$: The sor... | [
"combinatorics",
"dp",
"math"
] | 3,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 205;
int mod;
int power(long long n, long long k) {
int ans = 1 % mod; n %= mod; if (n < 0) n += mod;
while (k) {
if (k & 1) ans = (long long) ans * n % mod;
n = (long long) n * n % mod;
k >>= 1;
}
return ans;
}
int dp[N][N][40], fac[N],... |
1603 | F | October 18, 2017 | It was October 18, 2017. Shohag, a melancholic soul, made a strong determination that he will pursue Competitive Programming seriously, by heart, because he found it fascinating. Fast forward to 4 years, he is happy that he took this road. He is now creating a contest on Codeforces. He found an astounding problem but h... | When $x = 0$, we need to count the number of sequences $(a_1, a_2, \ldots, a_n)$, such that the $a_i$s are linearly independent. Clearly, for $n>k$ there are no such sequences, and for $n \le k$, the answer is $(2^k-1)\cdot(2^k-2)\cdot \ldots \cdot (2^k - 2^{n-1})$, as $a_i$ can be any element not generated by the elem... | [
"combinatorics",
"dp",
"implementation",
"math"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e7 + 9, mod = 998244353;
template <const int32_t MOD>
struct modint {
int32_t value;
modint() = default;
modint(int32_t value_) : value(value_) {}
inline modint<MOD> operator + (modint<MOD> other) const { int32_t c = this->value + other.value; return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.