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
1534
D
Lost Tree
This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of $n$ nodes! The nodes of the tree are numbered from $1$ to $n$. The game master only allows him to ask one type of question: - Little Dormi picks a node $r$ ($1 \le r \le ...
If we had $n$ queries, solving this problem would be easy as we could just query every single node and add edges when $d_i=1$. However, notice that as long as we make a query for at least $1$ endpoint of every edge, we will be able to find all the edges using this method. Observe that a tree is bipartite, so we would b...
[ "constructive algorithms", "interactive", "trees" ]
1,800
#include "bits/stdc++.h" #include <random> using namespace std; // Defines #define fs first #define sn second #define pb push_back #define eb emplace_back #define mpr make_pair #define mtp make_tuple #define all(x) (x).begin(), (x).end() // Basic type definitions using ll = long long; using ull = unsigned long long; ...
1534
E
Lost Array
This is an interactive problem. Note: the XOR-sum of an array $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) is defined as $a_1 \oplus a_2 \oplus \ldots \oplus a_n$, where $\oplus$ denotes the bitwise XOR operation. Little Dormi received an array of $n$ integers $a_1, a_2, \ldots, a_n$ for Christmas. However, while p...
"tl;dr it's pure BFS" The only information we can obtain from a query is the XOR sum of the subset we queried. We can also try and obtain some frequency information about the bits (whether the number of bits at position $i$ is odd for every bit $i$), but trying to combine frequency information is ultimately analogous t...
[ "graphs", "greedy", "interactive", "shortest paths" ]
2,300
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll INF = 0x3f3f3f3f; const int MN = 2001; int N, K, dis[MN], par[MN]; int main() { cin >> N >> K; // BFS memset(dis, 0x3f, sizeof dis); queue<int> q; dis[0] = 0; par[0] = -1; q.push(0); while (!q.empty()) { ...
1534
F1
Falling Sand (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is the constraints on $a_i$. You can make hacks only if all versions of the problem are solved.} Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board wit...
Let's model the grid as a directed graph. Take every block of sand in the puzzle as a node. Now add an edge from a node $A$ to a node $B$ if: $B$ is the first block of sand below $A$. $B$ is the first block of sand next to or below $A$ and on the first column to the left of $A$. $B$ is the first block of sand next to o...
[ "dfs and similar", "graphs", "greedy" ]
2,500
#include "bits/stdc++.h" using namespace std; using ll = long long; using pii = pair<int,int>; using pll = pair<ll,ll>; template<typename T> int sz(const T &a){return int(a.size());} const int MN=4e5+1; vector<vector<char>> arr; vector<vector<int>> ind; int am[MN]; vector<int> adj[MN]; int nodecnt=0; int id[MN],low[MN]...
1534
F2
Falling Sand (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is the constraints on $a_i$. You can make hacks only if all versions of the problem are solved.} Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board wit...
Note: If you have not already read the editorial for $F1$, please do so, as this editorial continues on from where that editorial left off. Where $F2$ differs from $F1$ is that not all blocks of sand have to fall, instead only some subset of them within each column need to fall. Let's go back to the Directed Acyclic Gr...
[ "dfs and similar", "dp", "graphs", "greedy" ]
3,000
#include "bits/stdc++.h" using namespace std; using ll = long long; using pii = pair<int,int>; using pll = pair<ll,ll>; template<typename T> int sz(const T &a){return int(a.size());} const int MN=4e5+1; vector<vector<char>> arr; vector<vector<int>> ind; int am[MN]; vector<int> adj[MN]; int nodecnt=0; int id[MN],low[MN]...
1534
G
A New Beginning
Annie has gotten bored of winning every coding contest and farming unlimited rating. Today, she is going to farm potatoes instead. Annie's garden is an infinite 2D plane. She has $n$ potatoes to plant, and the $i$-th potato must be planted at $(x_i,y_i)$. Starting at the point $(0, 0)$, Annie begins walking, in one st...
Observe that for any point $(x,y)$ and some path $A$, the minimum distance from $A$ to $(x,y)$ will occur on the intersection of $A$ and the antidiagonal of $(x,y)$. Here the antidiagonal is defined as a line $y=-x+c$. Proof: Assume $(a,b)$ is the intersection of $A$ and the antidiagonal of $(x,y)$. If $(a,b) = (x,y)$,...
[ "data structures", "dp", "geometry", "sortings" ]
3,300
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/priority_queue.hpp> using namespace std; using namespace __gnu_pbds; #define foru(i,a,b) for(int i=(a);i<(b);i++) #define ford(i,a,b) for(int i=(a);i>=(b);i--) #define fori(a,b) foru(i,a,b) #define...
1534
H
Lost Nodes
This is an interactive problem. As he qualified for IOI this year, Little Ericyi was given a gift from all his friends: a tree of $n$ nodes! On the flight to IOI Little Ericyi was very bored, so he decided to play a game with Little Yvonne with his new tree. First, Little Yvonne selects two (not necessarily different...
Finding the theoretical maximum For now, let's only look at finding $k$ for fixed $f$. We will expand for all $f$ later. We know that $f$ is on the path from $a$ to $b$. Let us root the tree at $f$. Thus, we know that the path will pass through the root, and that there are exactly $2$ non-negative length chains beginni...
[ "constructive algorithms", "dp", "graphs", "interactive", "sortings", "trees" ]
3,500
#include "bits/stdc++.h" using namespace std; using ll = long long; using pii = pair<int,int>; using pll = pair<ll,ll>; template<typename T> int sz(const T &a){return int(a.size());} const int MN=1e5+1; vector<int> adj[MN]; int dp[MN],depth[MN]; void dfs(int loc, int parent){ vector<int> children; depth[loc]=de...
1535
A
Fair Playoff
Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament. It is known that in a match between two players, the o...
It is easier to determine the case when the players with the maximum skills will not meet in the finals. It means that they met in the semifinals, and in the other semifinals, both players are weaker. It's easy to check this case with the following formula: $\min(s_1, s_2) > \max(s_3, s_4)$ or $\max(s_1, s_2) < \min(s_...
[ "brute force", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { vector<int> s(4); for (int& x : s) cin >> x; if (min(s[0], s[1]) > max(s[2], s[3]) || max(s[0], s[1]) < min(s[2], s[3])) cout << "NO\n"; else cout << "YES\n"; } }
1535
B
Array Reodering
You are given an array $a$ consisting of $n$ integers. Let's call a pair of indices $i$, $j$ \textbf{good} if $1 \le i < j \le n$ and $\gcd(a_i, 2a_j) > 1$ (where $\gcd(x, y)$ is the greatest common divisor of $x$ and $y$). Find the maximum number of \textbf{good} index pairs if you can reorder the array $a$ in an ar...
If the value of $a_i$ is even, then $\gcd(a_i, 2a_j)$ at least $2$, regardless of the value of $a_j$. Therefore, we can put all the even values before the odd ones (it does not matter in what order). Now it remains to arrange the odd values. In fact, their order is not important, because $\gcd(a_i, 2a_j) = \gcd(a_i, a_...
[ "brute force", "greedy", "math", "number theory", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; sort(a.begin(), a.end(), [](int x, int y) { return x % 2 < y % 2; }); int ans = 0; for (int i = 0; i < n; ++i) { for...
1535
C
Unstable String
You are given a string $s$ consisting of the characters 0, 1, and ?. Let's call a string \textbf{unstable} if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...). Let's call a string \textbf{beautiful} if it consists of the characters 0, 1...
Let's find a simple condition when the string is not beautiful. A string is not beautiful if there are two characters 0 (or two characters 1) at an odd distance, or 0 and 1 at an even distance (because in this case, the string cannot be made unstable). Iterate over the right border of the substring $r$. Let $l$ be the ...
[ "binary search", "dp", "greedy", "implementation", "strings", "two pointers" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; vector<vector<int>> lst(2, vector<int>(2, -1)); long long ans = 0; for (int i = 0; i < int(s.size()); ++i) { int j = i - 1; int p = i & 1; if (s[i] != '1') j = min(...
1535
D
Playoff Tournament
$2^k$ teams participate in a playoff tournament. The tournament consists of $2^k - 1$ games. They are held as follows: first of all, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a ...
Denote $cnt_i$ as the number of teams that can be winners in the $i$-th game. The answer to the problem is $cnt_{2^k-1}$. If the $i$-th game is played between the winners of games $x$ and $y$ ($x < y$), then: $cnt_i = cnt_x$ if $s_i = 0$; $cnt_i = cnt_y$ if $s_i = 1$; $cnt_i = cnt_x + cnt_y$ if $s_i = ?$. So we can cal...
[ "data structures", "dfs and similar", "dp", "implementation", "trees" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int k; cin >> k; string s; cin >> s; reverse(s.begin(), s.end()); int n = 1 << k; vector<int> cnt(2 * n, 1); auto upd = [&](int i) { return cnt[i] = (s[i] != '0' ? cnt[i * 2 + ...
1535
E
Gold Transfer
You are given a rooted tree. Each vertex contains $a_i$ tons of gold, which costs $c_i$ per one ton. Initially, the tree consists only a root numbered $0$ with $a_0$ tons of gold and price $c_0$ per ton. There are $q$ queries. Each query has one of two types: - Add vertex $i$ (where $i$ is an index of query) as a son...
Note, that $c_i > c_{p_i}$ for each vertex $i$. So if we consider a path from some vertex $v$ to $0$, the closer you are to $0$, the cheaper the cost. In other words, it's always optimal to choose the highest vertex on the path with $a_i > 0$. Suppose we can find such vertex $u$ for a given $v$. How many times we will ...
[ "binary search", "data structures", "dp", "greedy", "interactive", "trees" ]
2,200
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out <<...
1535
F
String Distance
Suppose you are given two strings $a$ and $b$. You can apply the following operation any number of times: choose any \textbf{contiguous} substring of $a$ or $b$, and sort the characters in it in non-descending order. Let $f(a, b)$ the minimum number of operations you have to apply in order to make them equal (or $f(a, ...
Disclaimer: the model solution is very complicated compared to most participants' solutions. Feel free to discuss your approaches in the comments! First of all, it's easy to determine when two strings cannot be made equal using these operations: it's when their multisets of characters differ. So, we divide the strings ...
[ "binary search", "brute force", "data structures", "hashing", "implementation", "strings" ]
3,000
#include<bits/stdc++.h> using namespace std; const int LN = 20; const int K = 12000; int pw2[1 << LN]; vector<int> sorted_segments(const string& s) { int n = int(s.size()) - 1; vector<int> res(n); for(int i = 0; i < n; i++) if(s[i] <= s[i + 1]) res[i] = 0; else res[i] = 1; return res; } vec...
1536
A
Omkar and Bad Story
Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array $a = [a_1, a_2, \ldots, a_n]$ of $n$ distinct integers. An array $b = [b_1, b_2, \ldots, b_k]$ is called \textbf{nice} if for any two distinct elements $b_i, b_...
Consider what happens when $a$ contains a negative number. We first claim that if any negative number exists in $a$, then no solution exists. Denote $p$ as the smallest number in $a$ and $q$ as another arbitrary number in the array (as $n \geq 2$, $q$ always exists). Clearly, $|q - p| = q - p > 0$. However, because $p$...
[ "brute force", "constructive algorithms" ]
800
import Data.List (intercalate) import Control.Monad (replicateM) main = do t <- read <$> getLine replicateM t solve solve = do getLine xs <- (map read . words) <$> getLine putStrLn (if any (< 0) xs then "nO" else ("yEs\n101\n" ++ intercalate " " (map show [0..100])))
1536
B
Prinzessin der Verurteilung
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me. It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h...
Pigeonhole principle What is the longest the answer can be? Let's brute force check all substrings of length <= 3 and print the lexicographically smallest one that doesn't appear as a substring in the input. We can guarantee that we will come across the answer due to the pigeonhole principle. There are at most $n+n-1+n...
[ "brute force", "constructive algorithms", "strings" ]
1,200
import Data.List (intercalate, tails, isPrefixOf, head) import Control.Monad (replicateM) import Data.Maybe (fromJust, listToMaybe, catMaybes) main = do t <- read <$> getLine replicateM t solve solve = do getLine s <- getLine putStrLn (leastNonSubstring s) leastNonSubstring s = head $...
1536
C
Diluc and Kaeya
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance. This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of $n$ characters. Each character is e...
Turn into geometry problem Represent every prefix as $(x, y)$ point in cartesian plane where $x$ = frequency of 'D' and $y$ = frequency of 'K'. Draw a polyline connecting these points in order of increasing length of prefix. Draw a line from origin to point. What can we say about intersections of poly-line with this li...
[ "data structures", "dp", "hashing", "number theory" ]
1,500
import Data.List (intercalate) import Control.Monad (mapM, replicateM) import Data.Ratio ((%)) import Data.Map (empty, findWithDefault, insert) main = do t <- read <$> getLine replicateM t solve solve = do getLine s <- getLine putStrLn (intercalate " " (map show (maxBlocks s))) maxBlo...
1536
D
Omkar and Medians
Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $a$ with elements $a_1, a_2, \ldots, a_{2k-1}$, is the array $b$ with elements $b_1, b_2, \ldots, b_{k}$ such that $b_i$ is equal to the median of $a_1, a_2, \ld...
For some $k<n$, assume $b_1, b_2, \cdots, b_{k}$ is the OmkArray of some $a_1, a_2, \cdots, a_{2k-1}$, and we want to see what values of $a_{2k}, a_{2k+1}$ we can add so that $b_1, b_2, \cdots, b_{k+1}$ is the OmkArray of $a_1, a_2, \cdots, a_{2k+1}$. Let $c_1, c_2, \cdots, c_{2k-1}$ be $a_1, a_2, \cdots, a_{2k-1}$ sor...
[ "data structures", "greedy", "implementation" ]
2,000
import Data.List (intercalate) import Data.Set (singleton, lookupLT, lookupGT, insert) import Control.Monad (mapM, replicateM) main = do t <- read <$> getLine replicateM t solve solve = do getLine xs <- (map read . words) <$> getLine putStrLn (if isOmkArray xs then "yEs" else "nO") is...
1536
E
Omkar and Forest
Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an $n$ by $m$ grid ($1 \leq n, m \leq 2000$) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: - For any two adjacent (sharing a side) cells, the absolute value...
Consider forcing some set of '#' positions to be $0$ and the rest to be positive integers. Multisource BFS Imagine picking some subset of '#' and making them $0$. Then there is exactly one way to make all the remaining '#' positive integers. To see why, imagine multisource BFS with all $0$ as the sources. After the BFS...
[ "combinatorics", "graphs", "math", "shortest paths" ]
2,300
import Data.List (intercalate) import Control.Monad (replicateM) md x = mod x 1000000007 main = do t <- read <$> getLine replicateM t solve solve = do n:m:[] <- (map read . words) <$> getLine free <- (sum . map (sum . map (\chara -> if chara == '#' then 1 else 0))) <$> replicateM n getLine ...
1536
F
Omkar and Akmar
Omkar and Akmar are playing a game on a circular board with $n$ ($2 \leq n \leq 10^6$) cells. The cells are numbered from $1$ to $n$ so that for each $i$ ($1 \leq i \leq n-1$) cell $i$ is adjacent to cell $i+1$ and cell $1$ is adjacent to cell $n$. Initially, each cell is empty. Omkar and Akmar take turns placing eith...
Solve a simpler version of the problem, where you just need to print who would win if both players play optimally. Consider the possible ending states of the board. The 2nd player, Omkar, always wins no matter what either player does. The easiest way to see this is by considering ending states of the board. An ending s...
[ "chinese remainder theorem", "combinatorics", "constructive algorithms", "fft", "games", "geometry", "math", "meet-in-the-middle", "string suffix structures" ]
2,600
import Data.List (reverse) import Data.Array (listArray, (!)) chara = 1000000007 md x = mod x chara main = do n <- read <$> getLine putStrLn $ show (solve n) solve n = md $ 2 * (sum (map (\k -> md (factorials!k * (choose k (n - k) + choose (k - 1) (n - k - 1)))) [0,2..n])) where factorials = listArray (0...
1537
A
Arithmetic Array
An array $b$ of length $k$ is called good if its arithmetic mean is equal to $1$. More formally, if $$\frac{b_1 + \cdots + b_k}{k}=1.$$ Note that the value $\frac{b_1+\cdots+b_k}{k}$ is not rounded up or down. For example, the array $[1,1,1,2]$ has an arithmetic mean of $1.25$, which is not equal to $1$. You are give...
To make the arithmetic mean be equal to exactly $1$ the sum needs to be equal to the number of elements in the array. Let's consider $3$ cases for this problem: 1) The sum of the array equals $n$: Here the answer is $0$ since the arithmetic mean of the array is initially $1$. 2) The sum of the array is smaller than $n$...
[ "greedy", "math" ]
800
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--){ int n; cin >> n; int sum = 0; for (int i = 0;i < n; i++){ int a; cin >> a; sum += a; } if(sum < n)cout << "1\n"; else cout << sum - n << "\n"; } }
1537
B
Bad Boy
Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton. Anton's room can be represented as a grid with $n$ rows and $m$ columns. Let $(i, j)$ denote the cell in row $i$ and column $j$. Anton is currently standing at position $(i, j)$ in his...
We can notice that the optimal strategy is to put the yoyos in the corners of the board. One solution may be checking the best distance for all pairs of corners. But, if we think a bit more, we can notice that placing the yoyos in opposite corners the distance will always be maximum possible (the distance always being ...
[ "constructive algorithms", "greedy", "math" ]
900
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--){ int n, m, i, j; cin >> n >> m >> i >> j; cout << 1 << " " << 1 << " " << n << " " << m << "\n"; } }
1537
C
Challenging Cliffs
You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $n$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the gam...
We claim that the maximum difficulty is at least $n-2$. Assume the array is sorted. We first need to find the two mountains which go on the ends. To do this, we can iterate through every mountain in the sorted array and check the difference between a mountain and its neighbours in the array. Let $m_k$ and $m_{k+1}$ be ...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,200
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--){ int n; cin >> n; vector<int> h(n); for (int i = 0;i < n; i++){ cin >> h[i]; } sort(h.begin(), h.end()); if(n == 2){ cout << h[0] << " " <...
1537
D
Deleting Divisors
Alice and Bob are playing a game. They start with a positive integer $n$ and take alternating turns doing operations on it. Each turn a player can subtract from $n$ one of its divisors that isn't $1$ or $n$. The player who cannot make a move on his/her turn loses. Alice always moves first. Note that they subtract a d...
Let's consider $3$ cases for this problem: 1) n is odd 2) n is even, and $n$ is not a power of $2$ 3) n is a power of $2$ If $n$ is odd, the only move is to subtract an odd divisor (since all the divisors are odd). Doing this, we will obtain an even number that is not a power of $2$(case 2). If $D$ is the divisor of $n...
[ "games", "math", "number theory" ]
1,700
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--){ int n; cin >> n; if(n % 2 == 1){ cout << "Bob\n"; continue; } int cnt = 0; while(n % 2 == 0){ cnt++; n /= 2; ...
1537
E1
Erase and Extend (Easy Version)
\textbf{This is the easy version of the problem. The only difference is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} You have a string $s$, and you can do two types of operations on it: - Delete the last character of the string. - Duplicate the string: $s:=s+s$, ...
We claim that it is optimal to choose a prefix of the string, then duplicate it until we have a length bigger than $k$, then delete the excess elements. Let's relax the requirement so you have a position in the string and each time you either return to the beginning or advance to the next character. The answer will be ...
[ "binary search", "brute force", "dp", "greedy", "hashing", "implementation", "string suffix structures", "strings", "two pointers" ]
1,600
#include "bits/stdc++.h" using namespace std; string get(string s, int k){ while((int)s.size() < k){ s = s + s; } while((int)s.size() > k) s.pop_back(); return s; } int main() { int n, k; string s; cin >> n >> k; cin >> s; string pref = ""; pref += s[0]; st...
1537
E2
Erase and Extend (Hard Version)
\textbf{This is the hard version of the problem. The only difference is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} You have a string $s$, and you can do two types of operations on it: - Delete the last character of the string. - Duplicate the string: $s:=s+s$, ...
We know that the final string is some prefix repeated a bunch of times. Incrementally for $i$ from $1$ to $n$ we will keep the longest among the first $i$ prefixes that gives the best answer we've seen so far. So assume the $m-th$ prefix is currently the best and we're considering position $p$. If the $p-th$ character ...
[ "binary search", "data structures", "greedy", "hashing", "string suffix structures", "strings", "two pointers" ]
2,200
#include <bits/stdc++.h> using namespace std; using ll = long long; string s; int n, k; vector<int> z_func(string &s) { int n = s.size(), L = -1, R = -1; vector<int> z(n); z[0] = n; for(int i = 1; i < n; i++) { if(i <= R) z[i] = min(z[i - L], R - i + 1); while(i + z[i] < n ...
1537
F
Figure Fixing
You have a connected undirected graph made of $n$ nodes and $m$ edges. The $i$-th node has a value $v_i$ and a target value $t_i$. In an operation, you can choose an edge $(i, j)$ and add $k$ to both $v_i$ and $v_j$, where $k$ can be any \textbf{integer}. In particular, $k$ can be negative. Your task to determine if ...
If the parity of the sum of the initial values doesn't match the parity of the sum of the target values then there is no solution. Because $k$ is an integer and we always add the value $2 \cdot k$ to the sum of the initial values in each operation it's easy to notice that the parity of the sum of the initial values nev...
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "math" ]
2,200
#include "bits/stdc++.h" using namespace std; const int N = 2e5 + 10; vector<long long> adj[N]; long long s[N], n, m; bool bipartite() { bool bip = true; for(long long i = 0;i < n;i++) s[i] = -1; queue<long long> q; for(long long i = 0;i < n;i++){ if(s[i] != -1)continue; q.push(i); s[i] =...
1538
A
Stone Game
Polycarp is playing a new computer game. This game has $n$ stones in a row. The stone on the position $i$ has integer power $a_i$. \textbf{The powers of all stones are distinct}. Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the ...
If we want to destroy the largest and smallest stone, then there are only four options: Destroy the stones on the left until we destroy the smallest stone. Then destroy the stones on the right, until we destroy the largest stone. Destroy the stones on the right until we destroy the smallest stone. Then destroy the ston...
[ "brute force", "dp", "greedy" ]
800
#include <bits/stdc++.h> #include "random" using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using cd = complex<ld>; void solve() { int n; cin >> n; vector<int> v(n); for (int &e : v) { cin >> e; } int maxPos = max_element(v.begin(), v.end(...
1538
B
Friends and Candies
Polycarp has $n$ friends, the $i$-th of his friends has $a_i$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $a_i$ to be the same. To solve this, Polycarp performs the following set of actions exactly \textbf{once}: - Polycarp chooses $k$ ($0 \le k \le...
Let's denote for $s$ the number of candies all friends have: $s = \sum\limits_{i=1}^{n} a_i$. Note that at the end, each friend must have $\frac{s}{n}$ of candy. If $s$ is not completely divisible by $n$, then there is no answer. How to get the answer if it exists? If the $i$-th friend has more candies than $\frac{s}{n...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using cd = complex<ld>; void solve() { int n; cin >> n; vector<int> a(n); int s = 0; for (int i = 0; i < n; i++) { cin >> a[i]; s += a[i]; } if (s % n != 0) { cout << "-1"...
1538
C
Number of Pairs
You are given an array $a$ of $n$ integers. Find the number of pairs $(i, j)$ ($1 \le i < j \le n$) where the sum of $a_i + a_j$ is greater than or equal to $l$ and less than or equal to $r$ (that is, $l \le a_i + a_j \le r$). For example, if $n = 3$, $a = [5, 1, 2]$, $l = 4$ and $r = 7$, then two pairs are suitable: ...
The problem can be divided into two classic ones: Count the number of pairs $a_i+a_j \le r$; Count the number of pairs $a_i+a_j \le l-1$. Let $A$ - be the answer to the first problem, and $B$ - be the answer to the second problem. Then $A-B$ is the answer to the original problem. The new problem can be solved by binary...
[ "binary search", "data structures", "math", "two pointers" ]
1,300
#include <bits/stdc++.h> #include "random" using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using cd = complex<ld>; void solve() { int n, l, r; cin >> n >> l >> r; vector<int> v(n); for (int &e : v) { cin >> e; } sort(v.begin(), v.end()); ...
1538
D
Another Problem About Dividing Numbers
You are given two integers $a$ and $b$. In one turn, you can do one of the following operations: - Take an integer $c$ ($c > 1$ and \textbf{$a$ should be divisible by $c$}) and replace $a$ with $\frac{a}{c}$; - Take an integer $c$ ($c > 1$ and \textbf{$b$ should be divisible by $c$}) and replace $b$ with $\frac{b}{c}$...
Let's denote for $n$ the maximum number of moves for which the numbers $a$ and $b$ can be made equal. It is easy to understand that the number of moves is maximum when $a=b=1$ and each time we divided $a$ or $b$ by a prime number. That is, $n=$ sum of exponents of prime divisors of $a+$ sum of exponents of prime diviso...
[ "constructive algorithms", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using cd = complex<ld>; const int N = 50'000; bool isPrime[N]; vector<int> primes; void precalc() { fill(isPrime + 2, isPrime + N, true); for (int i = 2; i * i < N; i++) { for (int j = i ...
1538
E
Funny Substrings
Polycarp came up with a new programming language. There are only two types of statements in it: - "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a vari...
We can't model this process directly, since the maximum string length reaches $2^{50}$ (look at the second example from the statements). To optimize this process, you can store each row as a set of the following values. Number of occurrences of haha in the string - $cnt$. String length - $length$. The first three chara...
[ "data structures", "hashing", "implementation", "matrices", "strings" ]
2,100
#include <bits/stdc++.h> #include "random" using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using cd = complex<ld>; vector<string> split(const string& s, char p) { vector<string> res(1); for (char c : s) { if (c == p) { res.emplace_back(); ...
1538
F
Interesting Function
You are given two integers $l$ and $r$, where $l < r$. We will add $1$ to $l$ until the result is equal to $r$. Thus, there will be exactly $r-l$ additions performed. For each such addition, let's look at the number of digits that will be changed after it. For example: - if $l=909$, then adding one will result in $91...
For each digit, we will count how many times it has changed. The number of changes for the first digit (the lowest) is calculated using the formula $r-l$. The number of changes for the second digit is calculated by the formula $\left\lfloor\frac{r}{10}\right\rfloor-\left\lfloor\frac{l}{10}\right\rfloor$. That is, it is...
[ "binary search", "dp", "math", "number theory" ]
1,500
#include <iostream> using namespace std; void solve () { int L, R; cin >> L >> R; int ans = 0; while (L != 0 || R != 0) { ans += R - L; L /= 10; R /= 10; } cout << ans << '\n'; } int main () { ios::sync_with_stdio(false); cin.tie(0); int testc; cin >> testc; for (int i = 0; i <...
1538
G
Gift Set
Polycarp has $x$ of red and $y$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $a$ red candies and $b$ blue candies, or $a$ blue candies and $b$ red candies. Any candy can belong to at most one gift set. Help Polycarp to find the largest number of gift sets he can create. For e...
In this problem, we can use a binary search for the answer (If we can make $x$ sets, then we can make $y < x$ sets). So, we need to come up with the following test, whether we can make $n$ sets knowing the parameters $x, y, a, b$. Let $a > b$ (otherwise we will swap them). If $a == b$, the answer is $\lfloor\frac{min(x...
[ "binary search", "greedy", "math", "ternary search" ]
2,100
#include <bits/stdc++.h> #include "random" using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using cd = complex<ld>; void solve() { ll x, y, a, b; cin >> x >> y >> a >> b; ll l = 0, r = 1e9 + 100; if (a == b) { cout << min(x, y) / a << "\n"; ...
1539
A
Contest Start
There are $n$ people participating in some contest, they start participating in $x$ minutes intervals. That means the first participant starts at time $0$, the second participant starts at time $x$, the third — at time $2 \cdot x$, and so on. Duration of contest is $t$ minutes for each participant, so the first partic...
Let's find which participants will disturb participant $i$. Those are participants with number between $i + 1$ and $i + min(t / x, n)$. So each of first $max(0, n - t / x)$ participants will get $t / x$ dissatisfaction, and each next participant will get 1 dissatisfaction less, than previous. So the total answer is $ma...
[ "combinatorics", "geometry", "greedy", "math" ]
1,000
null
1539
B
Love Song
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $q$ questions about this song. Each question is about a subsegment of the song starting from the $l$-th letter to the $r$-th letter. Vasya considers a substring made up from characters on...
One can notice that letter with number $x$ will add exactly $x$ to the answer. So, all we have to do is calculate the sum of numbers of letters in our substring. This can be done using prefix sums.
[ "dp", "implementation", "strings" ]
800
null
1539
C
Stable Groups
There are $n$ students numerated from $1$ to $n$. The level of the $i$-th student is $a_i$. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than $x$. For example, if $x = 4$, then the group with l...
Firstly, we will find the amount of groups needed if we don't add any new students. Let's consider the students in the increasing order of their knowledge level. Students are greedily determined to the same group if the difference of their knowledge levels is not greater than $x$. Else we create another group. After th...
[ "greedy", "sortings" ]
1,200
null
1539
D
PriceFixed
Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store  — "PriceFixed". Here are some rules of that store: - The store has an infinite number of items of every product. - All products have the same price: $2$ rubles per item. - For e...
Let $m$ be the sum of all $a_i$ Important greedy observations: If there is an item which costs 1, then we will not make the answer worse by buying this item. If all prices are 2, then we will not make the answer worse by buying the item with max $b_i$. Therefore we can sort all items by $b_i$ and on each iteration we w...
[ "binary search", "greedy", "implementation", "sortings", "two pointers" ]
1,600
null
1539
E
Game with Cards
The Alice's computer is broken, so she can't play her favorite card game now. To help Alice, Bob wants to answer $n$ her questions. Initially, Bob holds one card with number $0$ in the left hand and one in the right hand. In the $i$-th question, Alice asks Bob to replace a card in the left or right hand with a card wi...
Let's use dynamic programming to solve the problem. $dp_L[i]$ is equal to 1 if we can correcly answer queries on suffix the way that $i$-th card is taken in left hand and $i+1$-th card is taken in right hand. $dp_R[i]$ is equal to 1 if we can correcly answer queries on suffix the way that $i$-th card is taken in right ...
[ "binary search", "constructive algorithms", "data structures", "dp", "greedy", "implementation" ]
2,500
null
1539
F
Strange Array
Vasya has an array of $n$ integers $a_1, a_2, \ldots, a_n$. Vasya thinks that all numbers in his array are strange for some reason. To calculate how strange the $i$-th number is, Vasya created the following algorithm. He chooses a subsegment $a_l, a_{l+1}, \ldots, a_r$, such that $1 \le l \le i \le r \le n$, sort its ...
Note that the distance from the given element to the median element (the center of a sorted segment) can be defined in terms of numbers of elements that are less, equal or bigger than the given element. Let $cnt_L$ be the number of elements that are less, $cnt_M$ - equal (excluding the given) and $cnt_R$ - bigger than ...
[ "data structures", "greedy", "sortings" ]
2,600
null
1540
A
Great Graphs
Farmer John has a farm that consists of $n$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it ...
Note that if there are two nodes $a$ and $b$ and you want to add an edge between them, the value of the edge must be $\geq d_b - d_a$. Otherwise, the cows could take a path to $b$ that goes through $d_a$ that's strictly less than $d_b$. With this in mind, let's add all edges $(a, b)$ with weight $d_b - d_a$ if and only...
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
1,400
null
1540
B
Tree Array
You are given a tree consisting of $n$ nodes. You generate an array from the tree by marking nodes one by one. Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked n...
Parsing through the problem statement, the process can be seen as choosing a starting node and "expanding" the subtree of marked nodes to nodes adjacent to the marked component. Fixing a given root $r$, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by $n$....
[ "brute force", "combinatorics", "dp", "graphs", "math", "probabilities", "trees" ]
2,300
null
1540
C2
Converging Array (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that in this version $1 \le q \le 10^5$. You can make hacks only if both versions of the problem are solved.} There is a process that takes place on arrays $a$ and $b$ of length $n$ and length $n-1$ respectively. The process is an infinite sequen...
First, reduce the operations into something more manageable. It turns out operation $i$ sets $a_{i+1}-a_i=\max(b_i, a_{i+1}-a_i)$ while keeping $a_{i+1}+a_i$ constant. Visually, this is simultaneously moving $a_i$ up and $a_{i+1}$ down until $a_{i+1}-a[i] \geq b_i$. Define $f$ to be the final converged array. Let's som...
[ "dp", "math" ]
2,900
null
1540
D
Inverse Inversions
You were playing with permutation $p$ of length $n$, but you lost it in Blair, Alabama! Luckily, you remember some information about the permutation. More specifically, you remember an array $b$ of length $n$, where $b_i$ is the number of indices $j$ such that $j < i$ and $p_j > p_i$. You have the array $b$, and you ...
We'll assume the arrays and the final permutation are 0-indexed from this point forward (you can shift values accordingly at the end). Let's start with calculating the final array, without any updates. Let $c_i$ be the number of indices $j$ such that $p_j < p_i$ and $i < j$. It is easy to see that $c_i = i - b_i$. Now ...
[ "binary search", "brute force", "data structures" ]
3,200
null
1540
E
Tasty Dishes
\textbf{Note that the memory limit is unusual.} There are $n$ chefs numbered $1, 2, \ldots, n$ that must prepare dishes for a king. Chef $i$ has skill $i$ and initially has a dish of tastiness $a_i$ where $|a_i| \leq i$. Each chef has a list of other chefs that he is allowed to copy from. To stop chefs from learning b...
All operations are conducted under a modulo, it can be proven that each operation we conduct is valid within the modulo. Key Idea 1 It's optimal to perform each operation if the number being added/multiplied is strictly positive. Specifically, it's optimal to do $a_i := i\cdot a_i$ and $a_i := a_i+a+j$ iif $a_i > 0$ an...
[ "math", "matrices" ]
3,500
null
1541
A
Pretty Permutations
There are $n$ cats in a line, labeled from $1$ to $n$, with the $i$-th cat at position $i$. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide...
There are two cases: if $n$ is even, print: $[2, 1, 4, 3, 6, 5 \ldots n, n-1]$ Formally, you swap every other pair of adjacent elements. This is optimal because the total distance is $n$, which has to be minimal since the distance of one cat must be $\geq 1$. if $n$ is odd, first print $[3, 1, 2]$ then solve the even c...
[ "constructive algorithms", "greedy", "implementation" ]
800
null
1541
B
Pleasant Pairs
You are given an array $a_1, a_2, \dots, a_n$ consisting of $n$ \textbf{distinct} integers. Count the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i \cdot a_j = i + j$.
Loop over all values of $a_i$ and $a_j$. Because $i + j \leq 2 \cdot n$, we only care about pairs $(a_i, a_j)$ if $a_i \cdot a_j \leq 2 \cdot n$. The number of such pairs is $O(n log n)$, so you can brute force all pairs. The reason the total number of pairs is $O(n log n)$ is because if the first element of the pair i...
[ "brute force", "implementation", "math", "number theory" ]
1,200
null
1542
A
Odd Set
You are given a multiset (i. e. a set that can contain multiple equal integers) containing $2n$ integers. Determine if you can split it into exactly $n$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is \textbf{odd} (i. e. when divided by $2$, the remainder is ...
The answer is 'yes' if and only if there are exactly $n$ odd numbers.
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ int n,cnt[2]={0}; cin>>n; for(int i=1,x;i<=n*2;i++)cin>>x,cnt[x%2]++; if(cnt[0]==n)puts("Yes"); else puts("No"); } return 0; }
1542
B
Plus and Multiply
There is an infinite set generated as follows: - $1$ is in this set. - If $x$ is in this set, $x \cdot a$ and $x+b$ both are in this set. For example, when $a=3$ and $b=6$, the five smallest elements of the set are: - $1$, - $3$ ($1$ is in this set, so $1\cdot a=3$ is in this set), - $7$ ($1$ is in this set, so $1+b...
First check specially if $b=1$. Let's consider when $n$ is in $S$. The answer is when the smallest number $m$ in $S$ that $n\ \mathrm{mod}\ b=m\ \mathrm{mod}\ b$ is less than $n$. It's easy to see that a new case of $x\ \mathrm{mod}\ b$ can only appear when you use $\times a$ to generate a new element. So the smallest ...
[ "constructive algorithms", "math", "number theory" ]
1,500
t=(int)(input()) for i in range(t): w=input().split() n=(int)(w[0]) a=(int)(w[1]) b=(int)(w[2]) if a==1 : if (n-1)%b==0 : print("Yes") else : print("No") else : t=1 flag=0 while t<=n : if t%b==n%b: flag=1 break t=t*a if fl...
1542
C
Strange Function
Let $f(i)$ denote the minimum positive integer $x$ such that $x$ is \textbf{not} a divisor of $i$. Compute $\sum_{i=1}^n f(i)$ modulo $10^9+7$. In other words, compute $f(1)+f(2)+\dots+f(n)$ modulo $10^9+7$.
Enumerate the value of $f(i)$. Since $f(n)=i$ means $lcm(1,2,...,i-1)\le n$, $f(n)$ will not be too big (less than $100$). The number of $k$s such that $f(k)=i$ is $\lfloor n/lcm(1,2,...,i-1)\rfloor -\lfloor n/lcm(1,2,...,i)\rfloor$. ($k$ should be divisible by $1\sim i-1$ but not $i$) So the answer is $\sum_{i>1} i(\l...
[ "math", "number theory" ]
1,600
#include<bits/stdc++.h> #define int long long #define re register using namespace std; int t,n; const int M=1e9+7; inline int gcd(re int x,re int y){ return y?gcd(y,x%y):x; } inline int LCM(re int x,re int y){ return x/gcd(x,y)*y; } signed main(){ scanf("%lld",&t); while(t--){ scanf("%lld",&n); re int G=1,ans=0...
1542
D
Priority Queue
You are given a sequence $A$, where its elements are either in the form + x or -, where $x$ is an integer. For such a sequence $S$ where its elements are either in the form + x or -, define $f(S)$ as follows: - iterate through $S$'s elements from the first one to the last one, and maintain a multiset $T$ as you itera...
For each $x$, count how many $B$s make the final set contain $x$. Let's say we have picked the $x$ in the $I$-th operation, call it $X$. Then, the subsequence we choose must satisfy the following conditions: It must contain the $i$-th operation (otherwise $X$ won't be added). Let $s$ denote the number of numbers less t...
[ "combinatorics", "dp", "implementation", "math", "ternary search" ]
2,200
mod=998244353 n=(int)(input()) a=[0 for i in range(n+1)] for i in range(1,n+1): m=input().split() if m[0]=="+": a[i]=(int)(m[1]) ans=0 for t in range(1,n+1): if a[t]==0: continue f=[[0 for i in range(n+2)] for j in range(n+2)] f[0][0]=1 for i in range(1,n+1): for j in range(0,i+1): if a[i]==0: if (...
1542
E1
Abnormal Permutation Pairs (easy version)
\textbf{This is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on $n$. You can only make hacks if both versions are solved.} A permutation of $1, 2, \ldots, n$ is a sequence of $n$ integers, where each integer from $1$ to $n$ appears exactly once. ...
Let's first calculate the number of permutation pair $(p,q)$s (with length $i$) that $p_1<q_1$ but $inv(p)>inv(q)$ ($inv(p)$ is the number of inversions in $p$). Call it $t_i$. Let's enumerate $p_1=j$ and $q_1=k$, then $inv(p[2...i])-inv(q[2...i])>k-j$. ($inv(p)=inv(p[2...i])+j-1,inv(q)=inv(q[2...i])+k-1$, with $inv(p)...
[ "combinatorics", "dp", "fft", "math" ]
2,400
#include<bits/stdc++.h> using namespace std; typedef long long ll; int n,mod,f[55][2005]={1},s[55][2005]={1},ans[55]; int main(){ cin>>n>>mod; for(int i=1;i<=n*(n-1)/2;i++)s[0][i]=1; for(int i=1;i<=n;i++){ for(int j=0;j<=n*(n-1)/2;j++){ if(j-i>=0)f[i][j]=(s[i-1][j]-s[i-1][j-i]+mod)%mod; else f[i][j]=s[i-1][j...
1542
E2
Abnormal Permutation Pairs (hard version)
\textbf{This is the hard version of the problem. The only difference between the easy version and the hard version is the constraints on $n$. You can only make hacks if both versions are solved.} A permutation of $1, 2, \ldots, n$ is a sequence of $n$ integers, where each integer from $1$ to $n$ appears exactly once. ...
We recommend you to read E1's editorial first. Let's directly count the number of permutation pairs $(p,q)$ of length $n$ with $inv(p)-inv(q)=k$, instead of counting it indirectly from "the number of permutation $p$s of length $i$ such that $inv(p)=j$.". Call this number $f(n,k)$. We have an $n^4$ transition: $f(n,k)=\...
[ "combinatorics", "dp", "fft", "math" ]
2,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int B=130000; int n,mod,w[2][2*B+5],s[2][2*B+5],ans[505]; int main(){ cin>>n>>mod; w[0][B]=s[0][B]=1; for(int i=B;i<=2*B;i++)s[0][i]=1; for(int i=1;i<=n;i++){ int curs=1,I=i&1,J=I^1; memset(w[I],0,sizeof(w[I])),memset(s[I],0,sizeof(s[I]));...
1543
A
Exciting Bets
Welcome to Rockport City! It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $a$ dollars and Ronnie has bet $b$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $gcd(a,b)$, where $gcd(x, y)$ denotes the greatest common divisor...
$GCD(a,b)=GCD(a-b,b)$ if $a>b$ $a-b$ does not change by applying any operation. However, $b$ can be changed arbitrarily. If $a=b$, the fans can get an infinite amount of excitement, and we can achieve this by applying the first operation infinite times. Otherwise, the maximum excitement the fans can get is $g=\lvert a-...
[ "greedy", "math", "number theory" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--) { long long a,b; cin >> a >> b; if(a==b) cout << 0 << " " << 0 << '\n'; else { long long g = ab...
1543
B
Customising the Track
Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $n$ sub-tracks. You are given an array $a$ where $a_i$ represents the number of traffic cars in the $i$-th sub-track....
In the optimal arrangement, the number of cars will be distributed as evenly as possible. In the optimal arrangement, the number of traffic cars will be distributed as evenly as possible, i.e., $\lvert a_i-a_j\rvert\leq 1$ for each valid $(i,j)$. Let's sort the array in non-decreasing order. Let $a_1=p$, $a_n=q$, $p\le...
[ "combinatorics", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--) { int n; cin >> n; int a[n]; long long s=0; for(int i=0;i<n;i++) { cin >> a[i]; s+=a[i]...
1543
C
Need for Pink Slips
After defeating a Blacklist Rival, you get a chance to draw $1$ reward slip out of $x$ hidden valid slips. Initially, $x=3$ and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are $c$, $m$, and $p$, respect...
Did you notice that $v\geq 0.1$? The probability of drawing a pink slip can never decrease. What would be the complexity of a bruteforce solution? Make sure to account for precision errors while comparing floating point numbers. Bruteforce over all the possible drawing sequences until we are sure to get a pink slip, i....
[ "bitmasks", "brute force", "dfs and similar", "implementation", "math", "probabilities" ]
1,900
#include <bits/stdc++.h> using namespace std; const long double eps = 1e-9; const long double scale = 1e+6; long double expectedRaces(int c,int m,int p,int v) { long double ans = p/scale; if(c>0) { if(c>v) { if(m>0) ans += (c/scale)*(1+expectedRaces(c-v,m+v/2,p+...
1543
D1
RPD and Rap Sheet (Easy Version)
\textbf{This is the easy version of the problem. The only difference is that here $k=2$. You can make hacks only if both the versions of the problem are solved.} This is an interactive problem. Every decimal number has a base $k$ equivalent. The individual digits of a base $k$ number are called $k$-its. Let's define ...
In this version, $x\oplus z=y$ or in other words, $z=x\oplus y$ where $\oplus$ is the Bitwise XOR operator. The number of queries allowed is equal to the number of possible initial passwords. The grader provides us no information other than whether our guess was correct or not. So, we need to find a way to ask queries ...
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { int t=1; cin >> t; while(t--) { int n,k; cin >> n >> k; int p=0; for(int i=0;i<n;i++) { int q=p^i; cout << q << endl; p=p^q; int v; cin >> v; ...
1543
D2
RPD and Rap Sheet (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that here $2\leq k\leq 100$. You can make hacks only if both the versions of the problem are solved.} \textbf{This is an interactive problem!} Every decimal number has a base $k$ equivalent. The individual digits of a base $k$ number are called $...
The generalised $k$-itwise XOR does not satisfy the Self-Inverse property. So, the solution for the Easy Version won't work here. Any property which is satisfied by $k$-its will also be satisfied by base $k$ numbers since a base $k$ number is nothing but a concatenation of $k$-its. So, try to prove properties for $k$-i...
[ "brute force", "constructive algorithms", "interactive", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; int knxor(int x,int y,int k) { int z=0; int p=1; while(x>0 || y>0) { int a=x%k; x=x/k; int b=y%k; y=y/k; int c=(a-b+k)%k; z=z+p*c; p=p*k; } return z; } int kxor(int x,int y,int k) { int z=...
1543
E
The Final Pursuit
Finally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune an...
In a simple $n$-Dimensional Hypercube, two vertices are connected if and only if they differ by exactly $1$ bit in their binary representation. The $n$-Dimensional Hypercubes are highly symmetric and all vertices are equivalent. If we select a particular vertex, then all directions in which the edges connected to it go...
[ "bitmasks", "constructive algorithms", "divide and conquer", "graphs", "greedy", "math" ]
2,700
#include <iostream> #include <iomanip> #include <vector> #include <cmath> #include <algorithm> #include <set> #include <utility> #include <queue> #include <map> #include <assert.h> #include <stack> #include <string> #include <ctime> #include <chrono> #include <random> using namespace std; const int MAX=65536; int pow...
1545
A
AquaMoon and Strange Sort
AquaMoon has $n$ friends. They stand in a row from left to right, and the $i$-th friend from the left wears a T-shirt with a number $a_i$ written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is \textbf{right}. AquaMoon can make some operations on friends. On each o...
It's easy to see that each number needs to move an even distance. For the same number, count how many of them are in the odd position and even position. Sort the array and count again. The given array named A, the sorted array named B. For every number, if the number of its occurrence in the odd position in A is differ...
[ "sortings" ]
1,500
#include <bits/stdc++.h> std::vector<int> a; int cnt[100001][2]; int main() { int n, T, flag; scanf("%d", &T); while(T--){ scanf("%d", &n), a.resize(n), flag = 0; for (int i = 0; i < n; ++i) scanf("%d", &a[i]), ++cnt[a[i]][i % 2]; std::sort(a.begin(), a.end()); for (int i = 0; i < n; ++i) ...
1545
B
AquaMoon and Chess
Cirno gave AquaMoon a chessboard of size $1 \times n$. Its cells are numbered with integers from $1$ to $n$ from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell $i$ with a pawn, and do \textbf{either} o...
We enumerate $i$ from $1$ to $n$. If position $i-1$ and $i$ both contain a chess and $i-1$ is not in other groups, then we divide them into one group. We can change the operation a little: Each time we can swap the two consecutive $1$ and the element to their left or right. It's easy to see this operation equals to the...
[ "combinatorics", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; const int MOD = 998244353; char str[MAXN]; long long F[MAXN], rF[MAXN]; long long inv(long long a, long long m) { if (a == 1) return 1; return inv(m%a, m) * (m - m/a) % m; } int main() { int T; int n; F[0] = rF[0] = 1; for (int i = 1; i < MA...
1545
C
AquaMoon and Permutations
Cirno has prepared $n$ arrays of length $n$ each. Each array is a permutation of $n$ integers from $1$ to $n$. These arrays are special: for all $1 \leq i \leq n$, if we take the $i$-th element of each array and form another array of length $n$ with these elements, the resultant array is also a permutation of $n$ integ...
Among all the arrays not be chosen, if an array have a number which appears exactly once at its column, that the array must belong to the $n$ original arrays. So, we can choose the array and delete all arrays have at least one same bit with it. If there not exists such an array discribed above, according to the Pigeonh...
[ "2-sat", "brute force", "combinatorics", "constructive algorithms", "graph matchings", "graphs" ]
2,800
#include<bits/stdc++.h> using namespace std; const int maxn=500; const long long mod=998244353; typedef pair<int,int> pii; int n,x,y,s,t; int a[maxn*2+5][maxn+5],b[maxn+5][maxn+5],f[maxn+5]; vector <pii> v; vector <int> c[maxn+5][maxn+5]; int main() { int T; scanf("%d",&T); while (T--) { scanf("...
1545
D
AquaMoon and Wrong Coordinate
Cirno gives AquaMoon a problem. There are $m$ people numbered from $0$ to $m - 1$. They are standing on a coordinate axis in points with positive integer coordinates. They are facing right (i.e. in the direction of the coordinate increase). At this moment everyone will start running with the constant speed in the direc...
Let's denote for $sum[t]$ the sum of all coordinates at the moment $t$, and for $sum2[t]$ the sum of all squared coordinates at the moment $t$. If there is no error, the sum of the coordinates of all moments will be an arithmetic series, and the difference is $\sum_{i=1}^m v_i$. It's easy to find the moment that contai...
[ "constructive algorithms", "interactive", "math" ]
3,000
#include<bits/stdc++.h> using namespace std; int n,m,i,j,k,ans1,ans2; long long a[1010][1010]; long long c[1010],x,y,s,t,temp; int main() { scanf("%d%d",&n,&m); for (i=0;i<m;i++) { for (j=1;j<=n;j++) { scanf("%lld",&a[i][j]); c[i]+=a[i][j]; } } x=(c[...
1545
E2
AquaMoon and Time Stop (hard version)
\textbf{Note that the differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if both versions are solved.} AquaMoon knew through foresight that some ghosts wanted to curse tourists on a pedestrian street. But unfortunately, this time, these ghosts were hiding ...
We scan through the time, each time. We need to get minimum answer for all positions of this certain time. We can use some data structure to maintain it. In detail, we use balance tree to maintain every segments which are not covered for some time $t$. We can see that after some time, the answer of every position of th...
[ "data structures", "dp" ]
3,500
#include<bits/stdc++.h> using namespace std; const int N=2000005,E=1000001; struct str{ int l; long long x; int d; long long las(){return x+(l-1)*d;} }a[N]; int ch[N][2],fa[N],h[N],tot,hc,ls[N],siz[N],i; struct seg{ int l,r,x; bool operator <(const seg &a)const { return a.r>r; } }; set<seg> p; void pushup(int...
1545
F
AquaMoon and Potatoes
AquaMoon has three integer arrays $a$, $b$, $c$ of length $n$, where $1 \leq a_i, b_i, c_i \leq n$ for all $i$. In order to accelerate her potato farming, she organizes her farm in a manner based on these three arrays. She is now going to complete $m$ operations to count how many potatoes she can get. Each operation w...
We seek a solution of roughly square root time complexity; the small constraint of $m$ hints at a solution in $O(m\sqrt n)$. This immediately rules out solutions based on square root decomposition on sequences, because of the overhead incurred with initializing such structures. Instead of directly solving the problem, ...
[ "brute force", "data structures", "dp" ]
3,500
// (insert magical incantation) // (insert offerings for the Gods of codeforces judging servers) //LXLORZ!!!!//rejudg #include <bits/stdc++.h> using namespace std; #define MAXN 200005 #define SQRTN 210 namespace io { const int __SIZE = (1 << 21) + 1; char ibuf[__SIZE], *iS, *iT, obuf[__SIZE], *oS = obuf, *oT = oS + _...
1546
A
AquaMoon and Two Arrays
AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $a$ and $b$, both consist of $n$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): - She chooses two indices $i$ and $j$ ($1 \le i, j \le n$), then decreases the...
First, if the sum of elements in $a$ is not equal to the sum of elements in $b$, then the solution does not exist. Each time find a position $i$ satisfying $a_i>b_i$, and find such a $j$ satisfying $a_j<b_j$. Then let $a_i-1$, $a_j+1$, until the two arrays become the same.
[ "brute force", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; #define O(x) cout<<#x<<" "<<(x)<<"\n" inline int read(){ int x=0,f=1,c=getchar(); while(!isdigit(c)){if(c=='-')f=-1;c=getchar();} while(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();} return f==1?x:-x; } const int N=104; int n,sum,a[N]; vector<pair<int,int> >ans; inline...
1546
B
AquaMoon and Stolen String
AquaMoon had $n$ strings of length $m$ each. $n$ is an \textbf{odd} number. When AquaMoon was gone, Cirno tried to pair these $n$ strings together. After making $\frac{n-1}{2}$ pairs, she found out that there was exactly one string without the pair! In her rage, she disrupted each pair of strings. For each pair, she ...
We can find that for each letter of the answer must appear an odd number of times in its column(Since for other strings, they appear twice in total. The operation does not change the number of the occurrence of some certain letter in one column). So we can consider each position individually. There is always exactly on...
[ "interactive", "math" ]
1,200
#include <cstdio> const int Maxn=1000000; char s[Maxn+5]; char ans[Maxn+5]; int n,m; void solve(){ scanf("%d%d",&n,&m); n=(n<<1)-1; for(int i=1;i<=m;i++){ ans[i]=0; } for(int i=1;i<=n;i++){ scanf("%s",s+1); for(int j=1;j<=m;j++){ ans[j]^=s[j]; } } ...
1547
A
Shortest Path with Obstacle
There are three cells on an infinite 2-dimensional grid, labeled $A$, $B$, and $F$. Find the length of the shortest path from $A$ to $B$ if: - in one move you can go to any of the four adjacent cells sharing a side; - visiting the cell $F$ is forbidden (it is an obstacle).
Let's suppose that the forbidden cell does not affect the shortest path. In that case, the answer would be $|x_A - x_B| + |y_A - y_B|$. The forbidden cell blocks the shortest path if and only if it belongs to every shortest path. In other words, if there is only one shortest path and the forbidden cell belongs to it. S...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { vector<int> a(2), b(2), f(2); cin >> a[0] >> a[1]; cin >> b[0] >> b[1]; cin >> f[0] >> f[1]; int ans = abs(a[0] - b[0]) + a...
1547
B
Alphabetical Strings
A string $s$ of length $n$ ($1 \le n \le 26$) is called alphabetical if it can be obtained using the following algorithm: - first, write an empty string to $s$ (i.e. perform the assignment $s$ := ""); - then perform the next step $n$ times; - at the $i$-th step take $i$-th lowercase letter of the Latin alphabet and wr...
For a start, let's find the position of the letter 'a' in string $s$. If this position does not exist, then the answer would be 'NO'. Suppose that this position exists and equals $\text{pos}_a$. Let's create two pointers $L$ and $R$. Initially $L := \text{pos}_a,~R := L$. We will try to build string $s$ using the algor...
[ "greedy", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { string s; cin >> s; size_t L = s.find('a'); if (L == string::npos) { cout << "NO" << endl; continue; ...
1547
C
Pair Programming
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming. It's known that they have worked together on the same file for $n + m$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $k$ lines written in the file. ...
The solution is that if we can do something, let's do it. It doesn't make sense not to act, because neither adding a new row nor modifying an existing one can prevent the existing row from being changed in the future. Therefore, we will iterate over the actions and eagerly act Monocarp or Polycarp. Let's create two poi...
[ "greedy", "two pointers" ]
1,100
#include <iostream> #include <vector> typedef std::vector<int> vi; int main() { int t; std::cin >> t; while (t--) { int k, n, m; std::cin >> k >> n >> m; vi a(n), b(m); for (int i = 0; i < n; i++) std::cin >> a[i]; for (int i = 0; i < m; i++) ...
1547
D
Co-growing Sequence
A sequence of non-negative integers $a_1, a_2, \dots, a_n$ is called growing if for all $i$ from $1$ to $n - 1$ all ones (of binary representation) in $a_i$ are in the places of ones (of binary representation) in $a_{i + 1}$ (in other words, $a_i \:\&\: a_{i + 1} = a_i$, where $\&$ denotes bitwise AND). If $n = 1$ then...
In order to build lexicographically minimal co-growing with $x_i$ sequence, it is enough to build its elements iteratively, beginning from $y_1$ and minimizing the $i$-th element assuming that $y_1, \ldots, y_{i - 1}$ have already been found. Assign $y_1 = 0$. According to the statement, all elements of the sequence ar...
[ "bitmasks", "constructive algorithms", "greedy" ]
1,300
def f(x, y): return x & ~y t = int(input()) for tt in range(t): n = int(input()) a = list(map(int, input().split())) ans = [0] * n for i in range(1, n): ans[i] = f(ans[i - 1] ^ a[i - 1], a[i]) print(" ".join(map(str, ans)))
1547
E
Air Conditioners
On a strip of land of length $n$ there are $k$ air conditioners: the $i$-th air conditioner is placed in cell $a_i$ ($1 \le a_i \le n$). Two or more air conditioners cannot be placed in the same cell (i.e. all $a_i$ are distinct). Each air conditioner is characterized by one parameter: temperature. The $i$-th air cond...
Let's calculate two arrays $L$ and $R$, where: $L_i$ is the temperature in cell $i$ if we take only air conditioners with numbers less than or equal to $i$; $R_i$ is the temperature in cell $i$ if we take only air conditioners with numbers greater than or equal to $i$; Let's show how to calculate array $L$. We will cal...
[ "data structures", "dp", "implementation", "shortest paths", "sortings", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int n, k; cin >> n >> k; vector<int> a(k); forn(i, k) cin >> a[i]; vector<int> t(k); forn(i, k) ...
1547
F
Array Stabilization (GCD version)
You are given an array of positive integers $a = [a_0, a_1, \dots, a_{n - 1}]$ ($n \ge 2$). In one step, the array $a$ is replaced with another array of length $n$, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right...
First, note that the array stabilizes if and only if it consists of equal elements, and the number the array $a$ will be consisted of is $T = \gcd(a_1, \ldots, a_n)$. Indeed, at the $i$-th step a number equal to $\gcd(a_j, \ldots, a_{(j + i) \mod n})$ will be written at the $j$-th position in the array. This is easy to...
[ "binary search", "brute force", "data structures", "divide and conquer", "number theory", "two pointers" ]
1,900
#include <iostream> #include <vector> #include <set> using namespace std; const unsigned int MAX_A = 1'000'000; vector<unsigned int> sieve(MAX_A + 1); vector<unsigned int> prime; unsigned int gcd(unsigned int a, unsigned int b) { return b == 0 ? a : gcd(b, a % b); } unsigned int solve() { unsigned int n; ...
1547
G
How Many Paths?
You are given a directed graph $G$ which can contain loops (edges from a vertex to itself). Multi-edges are absent in $G$ which means that for all ordered pairs $(u, v)$ exists at most one edge from $u$ to $v$. Vertices are numbered from $1$ to $n$. A path from $u$ to $v$ is a sequence of edges such that: - vertex $u...
The first motivation for solving this problem is to write a lot of standard code like "find strongly connected components", do some DP over the condensed graph (the graph of strongly connected components), and so on. In fact, this problem can be solved much more elegantly with less code if you have a little better unde...
[ "dfs and similar", "dp", "graphs", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int n; vector<vector<int>> g; set<int> s[2]; void dfs(int u, vector<int>& color, bool use_s) { color[u] = 1; for (int v: g[u]) if (color[v] == 0) dfs(v, color, use_s); else if (use_s...
1548
A
Web of Lies
\begin{quote} When you play the game of thrones, you win, or you die. There is no middle ground. \hfill Cersei Lannister, A Game of Thrones by George R. R. Martin \end{quote} There are $n$ nobles, numbered from $1$ to $n$. Noble $i$ has a power of $i$. There are also $m$ "friendships". A friendship between nobles $a$ ...
For various graphs, try and simulate the process. Determine a rule to figure out whether a noble survives or not. When you add or remove a single edge, how much can the answer change by? Try and recalculate the answer in $\mathcal{O}(1)$. Due to the queries, actually simulating the process each time will be too expensi...
[ "brute force", "graphs", "greedy" ]
1,400
//Written by m371 (Runtime: 202ms) #include <bits/stdc++.h> using namespace std; const int N=200050; int cnt[N],ans; int main(){ int n,m;scanf("%i %i",&n,&m); for(int i=1;i<=m;i++){ int u,v;scanf("%i %i",&u,&v); if(u>v)swap(u,v); cnt[u]++; if(cnt[u]==1)ans++; } int q;sca...
1548
B
Integers Have Friends
British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends." It turns out that positive integers can also be friends with each other! You are given an array $a$ of distinct positive integers. Define a \textbf{subarray} $a...
Let's say the subarray $A_i \dots A_j$ is all congruent to $n\mod{m}$. What does that imply about the subarray? What does the previous hint imply about the difference array generated by $D[i]=A[i+1]-A[i]$? GCD The key observation is to construct the difference array $D$ of size $N-1$, where $D[i]=abs(A[i+1]-A[i])$. If ...
[ "binary search", "data structures", "divide and conquer", "math", "number theory", "two pointers" ]
1,800
//Written by emorgan5289 (Runtime: 218ms) #include <bits/stdc++.h> using namespace std; using ll = long long; const int inf = 1e9+10; const ll inf_ll = 1e18+10; #define all(x) (x).begin(), (x).end() #define pb push_back #define cmax(x, y) (x = max(x, y)) #define cmin(x, y) (x = min(x, y)) template<typename it, typ...
1548
C
The Three Little Pigs
Three little pigs from all over the world are meeting for a convention! Every minute, a triple of 3 new pigs arrives on the convention floor. After the $n$-th minute, the convention ends. The big bad wolf has learned about this convention, and he has an attack plan. At some minute in the convention, he will arrive and...
Convert the word problem into a combinatorics equation. Write the equation for some $x$. Write the equation for $x+1$. How can we easily transition from the first to the second equation? For a given $x$, we want to calculate every third term in the sequence $\binom{i}{x}$ for $i \in [1,3N]$. Think about how computing t...
[ "combinatorics", "dp", "fft", "math" ]
2,500
//Written by Agnimandur (Runtime: 218ms) #include <bits/stdc++.h> #define ll long long #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() #define vi vector<int> #define vl vector<long long> #define REP(i,a) for (int i = 0; i < (a); i++) #define add push_back using namespace std; const ll MOD = ...
1548
D1
Gregor and the Odd Cows (Easy)
{This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are \textbf{even}.} There are $n$ fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line. There are an infinite number of cows on the pla...
"Enclosed cows" are just interior points. It's clear that Pick's Theorem will be useful. Manipulate Pick's Theorem into a modular equation. The number of boundary points between $(x_1,y_1)$ and $(x_2,y_2)$ is $\gcd{(x_1-x_2,y_1-y_2)}$. Working with relevant formulas, find a simple condition between two points, such tha...
[ "bitmasks", "geometry", "math", "number theory" ]
2,300
//Written by Agnimandur (Runtime: 31ms) #include <bits/stdc++.h> #define ll long long #define REP(i,a) for (int i = 0; i < (a); i++) using namespace std; int ni() { int x; cin >> x; return x; } ll choose(ll n, ll k) { if (n<k) return 0LL; if (k==2) return n*(n-1)/2; else ret...
1548
D2
Gregor and the Odd Cows (Hard)
{This is the hard version of the problem. The only difference from the easy version is that in this version the coordinates can be \textbf{both} odd and even.} There are $n$ fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line. There are an infinite number of...
Solve the easy version of the problem. Taking each coordinate modulo 4 no longer works. This is because if $\Delta{x}$ or $\Delta{y}$ are odd, there's no way to predict whether the boundary count (see editorial of the easy version) is 1 or 3 mod 4. By playing with Pick's Theorem, you should find that $B$ (the total num...
[ "brute force", "geometry", "math", "number theory" ]
3,300
//Written by Agnimandur (Runtime: 2886ms) #include <bits/stdc++.h> #define ll long long #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() #define vi vector<int> #define vl vector<long long> #define pii pair<int, int> #define pll pair<ll,ll> #define REP(i,a) for (int i = 0; i < (a); i++) #define ...
1548
E
Gregor and the Two Painters
Two painters, Amin and Benj, are repainting Gregor's living room ceiling! The ceiling can be modeled as an $n \times m$ grid. For each $i$ between $1$ and $n$, inclusive, painter Amin applies $a_i$ layers of paint to the entire $i$-th row. For each $j$ between $1$ and $m$, inclusive, painter Benj applies $b_j$ layers ...
For simplicity let's assume that all $a_i$ are distinct (and similarly, all $b_j$). If this is not the case, we may break ties arbitrarily. Say that two badly painted cells are directly reachable from each other if they are in the same row or column and all cells in between them are also badly painted. Also, define the...
[ "data structures", "divide and conquer", "graphs", "greedy", "math" ]
3,400
//Written by Benq (Runtime: 187ms) #include <bits/stdc++.h> using namespace std; using ll = long long; using db = long double; // or double, if TL is tight using str = string; // yay python! using pi = pair<int,int>; using pl = pair<ll,ll>; using pd = pair<db,db>; using vi = vector<int>; using vb = vector<bool>;...
1549
A
Gregor and Cryptography
Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them. Gregor's favorite \textbf{prime} number is $P$. Gregor wants to find two bases of $P$. Formally, Gregor is looking for two integers $a$ and $b$ which satisfy both of ...
Fix $a$ into a convenient constant. Since $P \ge 5$ and is also a prime number, we know that $P-1$ is an even composite number. A even composite number is guaranteed to have at least 2 unique divisors greater than 1. Let two of these divisors be $a$ and $b$. It is guaranteed that $P\mod{a} = P\mod{b} = 1$, and thus thi...
[ "math", "number theory" ]
800
//Written by penguinhacker (Runtime: 15ms) #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--) { int p; cin >> p; cout << "2 " << p-1 << " "; } return 0; }
1549
B
Gregor and the Pawn Game
There is a chessboard of size $n$ by $n$. The square in the $i$-th row from top and $j$-th column from the left is labelled $(i,j)$. Currently, Gregor has some pawns in the $n$-th row. There are also enemy pawns in the $1$-st row. On one turn, Gregor moves one of \textbf{his} pawns. A pawn can move one square up (from...
There a very limited number of squares where each of Gregor's pawns could end up. Identify a greedy strategy to maximize the answer. The key insight is that due to the fact that there is only one row of enemy pawns, and those pawns never move, there are only $3$ possible columns where one of Gregor's pawns can end up i...
[ "dfs and similar", "dp", "flows", "graph matchings", "graphs", "greedy", "implementation" ]
800
//Written by arvindr9 (Runtime: 31ms) #include <bits/stdc++.h> using namespace std; int t; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> t; while (t--) { int n; cin >> n; string st, tt; cin >> st >> tt; int ans = 0; vector<bool> taken(n); ...
1550
A
Find The Array
Let's call an array $a$ consisting of $n$ positive (greater than $0$) integers beautiful if the following condition is held for every $i$ from $1$ to $n$: either $a_i = 1$, or at least one of the numbers $a_i - 1$ and $a_i - 2$ exists in the array as well. For example: - the array $[5, 3, 1]$ is beautiful: for $a_1$,...
The maximum sum we can construct with $n$ elements is $1 + 3 + 5 + 7 + \dots + 2n-1 = n^2$, so we need at least $\lceil\sqrt{s}\rceil$ elements to construct the sum equal to $s$. Let's show how to express $s$ with exactly $\lceil\sqrt{s}\rceil$ elements. Let $\lceil\sqrt{s}\rceil = d$. By taking $1 + 3 + 5 + 7 + \dots ...
[ "greedy", "math" ]
800
def maxSum(x): return x ** 2 def getAns(x): res = 1 while maxSum(res) < x: res += 1 return res def main(): t = int(input()) for i in range(t): print(getAns(int(input()))) main()
1550
B
Maximum Cost Deletion
You are given a string $s$ of length $n$ consisting only of the characters 0 and 1. You perform the following operation until the string becomes empty: choose some \textbf{consecutive} substring of \textbf{equal} characters, erase it from the string and glue the remaining two parts together (any of them can be empty) ...
Let $l_1, l_2, \dots, l_k$ be the length of the substring deleted at the $i$-th step. Then the number of points will be equal to $\sum\limits_{i=1}^{k} (a \cdot l_i + b)$ or $a\sum\limits_{i=1}^{k}l_i + bk$. The sum of all $l_i$ is equal to $n$ (because in the end we deleted the entire string), so the final formula has...
[ "greedy", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, a, b; string s; cin >> n >> a >> b >> s; int m = unique(s.begin(), s.end()) - s.begin(); cout << n * a + max(n * b, (m / 2 + 1) * b) << '\n'; } }
1550
C
Manhattan Subarrays
Suppose you have two points $p = (x_p, y_p)$ and $q = (x_q, y_q)$. Let's denote the Manhattan distance between them as $d(p, q) = |x_p - x_q| + |y_p - y_q|$. Let's say that three points $p$, $q$, $r$ form a bad triple if $d(p, r) = d(p, q) + d(q, r)$. Let's say that an array $b_1, b_2, \dots, b_m$ is good if it is im...
Let's figure out criteria for the bad triple $p$, $q$, $r$. It's not hard to prove that the triple is bad, iff point $q$ lies inside the bounding box of points $p$ and $r$. In other words, if $\min(x_p, x_r) \le x_q \le \max(x_p, x_r)$ and $\min(y_p, y_r) \le y_q \le \max(y_p, y_r)$. Now, looking at points $p = (a_i, i...
[ "brute force", "geometry", "greedy", "implementation" ]
1,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<li, li> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; in...
1550
D
Excellent Arrays
Let's call an integer array $a_1, a_2, \dots, a_n$ good if $a_i \neq i$ for each $i$. Let $F(a)$ be the number of pairs $(i, j)$ ($1 \le i < j \le n$) such that $a_i + a_j = i + j$. Let's say that an array $a_1, a_2, \dots, a_n$ is excellent if: - $a$ is good; - $l \le a_i \le r$ for each $i$; - $F(a)$ is the maximu...
Firstly, let's learn the structure of good array $a$ with maximum $F(a)$. Suppose, $a_i = i + k_i$, then $a_i + a_j = i + j$ $\Leftrightarrow$ $k_i = -k_j$. In other words, we can group $a_i$ by $|k_i|$ and pairs will appear only inside each group. It's easy to prove that if the group has size $m$ then it's optimal to ...
[ "binary search", "combinatorics", "constructive algorithms", "implementation", "math", "sortings", "two pointers" ]
2,300
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) const int MOD = int(1e9) + 7; int norm(int a) { while (a >= MOD) a -= MOD; while (a < 0) a += MOD; return a; } int mul(int a, int b) { return int(a * 1ll * b % MOD); } int bi...
1550
E
Stringforces
You are given a string $s$ of length $n$. Each character is either one of the first $k$ lowercase Latin letters or a question mark. You are asked to replace every question mark with one of the first $k$ lowercase Latin letters in such a way that the following value is maximized. Let $f_i$ be the maximum length substr...
Notice that if there are substrings of length $x$ for each letter, then there are also substrings of length $x-1$. Thus, the function on the answer is monotonous, so the binary search is applicable. Let's have some answer $x$ fixed by binary search. We have to place $k$ blocks of letters of length $x$ somewhere in a st...
[ "binary search", "bitmasks", "brute force", "dp", "strings", "two pointers" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n, k; string s; bool check(int d){ vector<int> lst(k, n); vector<vector<int>> pos(n + 1, vector<int>(k, n + 1)); for (int i = n - 1; i >= 0; --i){ if (s[i] != '?'){ lst[s[i] - 'a'] = i; } int cur = n; ...
1550
F
Jumping Around
There is an infinite pond that can be represented with a number line. There are $n$ rocks in the pond, numbered from $1$ to $n$. The $i$-th rock is located at an integer coordinate $a_i$. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of the coordinate, so $a_1 < a_2 ...
Notice that increasing $k$ only increases the range of the jump distances in both directions. So every rock that was reachable with some $k$, will be reachable with $k+1$ as well. Thus, let's try to find the smallest possible value of $k$ to reach each rock. Let's imagine this problem as a graph one and consider the fo...
[ "binary search", "data structures", "divide and conquer", "dp", "dsu", "graphs", "shortest paths" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; struct edge2{ int u, w; }; vector<vector<edge2>> g; struct edge3{ int v, u, w; edge3(){} edge3(int v, int u, int w) : v(v), u(u), w(w) { if (v > u) swap(v, u); } }; bool operator <(const ...
1551
A
Polycarp and Coins
Polycarp must pay \textbf{exactly} $n$ burles at the checkout. He has coins of two nominal values: $1$ burle and $2$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other. Thus, Polycarp wants to minimize the difference between the count of coins ...
Let's initialize variables $c_1$ and $c_2$ by the same value of $\lfloor{\frac{n}{3}}\rfloor$. Then we need to gather additionally the remainder of dividing $n$ by $3$. If the remainder is equal to $0$, we don't need to gather anything else because the variables $c_1$ and $c_2$ have been already set to the correct answ...
[ "greedy", "math" ]
800
for i in range(0, int(input())): n = int(input()) c1 = n // 3; c2 = c1; if n % 3 == 1: c1 += 1 elif n % 3 == 2: c2 += 1 print(c1, c2)
1551
B1
Wonderful Coloring - 1
This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1. Paul and Mary have a favorite string $s$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a st...
Let's calculate the number of letters which occur exactly once in the string and letters that occur more than once - $c_1$ and $c_2$, respectively. If a letter occurs more than once, one of its occurrences may be painted in red and another one may be painted in green. We cannot paint all other occurrences because there...
[ "greedy", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int L = 26; int cnt[L]; int main() { int t; cin >> t; while (t--) { string s; cin >> s; memset(cnt, 0, sizeof(cnt)); for (auto c : s) cnt[c - 'a']++; int cnt1 = 0; int cnt2 = 0; for (int i = 0; i < L; i++) if (cnt[i] == 1) cnt1++; else i...
1551
B2
Wonderful Coloring - 2
This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely. Recently, Paul and Mary have found a new favorite sequence of integers $a_1, a_2, \dots, a_n$. They want to paint it using pieces of chalk of $k$ colors. The coloring of a ...
Since we must use exactly $k$ colors, each element that occurs in the sequence may have no more than $k$ painted occurrences. Let's select for each element $x$ $min(k, cnt_x)$ its occurrences where $cnt_x$ is the number of all its occurrences in the sequence. Let $b_1, b_2, \dots, b_m$ be a sequence of all elements tha...
[ "binary search", "constructive algorithms", "data structures", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; const int MAX_N = 200 * 1000 + 13; int ans[MAX_N]; map<int, vector<int>> indices; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; indices.clear(); memset(ans, 0, n * sizeof(ans[0])); for (int i = 0; i < n; i++) { int x; cin >> x;...
1551
C
Interesting Story
Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'! To compose a story, Stephen wrote out $n$ words consisting of the first $5$ lowercase letters of the Latin alphabet. He wants to select the \textbf{maximum} number of \textbf{words} to make an \textbf{in...
Let $f(s, c)$ be the number of the occurrences of the letter $c$ in the word $s$ minus the number of the occurrences of all other letters in total. Since for each two words $s_1$ and $s_2$ the number of the occurrences of a letter in the word $s_1 + s_2$ is the sum of the numbers of its occurrences in $s_1$ and $s_2$, ...
[ "greedy", "sortings", "strings" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAX_N = 2 * 100 * 1000 + 13; const int L = 26; vector<int> balance[L]; int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 0; i < L; i++) balance[i].clear(); for (int i = 1; i <= n; i++) { string s; cin >> s; int i...
1551
D2
Domino (hard version)
The only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem. There's a table of $n \times m$ cells ($n$ rows and $m$ columns). The value of $n \cdot m$ is even. A domino is a figure that consists of two cells having a c...
Suppose $n$ and $m$ are even. A necessary and sufficient condition of existence of the answer is that $k$ is even. Let's prove the sufficient condition. If the count of the horizontal dominoes is even, then we can combine them and vertical dominoes to blocks of size $2 \times 2$ (the number of the vertical dominoes is ...
[ "constructive algorithms", "implementation", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; char field[128][128]; int main() { int t; cin >> t; while (t--) { int n, m, kh; cin >> n >> m >> kh; int kv = n * m / 2 - kh; if (n & 1) { kh -= m / 2; if (kh < 0) { cout << "NO\n"; continue; } for (int i = 0; i < m / 2; i++) fiel...
1551
E
Fixed Points
Consider a sequence of integers $a_1, a_2, \ldots, a_n$. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by $1$ position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length de...
Let's use the concept of dynamic programming. Let's create an array $dp$ ($0$-indexed) with size of $(n + 1) \times (n + 1)$. $dp[i][j]$ will contain the maximal number of the elements equal to their indices if we have considered the first $i$ elements of the sequence $a$ and have not deleted $j$ elements. Let's fill t...
[ "binary search", "brute force", "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MAX_N = 6000; int dp[MAX_N][MAX_N]; int a[MAX_N]; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 0; i <= n; i++) for (int j = 0; j <= i; j++) dp[i][j] = 0; for(int ...
1551
F
Equidistant Vertices
A tree is an undirected connected graph without cycles. You are given a tree of $n$ vertices. Find the number of ways to choose exactly $k$ vertices in this tree (i. e. a $k$-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer $c$ ...
If $k = 2$, any set of two vertices may be taken so the answer is $\frac{n(n - 1)}{2}$ modulo $10^9 + 7$. Suppose $k \ge 3$. Consider three vertices $A$, $B$, $C$ such that $d_{A, B} = d_{A,C} = d_{B,C}$. If this equality is true, there's a vertex $Q$ that belongs to all three paths, otherwise, either one of the vertic...
[ "brute force", "combinatorics", "dfs and similar", "dp", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; const int MAX_N = 128; typedef long long ll; const ll mod = 1000 * 1000 * 1000 + 7; ll add(ll x, ll y) { return (x + y) % mod; } ll mul(ll x, ll y) { return x * y % mod; } vector<int> g[MAX_N]; bool used[MAX_N]; int cnt[MAX_N]; ll dp[MAX_N][MAX_N]; ll rundp(int m, int k...
1552
A
Subsequence Permutation
A string $s$ of length $n$, consisting of lowercase letters of the English alphabet, is given. You must choose some number $k$ between $0$ and $n$. Then, you select $k$ characters of $s$ and permute them however you want. In this process, the positions of the other $n-k$ characters remain unchanged. You have to perfor...
Let $\texttt{sort}(s)$ be $s$ sorted alphabetically. The answer to the problem is the number $m$ of mismatches between $s$ and $\texttt{sort}(s)$ (i.e., the positions with different characters in the two strings). Choosing $k=m$ characters is sufficient. Let us choose the mismatched characters between $s$ and $\texttt{...
[ "sortings", "strings" ]
800
#include <iostream> #include <string> #include <algorithm> using namespace std; void solve() { int n; string s; cin >> n >> s; string s_ord = s; sort(s_ord.begin(), s_ord.end()); int ans = 0; for (int i = 0; i < n; i++) ans += (s[i] != s_ord[i]); cout << ans << "\n"; } ...
1552
B
Running for Gold
The Olympic Games have just started and Federico is eager to watch the marathon race. There will be $n$ athletes, numbered from $1$ to $n$, competing in the marathon, and all of them have taken part in $5$ important marathons, numbered from $1$ to $5$, in the past. For each $1\le i\le n$ and $1\le j\le 5$, Federico re...
Solution 1 First of all, observe that athlete $i$ is superior to athlete $j$ if and only if athlete $j$ is not superior to athlete $i$. The issue is, of course, that we cannot iterate over all pairs of athletes as there are $\binom{n}{2} = O(n^2)$ pairs, which is too much to fit in the time limit. Notice that there can...
[ "combinatorics", "graphs", "greedy", "sortings" ]
1,500
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define SZ(x) ((int)((x).size())) // Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00. LL get_time() { return chrono::duration_cast<chrono::nanoseconds>( ch...
1552
C
Maximize the Intersections
On a circle lie $2n$ distinct points, with the following property: however you choose $3$ chords that connect $3$ disjoint pairs of points, no point strictly inside the circle belongs to all $3$ chords. The points are numbered $1, \, 2, \, \dots, \, 2n$ in clockwise order. Initially, $k$ chords connect $k$ pairs of po...
Let us forget about the original labeling of the points. Relabel the $2(n - k)$ "free" points $1, \, 2, \, \dots, \, 2(n - k)$ in clockwise order, starting from an arbitrary point. Also, in the following, we will color black the original $k$ chords, and red the additional $n - k$ chords. For $1 \le i \le n - k$, connec...
[ "combinatorics", "constructive algorithms", "geometry", "greedy", "sortings" ]
1,800
#include <iostream> #include <vector> using namespace std; bool intersect(pair<int, int> c, pair<int, int> d) { if (c.first > d.first) swap(c, d); return c.second > d.first and c.second < d.second; } void solve() { int n, k; cin >> n >> k; vector<pair<int, int>> chords; vector<bool> used...
1552
D
Array Differentiation
You are given a sequence of $n$ integers $a_1, \, a_2, \, \dots, \, a_n$. Does there exist a sequence of $n$ integers $b_1, \, b_2, \, \dots, \, b_n$ such that the following property holds? - For each $1 \le i \le n$, there exist two (not necessarily distinct) indices $j$ and $k$ ($1 \le j, \, k \le n$) such that $a_...
Suppose that a solution $b_1, \, \dots, \, b_n$ exists. For each $1 \le i \le n$, let $j_i, \, k_i$ be the indices such that $a_i = b_{j_i} - b_{k_i}$. Consider the directed graph on vertices $1, \, \dots, \, n$, with the $n$ edges $j_i \rightarrow k_i$. If we ignore, for a moment, the orientations, we are left with an...
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dp", "graphs", "math" ]
1,800
#include <iostream> #include <vector> using namespace std; void solve() { int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; i++) cin >> a[i]; int three2n = 1; for (int i = 1; i <= n; i++) three2n *= 3; for (int k = 1; k < three2n; k++) { int k_cp = k; ...
1552
E
Colors and Intervals
The numbers $1, \, 2, \, \dots, \, n \cdot k$ are colored with $n$ colors. These colors are indexed by $1, \, 2, \, \dots, \, n$. For each $1 \le i \le n$, there are exactly $k$ numbers colored with color $i$. Let $[a, \, b]$ denote the interval of integers between $a$ and $b$ inclusive, that is, the set $\{a, \, a + ...
Solution 1 We describe the algorithm and later we explain why the construction works. Let $x_{i, j}$ ($1 \le i \le n$, $1 \le j \le k$) denote the position of the $j$-th occurrence of color $i$ (from the left). First, sort the colors according to $x_{i, 2}$. Take the first $\left\lceil \frac{n}{k - 1} \right\rceil$ col...
[ "constructive algorithms", "data structures", "greedy", "sortings" ]
2,300
#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; struct Interval { int a, b; int color; Interval(int _a, int _b, int _color): a(_a), b(_b), color(_color) {} bool operator <(const Interval other) { return b < other.b; } }; void s...
1552
F
Telepanting
An ant moves on the real line with constant speed of $1$ unit per second. It starts at $0$ and always moves to the right (so its position increases by $1$ each second). There are $n$ portals, the $i$-th of which is located at position $x_i$ and teleports to position $y_i < x_i$. Each portal can be either active or ina...
Solution 1 The key insight is realizing that, if at some point the ant is located at position $x$, then all the portals with $x_i < x$ are active. One can prove this by induction on the time $t$. Indeed, when $t = 0$, $x = 0$ and there are no portals with $x_i < x$. Now suppose this is true at time $t$, and let $x$ be ...
[ "binary search", "data structures", "dp", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 1996488706 #define hmod 998244353 #define maxn 200010 ll i, i1, j, k, k1, t, n, m, res, flag[10], a, b; ll x[maxn], y[maxn], s[maxn], dp[maxn...
1552
G
A Serious Referee
Andrea has come up with what he believes to be a novel sorting algorithm for arrays of length $n$. The algorithm works as follows. Initially there is an array of $n$ integers $a_1,\, a_2,\, \dots,\, a_n$. Then, $k$ steps are executed. For each $1\le i\le k$, during the $i$-th step the subsequence of the array $a$ wit...
Let us say that an array of $n$ integers is good if it is sorted by Andrea's algorithm, and bad otherwise. First of all, we state and prove the following intuitive fact (which is well-known for sorting networks): Lemma. (Zero-One Principle) All arrays $a$ with values in $\{0, \, 1\}$ are good if and only if all arrays ...
[ "bitmasks", "brute force", "dfs and similar", "sortings" ]
3,000
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define SZ(x) ((int)((x).size())) // Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00. LL get_time() { return chrono::duration_cast<chrono::nanoseconds>( ch...