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
1290
D
Coffee Varieties (hard version)
This is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee. \textbf{This is an interactive problem.} You're considering moving to another city, where one of your friends already lives. There are...
Easy version (constant 2) Let's try to maintain representative positions for each value. In the beginning, when we know nothing, every position can be a potential representative. We will call them alive positions, and using queries, we will try to kill some positions and ending up with exactly one alive position per va...
[ "constructive algorithms", "graphs", "interactive" ]
3,000
#include <bits/stdc++.h> using namespace std; bool ask(int pos) { cout << "? " << pos+1 << endl << flush; char c; cin >> c; if (c == 'E') exit(0); return (c == 'Y'); } int main() { int nbElem, memSize, nbBlocks; cin >> nbElem >> memSize; nbBlocks = nbElem / memSize; vector<bool> isAli...
1290
E
Cartesian Tree
Ildar is the algorithm teacher of William and Harris. Today, Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William. A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: - If the sequence is empty...
Instead of inserting numbers one by one, let's imagine I have $n$ blanks in a row, and I will fill the blanks with integers from $[1,n]$ in order, and I want to know about the cartesian tree after each blank filled. In the following parts of the solution, I will use positions in the original array instead of positions ...
[ "data structures" ]
3,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=3e5+1; const int ts=1<<21; int n; ll mx[ts],se[ts],mxc[ts];//max, 2nd max, max count int sz; ll ch[N];//which values are changed ll df[N];//change in frequency void pass(int id,int c){ if(mx[c]>mx[id]) mx[c]=mx[id]; } void push(int id){ ...
1290
F
Making Shapes
You are given $n$ pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion: - Start at the origin $(0, 0)$. - Choose a vector and add the segment of the vector to the current point. For example, if your current point is at $(x, y)$ and...
Notice that there is a one-to-one correspondent between a non-degenerate convex shape and a non-empty multiset of vectors. That is because, for each shape, we can generate exactly one multiset of vectors by starting at the lowest-leftest point going counter-clockwise (this is possible because no two vectors are paralle...
[ "dp" ]
3,500
#include <bits/stdc++.h> using namespace std; const int N = 5, MX = 4 * N, LG = 31, MOD = 998244353; int n, m, x[N], y[N]; int px[1 << N], nx[1 << N], py[1 << N], ny[1 << N]; int dp[LG][MX][MX][MX][MX][2][2]; void add(int &x, int y) { x += y; if (x >= MOD) { x -= MOD; } } int main() { ios_ba...
1291
A
Even But Not Even
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by $2$ but the number itself is not divisible by $2$. For example, $13$, $1227$, $185217$ are ebne numbers, while $12$, $2$, $177013$, $265918$ are not. If you're still unsure what ebne numbers are, you can look at the sample n...
If the number of odd digits is smaller than or equal to $1$, it is impossible to create an ebne number. Otherwise, we can output any 2 odd digits of the number (in correct order of course).
[ "greedy", "math", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; int odd = 0; for (char c : s) if ((c - '0') & 1) odd++; if (odd <= 1) { cout << "-1\n"; ...
1291
B
Array Sharpening
You're given an array $a_1, \ldots, a_n$ of $n$ non-negative integers. Let's call it sharpened if and only if there exists an integer $1 \le k \le n$ such that $a_1 < a_2 < \ldots < a_k$ and $a_k > a_{k+1} > \ldots > a_n$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: ...
How to know if we can make the prefix $[1 ; k]$ strictly increasing? We just have to consider the following simple greedy solution: take down values to $0, 1, \ldots, k-1$ (minimal possible values). It's possible if and only if $a_i \ge i-1$ holds in the whole prefix. Similarly, the suffix $[k ; n]$ can be made strictl...
[ "greedy", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int nbTests; cin >> nbTests; while (nbTests--) { int nbElem; cin >> nbElem; vector<int> tab(nbElem); for (int i = 0; i < nbElem; ++i) cin >> tab[i]; int prefixEnd = -1, suffixEnd...
1292
A
NEKO's Maze Game
\begin{quote} 3R2 as DJ Mashiro - Happiness Breeze \end{quote} \begin{quote} Ice - DJ Mashiro is dead or alive \end{quote} NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a $2 \times n$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $(1, 1)$ to the...
The main observation is that, it is possible to travel from $(1, 1)$ to $(2, n)$ if and only if there exist no pair of forbidden cell $(1, a)$ and $(2, b)$ such that $|a - b| \le 1$. Therefore, to answer the query quickly, for every $d$ from $-1$ to $1$, one should keep track of the number of pair $(a, b)$ such that: $...
[ "data structures", "dsu", "implementation" ]
1,400
T = 1 for test_no in range(T): n, q = map(int, input().split()) lava = [[0 for j in range(n)] for i in range(2)] blockedPair = 0 while q > 0: q -= 1 x, y = map(lambda s: int(s)-1, input().split()) delta = +1 if lava[x][y] == 0 else -1 lava[x][y] = 1 - lava[x][y] for dy in range(-1, 2): if y + dy >= 0...
1292
B
Aroma's Search
\begin{quote} THE SxPLAY & KIVΛ - 漂流 \end{quote} \begin{quote} KIVΛ & Nikki Simmons - Perspectives \end{quote} With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space. The space can be considered a 2D plane, with an infinite number of data no...
First, keep a list of "important" nodes (nodes that are reachable from the starting point with $t$ seconds), and denote this list $[(x_1, y_1), (x_2, y_2), \ldots, (x_k, y_k)]$. Since $a_x, a_y \geq 2$, there are no more than $\log_2(t)$ important nodes (in other words, $k \leq \log_2(t))$. In an optimal route, we must...
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
1,700
T = 1 for test_no in range(T): x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) LIMIT = 2 ** 62 - 1 x, y = [x0], [y0] while ((LIMIT - bx) / ax >= x[-1] and (LIMIT - by) / ay >= y[-1]): x.append(ax * x[-1] + bx) y.append(ay * y[-1] + by) n = len(x) ans = 0 for i in ...
1292
C
Xenon's Attack on the Gangs
\begin{quote} INSPION FullBand Master - INSPION \end{quote} \begin{quote} INSPION - IOLITE-SUNSTONE \end{quote} On another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hac...
The first observation is that, the formula can be rewritten as: $S = \sum_{1 \leq u < v \leq n} mex(u, v) = \sum_{1 \leq x \leq n} \left( \sum_{mex(u, v) = x} x \right) = \sum_{1 \leq x \leq n} \left( \sum_{mex(u, v) \geq x} 1 \right) = \sum_{1 \leq x \leq n} f(x)$ Where $f(x)$ is number of pairs $(u, v)$ such that $1 ...
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
2,300
import sys # Read input and build the graph inp = [int(x) for x in sys.stdin.buffer.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) # Relabel to speed up n^2 ope...
1292
D
Chaotic V.
\begin{quote} Æsir - CHAOS \end{quote} \begin{quote} Æsir - V. \end{quote} "Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect. The time right now...... 00:01:12...... It's time." The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake ...
First of all, one can see that the network is a tree rooted at vertex $1$, thus for each pair of vertices in it there can only be one simple path. Also, the assembly node $P$ must be on at least one simple path of a fragment to the root (proof by contradiction, explicit solution is trivial). Let's start with $P$ being ...
[ "dp", "graphs", "greedy", "math", "number theory", "trees" ]
2,700
T = 1 for test_no in range(T): MAXK = 5000 n = int(input()) cnt = [0] * (MAXK + 1) primeExponential = [[0 for j in range(MAXK + 1)] for i in range(MAXK + 1)] line, num = (input() + ' '), 0 for c in line: if c != ' ': num = num * 10 + (ord(c) - 48) else: cnt[num] += 1 num = 0 for i in range(2, MAXK + ...
1292
E
Rin and The Unknown Flower
\begin{quote} MisoilePunch♪ - 彩 \end{quote} This is an interactive problem! On a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar. After much analysis, she now realizes that this artifact contains data about a strange flower, which has exis...
To be fair, this is a complicated decision tree problem. I recommend instead of heading straight to read the main solutions for this, try to spend some time and come up with at least 2 solutions for the case when the query limit is 5/3 first. <spoilers> There are many solutions when limit = 5/3, and I'll point 2 of the...
[ "constructive algorithms", "greedy", "interactive", "math" ]
3,500
import sys n, L, minID = None, None, None s = [] def fill(id, c): global n, L, s, minID L -= (s[id] == 'L') s = s[0:id] + c + s[id+1:] minID = min(minID, id) def query(cmd, str): global n, L, s, minID print(cmd, ''.join(str)) print(cmd, ''.join(str), file=sys.stderr) sys.stdout.flush() if (cmd == '?'): res...
1292
F
Nora's Toy Boxes
\begin{quote} SIHanatsuka - EMber \end{quote} \begin{quote} SIHanatsuka - ATONEMENT \end{quote} Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities. One day, Nora's adoptive father, Phoenix Wyle, brought Nora $n$ boxes of toys. B...
We consider a directed graph $G$, where we draw an edge from vertex $i$ to vertex $j$ if $a_i \mid a_j$. Notice that $G$ is a DAG and is transitive (if $(u, v), (v, w) \in G$ then $(u, w) \in G$). For each vertex, we consider two states: "on" (not deleted) and "off" (deleted). An edge is "on" if both end vertices are n...
[ "bitmasks", "combinatorics", "dp" ]
3,500
MOD = 1000000007 def isSubset(a, b): return (a & b) == a def isIntersect(a, b): return (a & b) != 0 # Solve for each weakly connected component (WCC) def cntOrder(s, t): p = len(s) m = len(t) inMask = [0 for i in range(m)] for x in range(p): for i in range(m): if t[i] % s[x] == 0: inMask[i] |= 1 ...
1293
A
ConneR and the A.R.C. Markland-N
\begin{quote} Sakuzyo - Imprinting \end{quote} A.R.C. Markland-N is a tall building with $n$ floors numbered from $1$ to $n$. Between each two adjacent floors in the building, there is a staircase connecting them. It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his m...
Since there's only $k$ closed restaurants, in the worst case we'll only have to walk for $k$ staircases only (one such case would be $s = n$ and all the restaurants from floor $s-k+1$ to $s$ are closed). Therefore, a brute force solution is possible: try out every distance $x$ from $0$ to $k$. For each, determine if ei...
[ "binary search", "brute force", "implementation" ]
1,100
T = int(input()) for test_no in range(T): n, s, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(0, k+1): if s-i >= 1 and not s-i in a: print(i); break if s+i <= n and not s+i in a: print(i); break else: assert(False) # if reached this line, the solution failed to find a ...
1293
B
JOE is on TV!
\begin{quote} 3R2 - Standby for Action \end{quote} Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. $n$"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JO...
This is a greedy problem, with the optimal scenario being each question eliminating a single opponent. It is easy to see that we will want each question to eliminate one opponent only, since after each elimination, the ratio $t/s$ will be more and more rewarding (as $s$ lowers overtime) - as a result, each elimination ...
[ "combinatorics", "greedy", "math" ]
1,000
T = 1 for test_no in range(T): n = int(input()) ans = sum([1.0 / i for i in range(1, n+1)]) print(ans)
1294
A
Collecting Coins
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $a$ coins, Barbara has $b$ coins and Cerene has $c$ coins. Recently Polycarp has returned from the trip around the world and brought $n$ coins. He wants to distribute \textbf{all} these $n$ coins between his sisters ...
Suppose $a \le b \le c$. If it isn't true then let's rearrange our variables. Then we need at least $2c - b - a$ coins to make $a$, $b$ and $c$ equal. So if $n < 2c - b - a$ then the answer is "NO". Otherwise, the answer if "YES" if the number $n - (2c - b - a)$ is divisible by $3$. This is true because after making $a...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int a[3], n; cin >> a[0] >> a[1] >> a[2] >> n; sort(a, a + 3); n -= 2 * a[2] - a[1] - a[0]; if (n < 0 ...
1294
B
Collecting Packages
There is a robot in a warehouse and $n$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $(0, 0)$. The $i$-th package is at the point $(x_i, y_i)$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that th...
It is obvious that if there is a pair of points $(x_i, y_i)$ and $(x_j, y_j)$ such that $x_i < x_j$ and $y_i > y_j$ then the answer is "NO". It means that if the answer is "YES" then there is some ordering of points such that $x_{i_1} \le x_{i_2} \le \dots \le x_{i_n}$ and $y_{i_1} \le y_{i_2} \le \dots \le y_{i_n}$ be...
[ "implementation", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; for (int tt = 0; tt < t; tt++) { int n; cin >> n; vector<pair<int, int>> a(n); for (int i = 0; i < n; ++i) { ...
1294
C
Product of Three Numbers
You are given one integer number $n$. Find three \textbf{distinct integers} $a, b, c$ such that $2 \le a, b, c$ and $a \cdot b \cdot c = n$ or say that it is impossible to do it. If there are several answers, you can print any. You have to answer $t$ independent test cases.
Suppose $a < b < c$. Let's try to minimize $a$ and maximize $c$. Let $a$ be the minimum divisor of $n$ greater than $1$. Then let $b$ be the minimum divisor of $\frac{n}{a}$ that isn't equal $a$ and $1$. If $\frac{n}{ab}$ isn't equal $a$, $b$ and $1$ then the answer is "YES", otherwise the answer is "NO". Time complexi...
[ "greedy", "math", "number theory" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; cin >> n; set<int> used; for (int i = 2; i * i <= n; ++i) { if (n % i == 0 && !used.count(i)) ...
1294
D
MEX maximizing
Recall that \textbf{MEX} of an array is a \textbf{minimum non-negative integer} that does not belong to the array. Examples: - for the array $[0, 0, 1, 0, 2]$ MEX equals to $3$ because numbers $0, 1$ and $2$ are presented in the array and $3$ is the minimum non-negative integer not presented in the array; - for the ar...
Firstly, let's understand what the operation does. It changes the element but holds the remainder modulo $x$. So we can consider all elements modulo $x$. Let $cnt_0$ be the number of elements with the value $0$ modulo $x$, $cnt_1$ be the number of elements with the value $1$ modulo $x$, and so on. Let's understand, whe...
[ "data structures", "greedy", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q, x; cin >> q >> x; vector<int> mods(x); set<pair<int, int>> vals; for (int i = 0; i < x; ++i) { vals.insert(make_pair(mods[i], i)); } for (int ...
1294
E
Obtain a Permutation
You are given a rectangular matrix of size $n \times m$ consisting of integers from $1$ to $2 \cdot 10^5$. In one move, you can: - choose \textbf{any element} of the matrix and change its value to \textbf{any} integer between $1$ and $n \cdot m$, inclusive; - take \textbf{any column} and shift it one cell up cyclical...
At first, let's decrease all elements by one and solve the problem in $0$-indexation. The first observation is that we can solve the problem independently for each column. Consider the column $j$ $(j \in [0; m-1])$. It consists of elements $[j; m + j, 2m + j, \dots, (n-1)m + j]$. Now consider some element $a_{i, j}$ $(...
[ "greedy", "implementation", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> a[i][j]; --a[i][...
1294
F
Three Paths on a Tree
You are given an unweighted tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles. Your task is to choose \textbf{three distinct} vertices $a, b, c$ on this tree such that the number of edges which belong to \textbf{at least} one of the simple paths between $a$ and $b$, $b$ and $c$,...
There is some obvious dynamic programming solution that someone can describe in the comments, but I will describe another one, that, in my opinion, much easier to implement. Firstly, let's find some diameter of the tree. Let $a$ and $b$ be the endpoints of this diameter (and first two vertices of the answer). You can p...
[ "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; #define x first #define y second vector<int> p; vector<vector<int>> g; pair<int, int> dfs(int v, int par = -1, int dist = 0) { p[v] = par; pair<int, int> res = make_pair(dist, v); for (auto to : g[v]) { if (to == par) continue; res = max(res, dfs(to, v, dist + 1)...
1295
A
Display The Number
You have a large electronic screen which can display up to $998244353$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $7$ segments which can be turned on and off to compose different digits. The following picture describes how you can...
First of all, we don't need to use any digits other than $1$ and $7$. If we use any other digit, it consists of $4$ or more segments, so it can be replaced by two $1$'s and the number will become greater. For the same reason we don't need to use more than one $7$: if we have two, we can replace them with three $1$'s. O...
[ "greedy" ]
900
t = int(input()) for i in range(t): n = int(input()) if(n % 2 == 1): print(7, end='') n -= 3 while(n > 0): print(1, end='') n -= 2 print()
1295
B
Infinite Prefixes
You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \dots$ For example, if $s =$ 10010, then $t =$ 100101001010010... Calculate the number of prefixes of $t$ with balance equal to $x$. The balance of so...
Let's denote a prefix of length $i$ as $pref(i)$. We can note that each $pref(i) = k \cdot pref(n) + pref(i \mod n)$ where $k = \left\lfloor \frac{i}{n} \right\rfloor$ and $+$ is a concatenation. Then balance $bal(i)$ of prefix of length $i$ is equal to $k \cdot bal(n) + bal(i \mod n)$. Now there two cases: $bal(n)$ is...
[ "math", "strings" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long li; int n, x; string s; inline bool read() { if(!(cin >> n >> x >> s)) return false; return true; } inline void solve() { int ans = 0; bool infAns = false; int cntZeros = (int)count(s.begin(), s.end(), '0'); int total = cntZeros - (n - cntZer...
1295
C
Obtain The String
You are given two strings $s$ and $t$ consisting of lowercase Latin letters. Also you have a string $z$ which is initially empty. You want string $z$ to be equal to string $t$. You can perform the following operation to achieve this: append any subsequence of $s$ at the end of string $z$. A subsequence is a sequence th...
The answer is $-1$ when in string $t$ there is a character that is not in string $s$. Otherwise let's precalculate the following array $nxt_{i, j}$ = minimum index $x$ from $i$ to $|s|$ such that $s_x = j$ (if there is no such index then $nxt_{i, j} = inf$). Now we can solve this problem by simple greed. Presume that n...
[ "dp", "greedy", "strings" ]
1,600
#include<bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; const int INF = int(1e9) + 99; int tc; string s, t; int nxt[N][26]; int main() { cin >> tc; while(tc--){ cin >> s >> t; for(int i = 0; i < s.size() + 5; ++i) for(int j = 0; j < 26; ++j) nxt[i...
1295
D
Same GCDs
You are given two integers $a$ and $m$. Calculate the number of integers $x$ such that $0 \le x < m$ and $\gcd(a, m) = \gcd(a + x, m)$. Note: $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$.
The Euclidean algorithm is based on the next fact: if $a \ge b$ then $\gcd(a, b) = \gcd(a - b, b)$. So, if $(a + x) \ge m$ then $\gcd(a + x, m) = \gcd(a + x - m, m)$. So we can declare that we are looking at $m$ different integers $x' = (a + x) \mod m$ with $0 \le x' < m$, so all $x'$ forms a segment $[0, m - 1]$. So, ...
[ "math", "number theory" ]
1,800
fun gcd(a : Long, b : Long) : Long { return if (a == 0L) b else gcd(b % a, a) } fun phi(a : Long) : Long { var (tmp, ans) = listOf(a, a) var d = 2L while (d * d <= tmp) { var cnt = 0 while (tmp % d == 0L) { tmp /= d cnt++ } if (cnt > 0) ans -= ans ...
1295
E
Permutation Separation
You are given a permutation $p_1, p_2, \dots , p_n$ (an array where each integer from $1$ to $n$ appears exactly once). The weight of the $i$-th element of this permutation is $a_i$. At first, you separate your permutation into two \textbf{non-empty} sets — prefix and suffix. More formally, the first set contains elem...
"All elements in the left set smaller than all elements in the right set" means that there is such value $val$ that all elements from the first set less than $val$ and all elements from the second set are more or equal to $val$. So let's make a sweep line on $val$ from $1$ to $n + 1$ while trying to maintain all answer...
[ "data structures", "divide and conquer" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = int(2e5) + 99; int n; int p[N]; int rp[N]; int a[N]; long long b[N]; long long t[4 * N]; long long add[4 * N]; void build(int v, int l, int r){ if(r - l == 1){ t[v] = b[l]; return; } int mid = (l + r) / 2; build(v * 2 + 1, l, mid); build(v * 2 + ...
1295
F
Good Contest
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $n$ problems; and since the platform is very popular, $998244351$ coder from all over the world is going to solve them. For each problem, the authors estimated the number of people who would solve it...
Model solution (slow, complicated and not cool): The naive solution is dynamic programming: let $dp_{i, x}$ be the probability that the first $i$ problems don't have any inversions, and the $i$-th one got $x$ accepted solutions. Let's somehow speed it up. For convenience, I will modify the variable denoting the maximum...
[ "combinatorics", "dp", "probabilities" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y &...
1296
A
Array with Odd Sum
You are given an array $a$ consisting of $n$ integers. In one move, you can choose two indices $1 \le i, j \le n$ such that $i \ne j$ and set $a_i := a_j$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of ass...
Firstly, if the array already has an odd sum, the answer is "YES". Otherwise, we need to change the parity of the sum, so we need to change the parity of some number. We can do in only when we have at least one even number and at least one odd number. Otherwise, the answer is "NO".
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; cin >> n; int sum = 0; bool odd = false, even = false; for (int i = 0; i < n; ++i) { int x; cin >> x; ...
1296
B
Food Buying
Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some \textbf{positive integer number} $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burle...
Let's do the following greedy solution: it is obvious that when we buy food that costs exactly $10^k$ for $k \ge 1$, we don't lose any burles because of rounding. Let's take the maximum power of $10$ that is not greater than $s$ (let it be $10^c$), buy food that costs $10^c$ (and add this number to the answer) and add ...
[ "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int s; cin >> s; int ans = 0; int pw = 1000 * 1000 * 1000; while (s > 0) { while (s < pw) pw /= 10; ans += pw; ...
1296
C
Yet Another Walking Robot
There is a robot on a coordinate plane. Initially, the robot is located at the point $(0, 0)$. Its path is described as a string $s$ of length $n$ consisting of characters 'L', 'R', 'U', 'D'. Each of these characters corresponds to some move: - 'L' (left): means that the robot moves from the point $(x, y)$ to the poi...
Formally, the problem asks you to remove the shortest cycle from the robot's path. Because the endpoint of the path cannot be changed, the number of 'L's should be equal to the number of 'R's and the same with 'U' and 'D'. How to find the shortest cycle? Let's create the associative array $vis$ (std::map for C++) which...
[ "data structures", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n; string s; cin >> n >> s; int l = -1, r = n; map<pair<int, int>, int> vis; pair<int, int> cur = {0, 0}; vis[...
1296
D
Fight with Monsters
There are $n$ monsters standing in a row numbered from $1$ to $n$. The $i$-th monster has $h_i$ health points (hp). You have your attack power equal to $a$ hp and your opponent has his attack power equal to $b$ hp. You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monste...
Let's calculate the minimum number of secret technique uses we need to kill each of the monsters. Let the current monster has $h$ hp. Firstly, it is obvious that we can take $h$ modulo $a+b$ (except one case). If it becomes zero, let's "rollback" it by one pair of turns. Then the number of uses of the secret technique ...
[ "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, a, b, k; cin >> n >> a >> b >> k; vector<int> h(n); for (int i = 0; i < n; ++i) { cin >> h[i]; h[i] %= a + b; if (h[i] == 0) h[i] += a + b; h[i...
1296
E1
String Coloring (easy version)
\textbf{This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different}. You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to color \textbf{all} its char...
Note that the actual problem is to divide the string into two subsequences that both of them are non-decreasing. You can note that this is true because you cannot the relative order of the elements colored in the same color, but you can write down subsequences of different colors in any order you want. In this problem,...
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; string res; char lst0 = 'a', lst1 = 'a'; for (int i = 0; i < n; ++i) { if (s[i] >= lst0) { res += '0'; lst0 = s[i]; ...
1296
E2
String Coloring (hard version)
\textbf{This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different}. You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to color \textbf{all} its chara...
The solution of this problem is based on Dilworth's theorem. You can read about it on Wikipedia. In two words, this theorem says that the minimum number of non-decreasing sequences we need to cover the whole sequence equals the length of longest decreasing subsequence. Let's calculate the dynamic programming $dp_i$ - t...
[ "data structures", "dp" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; vector<int> maxdp(26); vector<int> dp(n, 1); for (int i = 0; i < n; ++i) { for (int c = 25; c > s[i] - 'a'; --c) { dp...
1296
F
Berland Beauty
There are $n$ railway stations in Berland. They are connected to each other by $n-1$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the $n-1$ sections has some i...
Firstly, let's precalculate $n$ arrays $p_1, p_2, \dots, p_n$. The array $p_v$ is the array of "parents" if we run dfs from the vertex $v$. So, $p_{v, u}$ is the vertex that is the previous one before $u$ on the directed path $(v, u)$. This part can be precalculated in time $O(n^2)$ and we need it just for convenience....
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> val; vector<vector<pair<int, int>>> g; void dfs(int v, int pv, int pe, vector<pair<int, int>> &p) { p[v] = make_pair(pv, pe); for (auto it : g[v]) { int to = it.first; int idx = it.second; if (to == pv) continue; dfs(to, v, idx, p); } } ...
1299
A
Anu Has a Function
Anu has created her own function $f$: $f(x, y) = (x | y) - y$ where $|$ denotes the bitwise OR operation. For example, $f(11, 6) = (11|6) - 6 = 15 - 6 = 9$. It can be proved that for any nonnegative numbers $x$ and $y$ value of $f(x, y)$ is also nonnegative. She would like to research more about this function and has ...
If you work on the bits, you may see $f(a, b)$ can easily be written as $a \& (\sim b)$. And so, value of an array $[a_1, a_2, \dots, a_n]$ would be $a_1 \& (\sim a_2) \& \dots (\sim a_n)$, meaning that if we are to reorder, only the first element matters. By keeping prefix and suffix $AND$ after we apply $\sim$ to the...
[ "brute force", "greedy", "math" ]
1,500
null
1299
B
Aerodynamic
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a \textbf{strictly convex} (i. e. no three points are collinear) polygon $P$ which is defined by coordinates of its vertices. Define $P(x,y)$ as a polygon obtained by translating $P$ by vector $\overrightarrow {(x,y)}$. The picture below depict...
$T$ has the central symmetry: indeed, if $P(x,y)$ covers $(0,0)$ and $(x_0,y_0)$ then $P(x-x_0,y-y_0)$ covers $(-x_0,-y_0)$ and $(0,0)$. So the answer for polygons which don't have the sentral symmetry is NO. Let's prove if $P$ has the central symmetry then the answer is YES. Translate $P$ in such a way that the origin...
[ "geometry" ]
1,800
null
1299
C
Water Balance
There are $n$ water tanks in a row, $i$-th of them contains $a_i$ liters of water. The tanks are numbered from $1$ to $n$ from left to right. You can perform the following operation: choose some subsegment $[l, r]$ ($1\le l \le r \le n$), and redistribute water in tanks $l, l+1, \dots, r$ evenly. In other words, repla...
Let's try to make the operation simpler. When we apply the operation, only the sum of the segment matters. And so let's instead define the operation on prefix sum array: Replace each of $p_l, p_{l+1}, \dots, p_r$ by $p_i = p_{l-1} + \frac{p_r - p_{l - 1} }{r-l+1} \cdot (i - l + 1)$. You may see how similar it is to a l...
[ "data structures", "geometry", "greedy" ]
2,100
null
1299
D
Around the World
Guy-Manuel and Thomas are planning $144$ trips around the world. You are given a simple weighted undirected connected graph with $n$ vertexes and $m$ edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than $3$ which ...
It's common knowledge that in an undirected graph there is some subset (not necessarily unique) of simple cycles called basis such that any Eulerian subgraph (in connected graphs also known as a cyclic path) is a xor-combination of exactly one subset of basis cycles. In a given connected graph consider any spanning tre...
[ "bitmasks", "combinatorics", "dfs and similar", "dp", "graphs", "math", "trees" ]
3,000
null
1299
E
So Mean
\textbf{This problem is interactive}. We have hidden a permutation $p_1, p_2, \dots, p_n$ of numbers from $1$ to $n$ from you, where $n$ \textbf{is even}. You can try to guess it using the following queries: $?$ $k$ $a_1$ $a_2$ $\dots$ $a_k$. In response, you will learn if the average of elements with indexes $a_1, ...
Let's solve this problem in several steps. First, let's ask a query about each group of $n-1$ numbers. Note that $1 + 2 + \dots + (i-1) + (i+1) + \dots + n = \frac{n(n+1)}{2} - i \equiv \frac{1\cdot 2}{2} - i \bmod (n-1)$. Therefore, answer will be YES only for numbers $1$ and $n$. Find the positions where $1$ and $n$ ...
[ "interactive", "math" ]
3,400
null
1300
A
Non-zero
Guy-Manuel and Thomas have an array $a$ of $n$ integers [$a_1, a_2, \dots, a_n$]. In one step they can add $1$ to any element of the array. Formally, in one step they can choose any integer index $i$ ($1 \le i \le n$) and do $a_i := a_i + 1$. If either the sum or the product of all elements in the array is equal to ze...
While there are any zeros in the array, the product will be zero, so we should add $1$ to each zero. Now, if the sum is zero, we should add $1$ to any positive number, so the sum becomes nonzero. So the answer is the number of zeroes in the array plus $1$ if the sum of numbers is equal to zero after adding $1$ to zeros...
[ "implementation", "math" ]
800
null
1300
B
Assigning to Classes
\textbf{Reminder: the median} of the array $[a_1, a_2, \dots, a_{2k+1}]$ of odd number of elements is defined as follows: let $[b_1, b_2, \dots, b_{2k+1}]$ be the elements of the array in the sorted order. Then median of this array is equal to $b_{k+1}$. There are $2n$ students, the $i$-th student has skill level $a_i...
Let's sort the array. From now on, $a_1 \le a_2 \dots \le a_{2n}$. Consider any partition. Suppose that the first class has $2k+1$ students, and the skill level of this class is $a_i$, and the second class had $2l+1$ students, and the skill level of this class is $a_j$, where $(2k + 1) + (2l + 1) = 2n \implies k + l = ...
[ "greedy", "implementation", "sortings" ]
1,000
null
1301
A
Three Strings
You are given three strings $a$, $b$ and $c$ of the same length $n$. The strings consist of lowercase English letters only. The $i$-th letter of $a$ is $a_i$, the $i$-th letter of $b$ is $b_i$, the $i$-th letter of $c$ is $c_i$. For every $i$ ($1 \leq i \leq n$) you \textbf{must} swap (i.e. exchange) $c_i$ with either...
For every $i$ $(1 \leq i \leq n)$ where $n$ is the length of the strings. If $c_i$ is equal to $a_i$ we can swap it with $b_i$ or if $c_i$ is equal to $b_i$ we can swap it with $a_i$, otherwise we can't swap it. So we only need to check that $c_i$ is equal $a_i$ or $c_i$ is equal to $b_i$. Complexity is $O(n)$.
[ "implementation", "strings" ]
800
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000000\n#define mod 998244353\nconst int N = 500000;\nstring a , b , c;\n\nvoid solve(){\n cin >> a >> b >> c;\n for(int i = 0 ;i < (int)a.size();i++){\n if(c[i] != a[i] && c[i] != b[i]){\n puts(\"NO\");\n return;\n ...
1301
B
Motarack's Birthday
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $a$ of $n$ non-negative integers. Dark created that array $1000$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with ...
Let's take all non missing elements that are adjacent to at least one missing element, we need to find a value $k$ that minimises the maximum absolute difference between $k$ and these values. The best $k$ is equal to (minimum value + maximum value) / 2. Then we find the maximum absolute difference between all adjacent ...
[ "binary search", "greedy", "ternary search" ]
1,500
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000010\n#define mod 1000000007\nconst int N = 300010;\nint n , arr[N] ; \n\nvoid solve(){\n int mn = oo , mx = -oo;\n\tscanf(\"%d\",&n);\n\tfor(int i=0;i<n;i++){\n\t\tscanf(\"%d\",&arr[i]);\n\t}\n\tfor(int i = 0;i<n;i++){\n\t\tif(i > 0 && arr[i] == -1 &...
1301
C
Ayoub's function
Ayoub thinks that he is a very smart person, so he created a function $f(s)$, where $s$ is a binary string (a string which contains only symbols "0" and "1"). The function $f(s)$ is equal to the number of substrings in the string $s$ that contains at least one symbol, that is equal to "1". More formally, $f(s)$ is equ...
We can calculate the number of sub-strings that has at least one symbol equals to "1" like this: $f(s)$ $=$ (number of all sub-strings) $-$ (number of sub-strings that doesn't have any symbol equals to "1"). if the size of $s$ is equal to $n$, $f(s)$ $=$ $\frac{n\cdot(n+1)}{2}$ $-$ (number of sub-strings that doesn't h...
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
1,700
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000010\n#define mod 1000000007\nconst int N = 1010;\n\n\nvoid solve(){\n\tint n , m;\n\tscanf(\"%d%d\",&n,&m);\n\tlong long ans = (long long)n * (long long)(n + 1) / 2LL;\n\tint z = n - m;\n\tint k = z / (m + 1);\n\tans -= (long long)(m + 1) * (long long)k...
1301
D
Time to Run
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he sh...
A strategy that guarantees that you can visit all the edges exactly once: 1- keep going right until you reach the last column in the first row. 2- keep going left until you reach the first column in the first row again. 3- go down. 4- keep going right until you reach the last column in the current row. 5- keep going {u...
[ "constructive algorithms", "graphs", "implementation" ]
2,000
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000000\n#define mod 998244853\nconst int N = 100010;\n\nvector< pair< int , string > > v , v2;\n\nint n , m , k , all = 0 , cur;\n\nstring tmp;\n\nvoid fix(vector< pair< int , string > > &v){\n v2 = v;\n v.clear();\n for(int i = 0 ;i < (int)v2.siz...
1301
E
Nanosoft
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored w...
For each cell, we will calculate the maximum size of a Nanosoft logo in which it is the bottom right cell, in the top left square. The cell marked with $x$ in this picture: If we had a grid like this: If we take the cell in the second row, second column, it can make a Nanosoft logo with size $4 \times 4$, being the bot...
[ "binary search", "data structures", "dp", "implementation" ]
2,500
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000010\n#define mod 1000000007\nconst int N = 510 , LOG = 10;\nchar grid[N][N];\nint val[N][N] , sum[N][N][4];\nint st[N][N][LOG][LOG] , lg[N];\nint n , q , m , r1 , c1 , r2, c2 , nr , nc;\n\nstring S = \"RGYB\";\nint dr[4] = {0 , 0 , 1 , 1};\nint dc[4] = ...
1301
F
Super Jaber
Jaber is a superhero in a large country that can be described as a grid with $n$ rows and $m$ columns, where every cell in that grid contains a different city. Jaber gave every city in that country a specific color between $1$ and $k$. In one second he can go from the current city to any of the cities adjacent by the ...
In the shortest path between any two cells, you may use an edge that goes from a cell to another one with the same color at least once, or you may not. If you didn't use an edge that goes from a cell to another one with the same color then the distance will be the Manhattan distance. Otherwise you should find the best ...
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
2,600
"#include <bits/stdc++.h>\nusing namespace std;\n#define oo 1000000000\n#define mod 998244353\nconst int N = 1010 , K = 45; \nint n , m , k , r1 , r2 , c1 , c2 , grid[N][N] , ans = 0;\n\nint cost[K][N][N];\nbool done[K];\n\nqueue < pair<int,int> > q;\n\nint dr[4] = {0 , 1 , 0 , -1};\nint dc[4] = {1 , 0 ,-1 , 0};\n\nve...
1303
A
Erasing Zeroes
You are given a string $s$. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may er...
Let's find the first and the last position of $1$-characters (denote them as $l$ and $r$ respectively). Since the can't delete $1$-characters, all $1$-characters between $s_l$ and $s_r$ will remain. So, we have to delete all $0$-characters between $s_l$ and $s_r$.
[ "implementation", "strings" ]
800
for t in range(int(input())): print(input().strip('0').count('0'))
1303
B
National Project
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there ar...
There are two conditions that should be met according to the statement. On the one hand, we should repair the whole highway, so we must spend at least $n$ days to do it. On the other hand, at least half of it should have high-quality pavement or at least $needG = \left\lceil \frac{n}{2} \right\rceil$ units should be la...
[ "math" ]
1,400
fun main() { val t = readLine()!!.toInt() for (tc in 1..t) { val (n, g, b) = readLine()!!.split(' ').map { it.toLong() } val needG = (n + 1) / 2 var totalG = needG / g * (b + g) totalG += if (needG % g == 0L) -b else needG % g println(maxOf(n, totalG)) } }
1303
C
Perfect Keyboard
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $26$ lowercase Latin letters will be arranged in some order. Polycarp uses the same password $s$ on all websites where he is registered (it is bad, but he doesn't c...
The problem can be solved using a greedy algorithm. We will maintain the current layout of the keyboard with letters that have already been encountered in the string, and the current position on the layout. If the next letter of the string is already on the layout, it must be adjacent to the current one, otherwise ther...
[ "dfs and similar", "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i < int(n); ++i) void solve() { string s; cin >> s; vector<bool> used(26); used[s[0] - 'a'] = true; string t(1, s[0]); int pos = 0; ...
1303
D
Fill The Bag
You have a bag of size $n$. Also you have $m$ boxes. The size of $i$-th box is $a_i$, where each $a_i$ is an integer non-negative power of two. You can divide boxes into two parts of equal size. Your goal is to fill the bag completely. For example, if $n = 10$ and $a = [1, 1, 32]$ then you have to divide the box of s...
If $\sum\limits_{i=1}^{n} a_i \ge n$, then the answer is YES, because the just can divide all boxes to size $1$ and then fill the bag. Otherwise the answer is NO. If the answer is YES, let's calculate the minimum number of divisions. Let's consider all boxes from small to large. Presume that now we consider boxes of si...
[ "bitmasks", "greedy" ]
1,900
from math import log2 for t in range(int(input())): n, m = map(int, input().split()) c = [0] * 61 s = 0 for x in map(int, input().split()): c[int(log2(x))] += 1 s += x if s < n: print(-1) continue i, res = 0, 0 while i < 60: if (1<<i)&n != 0: ...
1303
E
Erase Subsequences
You are given a string $s$. You can build new string $p$ from $s$ using the following operation \textbf{no more than two times}: - choose any subsequence $s_{i_1}, s_{i_2}, \dots, s_{i_k}$ where $1 \le i_1 < i_2 < \dots < i_k \le |s|$; - erase the chosen subsequence from $s$ ($s$ can become empty); - concatenate chose...
Let's look at string $t$. Since we should get it using no more than two subsequences, then $t = a + b$ where $a$ is the first subsequence and $b$ is the second one. In the general case, $a$ can be empty. Let iterate all possible lengths of $a$ ($0 \le |a| < |s|$), so we can check the existence of solution for each pair...
[ "dp", "strings" ]
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; const int INF = int(1e9); const li INF64 = li(1e18); string s, t; inline bool read() { if(!(c...
1303
F
Number of Components
You are given a matrix $n \times m$, initially filled with zeroes. We define $a_{i, j}$ as the element in the $i$-th row and the $j$-th column of the matrix. Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected compo...
Note that because of the low constraints on the number of colors, the problem can be solved independently for each color. Now you can divide the queries into two types: add a cell to the field and delete it. You have to maintain the number of components formed by added cells. Cell deletions will occur after all additio...
[ "dsu", "implementation" ]
2,800
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define pb push_back #define mp make_pair #define sqr(a) ((a) * (a)) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i < int(n); ++i) #define fore(i, l, r) for (int i = int(l); i < int...
1303
G
Sum of Prefix Sums
We define the sum of prefix sums of an array $[s_1, s_2, \dots, s_k]$ as $s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + \dots + (s_1 + s_2 + \dots + s_k)$. You are given a tree consisting of $n$ vertices. Each vertex $i$ has an integer $a_i$ written on it. We define the value of the simple path from vertex $u$ to vertex $v$...
Let's use centroid decomposition to solve the problem. We need to process all the paths going through each centroid somehow. Consider a path from vertex $u$ to vertex $v$ going through vertex $c$, which is an ancestor of both $u$ and $v$ in the centroid decomposition tree. Suppose the sequence of numbers on path from $...
[ "data structures", "divide and conquer", "geometry", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; const int N = 150043; typedef pair<long long, long long> func; func T[4 * N]; bool usedT[4 * N]; void clear(int v, int l, int r) { if(!usedT[v]) return; usedT[v] = false; T[v] = make_pair(0ll, 0ll); if(l < r - 1) { int m = (l + r) / 2; ...
1304
A
Two Rabbits
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
We can see that the taller rabbit will be at position $x + Ta$ and the shorter rabbit will be at position $y - Tb$ at the $T$-th second. We want to know when these two values are equal. Simplifying the equation, we get $\cfrac{y - x}{a + b} = T$. Since we only consider positive integers for $T$, the answer is $\cfrac{y...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while (tc--) { int x, y, a, b; cin >> x >> y >> a >> b; cout << ((y - x) % (a + b) == 0 ? (y - x) / (a + b) : -1) << endl; } }
1304
B
Longest Palindrome
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. \textbf{An empty string is also a palindrome.} G...
Let's define $rev(S)$ as the reversed string of a string $S$. There are two cases when we choose $K$ strings to make a palindrome string $S_1 + S_2 + \cdots + S_K$: If $K$ is even, for every integer $X$ ($1 \le X \le \cfrac{K}{2}$), $S_X = rev(S_{K-X+1})$. if $K$ is odd, $S_{\frac{K+1}{2}}$ must be palindrome. Also for...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100; string s[MAX_N]; int main() { set<string> dict; int n, m, i; cin >> n >> m; for (i = 0; i < n; i++) { cin >> s[i]; dict.insert(s[i]); } vector<string> left, right; string mid; for (i = 0; i < n; i++) { string t = s[i]; reverse(t.be...
1304
C
Air Conditioner
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo...
Since the range of temperatures can be large, it is impossible to consider all possible cases. However, we only need to find any case that can satisfy all customers, so let's try to maximize the possible range for each customer in the order of their visit time. Let's define two variables $mn$ and $mx$, each representin...
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100; int t[MAX_N], lo[MAX_N], hi[MAX_N]; int main() { int tc; cin >> tc; while (tc--) { int n, m, i; cin >> n >> m; for (i = 0; i < n; i++) cin >> t[i] >> lo[i] >> hi[i]; int prev = 0; int mn = m, mx = m; bool flag = true; for (i = ...
1304
D
Shortest and Longest LIS
Gildong recently learned how to find the longest increasing subsequence (LIS) in $O(n\log{n})$ time for a sequence of length $n$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to mak...
There are various strategies to solve each part. I'll explain one of them for each. It would be fun to come up with your own strategy as well :) Shortest LIS Let's group each contiguously increasing part. We can easily see that we cannot make the LIS shorter than the maximum size among these groups. It can be shown tha...
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; const int MAX_N = 200000; int ans[MAX_N + 5]; int main() { int tc; cin >> tc; while (tc--) { int n, i, j; string s; cin >> n >> s; int num = n, last = 0; for (i = 0; i < n; i++) { if (i == n - 1 || s[i] == '>') { for (j = i; j >= last; j--) ...
1304
E
1-Trees and Queries
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree? Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wan...
Assume that the length of a path from $a$ to $b$ is $L$. It is obvious that for every non-negative integer $Z$, there exists a path from $a$ to $b$ of length $L + 2Z$ since we can go back and forth any edge along the path any number of times. So, we want to find the shortest path from $a$ to $b$ where the parity (odd o...
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100000; const int LIM = 17; const int INF = (int)1e9 + 7; vector<int> adj[MAX_N + 5]; int depth[MAX_N + 5]; int par[MAX_N + 5][LIM + 1]; void build(int cur, int p) { int i; depth[cur] = depth[p] + 1; par[cur][0] = p; for (i = 1; i <= LIM; i++) pa...
1304
F1
Animal Observation (easy version)
\textbf{The only difference between easy and hard versions is the constraint on} $k$. Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue. Gildong is going to take videos for $n$ days, starting from day...
For simplicity, we'll assume that there is the $n+1$-st day when no animals appear at all. Let's say $animal[i][j]$ is the number of animals appearing in the $j$-th area on the $i$-th day. Let's define $DP[i][j]$ ($1 \le i \le n, 1 \le j \le m - k + 1$) as the maximum number of animals that can be observed in total sin...
[ "data structures", "dp" ]
2,300
#include <bits/stdc++.h> using namespace std; const int MAX_N = 50; const int MAX_M = 20000; const int MAX_K = 20; int animal[MAX_N + 5][MAX_M + 5]; int psum[MAX_N + 5][MAX_M + 5]; int lmax[MAX_N + 5][MAX_M + 5]; int rmax[MAX_N + 5][MAX_M + 5]; int dp[MAX_N + 5][MAX_M + 5]; inline int ps(int i, int j, int k) { retu...
1304
F2
Animal Observation (hard version)
\textbf{The only difference between easy and hard versions is the constraint on} $k$. Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue. Gildong is going to take videos for $n$ days, starting from day...
We can further advance the idea we used in F1 to reduce the time complexity. Solution: $O(nm\log{m})$ Let's generalize all three cases we discussed in F1. Let's make a lazy segment tree supporting range addition update and range maximum query. Each node represents the maximum value of ($DP[i-1]$ minus the sum of the an...
[ "data structures", "dp", "greedy" ]
2,400
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; using vi = vector<int>; using vvi = vector<vi>; const int MAX_N = 50; const int MAX_M = 20000; const int MAX_K = 20; int n, m, k; inline int ps(vvi &p, int i, int s, int e) { if (s < 1) return p[i][e]; return p[i][e] - p[i][s - 1]; } void...
1305
A
Kuroni and the Gifts
Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets: - the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are \textbf{pairwise distinct} (i.e. all $a_i$ are different), - the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are \textbf{pairwise distinct} (i.e....
We claim that if we sort the arrays $a$ and $b$, then giving the $i$-th daughter the $i$-th necklace and the $i$-th bracelet is a valid distribution. Notice that since all elements in each array are distinct, we have $a_1 < a_2 < \dots < a_n$ $b_1 < b_2 < \dots < b_n$ Then $a_i + b_i < a_{i + 1} + b_i < a_{i + 1} + b_{...
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
800
T = int(input()) for _ in range(T): n = int(input()) A = sorted(list(map(int, input().split()))) B = sorted(list(map(int, input().split()))) print(*A) print(*B)
1305
B
Kuroni and Simple Strings
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence! ...
We claim that the answer is always $0$ or $1$. First, note we can't apply any operations if and only if each '(' symbol is left from each ')' symbol, so that the string looks as ')))(((((('. Let $a_1, a_2, \dots, a_p$ be the indexes of symbols '(' in the string, and $b_1, b_2, \dots, b_q$ be the indexes of symbols ')' ...
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
1,200
string = input() oList, cList = [], [] for i in range(len(string)): if string[i] == '(': oList.append(i) if string[i] == ')': cList.append(i) oPtr, cPtr = 0, len(cList)-1 removal = [] while oPtr < len(oList) and cPtr >= 0: if oList[oPtr] > cList[cPtr]: break removal.append(oList[oPtr]) removal.append(cList[cPtr])...
1305
C
Kuroni and Impossible Calculation
To become the king of Codeforces, Kuroni has to solve the following problem. He is given $n$ numbers $a_1, a_2, \dots, a_n$. Help Kuroni to calculate $\prod_{1\le i<j\le n} |a_i - a_j|$. As result can be very big, output it modulo $m$. If you are not familiar with short notation, $\prod_{1\le i<j\le n} |a_i - a_j|$ i...
Let's consider $2$ cases. $n\le m$. Then we can calculate this product directly in $O(n^2)$. $n\le m$. Then we can calculate this product directly in $O(n^2)$. $n > m$. Note that there are only $m$ possible remainders under division by $m$, so some $2$ numbers of $n$ have the same remainder. Then their difference is di...
[ "brute force", "combinatorics", "math", "number theory" ]
1,600
n, m = map(int, input().split()) a = list(map(int, input().split())) if n > m: exit(print(0)) ans = 1 for i in range(n): for j in range(i+1, n): ans *= abs(a[i] - a[j]) ans %= m print(ans)
1305
D
Kuroni and the Celebration
\textbf{This is an interactive problem.} After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost! The United States of America can be modeled as a tree (why...
For each question, pick any two leaves $u$ and $v$ and ask for the lowest common ancestor of them. The answer is either $u$ or $v$: The root of the tree must be the answer we received. The answer is neither $u$ nor $v$: Since $u$ and $v$ are leaves, there are no other vertices that lie within the subtree of either of t...
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
1,900
from sys import stdout def ask(u, v): print('? {} {}'.format(u+1, v+1)) stdout.flush() return (int(input()) - 1) def answer(r): print('! {}'.format(r+1)) stdout.flush() exit() n = int(input()) adj = [{} for _ in range(n)] isLeaf = {} def purge(z, last, blockpoint): if z in isLeaf: isLeaf.pop(z) for t in ad...
1305
E
Kuroni and the Score Distribution
Kuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round. The round consists of $n$ problems, numbered from $1$ to $n$. The problems are ordered in increasing order of diffi...
Firstly, note that for each $i$, there can't be more than $\lfloor \frac{i-1}{2} \rfloor$ triples of form $(x, y, i)$ with $a_x + a_y = a_i$. This is true as every index $j$ can meet at most once among all $x, y$ (as the third index is uniquely determined by $i$, $j$). Therefore, the answer can't exceed $\lfloor \frac{...
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,200
n, m = map(int, input().split()) numList = [x+1 for x in range(n)] backdoor = [] count = sum([(i-1) // 2 for i in range(1, n+1)]) if count < m: exit(print(-1)) while count > m: lastpop = numList.pop() count -= (lastpop - 1) // 2 if count >= m: if len(backdoor) == 0: backdoor.append(10 ** 9) else: backdoor.a...
1305
F
Kuroni and the Punishment
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem: You have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element and either adding $1$ to it or subtracting $1$ from it, such that the element remai...
First, let's assume we have a fixed positive integer $d \ge 2$, and we want to find the minimum number of operations needed to make all elements divisible by $d$. Then a simple greedy algorithm gives us the answer: For each element $x$ just apply operations to transform it into the closest multiple of $d$, which is eit...
[ "math", "number theory", "probabilities" ]
2,500
import random n = int(input()) a = list(map(int, input().split())) limit = min(8, n) iterations = [x for x in range(n)] random.shuffle(iterations) iterations = iterations[:limit] def factorization(x): primes = [] i = 2 while i * i <= x: if x % i == 0: primes.append(i) while x % i == 0: x //= i i = i + 1...
1305
G
Kuroni and Antihype
Kuroni isn't good at economics. So he decided to found a new financial pyramid called \textbf{Antihype}. It has the following rules: - You can join the pyramid for free and get $0$ coins. - If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number o...
Let's forget about the structure of our graph of friendship first and let's solve a more general problem: what are the highest possible total gainings of all people given some edges. Firstly, let's suppose there is a $n+1$-th person with age $a_{n+1} = 0$ in Antihype already, who is friend with everybody. We can suppos...
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
3,500
import sys range = xrange input = raw_input n = int(input()) A = [int(x) for x in input().split()] m = 2**18 count = [0]*m for a in A: count[a] += 1 count[0] += 1 # Using dsu with O(1) lookup and O(log(n)) merge owner = list(range(m)) sets = [[i] for i in range(m)] total = 0 for profit in reversed(range(m)): ...
1305
H
Kuroni the Private Tutor
As a professional private tutor, Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him. The exam consists of $n$ questions, and $m$ students have taken the exam. Each question was worth $1$ point. Question $i$ was solved by at least $l_i$ and ...
Suppose we fix the scores of the students $b_0 \le b_1 \le \dots \le b_{m-1}$. We model our problem as a flow graph. Consider a flow graph where the left side contains the source and $n$ nodes denoting the problems, and the right side contains the sink and $m$ nodes denoting the students. Each problem node is connect...
[ "binary search", "greedy" ]
3,500
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair...
1307
A
Cow and Haybales
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to...
At any point, it is optimal to move a haybale in the closest pile from pile $1$ to the left. So, for every day, we can loop through the piles from left to right and move the first haybale we see closer. If all the haybales are in pile $1$ at some point, we can stop early. Time Complexity: $O(n \cdot d)$
[ "greedy", "implementation" ]
800
#include <iostream> using namespace std; int N,D,a[105],ans; int main(){ int T; cin>>T; while (T--){ cin>>N>>D; for (int i=1;i<=N;i++) cin>>a[i]; for (int i=2;i<=N;i++){ int move=min(a[i],D/(i-1)); //number of haybales we can move from pile i to pile 1 a[1]+=move; //update pile 1 ...
1307
B
Cow and Friend
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $(0,0)$ to $(x,0)$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance b...
If the distance $d$ is in the set, the answer is $1$. Otherwise, let $y$ denote Rabbit's largest favorite number. The answer is $max(2,\lceil \frac{d}{y}\rceil)$. This is true because clearly the answer is at least $\lceil\frac{d}{y}\rceil$: if it were less Rabbit can't even reach distance $d$ away from the origin. If ...
[ "geometry", "greedy", "math" ]
1,300
#include <iostream> #include <set> #include <algorithm> using namespace std; set<int>a; //you don't have to use set, it was just easier for us int main(){ int T; cin>>T; while (T--){ int N,X; cin>>N>>X; int far=0; //largest favorite number for (int i=0;i<N;i++){ int A; cin>>A; a....
1307
C
Cow and Message
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string $s$ of lowercase Latin letters. She considers a string $t$ as hidden in string $s$ if $t$ exists as a subsequence of $s$ whose indices form an ari...
We observe that if the hidden string that occurs the most times has length longer than $2$, then there must exist one that occurs just as many times of length exactly $2$. This is true because we can always just take the first $2$ letters; there can't be any collisions. Therefore, we only need to check strings of lengt...
[ "brute force", "dp", "math", "strings" ]
1,500
#include <iostream> using namespace std; typedef long long ll; ll arr1[26],arr2[26][26]; int main(){ string S; cin>>S; for (int i=0;i<S.length();i++){ int c=S[i]-'a'; for (int j=0;j<26;j++) arr2[j][c]+=arr1[j]; arr1[c]++; } ll ans=0; for (int i=0;i<26;i++) ans=max(ans,arr1[i]); for...
1307
D
Cow and Fields
Bessie is out grazing on the farm, which consists of $n$ fields connected by $m$ bidirectional roads. She is currently at field $1$, and will return to her home at field $n$ at the end of the day. The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $k$ special field...
There are a few solutions that involve breadth first search (BFS) and sorting, this is just one of them. First, let's use BFS to find the distance from fields $1$ and $n$ to each special field. For a special field $i$, let $x_i$ denote the distance to node $1$, and $y_i$ denote the distance to $n$. We want to choose tw...
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
1,900
#include <cstdio> #include <vector> #include <algorithm> const int INF=1e9+7; int N; int as[200005]; std::vector<int> edges[200005]; int dist[2][200005]; int q[200005]; void bfs(int* dist,int s){ std::fill(dist,dist+N,INF); int qh=0,qt=0; q[qh++]=s; dist[s]=0; while(qt<qh){ int x=q[qt++]; for(int...
1307
E
Cow and Treats
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass! On the field, there is a row of $n$ units of grass, each with a sweetness $s_i$. Farmer John has $m$ cows, each with a favorite sweetness $f_i$ and a hunger value $h_i$. He would like to pick two disjo...
First, we observe that it is impossible to send more than one cow with the same favorite sweetness on the same side without upsetting any of them. This means we can send at most two cows of each favorite sweetness, one on each side. Now, let's assume we know the index of the rightmost cow that came from the left side. ...
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
2,500
#include <cstdio> #include <vector> #include <algorithm> #include <cassert> const int MOD=1e9+7; int modexp(int base,int exp){ int ac=1; for(;exp;exp>>=1){ if(exp&1) ac=1LL*ac*base%MOD; base=1LL*base*base%MOD; } return ac; } int inverse(int x){ return modexp(x,MOD-2); } int fs[100005]; int left[10...
1307
F
Cow and Vacation
Bessie is planning a vacation! In Cow-lifornia, there are $n$ cities, with $n-1$ bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city. Bessie is considering $v$ possible vacation plans, with the $i$-th one consisting of a start city $a_i$ and destination city $b_i$. It...
We will run a BFS from all the rest stops in parallel and use union-find to determine which rest stops can reach each other directly. We will split each edge into two to simplify this process. Note that this means Bessie can now travel at most $2k$ roads before needing a rest. While we perform the BFS, we also color al...
[ "dfs and similar", "dsu", "trees" ]
3,300
#include <cstdio> #include <vector> #include <cassert> #include <queue> #include <algorithm> const int INF=1e9+7; std::vector<int> edges[400005]; int anc[19][400005]; int depth[400005]; void dfs(int node){ for(int child:edges[node]){ edges[child].erase(std::find(edges[child].begin(),edges[child].end(),node));...
1307
G
Cow and Exercise
Farmer John is obsessed with making Bessie exercise more! Bessie is out grazing on the farm, which consists of $n$ fields connected by $m$ directed roads. Each road takes some time $w_i$ to cross. She is currently at field $1$ and will return to her home at field $n$ at the end of the day. Farmer John has plans to in...
This problem can be formulated as a linear program, and looks like the LP dual of min-cost flow. LP formulation of min-cost flow (see for example here: https://imada.sdu.dk/%7Ejbj/DM85/mincostnew.pdf): $x_{vw}$ is flow on edge $(v,w)$ $c_{vw}$ is cost on edge $(v,w)$ $u_{vw}$ is capacity on edge $(v,w)$ $b_v$ is demand...
[ "flows", "graphs", "shortest paths" ]
3,100
#include <cstdio> #include <queue> #include <vector> #include <stdint.h> #include <algorithm> const long long INF=1e9+7; const long long MAXV=50; const long long MAXE=MAXV*(MAXV-1); long long SRC,SNK; long long elist[MAXE*2]; long long next[MAXE*2]; long long head[MAXV]; long long cap[MAXE*2]; long long cost[MAXE*2...
1310
A
Recommendations
VK news recommendation system daily selects interesting publications of one of $n$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $i$ batch algorithm selects $a_i$ publications. The latest A/B test suggests that users are reading recommended publications more act...
In this problem we have an array $a_1, \ldots, a_n$, we can increase each $a_i$ by one with cost $t_i$, and we want to make all $a_i$ different with minimal total cost. Let's sort $a_i$ in a non-decreasing way (and permute the $t$ in a corresponding way). Let's see at the minimal number, $a_1$. If it is unique, e.g. $a...
[ "data structures", "greedy", "sortings" ]
1,700
null
1310
B
Double Elimination
The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. $2^n$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from $1$ to $2^n$ and will play games one...
The main observation in this problem is that for each set of players that lie in the subtree of any vertex of a binary tree of the upper bracket, exactly one player will win all matches in the upper bracket, and exactly one player will win all matches in the lower bracket. We can define this set of players (in 0-indexa...
[ "dp", "implementation" ]
2,500
null
1310
C
Au Pont Rouge
VK just opened its second HQ in St. Petersburg! Side of its office building has a huge string $s$ written on its side. This part of the office is supposed to be split into $m$ meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0...
Let's list all distinct substrings, sort them and make a binary search. Now, we need to count number of ways to make minimal string no more then given one. Let's count inverse value - number of wat to make minimal string greater. It could be done by quadratic dynamic programming $dp_{pos, count}$ - number of ways to sp...
[ "binary search", "dp", "strings" ]
2,800
null
1310
D
Tourism
Masha lives in a country with $n$ cities numbered from $1$ to $n$. She lives in the city number $1$. There is a direct train route between each pair of distinct cities $i$ and $j$, where $i \neq j$. In total there are $n(n-1)$ distinct routes. Every route has a cost, cost for route from $i$ to $j$ may be different fro...
There are two different solutions possible. First, one is to fix all even vertices in the path. It can be done in $O(n^{k/2 - 1})$ time. If it's done, we need to join them by the minimal path of length 2, not going through these vertices. It can be done by precalculating 6 minimal paths of length 2 between each pair of...
[ "dp", "graphs", "probabilities" ]
2,300
null
1310
E
Strange Function
Let's define the function $f$ of multiset $a$ as the multiset of number of occurences of every number, that is present in $a$. E.g., $f(\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\}) = \{1, 1, 2, 2, 4\}$. Let's define $f^k(a)$, as applying $f$ to array $a$ $k$ times: $f^k(a) = f(f^{k-1}(a)), f^0(a) = a$. E.g., $f^2(\{5, 5, 1, 2,...
The solution of the task consists of three cases: $k = 1$. For fixed $n$ $f(a)$ can be equal to any partition of $n$. We need to count the number of arrays $b_1, b_2, \ldots, b_m$, such that $b_1 \ge b_2 \ge \ldots \ge b_m$ and $\sum \limits_{i=1}^m b_i \le n$. This can be done by simple dp in $\mathcal{O}(n^2)$ (or ev...
[ "dp" ]
2,900
null
1310
F
Bad Cryptography
In modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: \begin{center} Let's fix a finite field and two it's elements $a$ and $b$. One need to fun such $x$ that $a^x = b$ or detect there is no such...
One of the well-known algorithms for the discrete logarithm problem is baby step giant step algorithm based on the meet in the middle idea. It can solve the problem in $O(\sqrt{|F|})$ time, which is definitely too much for the field of size $2^64$. Multiplicative group of field has size $F = 2^64 - 1 = 3 \cdot 5 \cdot ...
[ "math", "number theory" ]
3,400
null
1311
A
Add Odd or Subtract Even
You are given two positive integers $a$ and $b$. In one move, you can \textbf{change} $a$ in the following way: - Choose any positive \textbf{odd} integer $x$ ($x > 0$) and replace $a$ with $a+x$; - choose any positive \textbf{even} integer $y$ ($y > 0$) and replace $a$ with $a-y$. You can perform as many such opera...
If $a=b$ then the answer is $0$. Otherwise, if $a > b$ and $a - b$ is even or $a < b$ and $b - a$ is odd then the answer is $1$. Otherwise the answer is $2$ (you can always make $1$-case in one move).
[ "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if (a == b) cout << 0 << endl; else cout << 1 + int((a < b) ^ ((b - a) & 1)) << endl; } ret...
1311
B
WeirdSort
You are given an array $a$ of length $n$. You are also given a set of \textbf{distinct} positions $p_1, p_2, \dots, p_m$, where $1 \le p_i < n$. The position $p_i$ means that you can swap elements $a[p_i]$ and $a[p_i + 1]$. You can apply this operation any number of times for each of the given \textbf{positions}. You...
The simple simulation works here: while there is at least one inversion (such a pair of indices $i$ and $i+1$ that $a[i] > a[i + 1]$) we can fix, let's fix it (we can fix this inversion if $i \in p$). If there are inversions but we cannot fix any of them, the answer is "NO". Otherwise, the answer is "YES". There is als...
[ "dfs and similar", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<int> p(n); for (...
1311
C
Perform the Combo
You want to perform the combo on your opponent in one popular fighting game. The combo is the string $s$ consisting of $n$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $s$. I.e. if $s=$"abca" then you have to press 'a', then 'b', 'c' and 'a' again. You know t...
We can consider all tries independently. During the $i$-th try we press first $p_i$ buttons, so it makes $+1$ on the prefix of length $p_i$. So the $i$-th character of the string will be pressed (the number of $p_i \ge i$ plus $1$) times. We can use sorting and some kind of binary search to find this number for each ch...
[ "brute force" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, m; string s; cin >> n >> m >> s; vector<int> pref(n); for (int i = 0; i < m; ++i) { int p; cin >> p; +...
1311
D
Three Integers
You are given three integers $a \le b \le c$. In one move, you can add $+1$ or $-1$ to \textbf{any} of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. \textbf{Note that ...
Let's iterate over all possible values of $A$ from $1$ to $2a$. It is obvious that $A$ cannot be bigger than $2a$, else we can just move $a$ to $1$. Then let's iterate over all possible multiples of $A$ from $1$ to $2b$. Let this number be $B$. Then we can find $C$ as the nearest number to $c$ that is divisible by $B$ ...
[ "brute force", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int a, b, c; cin >> a >> b >> c; int ans = 1e9; int A = -1, B = -1, C = -1; for (int cA = 1; cA <= 2 * a; ++cA) { f...
1311
E
Construct the Binary Tree
You are given two integers $n$ and $d$. You need to construct a rooted binary tree consisting of $n$ vertices with a root at the vertex $1$ and the sum of depths of all vertices equals to $d$. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $v$ is th...
This problem has an easy constructive solution. We can find lower and upper bounds on the value of $d$ for the given $n$. If the given $d$ does not belong to this segment, then the answer is "NO". Otherwise, the answer is "YES" for any $d$ in this segment. How to construct it? Let's start from the chain. The answer for...
[ "brute force", "constructive algorithms", "trees" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int t; cin >> t; while (t--) { int n, d; cin >> n >> d; int ld = 0, rd = n * (n - 1) / 2; for (int i = 1, cd = 0; i <= n; ++i) { if (!(i & (i - 1)))...
1311
F
Moving Points
There are $n$ points on a coordinate axis $OX$. The $i$-th point is located at the integer point $x_i$ and has a speed $v_i$. It is guaranteed that no two points occupy the same coordinate. All $n$ points move with the constant speed, the coordinate of the $i$-th point at the moment $t$ ($t$ \textbf{can be non-integer}...
Let's understand when two points $i$ and $j$ coincide. Let $x_i < x_j$. Then they are coincide when $v_i > v_j$. Otherwise, these two points will never coincide and the distance between them will only increase. So, we need to consider only the initial positions of points. Let's sort all points by $x_i$ and consider the...
[ "data structures", "divide and conquer", "implementation", "sortings" ]
1,900
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; typedef tree< pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; int main() { #ifdef _DEBUG freopen(...
1312
A
Two Regular Polygons
You are given two integers $n$ and $m$ ($m < n$). Consider a \textbf{convex} regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). \begin{center} Examples of convex regular polygons \end{center...
The answer is "YES" if and only if $n$ is divisible by $m$ because if you number all vertices of the initial polygon from $0$ to $n-1$ clockwise then you need to take every vertex divisible by $\frac{n}{m}$ (and this number obviously should be integer) and there is no other way to construct the other polygon.
[ "geometry", "greedy", "math", "number theory" ]
800
for i in range(int(input())): n, m = map(int, input().split()) print('YES' if n % m == 0 else 'NO')
1312
B
Bogosort
You are given an array $a_1, a_2, \dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if $...
Let's sort array $a$ in non-ascending order ($a_1 \ge a_2 \ge \dots \ge a_n$). In this case for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds.
[ "constructive algorithms", "sortings" ]
1,000
for t in range(int(input())): n = input() print(*sorted(map(int, input().split()))[::-1])
1312
C
Adding Powers
Suppose you are performing the following algorithm. There is an array $v_1, v_2, \dots, v_n$ filled with zeroes at start. The following operation is applied to the array several times — at $i$-th step ($0$-indexed) you can: - either choose position $pos$ ($1 \le pos \le n$) and increase $v_{pos}$ by $k^i$; - or not ch...
This is the solution that doesn't involve masks. Let's reverse the process and try to get all zeroes from the array $a$: since all $a_i \le 10^{16}$ we can start from maximum $k^s \le 10^{16}$. The key idea: since $k^s > \sum_{x=0}^{s-1}{k^x}$ then there should be no more than one position $pos$ such that $a_{pos} \ge ...
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
1,400
fun getMask(a: Long, k: Long): Long? { var (tmp, res) = listOf(a, 0L) var cnt = 0 while (tmp > 0) { if (tmp % k > 1) return null res = res or ((tmp % k) shl cnt) tmp /= k cnt++ } return res } fun main() { val T = readLine()!!.toInt() for (tc in 1....
1312
D
Count the Arrays
Your task is to calculate the number of arrays such that: - each array contains $n$ elements; - each element is an integer from $1$ to $m$; - for each array, there is \textbf{exactly} one pair of equal elements; - for each array $a$, there exists an index $i$ such that the array is \textbf{strictly ascending} before t...
First of all, there will be exactly $n - 1$ distinct elements in our array. Let's choose them, there are ${m}\choose{n-1}$ ways to do that. After that, there should be exactly one element that appears twice. There are $n - 1$ elements to choose from, but are all of them eligible? If we duplicate the maximum element, th...
[ "combinatorics", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; const int N = 200043; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y...
1312
E
Array Shrinking
You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: - Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). - Replace them by one element with value $a_i + 1$. After each such operation, the length of the array w...
Let's look at the answer: by construction, each element in the final answer was the result of replace series of elements on the corresponding segment. So all we need to find is the minimal (by size) partition of the array $a$ on segments where each segment can be transformed in one element by series of replaces. We can...
[ "dp", "greedy" ]
2,100
#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<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A,...
1312
F
Attack on Red Kingdom
The Red Kingdom is attacked by the White King and the Black King! The Kingdom is guarded by $n$ castles, the $i$-th castle is defended by $a_i$ soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the for...
This problem seems like a version of Nim with some forbidden moves, so let's try to apply Sprague-Grundy theory to it. First of all, we may treat each castle as a separate game, compute its Grundy value, and then XOR them to determine who is the winner of the game. When analyzing the state of a castle, we have to know ...
[ "games", "two pointers" ]
2,500
#include<bits/stdc++.h> using namespace std; const int N = 300043; const int K = 5; int x, y, z, n; long long a[N]; typedef vector<vector<int> > state; map<state, int> d; int cnt; int p; vector<vector<int> > state_log; int mex(const vector<int>& a) { for(int i = 0; i < a.size(); i++) { bool f = fal...
1312
G
Autocompletion
You are given a set of strings $S$. Each string consists of lowercase Latin letters. For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the follow...
First of all, the information given in the input is the structure of a trie built on $S$ and some other strings - so we can store this information in the same way as we store a trie. Okay, now let's calculate the number of seconds required to type each string with dynamic programming: let $dp_i$ be the number of second...
[ "data structures", "dfs and similar", "dp" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 1000043; map<char, int> nxt[N]; bool term[N]; int n, k; char buf[3]; int dp[N]; int dict[N]; int T[4 * N]; int f[4 * N]; void build(int v, int l, int r) { T[v] = int(1e9); if(l != r - 1) { int m = (l + r) / 2; build(v * 2 + 1, l...
1313
A
Fast Food Restaurant
Tired of boring office work, Denis decided to open a fast food restaurant. On the first day he made $a$ portions of dumplings, $b$ portions of cranberry juice and $c$ pancakes with condensed milk. The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of ...
Bruteforce solution There are seven possible sets of dishes, so the simplest solution is to iterate over all possible $2^7$ subsets of sets of dishes. You can also go over $7!$ permutations of sets of dishes and gather sets of dishes greedily in the selected order. Greedy solution Note that the solution can be optimal ...
[ "brute force", "greedy", "implementation" ]
900
null
1313
B
Different Rules
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $n$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest nu...
Without loss of generality, assume that $x \leq y$. For convenience, we will number the participants from 1 to $n$ in the order of their places in the first round. Thus, the participant we are interested in is the participant $x$. First we can prove the formula: $\operatorname{MIN\_PLACE} = \max(1, \min(n, x + y - n + ...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,700
null
1313
C2
Skyscrapers (hard version)
This is a harder version of the problem. In this version $n \le 500\,000$ The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the c...
Let's solve the task on an array $m$ of length $n$. Let's find a minimal element in this array. Let it be on the $i$-th ($1 \leq i \leq n$) position. We can build the skyscraper at the $i$-th position as high as possible, that is $a_i = m_i$. Now we should make a choice - we need to equate to $a_i$ either the left part...
[ "data structures", "dp", "greedy" ]
1,900
null
1313
D
Happy New Year
Being Santa Claus is very difficult. Sometimes you have to deal with difficult situations. Today Santa Claus came to the holiday and there were $m$ children lined up in front of him. Let's number them from $1$ to $m$. Grandfather Frost knows $n$ spells. The $i$-th spell gives a candy to every child whose place is in t...
We wil use scanline to solve this problem. For all segments, we add event of its beginning and end. Let's maintain $dp_{i, mask}$, where $i$ is number of events that we have already processed. $mask$ is mask of $k$ bits, where $1$ in some bit means that segment corresponding to this bit is taken. How to move from one c...
[ "bitmasks", "dp", "implementation" ]
2,500
null
1313
E
Concatenation with intersection
Vasya had three strings $a$, $b$ and $s$, which consist of lowercase English letters. The lengths of strings $a$ and $b$ are equal to $n$, the length of the string $s$ is equal to $m$. Vasya decided to choose a substring of the string $a$, then choose a substring of the string $b$ and concatenate them. Formally, he ch...
For all $1 \leq i \leq n$ let's define $fa_i$ as the length of the longest common prefix of strings $a[i, n]$ and $s[1, m - 1]$, $fb_i$ as the length of the longest common suffix of strings $b[1, i]$ and $s[2, m]$. Values of $fa$ can be easily found from $z$-function of the string "$s\#a$", values of $fb$ from $z$-func...
[ "data structures", "hashing", "strings", "two pointers" ]
2,700
null
1315
A
Dead Pixel
Screen resolution of Polycarp's monitor is $a \times b$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $(x, y)$ ($0 \le x < a, 0 \le y < b$). You can consider columns of pixels to be numbered from $0$ to $a-1$, and rows — from $0$ to $b-1$. Polycarp wants to open a rectangular window ...
You can see that you should place the window in such a way so that the dead pixel is next to one of the borders of the screen: otherwise we can definitely increase the size of the window. There are four possible ways to place the window right next to the dead pixel - you can place it below, above, to the left or to the...
[ "implementation" ]
800
null
1315
B
Homecoming
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $n$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string $s$ of length $n$, where $s_i = A$, if ...
The first thing you should do in this problem - you should understand the problem statement (which could be not very easy), and get the right answers to the sample test cases. Petya needs to find the minimal $i$ such that he has enough money to get from $i$ to $n$ (not $n+1$, he doesn't need to use the transport from t...
[ "binary search", "dp", "greedy", "strings" ]
1,300
null