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
1362
B
Johnny and His Hobbies
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set $S$ containing very important numb...
Consider $i$-th least significant bit ($0$ indexed). If it is set in $k$, but not in $s$, it will be set in $k \oplus s$. Hence $k \oplus s \geq 2^i$. Consider such minimal positive integer $m$, that $2^m > s$ holds for all $s \in S$. $k$ cannot have the $i$-th bit set for any $i \geq m$. From this follows that $k < 2^...
[ "bitmasks", "brute force" ]
1,200
//O(n * maxA) solution #include <bits/stdc++.h> using namespace std; const int N = 1025; int n; int in[N]; bool is[N]; bool check(int k){ for(int i = 1; i <= n; ++i) if(!is[in[i] ^ k]) return false; return true; } void solve(){ for(int i = 0; i < N; ++i) is[i] = false; scanf("%d", &n); for(int i = 1...
1362
C
Johnny and Another Rating Drop
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills. The boy is now looking at the ratings of consecutive participan...
Let us start by calculating the result for $n = 2^k$. It can be quickly done by calculating the results for each bit separately and summing these up. For $i$-th bit, the result is equal to $\frac{2^k}{2^{i}}$ as this bit is different in $d-1$ and $d$ iff $d$ is a multiple of $2^i$. Summing these up we get that the resu...
[ "bitmasks", "greedy", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; typedef long long LL; void solve(){ LL a; scanf("%lld", &a); LL ans = 0; for(int i = 0; i < 60; ++i) if(a & (1LL << i)) ans += (1LL << (i + 1)) - 1; printf("%lld\n", ans); } int main(){ int quest; scanf("%d", &quest); while(quest--) solve(); return 0...
1363
A
Odd Selection
Shubham has an array $a$ of size $n$, and wants to select exactly $x$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so.
Key Idea: The sum of $x$ numbers can only be odd if we have an odd number of numbers which are odd. (An odd statement, indeed). Detailed Explanation: We first maintain two variables, num_odd and num_even, representing the number of odd and even numbers in the array, respectively. We then iterate over the number of odd ...
[ "brute force", "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, x; int a[N], f[2]; int32_t main() { IOS; int t; cin >> t; while(t--) { f[0] = f[1] = 0; cin >> n >> x; for(int i =...
1363
B
Subsequence Hate
Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: - Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A...
Key Idea: There are two types of good strings: Those which start with a series of $1$'s followed by $0$'s (such as $1111100$) and those which start with a series of $0$'s followed by $1$'s (such as $00111$). Note that there are strings which do belong to both categories (such as $000$). Detailed Explanation: We will us...
[ "implementation", "strings" ]
1,400
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; int32_t main() { IOS; int t; cin >> t; while(t--) { string s; cin >> s; int suf0 = 0, suf1 = 0; for(auto &it:s) { suf0 += (it...
1363
C
Game On Leaves
Ayush and Ashish play a game on an unrooted tree consisting of $n$ nodes numbered $1$ to $n$. Players make the following move in turns: - Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $1$. A tr...
Key Idea: The main idea of this problem is to think backwards. Instead of thinking about how the game will proceed, we think about how the penultimate state of the game will look like, etc. Also, we take care of the cases where the game will end immediately (i.e, when the special node is a leaf node). Detailed Explanat...
[ "games", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, x; int deg[N]; vector<int> g[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { memset(deg, 0, sizeof(deg)); cin >> n >>...
1363
D
Guess The Maximums
\textbf{This is an interactive problem.} Ayush devised a new scheme to set the password of his lock. The lock has $k$ slots where each slot can hold integers from $1$ to $n$. The password $P$ is a sequence of $k$ integers each in the range $[1, n]$, $i$-th element of which goes into the $i$-th slot of the lock. To se...
Key Idea: The maximum of the array is the password integer for all except atmost $1$ position. We find the subset (if the maximum is in a subset) in which the maximum exists using binary search, and then query the answer for this subset seperately. (For all the subsets, the answer is the maximum for the whole array). D...
[ "binary search", "implementation", "interactive", "math" ]
2,100
#include<bits/stdc++.h> using namespace std; #define vint vector<int> int interact(vint S){ cout << "? " << S.size() << ' '; for(int i : S) cout << i << ' '; cout << endl; int x; cin >> x; return x; } vint get_complement(vint v, int n){ vint ask, occur(n + 1); for(int i : v) occur[i] = 1; for(int i =...
1363
E
Tree Shuffling
Ashish has a tree consisting of $n$ nodes numbered $1$ to $n$ rooted at node $1$. The $i$-th node in the tree has a cost $a_i$, and binary digit $b_i$ is written in it. He wants to have binary digit $c_i$ written in the $i$-th node in the end. To achieve this, he can perform the following operation any number of times...
Key Idea: Let the parent of node $i$ be $p$. If $a[i] \geq a[p]$, we can do the shuffling which was done at $i$, at $p$ instead. Thus, we can do the operation $a[i] = min(a[i],a[p])$. Detailed Explanation: Let us denote nodes that have $b_i = 1$ and $c_i = 0$ as type $1$, and those that have $b_i = 0$ and $c_i = 1$ as ...
[ "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, cost = 0; int arr[N], b[N], c[N]; vector<int> g[N]; pair<int, int> dfs(int u, int par, int mn) { pair<int, int> a = {0, 0}; if(b[u] ...
1363
F
Rotating Substrings
You are given two strings $s$ and $t$, each of length $n$ and consisting of lowercase Latin alphabets. You want to make $s$ equal to $t$. You can perform the following operation on $s$ any number of times to achieve it — - Choose any substring of $s$ and rotate it clockwise once, that is, if the selected substring is...
Key Idea: We note that a clockwise rotation is the same as taking a character at any position in the string, and inserting it anywhere to it's left. Thus, we process the strings from the end, build the suffixes and move towards the prefix. Detailed Explanation: The answer is $-1$ if both s and t do not have the same co...
[ "dp", "strings" ]
2,600
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2005; int n; string s, t; int suf[26][N], suf2[26][N]; int cache[N][N]; int dp(int i, int j) { if(j == 0) return 0; int &ans = cache[i][j]; if(an...
1364
A
XXXXX
Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements \textbf{isn't} divisible by $x$, or determine that such subarray doesn't exist. An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$...
Let's start with the whole array. If every element in it is divisible by $x$, the answer is $-1$; if its sum isn't divisible by $x$, the answer is $n$. Otherwise, we must remove some elements. The key idea is that removing an element that is divisible by $x$ doesn't do us any benefits, but once we remove an element tha...
[ "brute force", "data structures", "number theory", "two pointers" ]
1,200
"#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n,x,sum=0,l=-1,r;\n\t\tscanf(\"%d%d\",&n,&x);\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tint a;\n\t\t\tscanf(\"%d\",&a);\n\t\t\tif (a%x)\n\t\t\t{\n\t\t\t\tif (l==-1)\n\t\t\t\tl=i;\n\t\t\t\tr=i;\n\t\t...
1364
B
Most socially-distanced subsequence
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: - $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. - Among all such subsequences, choose the one whose length, $k$, is as sm...
TL;DR the answer contains the first element, last element, and all the local minima and maxima, where a local minimum is an element less than its 2 adjacents, and a local maximum is an element greater than it 2 adjacents. Let's look at the expression in the problem for 3 numbers. If $a>b$ and $b>c$ or if $a<b$ and $b<c...
[ "greedy", "two pointers" ]
1,300
"#include <bits/stdc++.h>\nusing namespace std;\nint p[100005];\nint main()\n{\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tscanf(\"%d\",&n);\n\t\tfor (int i=1;i<=n;i++)\n\t\tscanf(\"%d\",&p[i]);\n\t\tvector<int> ans;\n\t\tfor (int i=1;i<=n;i++)\n\t\t{\n\t\t\tif (i==1 || i==n || (p[i-1]<p[i])!=(p...
1364
C
Ehab and Prefix MEXs
Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that: - for each $i$ $(1 \le i \le n)$ $MEX(\{b_1$, $b_2$, $\ldots$, $b_i\})=a_i$. The $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this.
The key observation is: if for some index $i$, $a_i \neq a_{i-1}$, then $b_i$ must be equal to $a_{i-1}$, since it's the only way to even change the prefix $MEX$. We can use this observation to fill some indices of $b$. Now, how do we fill the rest? Let's start by avoiding every element in $a$. Something special will h...
[ "brute force", "constructive algorithms", "greedy" ]
1,600
"#include <bits/stdc++.h>\nusing namespace std;\nint a[100005],b[100005];\nbool ex[100005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=1;i<=n;i++)\n\tscanf(\"%d\",&a[i]);\n\tmemset(b,-1,sizeof(b));\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tif (a[i]!=a[i-1])\n\t\t{\n\t\t\tb[i]=a[i-1];\n\t\t\tex[b[i]]=1;\n\t\t...
1364
D
Ehab's Last Corollary
Given a connected undirected graph with $n$ vertices and an integer $k$, you have to either: - either find an independent set that has \textbf{exactly} $\lceil\frac{k}{2}\rceil$ vertices. - or find a \textbf{simple} cycle of length \textbf{at most} $k$. An independent set is a set of vertices such that no two of them...
The common idea is: if the graph is a tree, you can easily find an independent set with size $\lceil\frac{n}{2}\rceil$ by bicoloring the vertices and taking the vertices from the more frequent color. Otherwise, the graph is cyclic. Let's get a cycle that doesn't have any edges "cutting through it." In other words, it d...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy", "implementation", "trees" ]
2,100
"#include <bits/stdc++.h>\nusing namespace std;\nint pos[100005];\nbool ex[100005];\nvector<int> v[100005],col[100005],s;\nvector<pair<int,int> > e;\ndeque<int> cyc;\nvoid dfs(int node)\n{\n\tpos[node]=s.size();\n\tcol[pos[node]%2].push_back(node);\n\ts.push_back(node);\n\tfor (int u:v[node])\n\t{\n\t\tif (pos[u]==-1)\...
1364
E
X-OR
\textbf{This is an interactive problem!} Ehab has a hidden permutation $p$ of length $n$ consisting of the elements from $0$ to $n-1$. You, for some reason, want to figure out the permutation. To do that, you can give Ehab $2$ \textbf{different} indices $i$ and $j$, and he'll reply with $(p_i|p_j)$ where $|$ is the bi...
The common idea is: if we find the index that contains $0$, we can query it with every element in $p$ and finish in $n$ queries (if you didn't do that, pleaaase share your solution.) How to get this index? Let's try to make a magic function that takes an index $i$ and tells us $p_i$. Assume you have an array $z$ such t...
[ "bitmasks", "constructive algorithms", "divide and conquer", "interactive", "probabilities" ]
2,700
"#include <bits/stdc++.h>\nusing namespace std;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint p[(1<<11)+5];\nint query(int i,int j)\n{\n\tprintf(\"? %d %d\\n\",i,j);\n\tfflush(stdout);\n\tint ans;\n\tscanf(\"%d\",&ans);\n\tassert(ans!=-1);\n\treturn ans;\n}\nint main()\n{\n\tint n;\n\tscanf...
1365
A
Matrix Game
Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a play...
Key Idea: Vivek and Ashish can never claim cells in rows and columns which already have at least one cell claimed. So we need to look at the parity of minimum of the number of rows and columns which have no cells claimed initially. Solution: Let $a$ be the number of rows which do not have any cell claimed in them initi...
[ "games", "greedy", "implementation" ]
1,100
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 51; int n, m; int a[N][N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n >> m; set< int > r, c; for(int i = 1; i <= n; i++) { for(int j ...
1365
B
Trouble Sort
Ashish has $n$ elements arranged in a line. These elements are represented by two integers $a_i$ — the value of the element and $b_i$ — the type of the element (there are only two possible types: $0$ and $1$). He wants to sort the elements in non-decreasing values of $a_i$. He can perform the following operation any ...
Key Idea: If there is at least one element of type $0$ and at least one element of type $1$, we can always sort the array. Solution: If all the elements are of the same type, we cannot swap any two elements. So, in this case, we just need to check if given elements are already in sorted order. Otherwise, there is at le...
[ "constructive algorithms", "implementation" ]
1,300
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e3 + 5; int n; int a[N], b[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n; bool sorted = 1, have0 = 0, have1 = 0; for(int i = 1; i <= n; ...
1365
C
Rotation Matching
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $n$. Let's call them $a$ and $b$. Note that a permutation of $n$ elements is a sequence of numbers $a_1, a_2, \l...
Key Idea: We only need to perform shifts on one of the arrays. Moreover, all the shifts can be of the same type (right or left)! Solution: First of all, a left cyclic shift is the same as $n - 1$ right cyclic shifts and vice versa. So we only need to perform shifts of one type, say right. Moreover, a right cyclic shift...
[ "constructive algorithms", "data structures", "greedy", "implementation" ]
1,400
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n; int a[N], b[N], pos[N]; map< int, int > offset; int32_t main() { IOS; cin >> n; for(int i = 1; i <= n; i++) { cin >> a[i]; pos[a[i]] = i; } f...
1365
D
Solve The Maze
Vivek has encountered a problem. He has a maze that can be represented as an $n \times m$ grid. Each of the grid cells may represent the following: - Empty — '.' - Wall — '#' - Good person  — 'G' - Bad person — 'B' The only escape from the maze is at cell $(n, m)$. A person can move to a cell only if it shares a sid...
Key Idea: We can block all empty neighbouring cells of bad people and then check if all good people can escape and no bad people are able to escape. Solution: Consider all the neighbouring cells of bad people. There shouldn't be any path from these cells to the cell $(n, m)$. If there is a path from any such cell, the ...
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "implementation", "shortest paths" ]
1,700
#include using namespace std; #define int long long typedef int ll; typedef long double ld; const ll N = 55; char en = '\n'; ll inf = 1e16; ll mod = 1e9 + 7; ll power(ll x, ll n, ll mod) { ll res = 1; x %= mod; while (n) { if (n & 1) res = (res * x) % mod; x = (x * x) % mod; n >>= 1; } ret...
1365
E
Maximum Subsequence Value
Ridhiman challenged Ashish to find the maximum valued subsequence of an array $a$ of size $n$ consisting of positive integers. The value of a non-empty subsequence of $k$ elements of $a$ is defined as $\sum 2^i$ over all integers $i \ge 0$ such that at least $\max(1, k - 2)$ elements of the subsequence have the $i$-th...
Key Idea: For subsets of size up to $3$, their value is the bitwise OR of all elements in it. For any subset $s$ of size greater than $3$, it turns out that if we pick any subset of $3$ elements within it, then its value is greater than or equal to the value of $s$! Solution: Let $k$ be the size of the chosen subset. F...
[ "brute force", "constructive algorithms" ]
1,900
#include using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 505; int n; int a[N]; int32_t main() { IOS; cin >> n; for(int i = 1; i <= n; i++) cin >> a[i]; int ans = 0; for(int i = 1; i <= n; i++) for(int j = i; j <= n;...
1365
F
Swaps Again
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid. Each test case consists of an integer $n$ and two arrays $a$ and $b$, of size $n$. If after some (possibly zero) operations described below, array $a$ can be transformed into arr...
Key Idea: If we consider the unordered pair of elements $\{{a_i, a_{n - i + 1}\}}$, then after any operation, the multiset of these pairs (irrespective of the ordering of elements within the pair) stays the same! Solution: First of all, if the multiset of numbers in $a$ and $b$ are not the same, the answer is "No". Mor...
[ "constructive algorithms", "implementation", "sortings" ]
2,100
#include using namespace std; int main(){ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int tc; cin >> tc; while(tc--){ int n; cin >> n; map< pair < int, int >, int > pairs; vector< int > a(n), b(n); bool possible = 1; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) ...
1365
G
Secure Password
\textbf{This is an interactive problem.} Ayush devised yet another scheme to set the password of his lock. The lock has $n$ slots where each slot can hold any non-negative integer. The password $P$ is a sequence of $n$ integers, $i$-th element of which goes into the $i$-th slot of the lock. To set the password, Ayush...
Key Idea: Unlike the last version of the problem, this is not doable using a binary search. Solution using more queries: It is possible to solve the problem using $2\cdot \log{n}$ queries in the following way: For each $i$, we ask the bitwise OR of all numbers at indices which have the $i$-th bit set in their binary re...
[ "bitmasks", "combinatorics", "constructive algorithms", "interactive", "math" ]
2,800
#include using namespace std; #define ll long long #define vint vector< int > const int Q = 13; ll query(vint v){ cout << "? " << v.size() << ' '; for(ll i : v) cout << i + 1 << ' '; cout << endl; fflush(stdout); ll or_value; cin >> or_value; return or_value; } int main(){ int n; cin >> n; vector< vin...
1366
A
Shovels and Swords
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
There are three constraints on the number of emeralds: the number of emeralds can't be greater than $a$; the number of emeralds can't be greater than $b$; the number of emeralds can't be greater than $\frac{a+b}{3}$. So the answer is $\min(a, b, \frac{a+b}{3})$.
[ "binary search", "greedy", "math" ]
1,100
for _ in range(int(input())): l, r = map(int, input().split()) print(min(l, r, (l + r) // 3))
1366
B
Shuffle
You are given an array consisting of $n$ integers $a_1$, $a_2$, ..., $a_n$. Initially $a_x = 1$, all other elements are equal to $0$. You have to perform $m$ operations. During the $i$-th operation, you choose two indices $c$ and $d$ such that $l_i \le c, d \le r_i$, and swap $a_c$ and $a_d$. Calculate the number of ...
Let's consider how the set of possible indices where the $1$ can be changes. Initially, only one index is correct - $x$. After performing an operation $l, r$ such that $x < l$ or $x > r$ this set does not change. But after performing an operation $l, r$ such that $l \le x \le r$ we should insert the elements $\{l, l+1,...
[ "math", "two pointers" ]
1,300
for _ in range(int(input())): n, x, m = map(int, input().split()) l, r = x, x for _ in range(m): L, R = map(int, input().split()) if max(l, L) <= min(r, R): l = min(l, L) r = max(r, R) print(r - l + 1)
1366
C
Palindromic Paths
You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$. A chip is initially in the cell $(1, 1)$, and it will be moved to the cell $(n, m)$...
Let's group the cells by their distance from the starting point: the group $0$ consists of a single cell $(1, 1)$; the group $1$ consists of the cells $(1, 2)$ and $(2, 1)$, and so on. In total, there are $n + m - 1$ groups. Let's analyze the groups $k$ and $n + m - 2 - k$. There are two cases: if $k = 0$ or $n + m - 2...
[ "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; vector<vector<int> > a(n, vector<int>(m)); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cin >> a[i][j]; vector<vector<int> > cnt(n + m - 1, vector<int>(2)); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++)...
1366
D
Two Divisors
You are given $n$ integers $a_1, a_2, \dots, a_n$. For each $a_i$ find its \textbf{two divisors} $d_1 > 1$ and $d_2 > 1$ such that $\gcd(d_1 + d_2, a_i) = 1$ (where $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$) or say that there is no such pair.
Firstly, for the fast factorization of given $a_i$, let's use Sieve of Eratosthenes: let's for each value $val \le 10^7$ calculate its minimum prime divisor $minDiv[val]$ in the same manner as the sieve do. Now we can factorize each $a_i$ in $O(\log{a_i})$ time by separating its prime divisors one by one using precalcu...
[ "constructive algorithms", "math", "number theory" ]
2,000
fun main() { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() } val minDiv = IntArray(1e7.toInt() + 2) { it } for (i in 2 until minDiv.size) { if (minDiv[i] != i) continue for (j in i until minDiv.size step i) minDiv[j] = minOf(minDiv...
1366
E
Two Arrays
You are given two arrays $a_1, a_2, \dots , a_n$ and $b_1, b_2, \dots , b_m$. Array $b$ is sorted in ascending order ($b_i < b_{i + 1}$ for each $i$ from $1$ to $m - 1$). You have to divide the array $a$ into $m$ consecutive subarrays so that, for each $i$ from $1$ to $m$, the minimum on the $i$-th subarray is equal t...
At first, let's reverse arrays $a$ and $b$. Now array $b$ is sorted in descending order. Now let's find minimum index $x$ such that $a_x = b_1$. If there is no such index or if $\min\limits_{1 \le i \le x}a_i < b_1$ then the answer is $0$ (because minimum on any prefix of array $a$ will never be equal to $b_1$). Otherw...
[ "binary search", "brute force", "combinatorics", "constructive algorithms", "dp", "two pointers" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 200005; const int MOD = 998244353; int mul(int a, int b) { return (a * 1LL * b) % MOD; } int n, m; int a[N], b[N]; int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) scanf("%d", a + i); for (int i = 0; i < m; ++i) scanf("%d"...
1366
F
Jog Around The Graph
You are given a simple weighted connected undirected graph, consisting of $n$ vertices and $m$ edges. A path in the graph of length $k$ is a sequence of $k+1$ vertices $v_1, v_2, \dots, v_{k+1}$ such that for each $i$ $(1 \le i \le k)$ the edge $(v_i, v_{i+1})$ is present in the graph. A path from some vertex $v$ also...
Let's observe what does the maximum weight of some fixed length path look like. Among the edges on that path the last one has the maximum weight. If it wasn't then the better total weight could be achieved by choosing a bigger weight edge earlier and going back and forth on it for the same number of steps. It actually ...
[ "binary search", "dp", "geometry", "graphs" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const long long INF = 1e18; const int MOD = 1000'000'007; const int inv2 = (MOD + 1) / 2; struct edge{ int v, u, w; }; struct frac{ long long x, y; frac(long long a, long long b){ if (b < 0) a = -a, b = -b; x =...
1366
G
Construct the String
Let's denote the function $f(s)$ that takes a string $s$ consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows: - let $r$ be an empty string; - process the characters of $s$ from left to right. For each character $c$, do the following: if $c$ is a lowerca...
The core idea of the solution is the following dynamic programming: $dp_{i, j}$ is the minimum number of characters we have to delete if we considered a subsequence of $i$ first characters of $s$, and it maps to $j$ first characters of $t$. There are three obvious transitions in this dynamic programming: we can go from...
[ "data structures", "dp", "strings" ]
2,700
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) #define fore(i, l, r) for (int i = int(l); i < int(r); ++i) const int INF = 1e9; const int N = 10010; int n, m; s...
1367
A
Short Substrings
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string $a$ consisting of lowercase English letters. The string $a$ has a length of $2$ or more characters. Then, from string $a$ he builds a new string $b$ and offers Alice the string $b$ so that she can guess the string $a$. Bob b...
Note that the first two characters of $a$ match the first two characters of $b$. The third character of the string $b$ again matches the second character of $a$ (since it is the first character in the second substring, which contains the second and the third character of $a$). The fourth character $b$ matches with the ...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int test = 1; test <= t; test++) { string b; cin >> b; string a = b.substr(0, 2); for (int i = 3; i < b.size(); i += 2) { a += b[i]; } cout << a << endl; } return 0; }
1367
B
Even Array
You are given an array $a[0 \ldots n-1]$ of length $n$ which consists of non-negative integers. \textbf{Note that array indices start from zero.} An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $i$ ($0 \le i \le n - 1$) the...
We split all the positions in which the parity of the index does not match with the parity of the element into two arrays. If there is an odd number in the even index, add this index to the $e$ array. Otherwise, if there is an even number in the odd index, add this index to the $o$ array. Note that if the sizes of the ...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { int n; cin >> n; int a = 0, b = 0; for (int i = 0; i < n; i++) { int x; cin >> x; if (x % 2 != i % 2) { if (i % 2 == 0) { a++; } el...
1367
C
Social Distance
Polycarp and his friends want to visit a new restaurant. The restaurant has $n$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $1$ to $n$ in the order from left to right. The state of the restaurant is described by a string of length $n$ which contains cha...
Let's split a given string into blocks of consecutive zeros. Then in each such block, you can independently put the maximum number of people who fit in it. But there are three cases to consider. If the current block is not the first and not the last, then there are ones at the border and this means that the first $k$ t...
[ "constructive algorithms", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int test = 1; test <= t; test++) { int n, k; cin >> n >> k; string s; cin >> s; int res = 0; for (int i = 0; i < n;) { int j = i + 1; for (; j < n && s[j] != '1'; j++); int left = s[i] == '1' ? k : 0; int r...
1367
D
Task On The Board
Polycarp wrote on the board a string $s$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input. After that, he erased some letters from the string $s$, and he rewrote the remaining letters in \textbf{any} order. As a result, he got some new string $t$. You have to find ...
We will construct the string $t$, starting with the largest letters. Note that if $b_i = 0$, then the $i$-th letter of the string $t$ is maximal, so we know that the $i$-th letter affect all $b_j \ne 0$. While the string $t$ is not completely constructed, we will do the following: Find all $i$ such that $b_i = 0$ and t...
[ "constructive algorithms", "greedy", "implementation", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int q; cin >> q; forn(qq, q) { string s; cin >> s; int n; cin >> n; vector<int> b(n); forn(i, n) cin >> b[i]; vector<vector<in...
1367
E
Necklace Assembly
The store sells $n$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them. A necklace is a set of beads connected in a circle. For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can asse...
Let's iterate over the $m$ - length of the $k$-beautiful necklace. For each position $i$, make an edge to the position $p[i] = (i + k) \bmod m$, where $a \bmod b$ - is the remainder of dividing $a$ by $b$. What is a cyclic shift by $k$ in this construction? A bead located at position $i$ will go along the edge to posit...
[ "brute force", "dfs and similar", "dp", "graphs", "greedy", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { int test; cin >> test; while (test--) { int n, k; cin >> n >> k; string s; cin >> s; vector<int> cnt(26); for (char c : s) { cnt[c - 'a']++; } for (int len = n; len >= 1; len--) { vector<bool> used(len); vector<int> cycles; ...
1367
F2
Flying Sort (Hard Version)
\textbf{This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $n$ are greater than in the easy version of the problem.} You are given an array $a$ of $n$ integers \textbf{(the given array can contain equal elements)}. You can perform the following ope...
Let's replace each number $a_i$ with the number of unique numbers less than $a_i$. For example, the array $a=[3, 7, 1, 2, 1, 3]$ will be replaced by $[2, 3, 0, 1, 0, 2]$. Note that the values of the numbers themselves were not important to us, only the order between them was important. Let's sort such an array. Let's s...
[ "binary search", "data structures", "dp", "greedy", "sortings", "two pointers" ]
2,400
#include <bits/stdc++.h> using namespace std; using ld = long double; using ll = long long; void solve() { int n; cin >> n; vector<int> v(n); vector<pair<int, int>> a(n); for (int i = 0; i < n; i++) { cin >> v[i]; a[i] = {v[i], i}; } sort(a.begin(), a.end()); vector<int...
1368
A
C+=
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a =$2$, b =$3$ changes the value of a to $5$ (the value of b does not change). In a prototype p...
After any operation either $a$ or $b$ becomes $a + b$. Out of the two options, clearly it is better to increase the smaller number. For example, with numbers $2, 3$ we can either get a pair $2, 5$ or $3, 5$; to obtain larger numbers, the last pair is better in every way. With this we can just simulate the process and c...
[ "brute force", "greedy", "implementation", "math" ]
800
null
1368
B
Codeforces Subsequences
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least $k$ subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string $s$ is a subset of ten characters of $s$ that read codeforces...
Suppose that instead of codeforces subsequences we're looking for, say, abcde subsequences. Then in an optimal string all a's appear at the front. Indeed, moving any other occurence of a to the front will leave all the other occurences intact, and can only possibly create new ones. For a similar reason, all b's should ...
[ "brute force", "constructive algorithms", "greedy", "math", "strings" ]
1,500
null
1368
C
Even Picture
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction. To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the follo...
The sample picture was a red herring, it's hard to generalize to work for arbitrary $n$. After drawing for a while you may come up with something like this: or like this: or something even more complicated. Of course, having a simpler construction (like the first one) saves time on implementation compared to other ones...
[ "constructive algorithms" ]
1,500
null
1368
D
AND, OR and square sum
Gottfried learned about binary number representation. He then came up with this task and presented it to you. You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = ...
Let's look at a single operation $x, y \to x~\mathsf{AND}~y, x~\mathsf{OR}~y$, let the last two be $z$ and $w$ respectively. We can notice that $x + y = z + w$. Indeed, looking at each bit separately we can see that the number of $1$'s in this bit is preserved. Clearly $z \leq w$, and suppose also that $x \leq y$. Sinc...
[ "bitmasks", "greedy", "math" ]
1,700
null
1368
E
Ski Accidents
Arthur owns a ski resort on a mountain. There are $n$ landing spots on the mountain numbered from $1$ to $n$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are \textbf{no directed cycles} formed by the tracks. T...
Let's consider vertices from $1$ to $n$ (that is, in topological order). We divide them into three sets $V_0$, $V_1$, $V_2$: $V_0$ contains all vertices that only have incoming edges from $V_2$; $V_1$ contains all vertices that have an incoming edge from $V_0$, but not from $V_1$; $V_2$ contains all vertices that have ...
[ "constructive algorithms", "graphs", "greedy" ]
2,500
null
1368
F
Lamps on a Circle
This is an interactive problem. John and his imaginary friend play a game. There are $n$ lamps arranged in a circle. Lamps are numbered $1$ through $n$ in clockwise order, that is, lamps $i$ and $i + 1$ are adjacent for any $i = 1, \ldots, n - 1$, and also lamps $n$ and $1$ are adjacent. Initially all lamps are turned...
Let try to come up with an upper bound on $R(n)$. Let $x$ be the number of currently turned on lamps. Consider our last move that resulted in increasing $x$ (after the response was made), and suppose it turned on $k$ lamps. If the opponent could then find a segment of $k$ consecutive lamps and turn them off, the move c...
[ "games", "implementation", "interactive", "math" ]
2,600
null
1368
G
Shifting Dominoes
Bill likes to play with dominoes. He took an $n \times m$ board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and...
Let's think of how a certain cell can be freed up. One way is to just lift the domino covering it from the start. If we didn't do it, then we must move the domino covering the cell, and there is exactly one way of doing so. But at this point the cell we've moved to should have been free. We can follow this chain of eve...
[ "data structures", "geometry", "graphs", "trees" ]
3,200
null
1368
H2
Breadboard Capacity (hard version)
This is a harder version of the problem H with modification queries. Lester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer. The component is built on top of a breadboard — a grid-like base for a microchi...
We are basically asked to find the maximum flow value from red ports to blue ports in the grid network. All edges can be assumed to be bidirectional and have capacity $1$. By Ford-Fulkerson theorem, the maximum flow value is equal to the minimum cut capacity. In our context it is convenient to think about minimum cut a...
[]
3,500
null
1369
A
FashionabLee
Lee is going to fashionably decorate his house for a party, using some regular convex polygons... Lee thinks a regular $n$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $OX$-axis and at least one of its edges is parallel to the $OY$-...
$\mathcal Complete\;\mathcal Proof :$ Proof by contradiction : One can prove that if two edges in a regular polygon make a $x < 180$ degrees angle, then for each edge $a$ there exist two another edges $b$ and $c$ such that $a$ and $b$ make a $x$ degrees angle as well as $a$ and $c$. (proof is left as an exercise for th...
[ "geometry", "math" ]
800
#include <iostream> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; if(n % 4 == 0){ cout << "YES\n"; } else cout << "NO\n"; } }
1369
B
AccurateLee
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters $s_i$ an...
$\mathcal Complete\; \mathcal Proof$ : Realize that the answer is always non-descending, and we can't perform any operations on non-descending strings. First we know that we can't perform any operations on non-descending strings, so the answer to a non-descending string is itself. From now we consider our string $s$ to...
[ "greedy", "implementation", "strings" ]
1,200
#include <iostream> #include <string> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; string s; cin >> s; int sw = 1; for(int i = 1; i < s.size(); i++){ if(s[i] < s[i-1])sw = 0; } if(sw){ ...
1369
C
RationalLee
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $n$ integers, now it's time to distribute them between his friends rationally... Lee has $n$ integers $a_1, a_2, \ldots, a_n$ in his backpack and he has $k$ friends. Lee would like to distribute \textbf{all} integers...
$\mathcal Complete\; \mathcal Proof$ : First if $w_i = 1$ for some $i$, then assign the greatest element to $i$-th friends, it's always better obviously. Sort the elements in non-descending order and sort the friends in non-ascending order of $w_i$. Define $v_i$ the set of indices of elements to give to $i$-th friend. ...
[ "greedy", "math", "sortings", "two pointers" ]
1,400
#include <bits/stdc++.h> #define ll long long #define fr first #define sc second #define int ll using namespace std; const int MN = 2e5+7; vector<int> v[MN]; signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); int t; cin >> t; while(t--){ int n, k; cin >> n >> ...
1369
D
TediousLee
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes... Let's define a Rooted Dead Bush (RDB) of level $n...
$\mathcal Complete \mathcal Proof$ : First realize that a RDB of level $i$ is consisted of a vertex (the root of the RDB of level $i$) connected to the roots of two RDBs of level $i-2$ and a RDB of level $i-1$. Now define $dp_i$ equal to the answer for a RDB of level $i$. Also define $r_i$ equal to $1$ if Lee can achie...
[ "dp", "graphs", "greedy", "math", "trees" ]
1,900
#include <bits/stdc++.h> #define ll long long using namespace std; const int mod = int(1e9+7); const int MN = int(2e6+7); int dp[MN]; signed main(){ ios::sync_with_stdio(false); cin.tie(); cout.tie(); dp[0] = dp[1] = 0; dp[2] = 4; for(int i = 3; i < MN; i++){ long long w = dp[i-1]; ...
1369
E
DeadLee
Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020... There are $n$ different types of food and $m$ Lee's best friends. Lee has $w_i$ plates of the $i$-th type of food and each friend has two different...
$\mathcal Complete\;\mathcal Solution$ : Define $s_i$ equal to the number of friends who likes food $i$. We want to proof that if $\forall 1 \le i \le m \Rightarrow s_i > w_i\, \text{or} \, s_i = 0$ then no answer exist, it can be proved easily by contradiction, just look at the last friend in any suitable permutation,...
[ "data structures", "dfs and similar", "greedy", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> #define ll long long #define fr first #define sc second #define pii pair<int, int> #define all(v) v.begin(), v.end() using namespace std; const int MN = 2e5+7; int x[MN], y[MN], s[MN], w[MN], mark[MN], colmark[MN]; vector<int> v[MN], a; vector<pii> f; priority_queue<pii, vector<pii>, great...
1369
F
BareLee
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has $t$ rounds, each round has two integers $s_i$ and $e_i$ (which are det...
$\mathcal Complete \mathcal Proof$ : Define $w_{s,\,e}$ ($s \le e$) equal to $1$ if Lee can win the game when $s$ is written on the board, and equal to $0$ otherwise, also define $l_{s,\,e}$ the same way. This leads to a simple dp. Forget $l$ for now. Recall that a state ${i,\,j}$ of our dp is a losing state if $w_{i,\...
[ "dfs and similar", "dp", "games" ]
2,700
#include <iostream> #include <vector> #include <string> #define fr first #define sc second #define ll long long #define int ll using namespace std; const int MN = 1e5+7; pair<int, int> c[MN]; int chk(ll s, ll e){ if(e == s)return 0; if(e == s+1)return 1; if(e & 1){ if(s & 1)return 0; ret...
1370
A
Maximum GCD
Let's consider all integers in the range from $1$ to $n$ (inclusive). Among all pairs of \textbf{distinct} integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $\mathrm{gcd}(a, b)$, where $1 \leq a < b \leq n$. The greatest common divisor, ...
Key Idea: Answer for any $n \ge 2$ is equal to $\lfloor{\frac{n}{2}}\rfloor$ . Solution: Let the maximum gcd be equal to $g$. Since the two numbers in a pair are distinct, one of them must be $\gt g$ and both of them must be divisible by $g$. The smallest multiple of $g$, greater than $g$, is $2 \cdot g$. Since each nu...
[ "greedy", "implementation", "math", "number theory" ]
800
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e5 + 5; int32_t main() { IOS; int t; cin >> t; while(t--) { int n; cin >> n; cout << n / 2 << endl; } return 0; }
1370
B
GCD Compression
Ashish has an array $a$ of consisting of $2n$ positive integers. He wants to compress $a$ into an array $b$ of size $n-1$. To do this, he first discards exactly $2$ (any two) elements from $a$. He then performs the following operation until there are no elements left in $a$: - Remove any two elements from $a$ and appe...
Key Idea: It is always possible to form $n-1$ pairs of elements such that their gcd is divisible by $2$. Solution: We can pair up the odd numbers and even numbers separately so that the sum of numbers in each pair is divisible by $2$. Note that we can always form $n - 1$ pairs in the above manner because in the worst c...
[ "constructive algorithms", "math", "number theory" ]
1,100
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n; int a[N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n; vector< int > even, odd; for(int i = 1; i <= 2 * n;...
1370
C
Number Game
Ashishgup and FastestFinger play a game. They start with a number $n$ and play in turns. In each turn, a player can make \textbf{any one} of the following moves: - Divide $n$ by any of its odd divisors greater than $1$. - Subtract $1$ from $n$ if $n$ is greater than $1$. Divisors of a number include the number itsel...
Key Idea: FastestFinger wins for $n=1$ , $n=2^x$ where ($x>1$) and $n= 2 \cdot p$ where $p$ is a prime $\ge 3$ else Ashishgup wins. Solution: Let's analyse the problem for the following $3$ cases: Case $1$: n is oddHere Ashishgup can divide $n$ by itself, since it is odd and hence $\frac{n}{n} = 1$, and FastestFinger l...
[ "games", "math", "number theory" ]
1,400
#include< bits/stdc++.h > using namespace std; const int N = 50000; void player_1(){ cout << "Ashishgup" << endl; } void player_2(){ cout << "FastestFinger" << endl; } bool check_prime(int n){ for(int i = 2; i < min(N, n); i++) if(n % i == 0) return 0; return 1; } int main(){ int tc; cin >> tc; while(...
1370
D
Odd-Even Subsequence
Ashish has an array $a$ of size $n$. A subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements. Consider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between: - The maximum among a...
Key Idea: Binary search over the answer and check if given $x$, it is possible to form a subsequence of length at least $k$ such that either all elements at odd indices or even indices are $\le x$. Solution: Let us binary search over the answer and fix if the answer comes from elements at odd or even indices in the sub...
[ "binary search", "dp", "dsu", "greedy", "implementation" ]
2,000
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 2e5 + 5; int n, k; int a[N]; bool check(int x, int cur) { int ans = 0; for(int i = 1; i <= n; i++) { if(!cur) { ans++; cur ^= 1; } e...
1370
E
Binary Subsequence Rotation
Naman has two binary strings $s$ and $t$ of length $n$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $s$ into $t$ using the following operation as few times as possible. In one operation, he can choose any subsequence of $s$ and rotate it clockwise once. For exam...
Key Idea: Firstly, if $s$ is not an anagram of $t$, it is impossible to convert $s$ to $t$ - since total number of $0$s and $1$s are conserved. However, if they are anagrams, we can always convert $s$ to $t$. We can ignore all the indices where $s_i = t_i$ as it is never optimal to include those indices in a rotation. ...
[ "binary search", "constructive algorithms", "data structures", "greedy" ]
2,100
#include < bits/stdc++.h > using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 1e6 + 5; int n; string s, t; int a[N]; int get(int x) { int cur = 0, mx = 0; for(int i = 1; i <= n; i++) { cur += x * a[i]; mx = max(mx, cur); ...
1370
F2
The Hidden Pair (Hard Version)
\textbf{Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.} \textbf{This is an interactive problem.} You are given a tree consisting of $n$ nodes numbered with integers from $1$ to $n$. Ayush an...
Key Idea: We can find out one of the nodes in the path between the two hidden nodes using a single query. We can then root the tree at this node find one of the hidden nodes using binary search on its distance from the root. Solution: If we query all nodes in the tree, we will receive one of the nodes in the path betwe...
[ "binary search", "dfs and similar", "graphs", "interactive", "shortest paths", "trees" ]
2,700
#include< bits/stdc++.h > using namespace std; const int N = 1001; vector< int > adj[N], depth(N), max_depth(N); int n, root, dist; void dfs(int i, int par){ max_depth[i] = depth[i]; for(int j : adj[i]){ if(j == par) continue; depth[j] = 1 + depth[i], dfs(j, i); max_depth[i] = max(max_depth[i], max_dep...
1371
A
Magical Sticks
A penguin Rocher has $n$ sticks. He has exactly one stick with length $i$ for all $1 \le i \le n$. He can connect some sticks. If he connects two sticks that have lengths $a$ and $b$, he gets one stick with length $a + b$. Two sticks, that were used in the operation disappear from his set and the new connected stick a...
Output $\lceil \frac{n}{2} \rceil$. When $n$ is even, we can create $1+n = 2+(n-1) = 3+(n-2) = ...$ When $n$ is odd, we can create $n = 1+(n-1) = 2+(n-2) = ...$ Initially, there are only $1$ stick which has length $i (1 \le i \le n)$. If we connect $2$ sticks $s_1$ and $s_2$, after that, there is a stick which has a di...
[ "math" ]
800
#include<stdio.h> int main(){ long long n,t; scanf("%lld",&t); while(t>0){ t--; scanf("%lld",&n); if(n%2){printf("%lld\n",(n/2)+1);} else{printf("%lld\n",n/2);} } return 0; }
1371
B
Magical Calendar
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $7$ days! In detail, she can choose any integer $k$ which satisfies $1 \leq k \leq r$, and set $k$ days as the number of days in a week. Alice is going t...
First, let's consider in case of a week has exactly $w$ days. If $w<n$ , the length of painted cells is strictly more than one week. So there are $w$ valid shapes. (The first week contains $1,2,...,w$ days) The shapes have $w$-day width, then if the value of $w$ are different, the shapes are also different. Otherwise $...
[ "math" ]
1,200
#include<stdio.h> int main(){ long long n,l=1,r,t,res; scanf("%lld",&t); while(t>0){ t--; res=0; scanf("%lld%lld",&n,&r); if(n<=l){printf("1\n");continue;} if(n<=r){r=n-1;res=1;} printf("%lld\n",res+((l+r)*(r-l+1))/2); } return 0; }
1371
C
A Cookie for You
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $a$ vanilla cookies and $b$ chocolate cookies for the party. She invited $n$ guests of the first type and $m$ guests of the second type to the party. They will come...
If $m < \min (a,b) , n+m \le a+b$ are satisfied, the answer is "Yes". Otherwise, the answer is "No". Let's proof it. Of course, $n+m \le a+b$ must be satisfied, because violating this inequality means lack of cookies. When a type $2$ guest comes, or when $a=b$, the value of $\min(a,b)$ is decremented by $1$. You need t...
[ "greedy", "implementation", "math" ]
1,300
#include<stdio.h> int main(){ long long t,a,b,n,m,k; scanf("%lld",&t); while(t>0){ t--; scanf("%lld%lld%lld%lld",&a,&b,&n,&m); if(a>b){k=a;a=b;b=k;} if(a<m){printf("No\n");continue;} if(a+b<n+m){printf("No\n");continue;} printf("Yes\n"); } }
1371
D
Grid-00100
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers $n,k$. Construct a grid $A$ with size $n \times n$ \textbf{consisting of integers $0$ and $1$}. The very important condition should be satisfied: the sum of all elements in the grid is exactly $k$. In other words,...
We can construct a grid $A$ which has $f(A)=0$ if $k\%n=0$ , $f(A)=2(1^2+1^2)$ otherwise (the values are smallest almost obviously.) in following method: First, initialize $A_{i,j}=0$ for all $i,j$. Then, change a $0$ into $1$ $k$ times by using following pseudo code: let p=0 , q=0 for i = 1..k Change A[p+1][q+1] into ...
[ "constructive algorithms", "greedy", "implementation" ]
1,600
#include<stdio.h> int main(){ int n,k,t,i,j,p,q; char res[305][305]; scanf("%d",&t); while(t>0){ t--; scanf("%d%d",&n,&k); if(k%n==0){printf("0\n");} else{printf("2\n");} for(i=0;i<n;i++){ for(j=0;j<n;j++){ res[i][j]='0'; } res[i][n]=0; } p=0;q=0; whil...
1371
E1
Asterism (Easy Version)
\textbf{This is the easy version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.} First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originall...
Let's define $m = max(a_1,a_2,...,a_n)$. Yuzu should have at least $m-n+1$ candies initially to win all duels, then $f(x)=0$ for $x < m-n+1$. This is divisible by $p$. And if Yuzu have equal or more than $m$ candies initially, any permutation will be valid, then $f(x)=n!$ for $x \ge m$. This is divisible by $p$ , too. ...
[ "binary search", "brute force", "combinatorics", "math", "number theory", "sortings" ]
1,900
#include<stdio.h> int max(int a,int b){if(a>b){return a;}return b;} int main(){ int n,p; int st,fi; int a[131072],bk[262144]={0},bas=0,i,j; int res[131072],rc=0; scanf("%d%d",&n,&p); for(i=0;i<n;i++){ scanf("%d",&a[i]); bas=max(a[i],bas); } for(i=0;i<n;i++){bk[max(0,a[i]-bas+n)]++;} for(i=...
1371
E2
Asterism (Hard Version)
\textbf{This is the hard version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.} First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originall...
There are two different solutions to solve this problem. Solution 1: First, find the minimum $s$ which has $f(s) > 0$. You can use binary search or cumulative sum for it. Now, we can say the answers form a segment $[s,t]$ (or there are no answers). Find $t$ and proof this. Let's define $b_i$ as the number of the enemie...
[ "binary search", "combinatorics", "dp", "math", "number theory", "sortings" ]
2,300
#include<stdio.h> int max(int a,int b){if(a>b){return a;}return b;} int modp(int x,int p){ if(x>=0){return x%p;} x*=-1;x%=p; return (p-x)%p; } int main(){ int n,p; int st,fi; int a[131072],bk[262144]={0},bas=0,i; int fl[131072]={0}; int res[131072],rc=0; scanf("%d%d",&n,&p); for(i=0;i<n;i++)...
1371
F
Raging Thunder
You are a warrior fighting against the machine god Thor. Thor challenge you to solve the following problem: There are $n$ conveyors arranged in a line numbered with integers from $1$ to $n$ from left to right. Each conveyor has a symbol "<" or ">". The initial state of the conveyor $i$ is equal to the $i$-th characte...
First, observe where the balls fall. When there is a ">>>...>><<...<<<" structure, the balls on there will fall into one hole. So, our goal is handling this structure. Each query is asking about a segment. Then, to solve this problem, we can use segment tree. Each node maintains following: Prefix structure Suffix struc...
[ "data structures", "divide and conquer", "implementation" ]
2,800
#include<stdio.h> #include<stdbool.h> #define ssize 1048576 int max(int a,int b){if(a>b){return a;}return b;} typedef struct{ //str[0] = prefix //str[1] = suffix //str[][0] = >>>> //str[][1] = <<<< int str[2][2]; int res; int dvd; }stnode; stnode stree[2*ssize][2],vd; int fl[2*ssize]; void stnpr(s...
1372
A
Omkar and Completion
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array $a$ of length $n$ is called \textbf{complete} if all elements are positive and don't exceed $1000$, and for all indices $x$,$y$,$z$ ($1 \leq x,y,z \leq n$), $a_{x}+a_{y} \neq a_{z}$ (not necessarily dist...
Notice that since all elements must be positive, $k \neq 2k$. The most simple construction of this problem is to simply make all elements equal to $1$.
[ "constructive algorithms", "implementation" ]
800
import java.util.* fun main() { val jin = Scanner(System.`in`) for (c in 1..jin.nextInt()) { val n = jin.nextInt() for (j in 1..n) { print("1 ") } println() } }
1372
B
Omkar and Last Class of Math
In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$. Omkar, having a laudably curious mind, immediately thought of a problem involving the $LCM$ operation: given an integer $n$, find positive intege...
Short Solution: The two integers are $k$ and $n-k$, where $k$ is the largest proper factor of $n$. Proof: Let the two integers be $k$ and $n-k$. Assume WLOG that $k \leq n-k$. Notice that this implies that $n - k \geq \frac n 2$. We first claim that $LCM(k, n-k) = n-k < n$ if $k \mid n$, and we prove this as follows: i...
[ "greedy", "math", "number theory" ]
1,300
fun main() { for (c in 1..readLine()!!.toInt()) { val n = readLine()!!.toInt() var p = 0 for (m in 2..100000) { if (n % m == 0) { p = m break } } if (p == 0) { p = n } println("${n / p} ${n - ...
1372
C
Omkar and Baseball
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when...
You need at most $2$ special exchanges to sort the permutation. Obviously, $0$ special exchanges are needed if the array is already sorted. Let's look into cases in which you need $1$ special exchange to sort the array. Refer to i as a matching index if $a_i = i$. If there are no matching indices, then you can just use...
[ "constructive algorithms", "math" ]
1,500
import java.io.BufferedReader import java.io.InputStreamReader fun main() { val jin = BufferedReader(InputStreamReader(System.`in`)) for (c in 1..jin.readLine().toInt()) { val n = jin.readLine().toInt() val scores = jin.readLine().split(" ").map { it.toInt() - 1 } if ((1 until n).all {...
1372
D
Omkar and Circle
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem! You are given $n$ nonnegative integers $a_1, a_2, \dots, a_n$ arranged in a circle, where $n$ must be odd (ie. $n-1$ is divisible by $2$). Formally, for all $i$ such that $2 \leq i \leq n$, the ele...
First note that any possible circular value consists of the sum of some $(n+1)/2$ elements. Now let's think about how these $(n+1)/2$ values would look like in the circle. Let's consider any one move on index $i$. $a_i$ will be replaced with the sum of $a_{i-1}$ and $a_{i+1}$ (wrap around to index $1$ or $n$ if needed)...
[ "brute force", "dp", "games", "greedy" ]
2,100
import kotlin.math.max fun main() { val n = readLine()!!.toInt() val m = (n + 1) / 2 val array = readLine()!!.split(" ").map { it.toLong() } var curr = 0L for (j in 0 until m) { curr += array[2 * j] } var answer = curr for (j in 0..n - 2) { curr -= array[(2 * j) % n] ...
1372
E
Omkar and Last Floor
Omkar is building a house. He wants to decide how to make the floor plan for the last floor. Omkar's floor starts out as $n$ rows of $m$ zeros ($1 \le n,m \le 100$). Every row is divided into intervals such that every $0$ in the row is in exactly $1$ interval. For every interval for every row, Omkar can change exactly...
Let $dp_{l,r}$ be the answer for the columns from $l$ to $r$. To solve $dp_{l,r}$, it is optimal to always fill some column within $l$ to $r$ to the max. Let's call this column $k$. The transition is thus $dp_{l,k-1} + ($ number of intervals that are fully within $l$ and $r$ and include $k)^2 + dp_{k+1,r}$. For every $...
[ "dp", "greedy", "two pointers" ]
2,900
import java.io.BufferedReader import java.io.InputStreamReader import kotlin.math.max fun main() { val jin = BufferedReader(InputStreamReader(System.`in`)) val (n, m) = jin.readLine().split(" ").map { it.toInt() } val left = Array(n + 1) { IntArray(m + 1) } val right = Array(n + 1) { IntArray(m + 1) }...
1372
F
Omkar and Modes
Ray lost his array and needs to find it by asking Omkar. Omkar is willing to disclose that the array has the following qualities: - The array has $n$ ($1 \le n \le 2 \cdot 10^5$) elements. - Every element in the array $a_i$ is an integer in the range $1 \le a_i \le 10^9.$ - The array is sorted in nondecreasing order. ...
For both solutions, we must first make the critical observation that because the array is sorted, all occurrences of a value $x$ occur as a single contiguous block. Solution 1 We will define a recursive function $determine(l, r)$ which will use queries to determine the array. We will also store an auxiliary list of pre...
[ "binary search", "divide and conquer", "interactive" ]
2,700
import kotlin.math.max import kotlin.math.min fun main() { val n = readLine()!!.toInt() val answer = IntArray(n + 1) val occurrences = mutableMapOf<Int, MutableList<Int>>() fun query(l: Int, r: Int): Pair<Int, Int> { println("? $l $r") val line = readLine()!!.split(" ") return ...
1373
A
Donut Shops
There are two rival donut shops. The first shop sells donuts at retail: each donut costs $a$ dollars. The second shop sells donuts only in bulk: box of $b$ donuts costs $c$ dollars. So if you want to buy $x$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts ...
At first notice that if there exists a value for the second shop, then the value divisible by $b$ also exists. For any $x$ you can round it up to the nearest multiple of $b$. That won't change the price for the second shop and only increase the price for the first shop. You can also guess that if there exists a value f...
[ "greedy", "implementation", "math" ]
1,000
for tc in range(int(input())): a, b, c = map(int, input().split()) print(1 if a < c else -1, end=" ") print(b if c < a * b else -1)
1373
B
01 Game
Alica and Bob are playing a game. Initially they have a binary string $s$ consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two \textbf{different adj...
If there is at least one character 0 and at least one character 1, then current player can always make a move. After the move the number of character 0 decreases by one, and the number of character 1 decreases by one too. So the number of moves is always $min(c0, c1)$, where $c0$ is the number of characters 0 in string...
[ "games" ]
900
for _ in range(int(input())): s = input() print('DA' if min(s.count('0'), s.count('1')) % 2 == 1 else 'NET')
1373
C
Pluses and Minuses
You are given a string $s$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: \begin{verbatim} res = 0 for init = 0 to inf cur = init ok = true for i = 1 to |s| res = res + 1 if s[i] == '+' cur = cur + 1 else cur = cur - 1 if cur...
Let's replace all + with 1, and all - with -1. After that let's create a preffix-sum array $p$ ($p_i = \sum\limits_{j=1}^{i} s_j$). Also lets create array $f$ such that $f_i$ is equal minimum index $j$ such that $p_j = -i$ (if there is no such index $p_i = -1$). Let's consider the first iteration of loop $for ~ init ~ ...
[ "math" ]
1,300
for _ in range(int(input())): s = input() cur, mn, res = 0, 0, len(s) for i in range(len(s)): cur += 1 if s[i] == '+' else -1 if cur < mn: mn = cur res += i + 1 print(res)
1373
D
Maximum Sum on Even Positions
You are given an array $a$ consisting of $n$ integers. Indices of the array start from zero (i. e. the first element is $a_0$, the second one is $a_1$, and so on). You can reverse \textbf{at most one} subarray (continuous subsegment) of this array. Recall that the subarray of $a$ with borders $l$ and $r$ is $a[l; r] =...
Firstly, we can notice that the reverse of of odd length subarray does nothing because it doesn't change parities of indices of affected elements. Secondly, we can consider the reverse of the subarray of length $2x$ as $x$ reverses of subarrays of length $2$ (i.e. it doesn't matter for us how exactly the subarray will ...
[ "divide and conquer", "dp", "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto &it : a) cin >> it; vector<vector<long long>> dp(n + 1, vector<long long>...
1373
E
Sum of Digits
Let $f(x)$ be the sum of digits of a decimal number $x$. Find the smallest non-negative integer $x$ such that $f(x) + f(x + 1) + \dots + f(x + k) = n$.
There are many ways to solve this problem (including precalculating all answers), but the model solution is based on the following: In most cases, $f(x + 1) = f(x) + 1$. It is not true only when the last digit of $x$ is $9$ (and if we know the number of $9$-digits at the end of $x$, we can easily derive the formula for...
[ "brute force", "constructive algorithms", "dp", "greedy" ]
2,200
def get(s): return str(s % 9) + '9' * (s // 9) for tc in range(int(input())): n, k = map(int, input().split()) k += 1 bst = 10**100 for d in range(10): ends = 0 for i in range(k): ends += (d + i) % 10 if ends > n: continue if d + k > 10: for cnt in range(12): s = 9 * cnt * (10 - d) if s >...
1373
F
Network Coverage
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and $n$ cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the $i$-th city contains $a_i$ households that requir...
There are plenty of different solutions to this problem. Here is one that doesn't use Hall's theorem. Let's look at pair $(a_i, b_i)$ as fuction $f_i(in) = out$: how many connections $out$ will be left for the $(i + 1)$-th city if we take $in$ connections from the $(i - 1)$-th station. This function has the following s...
[ "binary search", "constructive algorithms", "data structures", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; typedef long long li; const int N = 1000 * 1000 + 13; int n; int a[N], b[N]; void solve() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n; ++i) scanf("%d", &b[i]); li need = 0, add = 0, extra = 2e9; for (int i = n - 1; i...
1373
G
Pawns
You are given a chessboard consisting of $n$ rows and $n$ columns. Rows are numbered from bottom to top from $1$ to $n$. Columns are numbered from left to right from $1$ to $n$. The cell at the intersection of the $x$-th column and the $y$-th row is denoted as $(x, y)$. Furthermore, the $k$-th column is a special colum...
For each pawn with initial position $(x, y)$ there exists a minimum index of row $i$ such that the pawn can reach the cell $(k, i)$, but cannot reach the cell $(k, i - 1)$. It's easy to see that $i = |k - x| + y$. In the resulting configuration, this pawn can occupy the cell $(k, i)$, $(k, i + 1)$, $(k, i + 2)$ or any ...
[ "data structures", "divide and conquer", "greedy" ]
2,600
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; int n, k; int m; int t[8 * N]; int add[8 * N]; int cnt[2 * N]; void push(int v, int l, int r) { if (r - l != 1 && add[v] != 0) { t[v * 2 + 1] += add[v]; t[v * 2 + 2] += add[v]; add[v * 2 + 1] += add[v]; add...
1374
A
Required Remainder
You are given three integers $x, y$ and $n$. Your task is to find the \textbf{maximum} integer $k$ such that $0 \le k \le n$ that $k \bmod x = y$, where $\bmod$ is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given $x, y$ and $n$ you need to find the maximum...
There are two cases in this problem. If we try to maximize the answer, we need to consider only two integers: $n - n \bmod x + y$ and $n - n \bmod x - (x - y)$. Of course, the first one is better (we get rid of the existing remainder and trying to add $y$ to this number). If it's too big, then we can and need to take t...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int x, y, n; cin >> x >> y >> n; if (n - n % x + y <= n) { cout << n - n % x + y << endl; } else { cout << n - n %...
1374
B
Multiply by 2, divide by 6
You are given an integer $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder). Your task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that. You have to answer $t$ independent test cases...
If the number consists of other primes than $2$ and $3$ then the answer is -1. Otherwise, let $cnt_2$ be the number of twos in the factorization of $n$ and $cnt_3$ be the number of threes in the factorization of $n$. If $cnt_2 > cnt_3$ then the answer is -1 because we can't get rid of all twos. Otherwise, the answer is...
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; int cnt2 = 0, cnt3 = 0; while (n % 2 == 0) { n /= 2; ++cnt2; } while (n % 3 == 0) { n /= 3...
1374
C
Move Brackets
You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'. In one move, you can choose \textbf{exactly one bracket} and move it to the beginning of the string or to the end of the string...
Let's go from left to right over characters of $s$ maintaining the current bracket balance (for the position $i$ the balance is the number of opening brackets on the prefix till the $i$-th character minus the number of closing brackets on the same prefix). If the current balance becomes less than zero, then let's just ...
[ "greedy", "strings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; string s; cin >> n >> s; int ans = 0; int bal = 0; for (int i = 0; i < n; ++i) { if (s[i] == '(') ++bal; ...
1374
D
Zero Remainder Array
You are given an array $a$ consisting of $n$ positive integers. Initially, you have an integer $x = 0$. During one move, you can do one of the following two operations: - Choose \textbf{exactly one} $i$ from $1$ to $n$ and increase $a_i$ by $x$ ($a_i := a_i + x$), then increase $x$ by $1$ ($x := x + 1$). - Just incre...
Firstly, we can understand that during each full cycle of $x$ from $0$ to $k-1$ we can fix each remainder only once. Notice that when we add some $x$ then we fix the remainder $k-x$ (and we don't need to fix elements which are already divisible by $k$). So, let $cnt_i$ be the number of such elements for which the condi...
[ "math", "sortings", "two pointers" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (auto &it : a) cin >> it; map<int, int> cnt; int mx = 0; for (auto &...
1374
E1
Reading Books (easy version)
\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully}. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and ...
Let's divide all books into four groups: 00 - both Alice and Bob doesn't like these books; 01 - only Alice likes these books; 10 - only Bob likes these books; 11 - both ALice and Bob like these books. Obviously, 00-group is useless now. So, how to solve the problem? Let's iterate over the number of books we take from 1...
[ "data structures", "greedy", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; const int INF = 2e9 + 1; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> times[4]; vector<int> sums[4]; for (int i = 0; i < n; ++i) { int t, a, b; cin >> t >> a >>...
1374
E2
Reading Books (hard version)
\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully}. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read \textbf{exactly} $m$ books before all entertainments. Alic...
A little explanation: this editorial will be based on the easy version editorial so I'll use some definitions from it. Here we go, the most beautiful problem of the contest is waiting us. Well, the key idea of this problem almost the same with the easy version idea. Let's iterate over the number of elements in 11-group...
[ "data structures", "greedy", "implementation", "sortings", "ternary search", "two pointers" ]
2,500
#include <bits/stdc++.h> using namespace std; const int INF = 2e9 + 1; #define size(a) int((a).size()) void updateSt(set<pair<int, int>> &st, set<pair<int, int>> &fr, int &sum, int need) { need = max(need, 0); while (true) { bool useful = false; while (size(st) > need) { sum -= st.rbegin()->first; fr.in...
1374
F
Cyclic Shifts Sorting
You are given an array $a$ consisting of $n$ integers. In one move, you can choose some index $i$ ($1 \le i \le n - 2$) and shift the segment $[a_i, a_{i + 1}, a_{i + 2}]$ cyclically to the right (i.e. replace the segment $[a_i, a_{i + 1}, a_{i + 2}]$ with $[a_{i + 2}, a_i, a_{i + 1}]$). Your task is to sort the init...
Firstly, let's solve the easier version of the problem. Assume we are given a permutation, not an array. Notice that the given operation applied to some segment of the permutation cannot change the parity of number of inversions (the number of inversions is the number of such pairs of indices $(i, j)$ that $j > i$ and ...
[ "brute force", "constructive algorithms", "implementation", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif auto make = [](vector<int> &a, int pos) { swap(a[pos + 1], a[pos + 2]); swap(a[pos], a[pos + 1]); }; int t; cin >> t; while (t--) { int n; cin >> n;...
1375
A
Sign Flipping
You are given $n$ integers $a_1, a_2, \dots, a_n$, where $n$ \textbf{is odd}. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: - At least $\frac{n - 1}{2}$ of the adjacent differences $a_{i + 1} - a_i$ for $i = 1,...
Notice that $a_{i + 1} - a_i \ge 0$ is equivalent to $a_{i + 1} \ge a_i$. Similarly $a_{i + 1} - a_i \le 0$ is equivalent to $a_{i + 1} \le a_i$. Flip the signs in such a way that $a_i \ge 0$ for odd $i$, while $a_i \le 0$ for even $i$. Then $a_{i + 1} \ge 0 \ge a_i$, and thus $a_{i + 1} \ge a_i$, for $i = 2, 4, \dots,...
[ "constructive algorithms", "math" ]
1,100
null
1375
B
Neighbor Grid
You are given a grid with $n$ rows and $m$ columns, where each cell has a non-negative integer written on it. We say the grid is \textbf{good} if for each cell the following condition holds: if it has a number $k > 0$ written on it, then exactly $k$ of its neighboring cells have a number greater than $0$ written on the...
For every cell $(i, j)$ let's denote by $n_{i, j}$ the number of neighbors it has (either zero or non-zero, it doesn't matter). Then for each cell, it must hold that $a_{i, j} \le n_{i, j}$, otherwise, no solution exists because it is impossible to decrease $a_{i, j}$. Let's now suppose that $a_{i, j} \le n_{i, j}$ for...
[ "constructive algorithms", "greedy" ]
1,200
null
1375
C
Element Extermination
You are given an array $a$ of length $n$, which initially is a \textbf{permutation} of numbers from $1$ to $n$. In one operation, you can choose an index $i$ ($1 \leq i < n$) such that $a_i < a_{i + 1}$, and remove either $a_i$ or $a_{i + 1}$ from the array (after the removal, the remaining parts are concatenated). Fo...
The answer is YES iff $a_1 < a_n$. Let's find out why. When $a_1 < a_n$, we can repeatedly use this algorithm while the permutation contains more than one element: Find the smallest index $r$ such that $a_1 < a_r$. Choose $a_r$ and the element comes right before $a_r$ and delete the element before $a_r$. Repeat step 2 ...
[ "constructive algorithms", "data structures", "greedy" ]
1,400
null
1375
D
Replace by MEX
You're given an array of $n$ integers between $0$ and $n$ inclusive. In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation). For example, if the current array is $[0, 2, 2, 1, 4]$, you can choose the second element and re...
(We consider the array $0$-indexed) Instead of trying to reach any non-decreasing array, we will try to reach precisely $[0, 1, \ldots, n-1]$. Let's call any index $i$ such that $a_i \neq i$ an unfixed point. We will repeat the following procedure in order to remove all unfixed points: If $\text{mex} = n$, we apply an ...
[ "brute force", "constructive algorithms", "sortings" ]
1,900
null
1375
E
Inversion SwapSort
Madeline has an array $a$ of $n$ integers. A pair $(u, v)$ of integers forms an inversion in $a$ if: - $1 \le u < v \le n$. - $a_u > a_v$. Madeline recently found a magical paper, which allows her to write two indices $u$ and $v$ and swap the values $a_u$ and $a_v$. Being bored, she decided to write a list of pairs $...
We can prove that the answer always exists. Let's first solve the problem for a permutation of length $n$. Let's define $pos_i (1 \le i \le n)$ as the index of $i$ in the permutation. First we are going to use all the pairs whose second element is $n$. Let's define the resulting permutation that we get, after using all...
[ "constructive algorithms", "greedy", "sortings" ]
2,500
null
1375
F
Integer Game
\textbf{This is an interactive problem.} Anton and Harris are playing a game to decide which of them is the king of problemsetting. There are three piles of stones, initially containing $a$, $b$, and $c$ stones, where $a$, $b$, and $c$ are \textbf{distinct} positive integers. On each turn of the game, the following s...
Let's prove that the first player can always win in at most three turns. Assume that the initial numbers of stones are $p < q < r$. On the first turn, choose $y = 2r - p - q$. We then have three cases: Case 1. $y$ is added to $p$. The piles now have $2r - q$, $q$ and $r$ stones. Now choose $y = r - q$. Since the pile w...
[ "constructive algorithms", "games", "interactive", "math" ]
2,600
null
1375
G
Tree Modification
You are given a tree with $n$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation: - Choose three vertices $a$, $b$, and $c$ such that $b$ is adjacent to both $a$ and $c$. - For every vertex $d$ \textbf{other than $b$} that is adjacent to $a$, remove the edge connec...
The solution is based on the following observation: Every tree is a bipartite graph, i. e. its vertices can be colored black or white in such a way that every white vertex is adjacent only to black vertices and vice versa. Notice that a tree is a star if and only if one of the colors appears exactly once. Let's fix a b...
[ "brute force", "constructive algorithms", "dfs and similar", "graph matchings", "graphs", "trees" ]
2,800
null
1375
H
Set Merging
You are given a permutation $a_1, a_2, \dots, a_n$ of numbers from $1$ to $n$. Also, you have $n$ sets $S_1,S_2,\dots, S_n$, where $S_i=\{a_i\}$. Lastly, you have a variable $cnt$, representing the current number of sets. Initially, $cnt = n$. We define two kinds of functions on sets: $f(S)=\min\limits_{u\in S} u$; ...
First, two sets $a$ and $b$ can be merged if and only if the range of elements in $a$ do not intersect with the range of elements in $b$. It is obvious because if they intersect, neither $g(a)<f(b)$ nor $g(b)<f(a)$ are satisfied. If they do not intersect, there must be one of them satisfied. Notice that $2\times n\sqrt...
[ "constructive algorithms", "divide and conquer" ]
3,300
null
1375
I
Cubic Lattice
A cubic lattice $L$ in $3$-dimensional euclidean space is a set of points defined in the following way: $$L=\{u \cdot \vec r_1 + v \cdot \vec r_2 + w \cdot \vec r_3\}_{u, v, w \in \mathbb Z}$$ Where $\vec r_1, \vec r_2, \vec r_3 \in \mathbb{Z}^3$ are some integer vectors such that: - $\vec r_1$, $\vec r_2$ and $\vec r...
$2$-dimensional version of this problem appeared as problem K in Makoto Soejima Contest 4 from Petrozavodsk Winter Training Camp 2016 (Also known as GP of Asia in OpenCup XVI). Solution for this case is based on the fact that the whole lattice equation may be represented as the product of two Gaussian integers $a_k = \...
[ "geometry", "math", "matrices", "number theory" ]
3,500
null
1379
A
Acacius and String
Acacius is studying strings theory. Today he came with the following problem. You are given a string $s$ of length $n$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a res...
At first, we will check if some string of length $n$ contains exactly one occurrence of "abacaba". Lemma 1. This check can be done in $O(n)$ time. Proof. We can try all the possible positions $i$ of a string $s$ and check whether $i$ is a starting position for a substring "abacaba". This check can be performed in a $O(...
[ "brute force", "implementation", "strings" ]
1,500
#include <bits/stdc++.h> using ll = long long; using ld = long double; using ull = unsigned long long; using namespace std; const string T = "abacaba"; int count(const string& s) { int cnt = 0; for (int i = 0; i < (int)s.size(); ++i) { if (s.substr(i, T.size()) == T) { ++cnt; } ...
1379
B
Dubious Cyrpto
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $n$, he encrypts it in the following way: he picks three integers $a$, $b$ and $c$ such that $l \leq a,b,c \leq r$, and then he computes the encrypted value $m = n \cdot a + b - c$. Unf...
The task is to solve equation $n\cdot a + b - c = m$ in integers, where $n$ - is some natural number, and $a, b, c \in [l; r]$. Note that the expression $b - c$ can take any value from $[l-r; r-l]$ and only these values. Indeed, if $0 \leq x \leq r-l$, then if we denote $b = x + l$, $c = l$, we get $b - c = x$. A simil...
[ "binary search", "brute force", "math", "number theory" ]
1,500
null
1379
C
Choosing flowers
Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her \textbf{exactly} $n$ flowers. Vladimir went to a flower shop, and he was amazed to see that there are $m$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to ch...
Let's look at sorts, for which there is more than one flower in the bouquet. We can prove, that there can be only one such sort. Let's assume that there are sorts $x$ and $y$ with $b_x \ge b_y$, such that for both sorts there are at least 2 flowers. Let's exclude flower of sort $y$ from bouquet and add flower of sort $...
[ "binary search", "brute force", "data structures", "dfs and similar", "dp", "greedy", "sortings", "two pointers" ]
2,000
null
1379
D
New Passenger Trams
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of $h$ hours, and each hour consists of $m$ minutes, where $m$ is an even number. Currently, there are $n$ freight trains, and they depart every day at the same time: $i$-th train departs at $h_i$ hours and $m_i$ minut...
Let's look what happens if we fix $t$ for answer. Start time leads to canceling every train, which has $m_i$ in one of ranges $[t - k + 1, t - 1],\ [t + \frac{m}{2} - k + 1, t + \frac{m}{2} - 1]$. Some borders may be either negative or greater than $m$, but values must be count modulo $m$. We may imagine them as segmen...
[ "binary search", "brute force", "data structures", "sortings", "two pointers" ]
2,300
null
1379
E
Inverse Genealogy
Ivan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in...
Let's rephrase the statement. Critical node - a non-leaf node with subtrees, where one $2$ or more times smaller than another. We need to find an example of the binary tree with $n$ nodes there $k$ of them are critical. First of all, let's count number of nodes if we know that there $m$ leafs. Because of the fact, that...
[ "constructive algorithms", "divide and conquer", "dp", "math", "trees" ]
2,800
null
1379
F1
Chess Strikes Back (easy version)
\textbf{Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.} Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The f...
Let's divide the grid into $nm$ squares of size $2 \times 2$. Each square contains exactly two white cells. So, we should put exactly one king into one square. Let's mark a square L, if its left upper cell is banned and R if its right down cell is banned. Square can be L and R at the same time. If there exists some L-s...
[ "binary search", "data structures" ]
2,700
null
1379
F2
Chess Strikes Back (hard version)
\textbf{Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.} Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The f...
Let's divide the grid into $nm$ squares of size $2 \times 2$. Each square contains exactly two white cells. So, we should put exactly one king into one square. Let's mark a square L, if its left upper cell is banned and R if its right down cell is banned. Square can be L and R at the same time. If there exists some L-s...
[ "data structures", "divide and conquer" ]
2,800
null
1380
A
Three Indices
You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once. Find three indices $i$, $j$ and $k$ such that: - $1 \le i < j < k \le n$; - $p_i < p_j$ and $p_j > p_k$. Or say that there are no such indices.
A solution in $O(n^2)$: iterate on $j$, check that there exists an element lower than $a_j$ to the left of it, and check that there exists an element lower than $a_j$ to the right of it. Can be optimized to $O(n)$ with prefix/suffix minima. A solution in $O(n)$: note that if there is some answer, we can find an index $...
[ "brute force", "data structures" ]
900
#include <bits/stdc++.h> using namespace std; const int N = 1000; int n; int a[N]; void solve() { cin >> n; for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 1; i < n - 1; ++i) { if (a[i] > a[i - 1] && a[i] > a[i + 1]) { cout << "YES" << endl; cout << i << ' ' << i + 1 << ' ' << i + 2 << endl; r...
1380
B
Universal Solution
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $s = s_1 s_2 \dots s_{n}$ of length $n$ where each letter is either R, S or P. While initializing, the bot is choosing a starting index $pos$ ($1 \le pos \le n$), and then it can ...
Let's look at the contribution of each choice $c_i$ to the total number of wins $win(1) + win(2) + \dots + win(n)$ (we can look at "total" instead of "average", since "average" is equal to "total" divided by $n$). For example, let's look at the first choice $c_1$: in $win(1)$ we compare $c_1$ with $s_1$, in $win(2)$ - ...
[ "greedy" ]
1,400
fun main() { val winBy = mapOf('R' to 'P', 'S' to 'R', 'P' to 'S') repeat(readLine()!!.toInt()) { val s = readLine()!! val maxCnt = s.groupingBy { it }.eachCount().maxBy { it.value }!!.key println("${winBy[maxCnt]}".repeat(s.length)) } }
1380
C
Create The Teams
There are $n$ programmers that you want to split into several non-empty teams. The skill of the $i$-th programmer is $a_i$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the...
At first, notice that if only $k < n$ programmers are taken, then the same or even better answer can be achieved if $k$ strongest programmers are taken. Now let's sort the programmers in a non-increasing order and choose some assignment into the teams. For each team only the rightmost taken programmer of that team matt...
[ "brute force", "dp", "greedy", "implementation", "sortings" ]
1,400
for _ in range(int(input())): n, x = map(int, input().split()) a = sorted(list(map(int, input().split())), reverse=True) res, cur = 0, 1 for s in a: if s * cur >= x: res += 1 cur = 0 cur += 1 print(res)
1380
D
Berserk And Fireball
There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct. You have two types of spells which you may cast: - Fireball: you spend $x$ mana and destroy \textbf{exactly} $k$ consecutive warriors; - Berserk: you spend $y$ mana, choose two consecutive warriors, and the wa...
The first thing we need to do is to find the occurrences of $b_i$ in the sequence $[a_1, a_2, \dots, a_n]$ - these are the monsters that have to remain. Since both spells (Fireball and Berserk) affect consecutive monsters, we should treat each subsegment of monsters we have to delete separately. Consider a segment with...
[ "constructive algorithms", "greedy", "implementation", "math", "two pointers" ]
2,000
#include <bits/stdc++.h> using namespace std; const int N = int(2e5) + 9; int n, m; long long x, k, y; int a[N]; int b[N]; bool upd(int l, int r, long long &res) { if (l > r) return true; bool canDel = false; int mx = *max_element(a + l, a + r + 1); int len = r - l + 1; if (l - 1 >= 0 && a[l - 1...