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
1822
D
Super-Permutation
A permutation is a sequence $n$ integers, where each integer from $1$ to $n$ appears exactly once. For example, $[1]$, $[3,5,2,1,4]$, $[1,3,2]$ are permutations, while $[2,3,2]$, $[4,3,1]$, $[0]$ are not. Given a permutation $a$, we construct an array $b$, where $b_i = (a_1 + a_2 +~\dots~+ a_i) \bmod n$. A permutatio...
Let $k$ be the position of the number $n$ in the permutation $a$, that is, $a_k = n$, then if $k > 1$, then $b_k = (b_{k-1} + a_k) \mod n = b_{k-1}$ therefore, $b$ is not a permutation, so $k = 1$. Now note that if $n > 1$ is odd, then $b_n = (a_1~+~a_2~+~\dots~+~a_n) \mod n = (1 +2 +~\dots~+ n) \mod n= n \cdot\frac{(n...
[ "constructive algorithms", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int q; cin >> q; while (q--) { int n; cin >> n; if (n == 1) { cout << "1\n"; continue; } if (n % 2) { cout << "-1\n"; } else { for (int i = 0; i < n; +...
1822
E
Making Anti-Palindromes
You are given a string $s$, consisting of lowercase English letters. In one operation, you are allowed to swap any two characters of the string $s$. A string $s$ of length $n$ is called an anti-palindrome, if $s[i] \ne s[n - i + 1]$ for every $i$ ($1 \le i \le n$). For example, the strings "codeforces", "string" are a...
If $n$ is odd, then there is no solution, since $s[(n + 1) / 2] = s[(n + 1) - (n + 1) / 2]$. If $n$ is even, then all symbols are split into pairs $s[i], s[n + 1 - i]$. Let's denote the number of occurrences of the symbol $c$ as $cnt[c]$. Note that if $cnt[c] > n / 2$ for some $c$, then after applying the operations th...
[ "greedy", "math", "strings" ]
1,600
#include <bits/stdc++.h> using namespace std; void solve(int n, string & s) { if (n % 2 == 1) { cout << -1 << endl; return; } vector<int> cnt(26); for (int i = 0; i < n; ++i) { ++cnt[s[i] - 'a']; } for (int i = 0; i < 26; ++i) { if (cnt[i] * 2 > n) { ...
1822
F
Gardening Friends
Two friends, Alisa and Yuki, planted a tree with $n$ vertices in their garden. A tree is an undirected graph without cycles, loops, or multiple edges. Each edge in this tree has a length of $k$. Initially, vertex $1$ is the root of the tree. Alisa and Yuki are growing the tree not just for fun, they want to sell it. T...
Let's first calculate its depth for each vertex. Let for a vertex $v$ its depth is $depth[v]$. All the values of $depth[v]$ can be calculated by a single depth-first search. We introduce several auxiliary quantities. Let for vertex $v$ the values $down_1[v], down_2[v]$ are the two largest distances to the leaves in the...
[ "brute force", "dfs and similar", "dp", "graphs", "trees" ]
1,700
#include<bits/stdc++.h> using namespace std; struct Value { int64_t value = 0; int vertex = 0; }; vector<vector<int>> nei; vector<vector<int>> depth_vertex; vector<int> depth; vector<int> parent; void dfs(int v, int p = -1, int cnt = 0) { depth_vertex[cnt].push_back(v); depth[v] = cnt; parent[v]...
1822
G1
Magic Triples (Easy Version)
\textbf{This is the easy version of the problem. The only difference is that in this version, $a_i \le 10^6$.} For a given sequence of $n$ integers $a$, a triple $(i, j, k)$ is called magic if: - $1 \le i, j, k \le n$. - $i$, $j$, $k$ are pairwise distinct. - there exists a positive integer $b$ such that $a_i \cdot b...
Let $M = \max {a_i}$, obviously $M\le 10^6$, $cnt[x]$ - the number of occurrences of the number $x$ in the array $a$. Separately, let's count the number of magic triples for $b=1$. The total number of such triples will be $\sum_{i=1}^{n}{(cnt[a_i] - 1) \cdot (cnt[a_i] - 2)}$. Next, we will count $b\ge 2$. Note that $a_...
[ "brute force", "data structures", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; #define int long long const int MAX_VAL = 1e6; int cnt[MAX_VAL + 1]; int32_t main() { int t; cin >> t; for (int _ = 0; _ < t; ++_) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; ...
1822
G2
Magic Triples (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that in this version, $a_i \le 10^9$.} For a given sequence of $n$ integers $a$, a triple $(i, j, k)$ is called magic if: - $1 \le i, j, k \le n$. - $i$, $j$, $k$ are pairwise distinct. - there exists a positive integer $b$ such that $a_i \cdot b...
Let $M = \max {a_i}$, obviously $M \le 10^9$, $cnt[x]$ - the number of occurrences of the number $x$ in the array $a$. Separately, let's count the number of magic triples for $b=1$. The total number of such triples will be $\sum_{i=1}^{n}{(cnt[a_i] - 1) \cdot (cnt[a_i] - 2)}$. Next, we will count $b \ge 2$. We will ite...
[ "brute force", "data structures", "math", "number theory" ]
2,200
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int K = 1e6; const int MAX_VAL = 1e9; int32_t main() { int t; scanf("%d", &t); for (int _ = 0; _ < t; ++_) { int n; scanf("%d", &n); vector<int> a(n); map<int, int> cnt; for (int i = 0; i < ...
1823
A
A-characteristic
Consider an array $a_1, a_2, \dots, a_n$ consisting of numbers $1$ and $-1$. Define $A$-characteristic of this array as a number of pairs of indices $1 \le i < j \le n$, such that $a_i \cdot a_j = 1$. Find any array $a$ with given length $n$ with $A$-characteristic equal to the given value $k$.
Note that the $A$-characteristic depends only on the number of $1$-s. Let the number of $1$-s be equal to $x$, then the number of $-1$-s is equal to $n - x$, and the $A$-characteristic is equal to $f(x) = \frac{(x - 1) \cdot x}{ 2} + \frac{(n - x - 1) \cdot (n - x)}{2}$. Let's iterate over all $x$ from $0$ to $n$, and ...
[ "combinatorics", "constructive algorithms", "math" ]
800
for tt in range(int(input())): n, k = map(int, input().split()) x = -1 for i in range(0, n + 1): if i * (i - 1) / 2 + (n - i) * (n - i - 1) / 2 == k: x = i if x == -1: print("NO") else: print("YES") for i in range(0, n): if i < x: ...
1823
B
Sort with Step
Let's define a permutation of length $n$ as an array $p$ of length $n$, which contains every number from $1$ to $n$ exactly once. You are given a permutation $p_1, p_2, \dots, p_n$ and a number $k$. You need to sort this permutation in the ascending order. In order to do it, you can repeat the following operation any ...
Let's fix a number $0 \le x < k$ and consider all indices $i$ such that $i \bmod k = x$. Note that numbers in these positions can be reordered however we want, but they can't leave this set of positions, since $i \bmod k$ stay the same. Moreover, in the sorted permutation these positions must contain numbers $j$ such t...
[ "brute force", "math", "sortings" ]
900
for tt in range(int(input())): n, k = map(int, input().split()) p = list(map(int, input().split())) for i in range(0, n): p[i] -= 1 bad = 0 for i in range(0, n): if p[i] % k != i % k: bad += 1 if bad == 0: print(0) elif bad == 2: print(1) els...
1823
C
Strongly Composite
A prime number is an integer greater than $1$, which has exactly two divisors. For example, $7$ is a prime, since it has two divisors $\{1, 7\}$. A composite number is an integer greater than $1$, which has more than two different divisors. Note that the integer $1$ is neither prime nor composite. Let's look at some ...
Let's understand criteria for a number $x$ being strongly composite. Let's factorize the number $x = {p_1}^{d_1} \cdot {p_2}^{d_2} \cdot \dots \cdot {p_m}^{d_m}$. The number of all divisors of $x$ is $D = \prod\limits_{i = 1}^{m} (d_i + 1)$. Since the number of prime divisors is $m$, then the number of composite diviso...
[ "greedy", "math", "number theory" ]
1,300
def is_prime(x): i = 2 while i * i <= x: if x % i == 0: return False i += 1 return True def is_strongly_composite(x): m = [] i = 2 while i * i <= x: while x % i == 0: x = x // i m.append(i) i += 1 if not x == 1: m.a...
1823
D
Unique Palindromes
A palindrome is a string that reads the same backwards as forwards. For example, the string abcba is palindrome, while the string abca is not. Let $p(t)$ be the number of unique palindromic substrings of string $t$, i. e. the number of substrings $t[l \dots r]$ that are palindromes themselves. Even if some substring o...
Let us estimate the possible number of unique palindromes $P$: for $n = 1$: $P = 1$; for $n = 2$: $P = 2$ (in both cases: if symbols are equal and if not); for $n \ge 3$: $3 \le P \le n$. Any combination of the first three characters gives $P = 3$. If you add a character to the string, $P$ will increase by either $0$ o...
[ "constructive algorithms", "math", "strings" ]
1,900
for tt in range(int(input())): n, k = map(int, input().split()) x = list(map(int, input().split())) c = list(map(int, input().split())) if c[0] < 3 or c[0] > x[0]: print("NO") continue s = "" cur = 'a' for i in range(0, c[0] - 3): s += "a" for i in range(c[0] ...
1823
E
Removing Graph
Alice and Bob are playing a game on a graph. They have an undirected graph without self-loops and multiple edges. All vertices of the graph have \textbf{degree equal to $2$}. The graph may consist of several components. Note that if such graph has $n$ vertices, it will have exactly $n$ edges. Alice and Bob take turn. ...
The solution requires knowledge of the Sprague-Grundy theory. Recall that $a \oplus b$ means the bitwise exclusive or operation, and $\operatorname{mex}(S)$ is equal to the minimum non-negative number that is not in the set $S$. The fact that $l \neq r$ is important. The given graph is a set of cycles, and the game run...
[ "brute force", "dp", "games", "graphs", "math" ]
2,500
from sys import setrecursionlimit import threading def main(): n, l, r = map(int, input().split()) g = [[] for i in range(0, n)] for i in range(0, n): a, b = map(int, input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) res = 0 used = [False for i i...
1823
F
Random Walk
You are given a tree consisting of $n$ vertices and $n - 1$ edges, and each vertex $v$ has a counter $c(v)$ assigned to it. Initially, there is a chip placed at vertex $s$ and all counters, except $c(s)$, are set to $0$; $c(s)$ is set to $1$. Your goal is to place the chip at vertex $t$. You can achieve it by a serie...
Let $deg(v)$ be the number of neighbors of vertex $v$. Let's fix a vertex $v$ and its neighboring vertices $c_1, \dots, c_{deg(v)}$. According to the linearity of the expected values: $e_v = \sum_{u \in \{c_1, \dots, c_{deg(v)}\}} \frac{e_u}{deg(u)}$ Solution by Igor_Parfenov: Let's solve the subproblem: given a bamboo...
[ "dp", "graphs", "math", "probabilities", "trees" ]
2,600
from sys import setrecursionlimit import threading mod = 998244353 def main(): n, s, t = map(int, input().split()) s -= 1 t -= 1 g = [[] for i in range(0, n)] previous = [-1 for i in range(0, n)] inPath = [False for i in range(0, n)] res = [0 for i in range(0, n)] for i in ...
1824
A
LuoTianyi and the Show
There are $n$ people taking part in a show about VOCALOID. They will sit in the row of seats, numbered $1$ to $m$ from left to right. The $n$ people come and sit in order. Each person occupies a seat in one of three ways: - Sit in the seat next to the left of the leftmost person who is already sitting, or if seat $1$...
First we can notice that, if someone with a specific favourite seat(i.e. not $-1$ nor $-2$) has got his seat taken by a $-1$ guy or a $-2$ guy, it's better to let the first man go first, and the $-1$ or $-2$ one go after him. Now, we know it's better to make those with a favourite seat go in first. After they have seat...
[ "greedy", "implementation" ]
1,400
// Problem: C. LuoTianyi and the Theater // Contest: Codeforces - test vocaloid cf round // URL: https://codeforces.com/gym/394370/problem/C // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) //By: OIer rui_er #include <bits/stdc++.h> #define rep(x,y,z) for(int x=(y);x<=(...
1824
B2
LuoTianyi and the Floating Islands (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that in this version $k\le n$. You can make hacks only if both versions of the problem are solved.} \begin{center} {\small Chtholly and the floating islands.} \end{center} LuoTianyi now lives in a world with $n$ floating islands. The floating isl...
Call a node special if there is a person in it. When $k$ is odd, we find that there is only one node satisfying the conditions. $\bf{Proof}.$ Assume distinct node $x$ and node $y$ are good nodes. Let $x$ be the root of the tree. Define $s_i$ as the number of special nodes in subtree $i$. Think about the process we move...
[ "combinatorics", "dfs and similar", "math", "probabilities", "trees" ]
2,300
//Was yea ra,rra yea ra synk sphilar yor en me exec hymme METAFALICA waath! #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #include<bits/stdc++.h> using namespace std; #define rg register #define ll long long #define ...
1824
C
LuoTianyi and XOR-Tree
LuoTianyi gives you a tree with values in its vertices, and the root of the tree is vertex $1$. In one operation, you can change the value in one vertex to any non-negative integer. Now you need to find the minimum number of operations you need to perform to make each path from the root to leaf$^{\dagger}$ has a bitw...
Hint: Consider a brute force dynamic programming solution and try to optimize it. Denote the minimum number of operations needed to make every path from a leaf inside the subtree of $u$ to the root have the xor value of $w$ as $f_{u,w}$. Observe that for every $u$, there are only $2$ possible different values for $f_{u...
[ "data structures", "dfs and similar", "dp", "dsu", "greedy", "trees" ]
2,500
#include<iostream> #include<cstdio> #include<vector> #include<set> #include<algorithm> #include<map> using namespace std; int n,a[100005]; vector<int> e[100005]; set<int> s[100005],stmp; int ans=0,sid[100005],stp=0; bool cmp(int x,int y) { return (int)s[sid[x]].size()>(int)s[sid[y]].size(); } void set_xor(int x,int y)...
1824
D
LuoTianyi and the Function
LuoTianyi gives you an array $a$ of $n$ integers and the index begins from $1$. Define $g(i,j)$ as follows: - $g(i,j)$ is the largest integer $x$ that satisfies $\{a_p:i\le p\le j\}\subseteq\{a_q:x\le q\le j\}$ while $i \le j$; - and $g(i,j)=0$ while $i>j$. There are $q$ queries. For each query you are given four in...
Consider an alternative method of calculating $g$. Notice that $g(i,j)$ is the minimum of the last appearing position of all colors(let's call different values of $a_x$ colors for short) in the interval $[i,j]$. Consider the sequence from $a_n$ to $a_1$. Adding $a_i$ to the front of the sequence only affects the values...
[ "data structures" ]
3,000
#include<bits/stdc++.h> using namespace std; #define N 1000005 #define L long long int n,m,stt,a[N],nxt[N],siz[N],top,ll[N],rr[N],xx[N],yy[N]; L out[N]; struct ds{ L t[2][N],ta; inline void add(int op,int x,L v){while(x<=n) t[op][x]+=v,x+=(x&-x);} inline L ask(int op,int x){ta=0;while(x) ta+=t[op][x],x^=(x&-x);retur...
1824
E
LuoTianyi and Cartridge
LuoTianyi is watching the anime Made in Abyss. She finds that making a Cartridge is interesting. To describe the process of making a Cartridge more clearly, she abstracts the original problem and gives you the following problem. You are given a tree $T$ consisting of $n$ vertices. Each vertex has values $a_i$ and $b_i...
Consider finding the maximum value of $B+D$ for every $\min(A,C)$. Denote $\min(A,C)$ as $x$. We call a vertex $u$ satisfying $a_u\geq x$ or an edge satisfying $c_e\geq x$ optional. Denote as $V$ the optional vertex set and as $E_0$ the optional edge set. Firstly, if all optional vertices are on the same side of an edg...
[ "data structures", "trees" ]
3,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; const int MAXN = 2e5 + 5; const int inf = 0x3f3f3f3f; const ll linf = 0x3f3f3f3f3f3f3f3f; struct Segment_Tree { static const int N = 1<<18, SIZ = N * 2 + 5; pii mx[SIZ]; Segment_Tree(void){ clear();} void clear(void) { ...
1825
A
LuoTianyi and the Palindrome String
LuoTianyi gives you \textbf{a palindrome}$^{\dagger}$ string $s$, and she wants you to find out the length of the longest non-empty subsequence$^{\ddagger}$ of $s$ which is not a palindrome string. If there is no such subsequence, output $-1$ instead. $^{\dagger}$ A palindrome is a string that reads the same backward ...
Consider the substring of $s$ from the second character to the last, or $s_2s_3\cdots s_n$. If it's not palindrome, then the answer must be $n-1$. What if it's palindrome? This implies that $s_2=s_n$, $s_3=s_{n-1}$, and so on. Meanwhile, the fact that $s$ is palindrome implies $s_1=s_n$, $s_2=s_{n-1}$, etc. So we get $...
[ "greedy", "strings" ]
800
#pragma GCC optimize(3,"Ofast","inline") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //#define ll int #define ft first #define sd second //#define endl ' ' #define pb push_back #define ll lo...
1825
B
LuoTianyi and the Table
LuoTianyi gave an array $b$ of $n \cdot m$ integers. She asks you to construct a table $a$ of size $n \times m$, filled with these $n \cdot m$ numbers, and each element of the array must be used \textbf{exactly once}. Also she asked you to maximize the following value: \begin{center} $\sum\limits_{i=1}^{n}\sum\limits_...
Assume that $n>m$. Greedily thinking, we want the maximum possible $a$ to appear as the maximum value of as many subtables as possible, meanwhile, we also want the minimum possible $a$ to appear as the minimum value of as many subtables as possible. This gives us two choices: making the upper-left square the minimum or...
[ "greedy", "math" ]
1,000
#include<bits/stdc++.h> #define ll long long using namespace std; const int mxn=2e5+5; ll a[mxn]; inline void solve(){ ll n,m; cin>>n>>m; for(int i=1;i<=n*m;++i)cin>>a[i]; sort(a+1,a+n*m+1); if(n>m)swap(n,m); if(n==1)cout<<(m-1)*(a[n*m]-a[1])<<' '; else{ ll ans1=(n*m-1)*(a[n*m])-a[1]*(n*(m-1))-a[2]*(n-1); ll...
1826
A
Trust Nobody
There is a group of $n$ people. Some of them might be liars, who \textbf{always} tell lies. Other people \textbf{always} tell the truth. The $i$-th person says "There are at least $l_i$ liars amongst us". Determine if what people are saying is contradictory, or if it is possible. If it is possible, output the number of...
Let's iterate over the number $x$ of liars in the group. Now everyone, who says $l_i > x$ is a liar, and vice versa. Let's count the actual number of liars. If those numbers match, output the answer. Now that we've checked all possible $x$'s, we can safely output $-1$, since no number of liars is possible.
[ "brute force", "greedy", "implementation", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> l(n); for (auto &i : l) { cin >> i; } for (int cnt_liars = 0; cnt_liars <= n; ++cnt_liars) { int actual = 0; for (auto i : l) { if (!(cnt_liars >= i)) { ...
1826
B
Lunatic Never Content
You have an array $a$ of $n$ non-negative integers. Let's define $f(a, x) = [a_1 \bmod x, a_2 \bmod x, \dots, a_n \bmod x]$ for some positive integer $x$. Find the biggest $x$, such that $f(a, x)$ is a palindrome. Here, $a \bmod x$ is the remainder of the integer division of $a$ by $x$. An array is a palindrome if it...
For the sequence to be a palindrome, it has to satisfy $b_i = b_{n - i + 1}$. In our case $b_i = a_i \pmod x$. We can rewrite the palindrome equation as $a_i \pmod x = a_{n - i + 1} \pmod x$. Moving all the terms to the left we get $a_i - a_{n - i + 1} \equiv 0 \pmod x$, which basically says $x$ divides $a_i - a_{n - i...
[ "math", "number theory" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (auto &i : a) cin >> i; int ans = 0; for (int i = 0; i < n; ++i) { ans = __gcd(ans, abs(a[i] - a[n - i - 1])); } cout << ans << '\n'; } int main() { cin.tie(0); cout....
1826
C
Dreaming of Freedom
\begin{quote} Because to take away a man's freedom of choice, even his freedom to make the wrong choice, is to manipulate him as though he were a puppet and not a person. \hfill — Madeleine L'Engle \end{quote} There are $n$ programmers choosing their favorite algorithm amongst $m$ different choice options. Before the ...
First we need to notice, that in order to keep some amount of options indefinetely, this number has to be at least $2$ and divide $n$. Let's find the smallest such number $d$. Now, if $d \leq m$, let's always vote for the first $d$ options evenly. In the other case $(d > m)$ each round would force us to to decrease the...
[ "greedy", "math", "number theory" ]
1,300
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 100; vector<int> min_div(N); void solve() { int n, m; cin >> n >> m; cout << (n == 1 || min_div[n] > m ? "YES" : "NO") << '\n'; } int main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); for (int d = 2; d * ...
1826
D
Running Miles
There is a street with $n$ sights, with sight number $i$ being $i$ miles from the beginning of the street. Sight number $i$ has beauty $b_i$. You want to start your morning jog $l$ miles and end it $r$ miles from the beginning of the street. By the time you run, you will see sights you run by (including sights at $l$ a...
There is a fairly straightforward solution using DP, but I'll leave that for the comment section and present a very short and simple solution. First we need to notice, that at two of the maximums are at the ends of $[l, r]$, otherwise we can move one of the boundaries closer to the other and improve the answer. Using t...
[ "brute force", "dp", "greedy" ]
1,700
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> b(n); for (auto &i : b) cin >> i; vector<int> pref_mx(n), suff_mx(n); for (int i = 0; i < n; ++i) { pref_mx[i] = b[i] + i; suff_mx[i] = b[i] - i; } for (int i = 1; i < n; ++i) { ...
1826
E
Walk the Runway
A fashion tour consists of $m$ identical runway shows in different cities. There are $n$ models willing to participate in the tour, numbered from $1$ to $n$. People in different cities have different views on the fashion industry, so they rate each model differently. In particular, people in city $i$ rate model $j$ wit...
At first, let's define the relation between two models, that go one after another in the show. Their ratings must satisfy $r_{i, j} < r_{i, k}$ for all cities $i$. Now let's precompute this relations for all pairs of models naively in $O(n^2m)$, which is ok for now. Now, we have the relations "model $i$ can go before m...
[ "bitmasks", "brute force", "data structures", "dp", "graphs", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; using ll = long long; using bs = bitset<5000>; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int m, n; cin >> m >> n; vector<ll> c(n); for (auto &i : c) { cin >> i; } vector<int> ind(n); iota(ind...
1826
F
Fading into Fog
\textbf{This is an interactive problem.} There are $n$ distinct hidden points with real coordinates on a two-dimensional Euclidean plane. In one query, you can ask some line $ax + by + c = 0$ and get the projections of all $n$ points to this line in some order. The given projections are not exact, please read the inte...
At first let's query two non-parallel lines. In this general case building perpendicular lines from projections and intersecting them will give us $O(n^2)$ candidates for the answer. This gives us the intuition, that 2 queries isn't enough. Also, the constraint from the statement suggests, that asking $x = 0$ and $y = ...
[ "geometry", "interactive", "math", "probabilities" ]
2,800
#pragma GCC optimize("O3", "unroll-loops") #pragma GCC target("sse4.2") #include <algorithm> #include <bitset> #include <cassert> #include <chrono> #include <cmath> #include <complex> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #inclu...
1827
A
Counting Orders
You are given two arrays $a$ and $b$ each consisting of $n$ integers. All elements of $a$ are pairwise distinct. Find the number of ways to reorder $a$ such that $a_i > b_i$ for all $1 \le i \le n$, modulo $10^9 + 7$. Two ways of reordering are considered different if the resulting arrays are different.
Sort the array $b$, and fix the values from $a_n$ to $a_1$. First, we can sort the array $b$, as it does not change the answer. Let's try to choose the values of $a$ from $a_n$ to $a_1$. How many ways are there to choose the value of $a_i$? The new $a_i$ must satisfies $a_i > b_i$. But some of the candidates are alread...
[ "combinatorics", "math", "sortings", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MOD = 1e9 + 7; struct testcase{ testcase(){ int n; cin >> n; vector<int> a(n); for (int i=0; i<n; i++) cin >> a[i]; sort(a.begin(), a.end()); vector<int> b(n); for (int i=0; i<n; i++) cin >...
1827
B2
Range Sorting (Hard Version)
\textbf{The only difference between this problem and the easy version is the constraints on $t$ and $n$.} You are given an array $a$, consisting of $n$ distinct integers $a_1, a_2, \ldots, a_n$. Define the beauty of an array $p_1, p_2, \ldots p_k$ as the minimum amount of time needed to sort this array using an arbit...
What is the minimum cost to sort just one subarray? What happens when two operations intersect each other? When can we sort two adjacency ranges independently? Try to calculate the contribution of each position. Let $a[l..r]$ denotes the subarray $a_l,a_{l+1},\ldots,a_r$. Observation 1: In an optimal sequence of operat...
[ "binary search", "data structures", "dp", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5; int n; int a[N]; pair <int, int> b[N]; signed main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tests; cin >> tests; while (tests--){ cin >> n; for (int i = 1; i <= n; i++){ cin >> a[i]; } for (int...
1827
C
Palindrome Partition
A substring is a continuous and non-empty segment of letters from a given string, without any reorders. An even palindrome is a string that reads the same backward as forward and has an even length. For example, strings "zz", "abba", "abccba" are even palindromes, but strings "codeforces", "reality", "aba", "c" are no...
Try to construct beautiful string greedily. What happens when we have two even palindromes share one of their endpoints? For the simplicity of the solution, we will abbreviate even palindrome as evp. Lemma: Consider a beautiful string $t$, we can find the unique maximal partition for it by greedily choosing the smalles...
[ "binary search", "brute force", "data structures", "dp", "hashing", "strings" ]
2,600
#include <bits/stdc++.h> using namespace std; const int N = 500005; const int LOG = 19; int n, pal[N], rmq[LOG][N], cnt[N]; string s; int main() { cin.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { cin >> n >> s; for (int i = 0, l = 0, r = 0; i < n; i++) { pal[i] = i >= r ? 0 : m...
1827
D
Two Centroids
You are given a tree (an undirected connected acyclic graph) which initially only contains vertex $1$. There will be several queries to the given tree. In the $i$-th query, vertex $i + 1$ will appear and be connected to vertex $p_i$ ($1 \le p_i \le i$). After each query, please find out the least number of operations ...
Is the answer related to the centroid of the current tree? How much the centroid will move after one query? Observation: The answer for the tree with $n$ vertices equals $n-2\cdot mx$ where $mx$ is the largest subtree among the centroid's children. Lemma: After one query, the centroid will move at most one edge, and wh...
[ "data structures", "dfs and similar", "greedy", "trees" ]
2,800
#include <bits/stdc++.h> using namespace std; const int N = 500005; const int LOG = 19; vector<int> adj[N]; int tin[N], tout[N], timer; int par[LOG][N], bit[N], dep[N]; void dfs(int u) { tin[u] = ++timer; dep[u] = dep[par[0][u]] + 1; for (int k = 1; k < LOG; k++) par[k][u] = par[k - 1][par[k - 1][u]]; f...
1827
E
Bus Routes
There is a country consisting of $n$ cities and $n - 1$ bidirectional roads connecting them such that we can travel between any two cities using these roads. In other words, these cities and roads form a tree. There are $m$ bus routes connecting the cities together. A bus route between city $x$ and city $y$ allows you...
You do not need to consider all pairs of nodes, only some of them will do. Find an equivalent condition of the statement. Let $S(u)$ be the set of all nodes reachable by u using at most one route. Consider all $S(l)$ where $l$ is a leaf in the tree. First, notice that for a pair of nodes $(u, v)$ such that $u$ is not a...
[ "binary search", "constructive algorithms", "dfs and similar", "greedy", "trees" ]
3,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll INF = 1e18; const int maxn = 2e6 + 10; const int mod = 1e9 + 7; const int mo = 998244353; using pi = pair < ll, ll > ; using vi = vector < ll > ; using pii = pair < pair < ll, ll > , ll > ; mt19937 rng(chrono::steady_clock::now().time_since_e...
1827
F
Copium Permutation
You are given a permutation $a_1,a_2,\ldots,a_n$ of the first $n$ positive integers. A subarray $[l,r]$ is called copium if we can rearrange it so that it becomes a sequence of consecutive integers, or more formally, if $$\max(a_l,a_{l+1},\ldots,a_r)-\min(a_l,a_{l+1},\ldots,a_r)=r-l$$ For each $k$ in the range $[0,n]$,...
Call the last $n-k$ elements as special numbers. Observation: In optimal rearrangement, every maximal segment of special numbers will be placed on consecutive positions in either ascending order or descending order. For simplicity, from now on we will call maximal segment of special number as maximal segment. For examp...
[ "constructive algorithms", "data structures", "greedy" ]
3,500
#include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 200005; const int LOG = 18; int n, a[N], pos[N]; int lef[N], rig[N]; vector<int> st_max, st_min; void connect(int x, int y) { rig[x] = y; lef[y] = x; } struct range_min { vector<int> spt[LOG]; void build() { for (int k...
1828
A
Divisible Array
You are given a positive integer $n$. Please find an array $a_1, a_2, \ldots, a_n$ that is perfect. A perfect array $a_1, a_2, \ldots, a_n$ satisfies the following criteria: - $1 \le a_i \le 1000$ for all $1 \le i \le n$. - $a_i$ is divisible by $i$ for all $1 \le i \le n$. - $a_1 + a_2 + \ldots + a_n$ is divisible b...
Remember the sum of the first $n$ positive integers? Every positive integer is divisible by $1$. Consider the array $a = \left[1, 2, \ldots, n\right]$ that satisfies the second condition. It has the sum of $1 + 2 + \dots + n = \frac{n(n+1)}{2}$. One solution is to notice that if we double every element $(a=\left[2, 4, ...
[ "constructive algorithms", "math" ]
800
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second const int N=2e6+1; const ll mod=998244353; ll n,m; ll a[N],b[N]; void solve(){ cin >> n; ll s=0; for(int i=n; i>=2 ;i--){ a[i]=i; s=(s+i)%n; } a[1]=n-s; for(int i=1; i<=n ;i++) cout << a[i] << ' '; cout << '...
1828
B
Permutation Swap
You are given an \textbf{unsorted} permutation $p_1, p_2, \ldots, p_n$. To sort the permutation, you choose a constant $k$ ($k \ge 1$) and do some operations on the permutation. In one operation, you can choose two integers $i$, $j$ ($1 \le j < i \le n$) such that $i - j = k$, then swap $p_i$ and $p_j$. What is the \t...
In order to move $p_i$ to its right position, what does the value of $k$ have to satisfy? In order to move $p_i$ to position $i$, it is easy to see that $|p_i - i|$ has to be divisible by $k$. So, $|p_1 - 1|, |p_2 - 2|, \ldots, |p_n - n|$ has to be all divisible by $k$. The largest possible value of $k$ turns out to be...
[ "math", "number theory" ]
900
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { int n, res = 0; cin >> n; for (int i = 1; i <= n; i++) { int x; cin >> x; res = __gcd(res, abs(x - i)); ...
1829
A
Love Story
Timur loves codeforces. That's why he has a string $s$ having length $10$ made containing only lowercase Latin letters. Timur wants to know how many indices string $s$ \textbf{differs} from the string "codeforces". For example string $s =$ "{co\textbf{ol}for\textbf{s}e\textbf{z}}" differs from "codeforces" in $4$ indi...
You need to implement what is written in the statement. You need to compare the given string $s$ with the string "codeforces" character by character, counting the number of differences. We know that the length of $s$ is $10$, so we can simply iterate through both strings and compare each character at the same index. If...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { string s, c = "codeforces"; cin >> s; int ans = 0; for(int i = 0; i < 10; i++) { if(s[i] != c[i]) { ans++; } } cout << ans << endl; } int32_t main(){ int t = 1; cin >> t; while (t-...
1829
B
Blank Space
You are given a binary array $a$ of $n$ elements, a binary array is an array consisting only of $0$s and $1$s. A blank space is a segment of \textbf{consecutive} elements consisting of only $0$s. Your task is to find the length of the longest blank space.
We can iterate through the array $a$ and keep track of the length of the current blank space. Whenever we encounter a $0$, we increase the length of the current blank space, and whenever we encounter a $1$, we check if the current blank space is longer than the previous longest blank space. If it is, we update the leng...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int a[n]; int cnt = 0, ans = 0; for(int i = 0; i < n; i++) { cin >> a[i]; if(a[i] == 0) { cnt++; } else { ans = max(ans, cnt); cnt = ...
1829
C
Mr. Perfectly Fine
Victor wants to become "Mr. Perfectly Fine". For that, he needs to acquire a certain set of skills. More precisely, he has $2$ skills he needs to acquire. Victor has $n$ books. Reading book $i$ takes him $m_i$ minutes and will give him some (possibly none) of the required two skills, represented by a binary string of ...
You can classify the books into four types "00", "01", "10", "11". We will take a book of any type at most once and wont take a book that learns a single skill if that skill is already learned, so there are only two cases to look at We take the shortest "01" and the the shortest "10". We take the shortest "11". Out of ...
[ "bitmasks", "greedy", "implementation" ]
800
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() void solve() { int n; cin >> n; ...
1829
D
Gold Rush
Initially you have a single pile with $n$ gold nuggets. In an operation you can do the following: - Take any pile and split it into two piles, so that one of the resulting piles has exactly twice as many gold nuggets as the other. (All piles should have an integer number of nuggets.) \begin{center} {\small One possib...
We can solve this problem recursively. Let the current pile have $n$ gold nuggets. If $n=m$, then we can make a pile with exactly $m$ gold nuggets by not doing any operations. If $n$ is not a multiple of $3$, then it is not possible to make a move, because after a move we split $n$ into $x$ and $2x$, so $n=x+2x=3x$ for...
[ "brute force", "dfs and similar", "dp", "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; bool ok(int n, int m) { if (n == m) {return true;} else if (n % 3 != 0) {return false;} else {return (ok(n / 3, m) || ok(2 * n / 3, m));} } void solve() { int n, m; cin >> n >> m; cout << (ok(n, m) ? "YES" : "NO") << '\n'; } int main() { ios::sync_with_stdio(fals...
1829
E
The Lakes
You are given an $n \times m$ grid $a$ of non-negative integers. The value $a_{i,j}$ represents the depth of water at the $i$-th row and $j$-th column. A lake is a set of cells such that: - each cell in the set has $a_{i,j} > 0$, and - there exists a path between any pair of cells in the lake by going up, down, left,...
We can approach this problem using Depth First Search (DFS) or Breadth First Search (BFS) on the given grid. The idea is to consider each cell of the grid as a potential starting point for a lake, and explore all the cells reachable from it by only moving up, down, left or right, without stepping on any cell with depth...
[ "dfs and similar", "dsu", "graphs", "implementation" ]
1,100
#include <bits/stdc++.h> #define startt ios_base::sync_with_stdio(false);cin.tie(0); typedef long long ll; using namespace std; #define vint vector<int> #define all(v) v.begin(), v.end() #define MOD 1000000007 #define MOD2 998244353 #define MX 1000000000 #define MXL 1000000000000000000 #define PI (ld)2*acos(0.0) #defi...
1829
F
Forever Winter
A snowflake graph is generated from two integers $x$ and $y$, both greater than $1$, as follows: - Start with one central vertex. - Connect $x$ new vertices to this central vertex. - Connect $y$ new vertices to \textbf{each} of these $x$ vertices. For example, below is a snowflake graph for $x=5$ and $y=3$. \begin{ce...
The degree of a vertex is the number of vertices connected to it. We can count the degree of a vertex by seeing how many times it appears in the input. Let's count the degrees of the vertices in a snowflake graph. The starting vertex has degree $x$. Each of the $x$ newly-generated vertices has degree $y+1$ (they have $...
[ "dfs and similar", "graphs", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n, m; cin >> n >> m; int cnt[n + 1]; for (int i = 1; i <= n; i++) { cnt[i] = 0; } for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; cnt[u]++; cnt[v]++; } map<int, int> cnts; fo...
1829
G
Hits Different
In a carnival game, there is a huge pyramid of cans with $2023$ rows, numbered in a regular pattern as shown. \begin{center} {\small If can $9^2$ is hit initially, then all cans colored red in the picture above would fall.} \end{center} You throw a ball at the pyramid, and it hits a single can with number $n^2$. This...
There are many solutions which involve going row by row and using some complicated math formulas, but here is a solution that requires no formulas and is much quicker to code. The cans are hard to deal with, but if we replace them with a different shape, a diamond, we get the following: To avoid finding the row and col...
[ "data structures", "dp", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; long long ans[2000007]; long long a[1500][1500] = {}, curr = 1; void solve() { int n; cin >> n; cout << ans[n] << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); for (int i = 1; i < 1500; i++) { for (int j = i - 1; j >= 1; j--) { a[j][i ...
1829
H
Don't Blame Me
Sadly, the problem setter couldn't think of an interesting story, thus he just asks you to solve the following problem. Given an array $a$ consisting of $n$ positive integers, count the number of \textbf{non-empty} subsequences for which the bitwise $\mathsf{AND}$ of the elements in the subsequence has exactly $k$ set...
We can notice that the numbers are pretty small (up to $63$) and the AND values will be up to $63$ as well. Thus, we can count the number of subsequences that have AND value equal to $x$ for all $x$ from $0$ to $63$. We can do this using dynamic programming. Let's denote $dp_{ij}$ as the number of subsequences using th...
[ "bitmasks", "combinatorics", "dp", "math" ]
1,700
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() const int mod = 1e9 + 7; void solve(...
1830
A
Copil Copac Draws Trees
Copil Copac is given a list of $n-1$ edges describing a tree of $n$ vertices. He decides to draw it using the following algorithm: - Step $0$: Draws the first vertex (vertex $1$). Go to step $1$. - Step $1$: For every edge in the input, in order: if the edge connects an already drawn vertex $u$ to an undrawn vertex $v...
What is the answer if $n=3$? The previous case can be generalised to find the answer for any tree. This problem can be solved via dynamic programming. From here on out, step $1$ from the statement will be called a "scan". Let $dp[i]$ be the number of scans needed to activate node $i$, and $id[i]$ be the index (in the o...
[ "dfs and similar", "dp", "graphs", "trees" ]
1,400
#include <bits/stdc++.h> const int NMAX = 3e5 + 5, INF = 1e9; int n, f[NMAX], d[NMAX]; std :: vector < std :: pair < int, int > > G[NMAX]; void DFS(int node, int t) { f[node] = true; for (int i = 0; i < G[node].size(); ++ i) { int u = G[node][i].first, c = G[node][i].second; if (f[u] == fal...
1830
B
The BOSS Can Count Pairs
You are given two arrays $a$ and $b$, both of length $n$. Your task is to count the number of pairs of integers $(i,j)$ such that $1 \leq i < j \leq n$ and $a_i \cdot a_j = b_i+b_j$.
Since $b_i \le n$ and $b_j \le n$, $b_i+b_j = a_i \cdot a_j \le 2 \cdot n$. Since $a_i \cdot a_j \le 2 \cdot n$, then $\min(a_i,a_j) \le \sqrt{2 \cdot n}$. Since $b_i \le n$ and $b_j \le n$, $b_i+b_j = a_i \cdot a_j \le 2 \cdot n$. Therefore, $\min(a_i,a_j) \le \sqrt{2 \cdot n}$. Let $lim=\sqrt{2 \cdot n}$ and $fr[a_i]...
[ "brute force", "math" ]
2,000
for _ in range(int(input())): n = int(input()) ta = list(map(int, input().split())) tb = list(map(int, input().split())) a = [(x, y) for x, y in zip(ta, tb)] a.sort() cnt = [0] * (2 * n + 1) pr = 0 ans = 0 for i in range(n): if pr != a[i][0]: ...
1830
C
Hyperregular Bracket Strings
You are given an integer $n$ and $k$ intervals. The $i$-th interval is $[l_i,r_i]$ where $1 \leq l_i \leq r_i \leq n$. Let us call a \textbf{regular} bracket sequence$^{\dagger,\ddagger}$ of length $n$ hyperregular if for each $i$ such that $1 \leq i \leq k$, the substring $\overline{s_{l_i} s_{l_{i}+1} \ldots s_{r_i}...
While not necessarily a hint, this problem cannot be solved without knowing that there are $C_n=\frac{1}{n+1}\binom{2n}{n}$ Regular Bracket Strings of length $2 \cdot n$. What's the answer if $q=1$? What's the answer if $q=2$ and the two intervals partially overlap? Based on the previous hint, we can get rid of all par...
[ "combinatorics", "greedy", "hashing", "math", "number theory", "sortings" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int NMAX=3e5+5, MOD=998244353; mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count()); uniform_int_distribution<ll> rnd(0,LLONG_MAX); ll fact[NMAX], invfact[NMAX], C[NMAX]; ll binPow(ll x, ll y){ ll ans=1; for(;y ;y>>=1...
1830
D
Mex Tree
You are given a tree with $n$ nodes. For each node, you either color it in $0$ or $1$. The value of a path $(u,v)$ is equal to the MEX$^\dagger$ of the colors of the nodes from the shortest path between $u$ and $v$. The value of a coloring is equal to the sum of values of all paths $(u,v)$ such that $1 \leq u \leq v ...
Why is bipartite coloring not always optimal? How good is a bipartite coloring actually? Disclaimer: I ( tibinyte2006 ) wanted to cut $O(n \sqrt{n})$ memory because I thought that setting 1024 MB memory limit would spoil the solution. So only blame me for this. We will do a complementary problem which is finding the mi...
[ "brute force", "dp", "trees" ]
2,800
#include <bits/stdc++.h> #define int long long using namespace std; const int lim = 893; const int inf = 1e16; struct dp_state { vector<int> a; vector<int> b; void init() { a.resize(lim + 1, inf); b.resize(lim + 1, inf); a[1] = 1; b[1] = 2; } }; int32_t main() { ...
1830
E
Bully Sort
On a permutation $p$ of length $n$, we define a bully swap as follows: - Let $i$ be the index of the largest element $p_i$ such that $p_i \neq i$. - Let $j$ be the index of the smallest element $p_j$ such that $i < j$. - Swap $p_i$ and $p_j$. We define $f(p)$ as the number of bully swaps we need to perform until $p$ ...
First of all, we notice that if some element moves left, it will never move right. Proving this is not hard, imagine $S$ to be the set of suffix minimas. Then if an element is in $S$ we know that $p_x \le x$. Since after every bully swap an element cannot disappear from $S$ and after each bully swap, the $2$ swapped el...
[ "data structures", "math" ]
3,500
#include <bits/stdc++.h> using namespace std; #define ll long long #define ii pair<int,int> #define i4 tuple<int,int,int,int> #define fi first #define se second #define endl '\n' #define debug(x) cout << #x << ": " << x << endl #define pub push_back #define pob pop_back #define puf push_front #define pof pop_front #...
1830
F
The Third Grace
You are given $n$ intervals and $m$ points on the number line. The $i$-th intervals covers coordinates $[l_i,r_i]$ and the $i$-th point is on coordinate $i$ and has coefficient $p_i$. Initially, all points are not activated. You should choose a subset of the $m$ points to activate. For each of $n$ interval, we define ...
Let $dp_i$ be the maximum sum of costs of activated points that are $< i$ over all states that has point $i$ activated. When we transition from $dp_i$ to $dp_j$, we need to add the cost contributed by point $i$. The number of ranges where point $i$ is the largest coordinate within it are the ranges $[l,r]$ which satisf...
[ "data structures", "dp" ]
3,200
#include <bits/stdc++.h> #define all(x) (x).begin(),(x).end() using namespace std; using ll = long long; using ld = long double; //#define int ll #define sz(x) ((int)(x).size()) using pii = pair<ll,ll>; using tii = tuple<int,int,int>; const int nmax = 5e5 + 5, qmax = 2e6 + 5; const ll inf = 1e18 + 5; struct line...
1831
A
Twin Permutations
You are given a permutation$^\dagger$ $a$ of length $n$. Find any permutation $b$ of length $n$ such that $a_1+b_1 \le a_2+b_2 \le a_3+b_3 \le \ldots \le a_n+b_n$. It can be proven that a permutation $b$ that satisfies the condition above always exists. $^\dagger$ A permutation of length $n$ is an array consisting o...
If $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Building on the idea from the first hint, can we build a permutation $b$ such that $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$? Since $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Therefore, any permutation $b$ w...
[ "constructive algorithms" ]
800
#include<bits/stdc++.h> using namespace std; typedef long long ll; void tc(){ ll n; cin>>n; for(ll i=0;i<n;i++){ ll x; cin>>x; cout<<n+1-x<<' '; } cout<<'\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); ll t; cin>>t; while(t--) tc(); retu...
1831
B
Array merging
You are given two arrays $a$ and $b$ both of length $n$. You will merge$^\dagger$ these arrays forming another array $c$ of length $2 \cdot n$. You have to find the maximum length of a subarray consisting of equal values across all arrays $c$ that could be obtained. $^\dagger$ A merge of two arrays results in an arra...
When we merge two arrays $a$ and $b$, we can force the resulting array to have $[a_{l_1},a_{l_1+1},\ldots,a_{r_1},b_{l_2},b_{l_2+1},\ldots,b_{r_1}]$ as a subarray, for some $1 \le l_1 \le r_1 \le n$ and $1 \le l_2 \le r_2 \le n$. If $a_{l_1}=b_{l_1}$, then we can achieve a contiguous sequence of $(r_1-l_1+1)+(r_2-l_2+1...
[ "constructive algorithms", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int32_t main() { cin.tie(nullptr)->sync_with_stdio(false); int q; cin >> q; while (q--) { int n; cin >> n; vector<int> a(n + 1); vector<int> b(n + 1); for (int i = 1; i <= n; ++i) { cin >> a[i...
1832
A
New Palindrome
A palindrome is a string that reads the same from left to right as from right to left. For example, abacaba, aaaa, abba, racecar are palindromes. You are given a string $s$ consisting of lowercase Latin letters. The string $s$ is a palindrome. You have to check whether it is possible to rearrange the letters in it to...
Let's look at the first $\left\lfloor\frac{|s|}{2}\right\rfloor$ characters. If all these characters are equal, then there is no way to get another palindrome. Otherwise, there are at least two different characters, you can swap them (and the characters symmetrical to them on the right half of the string), and get a pa...
[ "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; s = s.substr(0, s.size() / 2); int k = unique(s.begin(), s.end()) - s.begin(); cout << (k == 1 ? "NO" : "YES") << '\n'; } }
1832
B
Maximum Sum
You are given an array $a_1, a_2, \dots, a_n$, where all elements are different. You have to perform \textbf{exactly} $k$ operations with it. During each operation, you do \textbf{exactly one} of the following two actions (you choose which to do yourself): - find \textbf{two minimum elements} in the array, and delete...
The first instinct is to implement a greedy solution which removes either two minimums or one maximum, according to which of the options removes elements with smaller sum. Unfortunately, this doesn't work even on the examples (hint to the participants of the round: if your solution gives a different answer on the examp...
[ "brute force", "sortings", "two pointers" ]
1,100
for _ in range(int(input())): n, k = map(int, input().split()) a = sorted(list(map(int, input().split()))) ans = 0 pr = [0] * (n + 1) for i in range(n): pr[i + 1] = pr[i] + a[i] for i in range(k + 1): ans = max(ans, pr[n - (k - i)] - pr[2 * i]) print(ans)
1832
C
Contrast Value
For an array of integers $[a_1, a_2, \dots, a_n]$, let's call the value $|a_1-a_2|+|a_2-a_3|+\cdots+|a_{n-1}-a_n|$ the contrast of the array. Note that the contrast of an array of size $1$ is equal to $0$. You are given an array of integers $a$. Your task is to build an array of $b$ in such a way that all the followin...
Let's rephrase the problem in the following form: let the elements of the array be points on a coordinate line. Then the absolute difference between two adjacent elements of the array can be represented as the distance between two points, and the contrast of the entire array is equal to the total distance to visit all ...
[ "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int& x : a) cin >> x; n = unique(a.begin(), a.end()) - a.begin(); int ans = n; for (int i = 0; i + 2 < n; ++i) ...
1832
D1
Red-Blue Operations (Easy Version)
\textbf{The only difference between easy and hard versions is the maximum values of $n$ and $q$}. You are given an array, consisting of $n$ integers. Initially, all elements are red. You can apply the following operation to the array multiple times. During the $i$-th operation, you select an element of the array; the...
Let's try applying the operation to a single element multiple times. You can see that when you apply an operation an odd number of times, the element always gets larger. Alternatively, applying an operation an even amount of times always makes it smaller (or equal in case of $0$). Thus, generally, we would want to appl...
[ "binary search", "greedy", "implementation", "math" ]
2,100
null
1832
D2
Red-Blue Operations (Hard Version)
\textbf{The only difference between easy and hard versions is the maximum values of $n$ and $q$}. You are given an array, consisting of $n$ integers. Initially, all elements are red. You can apply the following operation to the array multiple times. During the $i$-th operation, you select an element of the array; the...
Read the editorial to the easy version to get the general idea of the solution. Now, we should only optimize the calculations. First, the sorting can obviously be done beforehand. Now we want to get the minimum and the sum after applying the last increase operations. Consider $(n + k) \bmod 2 = 0$ and $k > n$, the othe...
[ "binary search", "constructive algorithms", "greedy", "implementation", "math" ]
2,400
n, q = map(int, input().split()) a = list(map(int, input().split())) a.sort() pr = [10**9 for i in range(n + 1)] for i in range(n): pr[i + 1] = min(pr[i], a[i] - i) s = sum(a) - n * (n - 1) // 2 ans = [] for k in map(int, input().split()): if k < n: ans.append(min(pr[k] + k, a[k])) continue if k % 2 == n % 2: ...
1832
E
Combinatorics Problem
Recall that the binomial coefficient $\binom{x}{y}$ is calculated as follows ($x$ and $y$ are non-negative integers): - if $x < y$, then $\binom{x}{y} = 0$; - otherwise, $\binom{x}{y} = \frac{x!}{y! \cdot (x-y)!}$. You are given an array $a_1, a_2, \dots, a_n$ and an integer $k$. You have to calculate a new array $b_...
Unfortunately, it looks like the constraints were insufficient to cut the convolution solutions off. So it's possible to solve this problem using a very fast convolution implementation, but the model approach is different from that. One of the properties of Pascal's triangle states that $\binom{x}{y} = \binom{x-1}{y} +...
[ "brute force", "combinatorics", "dp" ]
2,200
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y, int mod = MOD) { return ((x + y) % mod + mod) % mod; } int mul(int x, int y, int mod = MOD) { return (x * 1ll * y) % mod; } int binpow(int x, int y, int mod = MOD) { int z = add(1, 0, mod); while(y > 0) { if(y % 2 ...
1832
F
Zombies
Polycarp plays a computer game in a post-apocalyptic setting. The zombies have taken over the world, and Polycarp with a small team of survivors is defending against hordes trying to invade their base. The zombies are invading for $x$ minutes starting from minute $0$. There are $n$ entrances to the base, and every minu...
First of all, let's rephrase the problem a bit. For each entrance, we will have two time segments: the segment when it is guarded, and the segment when the corresponding generator works. The zombies will arrive through that entrance at every moment not belonging to these two segments; so, if we want to maximize the num...
[ "binary search", "dp" ]
3,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct seg{ int l, r; }; int n; vector<long long> dp_before, dp_cur; vector<vector<long long>> bst; void compute(int l, int r, int optl, int optr){ if (l > r) return; int mid = (l + r) / 2; pair<long long, int> be...
1833
A
Musical Puzzle
Vlad decided to compose a melody on his guitar. Let's represent the melody as a sequence of notes corresponding to the characters 'a', 'b', 'c', 'd', 'e', 'f', and 'g'. However, Vlad is not very experienced in playing the guitar and can only record \textbf{exactly two} notes at a time. Vlad wants to obtain the melody ...
Let's construct the melody sequentially. In the first step, we can record the notes $s_1$ and $s_2$. In the next step, we need to record $s_2$ and $s_3$, because there must be a common symbol when gluing and so on. That is, we need to have recorded melodies $s_i$+$s_{i+1}$ for all $1 \le i < n$. We only need to count h...
[ "implementation", "strings" ]
800
def solve(): n = int(input()) s = input() cnt = set() for i in range(1, n): cnt.add(s[i - 1] + s[i]) print(len(cnt)) t = int(input()) for _ in range(t): solve()
1833
B
Restore the Weather
You are given an array $a$ containing the weather forecast for Berlandia for the last $n$ days. That is, $a_i$ — is the estimated air temperature on day $i$ ($1 \le i \le n$). You are also given an array $b$ — the air temperature that was actually present on each of the days. However, all the values in array $b$ are m...
Let's solve the problem using a greedy algorithm. Based on the array $a$, form an array of pairs {temperature, day number} and sort it in ascending order of temperature. Also sort the array $b$ in ascending order. Now, the values $a[i].first$ and $b[i]$ are the predicted and real temperature on day $a[i].second$. Indee...
[ "greedy", "sortings" ]
900
#include<bits/stdc++.h> using namespace std; void solve(){ int n, k; cin >> n >> k; vector<pair<int, int>>a(n); vector<int>b(n), ans(n); for(int i = 0; i < n; i++){ cin >> a[i].first; a[i].second = i; } for(auto &i : b) cin >> i; sort(b.begin(), b.end()); sort(a.begi...
1833
C
Vlad Building Beautiful Array
Vlad was given an array $a$ of $n$ positive integers. Now he wants to build a beautiful array $b$ of length $n$ from it. Vlad considers an array beautiful if all the numbers in it are positive and have the same parity. That is, all numbers in the beautiful array are \textbf{greater} than zero and are either all even o...
If all the numbers in the array already have the same parity, then for each $i$ it is sufficient to assign $b_i=a_i$. Otherwise, it is impossible to make all the numbers even by leaving them positive, because the parity changes only when subtracting an odd number, and we cannot make the minimum odd number an even numbe...
[ "greedy", "math" ]
800
def solve(): n = int(input()) a = [int(x) for x in input().split()] a.sort() if a[0] % 2 == 1: print("YES") return for i in range(n): if a[i] % 2 == 1: print("NO") return print("YES") t = int(input()) for _ in range(t): solve()
1833
D
Flipper
You are given a permutation $p$ of length $n$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $\{2,3,1,5,4\}$ is a permutation, while $\{1,2,2\}$ is not (since $2$ appears twice), and $\{1,3,4\}$ is also not a permutation (as $n=3$, but the array contains $4$)....
In these constraints we could solve the problem for $O(n^2)$. Let us note that there can be no more than two candidates for the value $r$. Since the first number in the permutation will be either $p_{r+1}$ if $r < n$, or $p_r$ if $r = n$. Then let's go through the value of $r$ and choose the one in which the first numb...
[ "brute force", "constructive algorithms", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void solve() { int n; cin >> n; vector<int> p(n); for (auto &e : p) cin >> e; int r = 0; for (int i = 0; i < n;...
1833
E
Round Dance
$n$ people came to the festival and decided to dance a few round dances. There are at least $2$ people in the round dance and each person has exactly two neighbors. If there are $2$ people in the round dance then they have the same neighbor on each side. You decided to find out exactly how many dances there were. But ...
Let's build an undirected graph, draw the edges $i \to a_i$. Let's split this graph into connectivity components, denote their number by $k$. There could not be more than $k$ round dances. Since the degree of each vertex is no more than two, the connectivity components are simple cycles and bamboos. If we connect the v...
[ "dfs and similar", "dsu", "graphs", "shortest paths" ]
1,600
#include <iostream> #include <vector> #include <set> #include <queue> #include <algorithm> using namespace std; typedef long long ll; void solve() { int n; cin >> n; vector<int> a(n); vector<set<int>> g(n); vector<set<int>> neighbours(n); vector<int> d(n); for (int i = 0; i < n; ++i) { ...
1833
F
Ira and Flamenco
Ira loves Spanish flamenco dance very much. She decided to start her own dance studio and found $n$ students, $i$th of whom has level $a_i$. Ira can choose several of her students and set a dance with them. So she can set a huge number of dances, but she is only interested in magnificent dances. The dance is called ma...
Reformulate the definition of magnificent dance. A dance $[x_1, x_2, \ldots, x_m]$ is called magnificent if there exists such a non-negative integer $d$ that $[x_1 - d, x_2 - d, \ldots, x_m - d]$ forms a permutation. Let's build an array $b$ such that it is sorted, all the numbers in it are unique and each number from ...
[ "combinatorics", "constructive algorithms", "data structures", "implementation", "math", "sortings", "two pointers" ]
1,700
/* `) _ \ (( }/ ,_ )))__ / (((---' \ ' )|____.---- ) / \ ` ( / ' \ ` ) / ' \ ` / / ' _/ / _!____.-' /_.-'/ \ |`_ |`_ */ #include <bits/stdc++.h> using namespace std; typedef pair<int, int> ipair; const in...
1833
G
Ksyusha and Chinchilla
Ksyusha has a pet chinchilla, a tree on $n$ vertices and huge scissors. A tree is a connected graph without cycles. During a boring physics lesson Ksyusha thought about how to entertain her pet. Chinchillas like to play with branches. A branch is a tree of $3$ vertices. \begin{center} {\small The branch looks like th...
Let's hang the tree by the vertex $1$. This problem can be solved by dynamic programming. $dpc_v$ - the ability to cut a subtree of $v$ if the edges in all children of $v$ must be cut off. $dpo_v$ - the ability to cut a subtree of $v$ if exactly one edge needs to be saved from $v$ to the child. $dp_v$ - ability to cut ...
[ "constructive algorithms", "dfs and similar", "dp", "dsu", "greedy", "implementation", "trees" ]
1,800
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> ipair; const int MAXN = 200200; int n; vector<ipair> gr[MAXN]; vector<int> res; queue<int> qu; int par[MAXN], ipar[MAXN], deg[MAXN], hard[MAXN]; void init() { res.clear(); while (!qu.empty()) qu.pop(); memset(deg, 0, sizeof(int) * n); memset(h...
1834
A
Unit Array
Given an array $a$ of length $n$, which elements are equal to $-1$ and $1$. Let's call the array $a$ good if the following conditions are held at the same time: - $a_1 + a_2 + \ldots + a_n \ge 0$; - $a_1 \cdot a_2 \cdot \ldots \cdot a_n = 1$. In one operation, you can select an arbitrary element of the array $a_i$ an...
First, let's make the sum of the array elements $\ge 0$. To do this, we just need to change some $-1$ to $1$. The number of such replacements can be calculated using a formula or explicitly simulated. After that, there are two possible situations: either the product of all elements is equal to $1$, or the product of al...
[ "greedy", "math" ]
800
null
1834
B
Maximum Strength
Fedya is playing a new game called "The Legend of Link", in which one of the character's abilities is to combine two materials into one weapon. Each material has its own strength, which can be represented by a positive integer $x$. The strength of the resulting weapon is determined as the sum of the absolute difference...
Let's add leading zeros to $L$ if necessary. Now we can represent the numbers $L$ and $R$ as their longest common prefix, the digit $k$ at which the values differ, and the remaining digits. After digit $k$, any digits can be placed, so it is advantageous to put $9$ in one number and $0$ in the other. Then the answer is...
[ "greedy", "math" ]
1,000
null
1834
C
Game with Reversing
Alice and Bob are playing a game. They have two strings $S$ and $T$ of the same length $n$ consisting of lowercase latin letters. Players take turns alternately, with Alice going first. On her turn, Alice chooses an integer $i$ from $1$ to $n$, one of the strings $S$ or $T$, and any lowercase latin letter $c$, and rep...
Let's show that the specific choice of a turn by Bob (which of the strings to reverse) does not affect Alice's strategy and therefore the answer to the problem. Reversing the string twice does not change anything $\to$ we are only interested in the parity of the number of reverses for both strings. If Bob made an even ...
[ "games", "greedy", "math", "strings" ]
1,200
null
1834
D
Survey in Class
Zinaida Viktorovna has $n$ students in her history class. The homework for today included $m$ topics, but the students had little time to prepare, so $i$-th student learned only topics from $l_i$ to $r_i$ inclusive. At the beginning of the lesson, each student holds their hand at $0$. The teacher wants to ask some top...
Let's fix the students who will end up with the highest and lowest hands. Then, to maximize the difference, we can ask all the topics that the student with the highest hand knows. Then the second student will raise his hand for each topic in the intersection of their segments, and lower for each topic that only the fir...
[ "brute force", "data structures", "greedy", "implementation", "sortings" ]
1,900
null
1834
E
MEX of LCM
You are given an array $a$ of length $n$. A \textbf{positive} integer $x$ is called good if it is \textbf{impossible} to find a subsegment$^{\dagger}$ of the array such that the least common multiple of all its elements is equal to $x$. You need to find the smallest good integer. A subsegment$^{\dagger}$ of the array...
Notice that the MEX of $n^2$ numbers will not exceed $n^2+1$. Let's calculate all possible LCM values on segments that do not exceed $n^2$. To do this, we will iterate over the right endpoint of the segments and maintain a set of different LCM values on segments with such a right endpoint. Let these values be $x_1 < x_...
[ "binary search", "data structures", "implementation", "math", "number theory" ]
2,300
null
1834
F
Typewriter
Recently, Polycarp was given an unusual typewriter as a gift! Unfortunately, the typewriter was defective and had a rather strange design. The typewriter consists of $n$ cells numbered from left to right from $1$ to $n$, and a carriage that moves over them. The typewriter cells contain $n$ \textbf{distinct} integers f...
Let's solve the problem if there are no requests. The key object for us will be such cells that the number in them is less than the cell index. Note that for one carriage reset, we can transfer no more than one such number. So we have a lower bound on the answer. Let's build a graph with edges $i\rightarrow a[i]$. Then...
[ "brute force", "math" ]
2,500
null
1835
A
k-th equality
Consider all equalities of form $a + b = c$, where $a$ has $A$ digits, $b$ has $B$ digits, and $c$ has $C$ digits. All the numbers are \textbf{positive} integers and are written without leading zeroes. Find the $k$-th lexicographically smallest equality when written as a string like above or determine that it does not ...
The largest possible value for $a$ is $10^6 - 1$, so we can iterate over each possibility. When we fix $a$, we can find the range of values for $b$ such that $10^{C - 1} \leq a + b < 10^C$, and $10^{B - 1} \leq b < 10^B$. For each such value, we have a correct equality. We can easily find this range. We get that $\max ...
[ "brute force", "implementation", "math" ]
1,700
#include <bits/stdc++.h> int power(int a, int e) { if (e == 0) return 1; return e == 1 ? a : a * power(a, e-1); } void answer(int a, int b) { std::cout << a << " + " << b << " = " << a+b << std::endl; } int main() { using ll = long long; int t; std::cin >> t; while (t--) { i...
1835
B
Lottery
$n$ people indexed with integers from $1$ to $n$ came to take part in a lottery. Each received a ticket with an integer from $0$ to $m$. In a lottery, one integer called target is drawn uniformly from $0$ to $m$. $k$ tickets (or less, if there are not enough participants) with the closest numbers to the target are dec...
Let's assume that Bytek has selected a certain position $c$. Let the closest occupied position to the left be $d$, and the closest occupied position to the right be $e$. Let's denote the position of the $k$-th person to the left as $a$ and the $k$-th person to the right as $b$ (on the picture $k=3$). Note that for Byte...
[ "binary search", "brute force", "greedy", "math", "two pointers" ]
2,500
#include <bits/stdc++.h> #define forr(i, n) for (int i = 0; i < n; i++) #define FOREACH(iter, coll) for (auto iter = coll.begin(); iter != coll.end(); ++iter) #define FOREACHR(iter, coll) for (auto iter = coll.rbegin(); iter != coll.rend(); ++iter) #define lbound(P, K, FUN) ({auto SSS=P, PPP = P-1, KKK=(K)+1; while(P...
1835
C
Twin Clusters
Famous worldwide astrophysicist Mleil waGrasse Tysok recently read about the existence of twin galaxy clusters. Before he shares this knowledge with the broader audience in his podcast called S.tarT-ok, he wants to prove their presence on his own. Mleil is aware that the vastness of the universe is astounding (almost a...
Deterministic solution: Let us first look for segments that zeros first $k$ (out of $2k$) bits. Since we have $n = 2^{k + 1}$, then we have $n + 1$ prefix xors of the array (along with en empty prefix). Let us look at the xor prefix modulo $2^k$. Each time we have a prefix xor that has already occurred before let us ma...
[ "bitmasks", "brute force", "constructive algorithms", "math", "probabilities" ]
2,600
#include <bits/stdc++.h> using namespace std; void solve() { int k, n; scanf("%d", &k); n = 2 << k; vector <long long> input(n + 1); vector <int> memHighBits(1 << k, -1); vector <pair <int, int> > memLowBits(1 << k, {-1, -1}); auto addInterval = [&memLowBits, &input](int s, int e) {...
1835
D
Doctor's Brown Hypothesis
The rebels have been crushed in the most recent battle with the imperial forces, but there is a ray of new hope. Meanwhile, on one of the conquered planets, Luke was getting ready for an illegal street race (which should come as no surprise, given his family history). Luke arrived at the finish line with 88 miles per ...
As both vertices must visit each other, they must be in the same strongly connected component. We can compute all SCC and solve for them independently. Further, we will assume that we are solving for a fixed SCC. The critical observation is that $n^3$ is enormous, and we can visit an entire graph. This gives us hope th...
[ "dfs and similar", "graphs", "math", "number theory" ]
2,900
#include<bits/stdc++.h> using namespace std; #define sz(s) (int)s.size() #define all(s) s.begin(), s.end() #define pb push_back #define FOR(i, n) for(int i = 0; i < n; i++) using vi = vector<int>; using vvi = vector<vi>; struct SCC { int cnt = 0; vi vis, scc_nr; vvi scc_list, DAG; SCC(){} ...
1835
E
Old Mobile
During the latest mission of the starship U.S.S. Coder, Captain Jan Bitovsky was accidentally teleported to the surface of an unknown planet. Trying to find his way back, Jan found an artifact from planet Earth's ancient civilization — a mobile device capable of interstellar calls created by Byterola. Unfortunately, t...
Let us make some observations. First of them is that if a phone number consists of two or more digits of the same kind then we will always pay exactly $1$ click for each but the first occurrence of it (it follows from the fact, that we have to already the key responsible for this digit). This is why we can reduce the p...
[ "combinatorics", "dp", "probabilities" ]
3,500
#include <bits/stdc++.h> using namespace std; constexpr int MAX_M = 1000 + 7; constexpr int PRECISION = 9; constexpr long long MOD = 1e9 + 7; long long mod_inv[MAX_M]; long long DP[MAX_M][MAX_M][2][2]; long long DPprob[MAX_M][MAX_M][2][2]; bool updated[MAX_M][MAX_M][2][2]; // DP[correct][incorrect][backspace][bad...
1835
F
Good Graph
You are given a bipartite graph $G$ with the vertex set in the left part $L$, in the right part $R$, and $m$ edges connecting these two sets. We know that $|L| = |R| = n$. For any subset $S \subseteq L$, let $N(S)$ denote the set of all neighbors of vertices in $S$. We say that a subset $S \subseteq L$ in graph $G$ is...
According to Hall's theorem, a graph is good if and only if a perfect matching exists. We run any reasonable algorithm to find a perfect matching (e.g. the Hopcroft-Karp's algorithm). We call the found matching $\mathcal{M}$ (any perfect matching is fine). We look for a counterexample if we do not find a perfect matchi...
[ "bitmasks", "dfs and similar", "graph matchings", "graphs", "implementation" ]
3,500
#include <bits/stdc++.h> #define forr(i, n) for (int i = 0; i < n; i++) #define FOREACH(iter, coll) for (auto iter = coll.begin(); iter != coll.end(); ++iter) #define FOREACHR(iter, coll) for (auto iter = coll.rbegin(); iter != coll.rend(); ++iter) #define lbound(P, K, FUN) ({auto SSS=P, PPP = P-1, KKK=(K)+1; while(PP...
1836
A
Destroyer
John is a lead programmer on a destroyer belonging to the space navy of the Confederacy of Independent Operating Systems. One of his tasks is checking if the electronic brains of robots were damaged during battles. A standard test is to order the robots to form one or several lines, in each line the robots should stan...
We can simplify the statement to the following - can we divide the input sequence into multiple arithmetic sequences starting with $0$ and a common difference equal to $1$? Note that for each such arithmetic sequence, if a number $x > 0$ belongs to it, then $x - 1$ must also be included in it. Thus, if we denote $cnt_x...
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; const int N = 1e6; int main() { int cases; scanf("%d", &cases); while (cases--) { int n; scanf ("%d", &n); vector <int> cnt(n + 1); for (int i = 0; i < n; i++) { int d; scanf("%d", &d); if (d < n) { ...
1836
B
Astrophysicists
In many, many years, far, far away, there will be a launch of the first flight to Mars. To celebrate the success, $n$ astrophysicists working on the project will be given bonuses of a total value of $k$ gold coins. You have to distribute the money among the astrophysicists, and to make it easier, you have to assign bo...
Note that in the perfect world, we'd give each astrophysicist precisely $\lfloor \frac{G - 1}{2} \rfloor$, and we'd spare $N \cdot \lfloor \frac{G - 1}{2} \rfloor$ silver coins. Unfortunately, two things may happen: First, we may run out of money. This is an easy case; it is enough to output $K \cdot G$ if it is less t...
[ "greedy", "math" ]
1,100
#include "bits/stdc++.h" using namespace std; int main() { int t; scanf ("%d", &t); while (t--) { long long n, k, g; scanf ("%lld %lld %lld", &n, &k, &g); long long stolen = min((g - 1) / 2 * n, k * g); long long rest = (k * g - stolen) % g; if (rest > 0) { stolen -= (g - 1) / 2; long lon...
1837
A
Grasshopper on a Line
You are given two integers $x$ and $k$. Grasshopper starts in a point $0$ on an OX axis. In one move, it can jump some integer distance, \textbf{that is not divisible by $k$}, to the left or to the right. What's the smallest number of moves it takes the grasshopper to reach point $x$? What are these moves? If there ar...
When $x$ is not divisible by $k$, the grasshopper can reach $x$ in just one jump. Otherwise, you can show that two jumps are always enough. For example, jumps $1$ and $x-1$. $1$ is not divisible by any $k > 1$. Also, $x$ and $x-1$ can't be divisible by any $k > 1$ at the same time. 1837B - Comparison String
[ "constructive algorithms", "math" ]
800
for _ in range(int(input())): x, k = map(int, input().split()) if x % k != 0: print(1) print(x) else: print(2) print(1, x - 1)
1837
B
Comparison String
You are given a string $s$ of length $n$, where each character is either < or >. An array $a$ consisting of $n+1$ elements is compatible with the string $s$ if, for every $i$ from $1$ to $n$, the character $s_i$ represents the result of comparing $a_i$ and $a_{i+1}$, i. e.: - $s_i$ is < if and only if $a_i < a_{i+1}$...
Suppose there is a segment of length $k$ that consists of equal characters in $s$. This segment implies that there are at least $k+1$ distinct values in the answer: for example, if the segment consists of < signs, the first element should be less than the second element, the second element should be less than the third...
[ "greedy" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) { int n; cin >> n; string s; cin >> s; int ans = 1, cur = 1; for(int i = 1; i < n; i++) { ...
1837
C
Best Binary String
You are given a string $s$ consisting of the characters 0, 1 and/or ?. Let's call it a pattern. Let's say that the binary string (a string where each character is either 0 or 1) matches the pattern if you can replace each character ? with 0 or 1 (for each character, the choice is independent) so that the strings becom...
First of all, let's try solving an easier problem - suppose we have a binary string, how many operations of the form "reverse a substring" do we have to perform so that it is sorted? To solve this problem, we need to consider substrings of the form 10 in the string (i. e. situations when a zero immediately follows a on...
[ "constructive algorithms", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { string s; cin >> s; char x = '0'; for (auto& c : s) { if (c == '?') c = x; x = c; } cout << s << '\n'; } }
1837
D
Bracket Coloring
A regular bracket sequence 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: - the bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"...
What properties do beautiful bracket sequences have? Well, each beautiful sequence is either an RBS (regular bracket sequence) or a reversed RBS. For RBS, the balance (the difference between the number of opening and closing brackets) is non-negative for every its prefix, and equal to zero at the end of the string. For...
[ "constructive algorithms", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) { int n; cin >> n; string s; cin >> s; vector<int> bal(n + 1); for(int j = 0; j < n; j++) ...
1837
E
Playoff Fixing
$2^k$ teams participate in a playoff tournament. The teams are numbered from $1$ to $2^k$, in order of decreasing strength. So, team $1$ is the strongest one, team $2^k$ is the weakest one. A team with a smaller number always defeats a team with a larger number. First of all, the teams are arranged in some order durin...
Let's investigate the structure of the tournament, starting from the first round. We know that teams from $2^{k-1}+1$ to $2^k$ have to lose during this round. At the same time, there are exactly $2^{k-1}$ losers in this round. So, every pairing has to look like this: a team from $1$ to $2^{k-1}$ versus a team from $2^{...
[ "combinatorics", "trees" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int MOD = 998244353; int main() { int k; scanf("%d", &k); vector<int> a(1 << k); forn(i, 1 << k){ scanf("%d", &a[i]); if (a[i] != -1) --a[i]; } int ans = 1; for (int st = k - 1; st >= 0; --st){ int b...
1837
F
Editorial for Two
Berland Intercollegiate Contest has just finished. Monocarp and Polycarp, as the jury, are going to conduct an editorial. Unfortunately, the time is limited, since they have to finish before the closing ceremony. There were $n$ problems in the contest. The problems are numbered from $1$ to $n$. The editorial for the $...
In the problem, we are asked to first choose $k$ problems, then fix a split into a prefix and a suffix. But nothing stops us from doing that in reverse. Let's fix the split of an entire problemset first, then choose some $l$ ($0 \le l \le k$) and $l$ problems to the left of the split and the remaining $k - l$ problems ...
[ "binary search", "data structures", "greedy", "implementation" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int t; scanf("%d", &t); while (t--){ int n, k; scanf("%d%d", &n, &k); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); vector<pair<int, int>> xs(n); forn(i, n) xs[i] = {a[i], i}; sort(xs.be...
1838
A
Blackboard List
Two integers were written on a blackboard. After that, the following step was carried out $n-2$ times: - Select any two integers on the board, and write the absolute value of their difference on the board. After this process was complete, the list of $n$ integers was shuffled. You are given the final list. Recover \t...
Note that any negative integers on the board must have been one of the original two numbers, because the absolute difference between any two numbers is nonnegative. So, if there are any negative numbers, print one of those. If there are only nonnegative integers, note that the maximum number remains the same after perf...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int tc = 1; tc <= t; ++tc) { int n; cin >> n; int mn = INT_MAX, mx = INT_MIN; for(int i = 0; i < n; ++i) { int x; cin >> x; mn = min(mn, x); mx = max(mx, x); } ...
1838
B
Minimize Permutation Subarrays
You are given a permutation $p$ of size $n$. You want to minimize the number of subarrays of $p$ that are permutations. In order to do so, you must perform the following operation \textbf{exactly} once: - Select integers $i$, $j$, where $1 \le i, j \le n$, then - Swap $p_i$ and $p_j$. For example, if $p = [5, 1, 4, 2...
Let $\mathrm{idx}_x$ be the position of the element $x$ in $p$, and consider what happens if $\mathrm{idx}_n$ is in between $\mathrm{idx}_1$ and $\mathrm{idx}_2$. Notice that any subarray of size greater than $1$ that is a permutation must contain $\mathrm{idx}_1$ and $\mathrm{idx}_2$. So it must also contain every ind...
[ "constructive algorithms", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; #define N 200010 int idx[N]; int main() { int t; cin >> t; for(int tc = 1; tc <= t; ++tc) { int n; cin >> n; for(int i = 1; i <= n; ++i) { int x; cin >> x; idx[x] = i; } if(idx[n] < min(idx[1], idx[2])) {...
1838
C
No Prime Differences
You are given integers $n$ and $m$. Fill an $n$ by $m$ grid with the integers $1$ through $n\cdot m$, in such a way that for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime number. Two cells in the grid are considered adjacent if they share a side. It can be show...
Note that if we fill in the numbers in order from the top left to the bottom right, for example, for $n=5$, $m=7$, the only adjacent differences are $1$ and $m$. So if $m$ is not prime, this solves the problem. We'll now rearrange the rows so that it works regardless of whether $m$ is prime. Put the first $\lfloor\frac...
[ "constructive algorithms", "math", "number theory" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int tc = 1; tc <= t; ++tc) { int n, m; cin >> n >> m; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { if(i % 2 == 0) cout << (n / 2 + i / 2) * m + j + 1 << ' '; ...
1838
D
Bracket Walk
There is a string $s$ of length $n$ consisting of the characters '(' and ')'. You are walking on this string. You start by standing on top of the first character of $s$, and you want to make a sequence of moves such that you end on the $n$-th character. In one step, you can move one space to the left (if you are not st...
For a string to be walkable, we need $n$ to be even, because the parity of the balance factor changes on each move, and it has to be zero at the end of the process. So if $n$ is odd, the string is never walkable. Now, consider the set $A$ that contains all indices $i$ ($1$-indexed) satisfying one of the below condition...
[ "data structures", "greedy", "strings" ]
2,100
#include <bits/stdc++.h> using namespace std; int main() { int n, q; string s; cin >> n >> q >> s; set<int> a; for(int i = 1; i <= n; ++i) if((i % 2) != (s[i - 1] == '(')) a.insert(i); while(q--) { int i; cin >> i; if(a.count(i)) a.erase(i); else a.i...
1838
E
Count Supersequences
You are given an array $a$ of $n$ integers, where all elements $a_i$ lie in the range $[1, k]$. How many different arrays $b$ of $m$ integers, where all elements $b_i$ lie in the range $[1, k]$, contain $a$ as a subsequence? Two arrays are considered different if they differ in at least one position. A sequence $x$ is...
Let's first consider a DP solution. Let $dp_{i,j}$ be the number of arrays of length $i$, such that the longest prefix of $a$ that appears as a subsequence of the array is of length $j$. To compute this DP, consider some cases. Let $b'$ be the subarray of the first $i$ elements of $b$, and $a'$ be the subarray of the f...
[ "combinatorics", "dp", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; typedef long long int ll; ll M = 1000000007; ll pw(ll a, ll p) { return p ? pw(a * a % M, p / 2) * (p & 1 ? a : 1) % M : 1; } ll inv(ll a) { return pw(a, M - 2); } int main() { ll t; cin >> t; for(ll tc = 1; tc <= t; ++tc) { ll n, m, k, ai; ci...
1838
F
Stuck Conveyor
This is an interactive problem. There is an $n$ by $n$ grid of conveyor belts, in positions $(1, 1)$ through $(n, n)$ of a coordinate plane. Every other square in the plane is empty. Each conveyor belt can be configured to move boxes up ('^'), down ('v'), left ('<'), or right ('>'). If a box moves onto an empty square...
The key to our solution will be these two "snake" configurations: We will initially query the first snake with the box on the top left, and the second snake with the box on the bottom left (or bottom right, depending on parity of $n$). Note that these two snakes, with the box on the given starting positions, each form ...
[ "binary search", "constructive algorithms", "interactive" ]
3,000
#include <bits/stdc++.h> using namespace std; char grid[110][110]; int n; vector<pair<int, int>> snake; map<pair<int, int>, char> getChar = { {{1, 0}, 'v'}, {{-1, 0}, '^'}, {{0, 1}, '>'}, {{0, -1}, '<'} }; pair<pair<int, int>, char> getBeltAndDir(pair<int, int> p) { if(p.first == -1) return {p, 'X...
1839
A
The Good Array
You are given two integers $n$ and $k$. An array $a_1, a_2, \ldots, a_n$ of length $n$, consisting of zeroes and ones is good if for \textbf{all} integers $i$ from $1$ to $n$ \textbf{both} of the following conditions are satisfied: - at least $\lceil \frac{i}{k} \rceil$ of the first $i$ elements of $a$ are equal to $...
Let's find lower bound for answer. In any good array, there are at least $\lceil \frac{n - 1}{k} \rceil$ ones among the first $n - 1$ elements. Also, $a_n$ is always $1$, as $\lceil \frac{1}{k} \rceil = 1$. So there are at least $\lceil \frac{n - 1}{k} \rceil + 1$ ones in any good array. This lower bound can always be ...
[ "greedy", "implementation", "math" ]
800
null
1839
B
Lamps
You have $n$ lamps, numbered by integers from $1$ to $n$. Each lamp $i$ has two integer parameters $a_i$ and $b_i$. At each moment each lamp is \textbf{in one of three states}: it may be turned on, turned off, or broken. Initially all lamps are turned off. In one operation you can select one lamp that is turned off a...
Let's denote number of lamps with $a_i = k$ as $c_k$. If $c_k \ge k$ and you turn $k$ lamps with $a_i = k$ lamps on, all $c_k$ of them will break and you will not be able to receive points for the other $c_k - k$ lamps. If we denote values $b_i$ for all $i$ such that $a_i = k$ as $d_{k, 1}, d_{k, 2}, \ldots, d_{k, c_k}...
[ "greedy", "sortings" ]
1,100
null
1839
C
Insert Zero and Invert Prefix
You have a sequence $a_1, a_2, \ldots, a_n$ of length $n$, each element of which is either $0$ or $1$, and a sequence $b$, which is initially empty. You are going to perform $n$ operations. On each of them you will increase the length of $b$ by $1$. - On the $i$-th operation you choose an integer $p$ between $0$ and ...
It's easy to see that last element of $b$ is always zero, so if $a_n$ is $1$, then the answer is "NO". It turns out that if $a_n$ is $0$, then answer is always "YES". First, let's try to get $b$ equal to array of form $[\, \overbrace{1, 1, \ldots, 1}^{k}, 0 \,]$ for some $k \ge 0$. Further in the editorial I will call ...
[ "constructive algorithms" ]
1,300
null
1839
D
Ball Sorting
There are $n$ colorful balls arranged in a row. The balls are painted in $n$ distinct colors, denoted by numbers from $1$ to $n$. The $i$-th ball from the left is painted in color $c_i$. You want to reorder the balls so that the $i$-th ball from the left has color $i$. Additionally, you have $k \ge 1$ balls of color $0...
Let's solve the problem for some fixed $k$. Consider the set $S$ of all balls that were never moved with operation of type $2$. Let's call balls from $S$ fixed and balls not from $S$ mobile. The relative order of fixed balls never changes, so their colors must form an increasing sequence. Let's define $f(S)$ as the num...
[ "data structures", "dp", "sortings" ]
2,100
null
1839
E
Decreasing Game
\textbf{This is an interactive problem.} Consider the following game for two players: - Initially, an array of integers $a_1, a_2, \ldots, a_n$ of length $n$ is written on blackboard. - Game consists of rounds. On each round, the following happens: - The first player selects any $i$ such that $a_i \gt 0$. If there i...
I claim that the second player wins if and only if array $a$ can be divided into two sets with equal sum, or, equivalently, there is a subset of $a$ with sum $\frac{a_1 + a_2 + \ldots + a_n}{2}$. The strategy for the second player in this case is quite simple: before the game starts, the second player splits $a$ into t...
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "interactive" ]
2,400
null
1840
A
Cipher Shifer
There is a string $a$ (unknown to you), consisting of lowercase Latin letters, encrypted according to the following rule into string $s$: - after each character of string $a$, an arbitrary (possibly zero) number of any lowercase Latin letters, different from the character itself, is added; - after each such addition, ...
Note that during encryption, only characters different from $c$ are added after the character $c$. However, when the character $c$ is encrypted with different characters, another $c$ character is added to the string. This means that for decryption, we only need to read the characters of the string after $c$ until we fi...
[ "implementation", "strings", "two pointers" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; int i = 0; while (i < n) { int start = i; cout << s[i++]; while (s[i++] != s[start]); } cout << e...
1840
B
Binary Cafe
Once upon a time, Toma found himself in a binary cafe. It is a very popular and unusual place. The cafe offers visitors $k$ different delicious desserts. The desserts are numbered from $0$ to $k-1$. The cost of the $i$-th dessert is $2^i$ coins, because it is a binary cafe! Toma is willing to spend no more than $n$ co...
On the one hand, if Tema had an infinite number of coins, he could buy any set of desserts offered in the coffee shop. This can be done in $2^k$ ways, since each of the desserts can either be taken or not taken. On the other hand, if the coffee shop offered an infinite number of desserts for tasting, Tema could spend a...
[ "bitmasks", "combinatorics", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; int32_t main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; k = min(k, 30); cout << min(n, (1 << k) - 1) + 1 << "\n"; } return 0; }
1840
C
Ski Resort
Dima Vatrushin is a math teacher at school. He was sent on vacation for $n$ days for his good work. Dima has long dreamed of going to a ski resort, so he wants to allocate several \textbf{consecutive days} and go skiing. Since the vacation requires careful preparation, he will only go for \textbf{at least $k$ days}. Y...
To simplify the task, let's replace all numbers in the array $a$. If the value of $a_i$ is greater than $q$, then replace it with $0$. Otherwise, replace it with $1$. Now Dima can go on this day if $a_i = 1$. Therefore, we need to consider segments consisting only of $1$. Note that if the segment consists of less than ...
[ "combinatorics", "math", "two pointers" ]
1,000
testCases = int(input()) for testCase in range(testCases): n, k, q = map(int, input().split(' ')) a = list(map(int, input().split(' '))) ans = 0 len = 0 for i in range(n): if a[i] <= q: len += 1 else: if len >= k: ans += (len - k + 1) * ...
1840
D
Wooden Toy Festival
In a small town, there is a workshop specializing in woodwork. Since the town is small, only \textbf{three} carvers work there. Soon, a wooden toy festival is planned in the town. The workshop employees want to prepare for it. They know that $n$ people will come to the workshop with a request to make a wooden toy. Pe...
Let the carvers choose patterns $x_1$, $x_2$, $x_3$ for preparation. For definiteness, let us assume that $x_1 \le x_2 \le x_3$, otherwise we will renumber the carvers. When a person comes to the workshop with a request to make a toy of pattern $p$, the best solution is to give his order to the carver for whom $|x_i - ...
[ "binary search", "greedy", "sortings" ]
1,400
#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]; } sort(a.begin(), a.end()); int l = -1, r = 1e9; while (r - ...
1840
E
Character Blocking
You are given two strings of equal length $s_1$ and $s_2$, consisting of lowercase Latin letters, and an integer $t$. You need to answer $q$ queries, numbered from $1$ to $q$. The $i$-th query comes in the $i$-th second of time. Each query is one of three types: - block the characters at position $pos$ (indexed from ...
Two strings are equal if and only if there is no position $pos$ such that the characters at position $pos$ are not blocked and $s_1[pos] \neq s_2[pos]$ (we will call such a position bad). We will use this observation to maintain the current number of bad positions, denoted by $cnt$. Let $I_{pos}$ be an indicator variab...
[ "data structures", "hashing", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int x; cin >> x; while (x--) { vector<string> s(2); cin >> s[0] >> s[1]; int n = s[0].size(); int bad = 0; for (int i = 0; i < n; ++i) { if (s[0][i] != s[1][i]) { ++bad; ...
1840
F
Railguns
Tema is playing a very interesting computer game. During the next mission, Tema's character found himself on an unfamiliar planet. Unlike Earth, this planet is flat and can be represented as an $n \times m$ rectangle. Tema's character is located at the point with coordinates $(0, 0)$. In order to successfully complet...
Let's first solve it in $\mathcal{O}(nmt)$. This can be done using dynamic programming. $dp[i][j][k] = true$ if the character can be at coordinates $(i, j)$ at time $t$, otherwise $dp[i][j][k] = false$. Such dynamics can be easily recalculated: $dp[i][j][k] = dp[i - 1][j][k - 1] | dp[i][j - 1][k - 1] | dp[i][j][k - 1]$...
[ "brute force", "dfs and similar", "dp", "graphs" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int q; cin >> q; while (q--) { int n, m; cin >> n >> m; int r; cin >> r; bool free[n + 1][m + 1][r + 1]; for (int i = 0; i <= n; +...
1840
G1
In Search of Truth (Easy Version)
\textbf{The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $2023$ queries.} This is an interactive problem. You are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in t...
Let $a_1, a_2, \dots, a_n$ be the numbers of the sectors in clockwise order, and let the arrow initially point to the sector with number $a_1$. First, let's make $999$ queries of "+ 1", then we will know the numbers of $1000$ consecutive sectors. If $n < 1000$, then the number of the first query that gives the answer $...
[ "constructive algorithms", "interactive", "math", "meet-in-the-middle", "probabilities" ]
2,200
#include <bits/stdc++.h> using namespace std; #define int long long const int MAXN = 1e6 + 7; int pos[MAXN]; int32_t main() { int num; cin >> num; int ans = 0; int cur = 1; pos[num] = 1; for (int i = 0; i < 1000; ++i) { cout << '+' << " " << 1 << endl; ++cur; ci...