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
1552
H
Guess the Perimeter
Let us call a point of the plane admissible if its coordinates are positive integers less than or equal to $200$. There is an invisible rectangle such that: - its vertices are all admissible; - its sides are parallel to the coordinate axes; - its area is strictly positive. Your task is to guess the perimeter of this...
Let $b$ and $h$ be the lengths of base and height of the rectangle. We will solve a harder problem, that is, finding the explicit values of $b$ and $h$. For a positive integer $d$, define $S(d)$ as the set of admissible points $(x, \, y)$ with $d \mid x$, and define $f(d)$ as the answer to the query with subset $S(d)$....
[ "binary search", "interactive", "number theory" ]
3,300
#include <iostream> #include <vector> using namespace std; vector<pair<int, int>> get_S(int d) { vector<pair<int, int>> S; for (int i = d; i <= 200; i += d) for (int j = 1; j <= 200; j++) S.push_back(make_pair(i, j)); return S; } int query(int d) { vector<pair<int, int>> S = ge...
1552
I
Organizing a Music Festival
You are the organizer of the famous "Zurich Music Festival". There will be $n$ singers who will perform at the festival, identified by the integers $1$, $2$, $\dots$, $n$. You must choose in which order they are going to perform on stage. You have $m$ friends and each of them has a set of favourite singers. More preci...
Let $S_i := \{s_{i,1}, \, s_{i,2}, \, \dots, \, s_{i, q_i}\}$. Consider the graph on the subsets $S_1, \, S_2, \, \dots, \, S_k$ such that $S_i$ is adjacent to $S_j$ if and only if $S_i \cap S_j \ne \varnothing, \, S_i, \, S_j$. Without loss of generality we can assume that the sets $S_1, \, S_2, \, \dots, \, S_m$ are ...
[ "dfs and similar", "math" ]
3,400
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define SZ(x) ((int)((x).size())) // Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00. LL get_time() { return chrono::duration_cast<chrono::nanoseconds>( ch...
1553
A
Digits Sum
Let's define $S(x)$ to be the sum of digits of number $x$ written in decimal system. For example, $S(5) = 5$, $S(10) = 1$, $S(322) = 7$. We will call an integer $x$ \textbf{interesting} if $S(x + 1) < S(x)$. In each test you will be given one integer $n$. Your task is to calculate the number of integers $x$ such that ...
Let's think: what properties do all interesting numbers have? Well, if a number $x$ does not end with $9$, we can say for sure that $f(x+1) = f(x) + 1$, because the last digit will get increased. What if the number ends with $9$? Then the last digit will become $0$, so, no matter what happens to other digits, we can sa...
[ "math", "number theory" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { //freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false); int tst; cin >> tst; while (tst--) { int n; cin >> n; cout << (n + 1) / 10 << '\n'; } }
1553
B
Reverse String
You have a string $s$ and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $i$, you move it to the position $i + 1$. Of course, movi...
Let's iterate over starting positions, the number of times we go to the right and the number of times we go to the left. After that we can check that resulting string is equal to the needed one. This solution works in $O(n^4)$, since there are $O(n^3)$ possible combinations of starting position, number of moves to the ...
[ "brute force", "dp", "hashing", "implementation", "strings" ]
1,300
q = int(input()) for i in range(q): s = input() t = input() n = len(s) m = len(t) ans = False for i in range(n): for j in range(0, n - i): k = m - 1 - j if i + j < k: continue l1 = i r = i + j l2 = r - k if s[l1:r+1] + s[l2:r...
1553
C
Penalty
Consider a simplified penalty phase at the end of a football match. A penalty phase consists of at most $10$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number ...
After you have fixed the values of ? you can easily find the number of kicks needed to decide the winners in constant time. If you iterate over all possible values of ? you can get solution which works in $O(2^10 \cdot check)$ for one testcase, which is enough to pass. The other possible solution is to notice that it's...
[ "bitmasks", "brute force", "dp", "greedy" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int ans = 9; { int cnt0 = 0, cnt1 = 0; for (int i = 0; i < 10; ++i) { if (i % 2 == 0) cnt0 += s[i] != '0'; else cnt1 += s[i] == '1'; if (cnt0 > cnt1 + (10 - i) / 2) ans = min(...
1553
D
Backspace
You are given two strings $s$ and $t$, both consisting of lowercase English letters. You are going to type the string $s$ character by character, from the first character to the last one. When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the l...
The main idea of the problem is that backspace results in losing $2$ characters, the one we intended to type (which we replace with a backspace) and the character that the backspace will remove. In general, the idea is to compare every letter $s_i$ with $t_j$ starting from right to left, if they match we will move to c...
[ "dp", "greedy", "strings", "two pointers" ]
1,500
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> ...
1553
E
Permutation Shift
An identity permutation of length $n$ is an array $[1, 2, 3, \dots, n]$. We performed the following operations to an identity permutation of length $n$: - firstly, we cyclically shifted it to the right by $k$ positions, where $k$ is unknown to you (the only thing you know is that $0 \le k \le n - 1$). When an array i...
Let's decrease all numbers by $1$ and start the numeration from $0$, because cyclic shifts are very easy to describe this way. Let's observe for $n = 4$: $k = 0$. $p = [0, 1, 2, 3]$. So, $p_i = i$. $k = 1$. $p = [3, 0, 1, 2]$. So, $p_i = (i-1) \bmod n$. ... Continuing this process, we verify that indeed, $p_i = (i-k) \...
[ "brute force", "combinatorics", "constructive algorithms", "dfs and similar", "dsu", "graphs", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; int cycle_count(vector<int> q, int n) { for(int i = 0; i < n; i++) q[i]--; vector<int> used(n); int ans = 0; for(int i = 0; i < n; i++) { if(used[i] == 1) continue; int j = i; while(used[j] == 0) { used[j] = 1; j = q[j]; } an...
1553
F
Pairwise Modulo
You have an array $a$ consisting of $n$ distinct positive integers, numbered from $1$ to $n$. Define $p_k$ as $$p_k = \sum_{1 \le i, j \le k} a_i \bmod a_j,$$ where $x \bmod y$ denotes the remainder when $x$ is divided by $y$. You have to find and print $p_1, p_2, \ldots, p_n$.
First of all, we have to get rid of the mod operation. The following formula helps very much: $x \bmod y = x - y \cdot \lfloor \frac{x}{y} \rfloor$. Since the sum is hard to deal with, we will divide it into two separate sums $s_k$ and $t_k$ defined as: $s_k = \sum_{1 \le i, j \le k, i > j} (a_i \bmod a_j),$ $t_k = \su...
[ "data structures", "math" ]
2,300
// chrono::system_clock::now().time_since_epoch().count() #include <bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define sz(x) (int)(x).size() #define rep(i, a, b) for (int i = (a); i < (b); ++i) #define debug(...
1553
G
Common Divisor Graph
Consider a sequence of distinct integers $a_1, \ldots, a_n$, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than $1$. There are $q$ queries, in each query, you want to get from one given node $a_s$ to another $a_t$. ...
tl;dr - Find initial CCs. Then for every $a_i$, find prime divisors of $a_i+1$ and draw new edges of cost 1 between each pair of those primes, and between $a_i$ and those primes. Part 1, notation and observations Two numbers are not coprime iff they have a common prime divisor. Let $P(x)$ denote distinct prime divisors...
[ "brute force", "constructive algorithms", "dsu", "graphs", "hashing", "math", "number theory" ]
2,700
// gcd, AC, O((N+Q) * log^2), by Errichto #include <bits/stdc++.h> using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge { c b, e; }; sim > rge<c> ...
1553
H
XOR and Distance
You are given an array $a$ consisting of $n$ distinct elements and an integer $k$. Each element in the array is a non-negative integer not exceeding $2^k-1$. Let's define the XOR distance for a number $x$ as the value of $$f(x) = \min\limits_{i = 1}^{n} \min\limits_{j = i + 1}^{n} |(a_i \oplus x) - (a_j \oplus x)|,$$...
There are two main approaches to this problem, both of them utilize the same data structure - a trie. But not the usual trie. We will build a trie with each node storing the following four values. Let the interval represented by a node be $[L, R)$, then the values are: $minval$ - minimum existing value in the segment r...
[ "bitmasks", "divide and conquer", "trees" ]
2,900
#include<bits/stdc++.h> using namespace std; const int INF = int(1e9); const int K = 20; struct node { int max_val, min_val, ans, len; node(const node& left, const node& right) { len = left.len + right.len; max_val = max(left.max_val, right.max_val + left.len); min_val = min(left.min_val, right.min...
1553
I
Stairs
For a permutation $p$ of numbers $1$ through $n$, we define a stair array $a$ as follows: $a_i$ is length of the longest segment of permutation which contains position $i$ and is made of consecutive values in sorted order: $[x, x+1, \ldots, y-1, y]$ or $[y, y-1, \ldots, x+1, x]$ for some $x \leq y$. For example, for pe...
First of all, we need to transform the stair array into some other structure. Let's show that for each number, there is only one longest stair covering it, and these longest stairs are disjoint. Suppose that some number $x$ belongs to two different ascending stairs. We can easily expand these stairs to the left and to ...
[ "combinatorics", "divide and conquer", "dp", "fft", "math" ]
3,400
#include<bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) #define sz(a) ((int)((a).size())) #define fore(i, l, r) for(int i = int(l); i < int(r); i++) template<const int &MOD> struct _m_int { int val; _m_int(int64_t v = 0) { if (v < 0) v = v % MOD + MOD; if (v >= MOD) v ...
1554
A
Cherry
You are given $n$ integers $a_1, a_2, \ldots, a_n$. Find the maximum value of $max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r)$ over all pairs $(l, r)$ of integers for which $1 \le l < r \le n$.
Do we really need to check all the subarrays? Consider a subarray $(a_i, a_{i + 1}, \ldots, a_{j})$. If we add a new element $a_{j + 1}$, when will the new subarray $(a_i, a_{i + 1}, \ldots, a_{j}, a_{j + 1})$ give a better result? Pause and think. The minimum of the new subarray can't get better(the minimum of a small...
[ "greedy" ]
800
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): ans = max(ans, a[i] * a[i + 1]) print(ans)
1554
B
Cobb
You are given $n$ integers $a_1, a_2, \ldots, a_n$ and an integer $k$. Find the maximum value of $i \cdot j - k \cdot (a_i | a_j)$ over all pairs $(i, j)$ of integers with $1 \le i < j \le n$. Here, $|$ is the bitwise OR operator.
Let $f(i, j) = i \cdot j - k \cdot (a_i | a_j)$ for $i < j$. Do we really need to check all pairs? The value of $k$ is small, which is suspicious. There must be something revolving around it. What can that be? In the equation, $i \cdot j$ can be $\mathcal{O}(n^2)$, but $k \cdot (a_i | a_j)$ is $\mathcal{O}(n \cdot 100)...
[ "bitmasks", "brute force", "greedy", "math" ]
1,700
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) l = max(0, n - 2 * k - 1) ans = -1e12 for i in range(l, n): for j in range(i + 1, n): ans = max(ans, (i + 1) * (j + 1) - k * (a[i] | a[j])) print(an...
1554
C
Mikasa
You are given two integers $n$ and $m$. Find the $\operatorname{MEX}$ of the sequence $n \oplus 0, n \oplus 1, \ldots, n \oplus m$. Here, $\oplus$ is the bitwise XOR operator. $\operatorname{MEX}$ of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For ex...
How can we check if $k$ is present in the sequence $n\oplus 0,n\oplus 1,...,n\oplus m$ ? Think. If $k$ is present in the sequence, then there must be some $x$ such that $0 \le x \le m$ and $n\oplus x = k$, right? Did you know that $n\oplus k = x$ is equivalent to $n\oplus x = k$ ? So we can just check if $n\oplus k \le...
[ "binary search", "bitmasks", "greedy", "implementation" ]
1,800
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n, m = map(int, input().split()) m += 1 ans = 0 for k in range(30, -1, -1): if (n >= m): break if ((n >> k & 1) == (m >> k & 1)): continue if (m >> k & 1): ans |= 1 << k n |= 1 << k print(ans)
1554
D
Diane
You are given an integer $n$. Find any string $s$ of length $n$ consisting only of English lowercase letters such that each non-empty substring of $s$ occurs in $s$ an \textbf{odd} number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints...
Consider the strings of type "$aa \ldots a$". Which substring occurs in which parity? Observe. Play with them. Consider the string "$aa \ldots a$" ($k$ times '$a$'). WLOG Let $k$ be an odd integer. In this string "$a$" occurs $k$ times, "$aa$" occurs $k - 1$ times and so on. So "$a$", "$aa$", "$aaa$", $\ldots$ occurs o...
[ "constructive algorithms", "greedy", "strings" ]
1,800
#include<bits/stdc++.h> #include "testlib.h" using namespace std; // len -> largest string length of the corresponding endpos-equivalent class // link -> longest suffix that is another endpos-equivalent class. // firstpos -> 1 indexed end position of the first occurrence of the largest string of that node // minlen(v)...
1554
E
You
You are given a tree with $n$ nodes. As a reminder, a tree is a connected undirected graph without cycles. Let $a_1, a_2, \ldots, a_n$ be a sequence of integers. Perform the following operation \textbf{exactly} $n$ times: - Select an \textbf{unerased} node $u$. Assign $a_u :=$ number of \textbf{unerased} nodes adjace...
Let's find which sequences of $a$ are possible to obtain by performing the mentioned operations exactly $n$ times in some order. (Critical) Observation 1: Consider all $a_i = 0$ initially. For each edge $(u, v)$, either increase $a_u$ by $1$ (assign $(u, v)$ to $u$) or increase $a_v$ by $1$ ((assign $(u, v)$ to $v$). T...
[ "dfs and similar", "dp", "math", "number theory" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 1e5 + 9, mod = 998244353; vector<int> g[N]; int dp[N], d, ok, ans[N]; void dfs(int u, int p = 0) { if (!ok) return; for (auto v: g[u]) { if (v ^ p) { dfs(v, u); } } if (dp[u] % d != 0) { if (p) { dp[u]++; } if (dp[u] % ...
1555
A
PizzaForces
PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $6$ slices, medium ones consist of $8$ slices, and large pizzas consist of $10$ slices each. Baking them takes $15$, $20$ and $25$ minutes, respectively. Petya's birthday is today, and $n$ of his friend...
Note that the "speed" of cooking $1$ slice of pizza is the same for all sizes - $1$ slice of pizza for $2.5$ minutes. If $n$ is odd, then we will increase it by $1$ (since the pizza is cooked only with an even number of pieces). Now the value of $n$ is always even. If $n < 6$, then for such $n$ the answer is equal to t...
[ "brute force", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { long long n; cin >> n; cout << max(6LL, n + 1) / 2 * 5 << '\n'; } }
1555
B
Two Tables
You have an axis-aligned rectangle room with width $W$ and height $H$, so the lower left corner is in point $(0, 0)$ and the upper right corner is in $(W, H)$. There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $(x_1, y_1)$, and the upper r...
Firstly, let's notice the next property: if two axis-aligned rectangles don't intersect, then we can draw a vertical or horizontal line between them. In other words, either $\max(x_1, x_2) \le \min(x_3, x_4)$ or $\max(x_3, x_4) \le \min(x_1, x_2)$ if $x_1$ and $x_2$ are coordinates of the one rectangle and $x_3$ and $x...
[ "brute force" ]
1,300
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); int W, H; int x1, y1, x2, y2; int w, h; inline bool read() { if(!(cin ...
1555
C
Coin Rows
Alice and Bob are playing a game on a matrix, consisting of $2$ rows and $m$ columns. The cell in the $i$-th row in the $j$-th column contains $a_{i, j}$ coins in it. Initially, both Alice and Bob are standing in a cell $(1, 1)$. They are going to perform a sequence of moves to reach a cell $(2, m)$. The possible mov...
First, observe that each of the players has only $m$ options for their path - which column to go down in. Let's consider a Bob's response to a strategy chosen by Alice. The easiest way to approach that is to look at the picture of the Alice's path. The path clearly separates the field into two independent pieces - suff...
[ "brute force", "constructive algorithms", "dp", "implementation" ]
1,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 2e9 + 10; int main() { int t; scanf("%d", &t); forn(_, t){ int n; scanf("%d", &n); vector<vector<int>> a(2, vector<int>(n)); forn(i, 2) forn(j, n) scanf("%d", &a[i][j]); int ans = INF; ...
1555
D
Say No to Palindromes
Let's call the string \textbf{beautiful} if it does not contain a substring of length at least $2$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are pali...
Note that in the beautiful string $s_i \neq s_{i-1}$ (because it is a palindrome of length $2$) and $s_i \neq s_{i-2}$ (because it is a palindrome of length $3$). This means $s_i = s_{i-3}$, i.e. a beautiful string has the form abcabcabc..., up to the permutation of the letters a, b and c. For each permutation of the l...
[ "brute force", "constructive algorithms", "dp", "strings" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; string s; cin >> s; vector<vector<int>> pr(6, vector<int>(n + 1)); string t = "abc"; int cur = 0; do { for (int i = 0; i < n; ++i) pr[cur][i + 1] = pr[cur...
1555
E
Boring Segments
You are given $n$ segments on a number line, numbered from $1$ to $n$. The $i$-th segments covers all integer points from $l_i$ to $r_i$ and has a value $w_i$. You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if ...
Take a look at the condition for a good subset. The major implication it makes is that every point (even non-integer) of the segment $[1; m]$ should be covered by at least one segment. If some point isn't, then there is no way to jump across the gap it produces. At the same time, this condition is enough to have a path...
[ "data structures", "sortings", "trees", "two pointers" ]
2,100
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; vector<int> t, ps; void push(int v){ if (v * 2 + 1 < int(ps.size())){ ps[v * 2] += ps[v]; ps[v * 2 + 1] += ps[v]; } t[v] += ps[v]; ps[v] = 0; } void upd(int v, int l, int r, int L, int R,...
1555
F
Good Graph
You have an undirected graph consisting of $n$ vertices with weighted edges. A simple cycle is a cycle of the graph without repeated vertices. Let the weight of the cycle be the XOR of weights of edges it consists of. Let's say the graph is good if all its simple cycles have weight $1$. A graph is bad if it's not goo...
Firstly, let's prove that a good graph has one important property: any two of its simple cycles intersect by at most one vertex, i. e. there is no edge that belongs to more than one simple cycle (cactus definition, yeah). Let's prove it by showing that if two simple cycles of weight $k > 0$ intersects (by edges) then t...
[ "data structures", "dsu", "graphs", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out <<...
1556
A
A Variety of Operations
William has two numbers $a$ and $b$ initially both equal to \textbf{zero}. William mastered performing three different operations with them quickly. Before performing each operation some positive integer $k$ is picked, which is then used to perform one of the following operations: (note, that for each operation you can...
Note, that after any of the operations, the parity of the expression $a - b$ does not change, so if the initial difference of the pair $c - d$ is odd, then it is impossible to get this pair. Now, note that if we can get a $(c, d)$ pair, then it can be obtained in no more than $2$ operations. To do this, consider three ...
[ "math" ]
800
null
1556
B
Take Your Places!
William has an array of $n$ integers $a_1, a_2, \dots, a_n$. In one move he can swap two neighboring items. Two items $a_i$ and $a_j$ are considered neighboring if the condition $|i - j| = 1$ is satisfied. William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array ...
Note that if the condition $|odd - even| > 1$ is satisfied, where $odd$ is the number of odd numbers, and $even$ is the number of even numbers, then it is impossible to get the required array. Now, note that it is enough to consider two cases and choose the minimum answer from these cases: The first element will be an ...
[ "implementation" ]
1,300
null
1556
C
Compressed Bracket Sequence
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $c_1, c_2, \dots, c_n$ where $c_i$ is the number of consecutive brackets "(" if $i$ is an odd number or the number of consecutive brackets ")" if $i$ is an even number. For example...
Let's examine a compressed sequence and fix two indexes $l < r, l$ % $2 = 0, r$ % $2 = 1$. Note that it makes no sense to examine other indexes because the correct bracket sequence always begins with the opening bracket and ends with the closing one. Next, we can calculate the minimum bracket balance on the segment fro...
[ "brute force", "implementation" ]
1,800
null
1556
D
Take a Guess
\textbf{This is an interactive task} William has a certain sequence of integers $a_1, a_2, \dots, a_n$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $2 \cdot n$ of the following questions: - What is the result of a bitwise AND o...
To solve this problem, we can use the fact that $a+b=(a$ or $b) + (a$ and $b)$. Then we can determine the first $3$ numbers in $6$ operations using the sums $a_{01} = a_0 + a_1$, $a_{12} = a_1 + a_2$ and $a_{02} = a_0 + a_2$. Using the formula $a_1 = \frac{a_{01}+a_{12}-a_{02}}{2}$, $a_0 = a_{01} - a_1$ and $a_2 = a_{1...
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
1,800
null
1556
E
Equilibrium
William has two arrays $a$ and $b$, each consisting of $n$ items. For some segments $l..r$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $i$ from $l$ to $r$ holds $a_i = b_i$. To per...
The first step to solving this problem is to create some array $C$, where $c_i = a_i - b_i$. Then we can select some elements from this array C and do operations $+1, -1, +1, -1 \dots$ for these elements for the corresponding elements. And the challenge is to make this array consist of zeros. It is argued that this can...
[ "data structures", "dp", "greedy" ]
2,200
null
1556
F
Sports Betting
William is not only interested in trading but also in betting on sports matches. $n$ teams participate in each match. Each team is characterized by strength $a_i$. Each two teams $i < j$ play with each other exactly once. Team $i$ wins with probability $\frac{a_i}{a_i + a_j}$ and team $j$ wins with probability $\frac{a...
Let $ALL$ be all teams, and $F(winners)$ be the probability that a set of $winners$ teams are winners, and the rest of $ALL \setminus winners$ teams are not. Then the answer will be the following value: $\sum_{winners \neq \varnothing, winners \subseteq ALL} F(winners) \cdot |winners|$ Let's define extra value: $P(winn...
[ "bitmasks", "combinatorics", "dp", "graphs", "math", "probabilities" ]
2,500
null
1556
G
Gates to Another World
As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from $0$ to $2^n - 1$. On each planet, there are gates that allow the player to move from planet $i$ to planet $j$ if the binary repre...
Let's change the formulation of the problem: we will execute queries in reverse order, and assign a lifetime to each segment of blocked vertices. Lifetime - until what moment the segment is blocked. Note, if we look through the requests in reverse order, then for each segment it is possible to determine the moment of t...
[ "bitmasks", "data structures", "dsu", "two pointers" ]
3,300
null
1556
H
DIY Tree
William really likes puzzle kits. For one of his birthdays, his friends gifted him a complete undirected edge-weighted graph consisting of $n$ vertices. He wants to build a spanning tree of this graph, such that for the first $k$ vertices the following condition is satisfied: the degree of a vertex with index $i$ does...
Let's call the first $k$ vertices special. First of all, let's note that the number of different forests on $5$ vertices is at most $300$. It means that we can try all of them, one by one, as the set of all edges of the answer with both endpoints being the special vertices. Let $T$ be the set of chosen edges with both ...
[ "graphs", "greedy", "math", "probabilities" ]
3,300
null
1557
A
Ezzat and Two Subsequences
Ezzat has an array of $n$ integers \textbf{(maybe negative)}. He wants to split it into two \textbf{non-empty} subsequences $a$ and $b$, such that every element from the array belongs to exactly one subsequence, and the value of $f(a) + f(b)$ is the maximum possible value, where $f(x)$ is the average of the subsequence...
The average of a group of numbers always has a value between the minimum and maximum numbers in that group. Since the average of a group of numbers always has a value between the minimum and maximum numbers in that group, it can be proved that the best approach to obtain the maximum sum of averages of two subsequences ...
[ "brute force", "math", "sortings" ]
800
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> using namespace std; void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } int main() { run(); cout << fixed << setprecision(10); int t; cin >> t; while (t--) { ...
1557
B
Moamen and k-subarrays
Moamen has an array of $n$ \textbf{distinct} integers. He wants to sort that array in non-decreasing order by doing the following operations in order \textbf{exactly once}: - Split the array into exactly $k$ non-empty subarrays such that each element belongs to exactly one subarray. - Reorder these subarrays arbitrary...
You can ignore the $k$ given in the input, try to find the minimum $k$ you need to sort the array (let call it $mnK$). If $mnK$ $\le$ $k$ then you can split some subarrays to make it equal $k$, so the answer is will be "YES". otherwise, the answer will be "NO". You need to split the array into the minimum number of sub...
[ "greedy", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; #define endl "\n" void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } int main() { run(); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<pair<int, in...
1557
C
Moamen and XOR
Moamen and Ezzat are playing a game. They create an array $a$ of $n$ non-negative integers where every element is less than $2^k$. Moamen wins if $a_1 \,\&\, a_2 \,\&\, a_3 \,\&\, \ldots \,\&\, a_n \ge a_1 \oplus a_2 \oplus a_3 \oplus \ldots \oplus a_n$. Here $\&$ denotes the bitwise AND operation, and $\oplus$ denot...
We don't care about the values in the array to know it's valid or not, we just need to know for every bit how many numbers have this bit on or off. Try to build the array from the most significant bit ($k-1$) to the least significant bit $0$ using dynamic programming. Can you optimize dynamic programming code with some...
[ "bitmasks", "combinatorics", "dp", "math", "matrices" ]
1,700
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; #define endl "\n" #define ll long long void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } con...
1557
D
Ezzat and Grid
Moamen was drawing a grid of $n$ rows and $10^9$ columns containing only digits $0$ and $1$. Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful. A grid is beautiful if and only if for every two consecutive rows there is at least one ...
Try to count the maximum number of rows that makes a beautiful grid, and remove the others. Can you get some dynamic programming formula, and then optimize it with some ranges data structures? We can use dynamic programming to get the maximum number of rows that make a beautiful grid. Define the 2d array, $dp$, where $...
[ "data structures", "dp", "greedy" ]
2,200
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; #define endl "\n" #define ll long long #define sz(s) (int)(s.size()) #define INF 0x3f3f3f3f3f3f3f3fLL #define all(v) v.begin(),v.end() #define watch(x) cout<<(#x)<<" = "<<x<<endl const int dr...
1557
E
Assiut Chess
This is an interactive problem. ICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king. You compete on an $8\times8$ chessboard, the rows are numerated from top to bottom, and the co...
Try to force the king to move into one of the corners down. If you put the queen in a row $x$, move the queen to the left of the row, then start swiping the row right, one square at a time. If you've visited all $8$ squares on the row and the king never made a vertical move, it means $|$ current king row $-$ current qu...
[ "brute force", "constructive algorithms", "interactive" ]
2,800
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; //#define endl "\n" #define ll long long #define sz(s) (int)(s.size()) #define INF 0x3f3f3f3f3f3f3f3fLL #define all(v) v.begin(),v.end() #define watch(x) cout<<(#x)<<" = "<<x<<endl const int ...
1558
A
Charmed by the Game
Alice and Borys are playing tennis. A tennis match consists of games. In each game, one of the players is serving and the other one is receiving. Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa. Each game ends with a victory of one of the players. If ...
First of all, we don't know who served first, but there are only two options, so let's just try both and unite the sets of $k$'s we get. Assume that Alice served first. Exactly $a+b$ games were played. If $a+b$ is even, both players served exactly $\frac{a+b}{2}$ times, and if $a+b$ is odd, Alice served one more time t...
[ "brute force", "math" ]
1,300
null
1558
B
Up the Strip
\textbf{Note that the memory limit in this problem is lower than in others.} You have a vertical strip with $n$ cells, numbered consecutively from $1$ to $n$ from top to bottom. You also have a token that is initially placed in cell $n$. You will move the token up until it arrives at cell $1$. Let the token be in ce...
This problem was inspired by Blogewoosh #4 a long time ago (Blogewoosh #8 when?). Pretty clearly, we are facing a dynamic programming problem. Let $f(x)$ be the number of ways to move from cell $x$ to cell $1$. Then, $f(1) = 1$, $f(x) = \sum \limits_{y=1}^{x-1} f(x-y) + \sum \limits_{z=2}^{x} f(\lfloor \frac{x}{z} \rfl...
[ "brute force", "dp", "math", "number theory", "two pointers" ]
1,900
null
1558
C
Bottom-Tier Reversals
You have a permutation: an array $a = [a_1, a_2, \ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd. You need to sort the permutation in increasing order. In one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if $a = [a_1, a_2,...
First of all, consider what happens when we reverse a prefix of odd length $p$. Elements $a_{p+1}$ to $a_n$ don't move at all, and for each $i$ from $1$ to $p$, $a_i$ moves to $a_{p-i+1}$. Note that $i$ and $p-i+1$ have the same parity: therefore, no element can ever change the parity of its position. In the final sort...
[ "constructive algorithms", "greedy" ]
2,000
null
1558
D
Top-Notch Insertions
Consider the insertion sort algorithm used to sort an integer sequence $[a_1, a_2, \ldots, a_n]$ of length $n$ in non-decreasing order. For each $i$ in order from $2$ to $n$, do the following. If $a_i \ge a_{i-1}$, do nothing and move on to the next value of $i$. Otherwise, find the smallest $j$ such that $a_i < a_j$,...
First of all, note that the sequence of insertions uniquely determines where each element goes. For example, for $n = 5$ and a sequence of insertions $(3, 1), (4, 1), (5, 3)$, the initial sequence $[a_1, a_2, a_3, a_4, a_5]$ is always transformed into $[a_4, a_3, a_5, a_1, a_2]$, no matter what $a_i$ are. Thus, instead...
[ "combinatorics", "data structures" ]
2,600
null
1558
E
Down Below
In a certain video game, the player controls a hero characterized by a single integer value: power. On the current level, the hero got into a system of $n$ caves numbered from $1$ to $n$, and $m$ tunnels between them. Each tunnel connects two distinct caves. Any two caves are connected with at most one tunnel. Any cav...
Let's find the smallest possible initial power with binary search. Suppose the initial power is $p$. The main idea behind the solution is to maintain a set of caves where we have beaten all the monsters, and try to extend the set by finding "augmenting" paths. However, we can not just go in an arbitrary unvisited cave ...
[ "binary search", "dfs and similar", "graphs", "greedy", "meet-in-the-middle", "shortest paths" ]
3,000
null
1558
F
Strange Sort
You have a permutation: an array $a = [a_1, a_2, \ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd. Consider the following algorithm of sorting the permutation in increasing order. A helper procedure of the algorithm, $f(i)$, takes a single argument $i$ ($1 \le i \le n-1$) a...
Let's draw a wall of $n$ towers of cubes, with the $i$-th tower having height $a_i$. For example, for $a = [4, 5, 7, 1, 3, 2, 6]$ the picture will look as follows ($1$ stands for a cube): Note that applying $f(i)$ to the permutation (swapping $a_i$ and $a_{i+1}$ if $a_i > a_{i+1}$) is equivalent to applying $f(i)$ to e...
[ "data structures", "sortings" ]
3,300
null
1559
A
Mocha and Math
Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation. This day, Mocha got a sequence $a$ of length $n$. In each operation, she can select an arbitrar...
We assume the answer is $x$. In its binary representation, one bit will be $1$ only if in all the $a_i$'s binary representation,this bit is $1$. Otherwise, we can use one operation to make this bit in $x$ become 0, which is a smaller answer. So we can set $x=a_1$ initially. Then we iterate over the sequence and make $x...
[ "bitmasks", "constructive algorithms", "math" ]
900
#include<bits/stdc++.h> #define inf 0x3f3f3f3f #define maxm 100005 #define maxn 2005 #define PII pair<int, int> #define fi first #define se second typedef long long ll; typedef unsigned long long ull; using namespace std; const double pi = acos(-1); const int mod = 998244353; const double eps = 1e-10; const int N =1e2+...
1559
B
Mocha and Red and Blue
As their story unravels, a timeless tale is told once again... Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to s...
For a longest period of "?", it is optimized to paint either "RBRB..." or "BRBR...", so the imperfectness it made is only related to the colors of both sides of it. Choose the one with the lower imperfectness for each longest period of "?" in $O(n)$ is acceptable. More elegantly, if the square on the left or on the rig...
[ "dp", "greedy" ]
900
#include <cstdio> using namespace std; const int N=105; int t,n,cnt; char s[N]; int main() { scanf("%d",&t); while (t--) { cnt=0; scanf("%d",&n); scanf("%s",s+1); for (int i=1;i<=n;i++) cnt+=(s[i]!='?'); if (!cnt) s[1]='R'; for (int i=2;i<=n;i++) if (s[i]=='?'&&s[i-1]!='?') s[i]=s[i-1]^('B'^...
1559
C
Mocha and Hiking
The city where Mocha lives in is called Zhijiang. There are $n+1$ villages and $2n-1$ directed roads in this city. There are two kinds of roads: - $n-1$ roads are from village $i$ to village $i+1$, for all $1\leq i \leq n-1$. - $n$ roads can be described by a sequence $a_1,\ldots,a_n$. If $a_i=0$, the $i$-th of these...
If $a_1=1$, then the path $\Big[(n+1) \to 1 \to 2 \to \cdots \to n\Big]$ is valid. If $a_n=0$, then the path $\Big[1 \to 2 \to \cdots \to n \to (n+1) \Big]$ is valid. Otherwise, since $a_1=0 \land a_n=1$, there must exists an integer $i$ ($1 \le i < n$) where $a_i=0 \land a_{i+1}=1$, then the path $\Big[1 \to 2 \to \cd...
[ "constructive algorithms", "graphs" ]
1,200
#include <bits/stdc++.h> #define maxn 100086 using namespace std; int t, n; int a[maxn]; void solve(){ scanf("%d", &n); for(int i = 1;i <= n;i++) scanf("%d", &a[i]); if(a[1]){ printf("%d ", n + 1); for(int i = 1;i <= n;i++) printf("%d ", i); return; } for(int i = 1;i < n;i++){ if(!a[i] && a[i + 1]){ ...
1559
D1
Mocha and Diana (Easy Version)
\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.} A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them ...
In the final situation, if one forest has more than one tree, we choose two trees from it, such as tree $A$ and tree $B$. Then we consider node $a$ in $A$ and node $b$ in $B$, they must be connected in another forest. We can easily find node $b$ is connected with all the nodes in $A$ and node $a$ is connected with all ...
[ "brute force", "constructive algorithms", "dsu", "graphs", "greedy", "trees" ]
1,400
#include<bits/stdc++.h> #define maxn 2005 #define fi first #define se second #define PII pair<int, int> using namespace std; typedef long long ll; const ll mod = 10007; inline ll read(){ ll x = 0, f = 1;char ch = getchar(); while(ch > '9' || ch < '0'){if(ch == '-') f = -1;ch = getchar();} while(ch >= '0...
1559
D2
Mocha and Diana (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.} A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them ...
To have a clearer understanding, let's visualize the problem with a grid where each row is a component in the left forest and each column is a component in the right forest. For example, the cell (i,j) contains vertexes which belongs to $i^{th}$ component in the left forest and $j^{th}$ component in the right tree. (So...
[ "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "trees", "two pointers" ]
2,500
#include<bits/stdc++.h> using namespace std; #define N 100010 int fa1[N],fa2[N]; set<pair<int,int> > rows; set<int> row[N],col[N]; set<int>::iterator it; map<int,int> mp[N]; pair<int,int> Ans[N]; int getfa(int *fa,int x){ if (x==fa[x]){ return x; } return fa[x]=getfa(fa,fa[x]); } void Merge_row(int x,int y){ for ...
1559
E
Mocha and Stars
Mocha wants to be an astrologer. There are $n$ stars which can be seen in Zhijiang, and the brightness of the $i$-th star is $a_i$. Mocha considers that these $n$ stars form a constellation, and she uses $(a_1,a_2,\ldots,a_n)$ to show its state. A state is called mathematical if all of the following three conditions a...
We firstly ignore the constraint of $\gcd$, let $f([l_1,l_2,\ldots,l_n],[r_1,r_2,\ldots,r_n],M)$ be the number of integers $(a_1,a_2,\cdots,a_n)$ satisfy the following two conditions: For all $i$ ($1\le i\le n$), $a_i$ is an integer in the range $[l_i, r_i]$. $\sum \limits _{i=1} ^ n a_i \le m$. We can compute it in $O...
[ "combinatorics", "dp", "fft", "math", "number theory" ]
2,200
#include <bits/stdc++.h> #define maxn 100086 using namespace std; const int p = 998244353; int n, m; int l[maxn], r[maxn]; int f[maxn], sum[maxn]; int cal(int d){ int M = m / d; f[0] = 1; for(int i = 1;i <= M;i++) f[i] = 0; for(int i = 1;i <= n;i++){ int L = (l[i] + d - 1) / d, R = r[i] / d; if(L > R) retur...
1560
A
Dislike of Threes
Polycarp doesn't like integers that are divisible by $3$ or end with the digit $3$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too. Polycarp starts to write out the positive (greater than $0$) integers which he likes: $1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \dots$. Output t...
The solution is simple: let's create an integer variable (initially set to $0$) that will contain the number of considered liked integers. Let's iterate over all positive integers starting with $1$. Let's increase the variable only when the considered number is liked. If the variable is equal to $k$, let's stop the ite...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int k; cin >> k; for (int i = 1; ; i++) { if (i % 3 == 0 || i % 10 == 3) continue; if (--k == 0) { cout << i << '\n'; break; } } } }
1560
B
Who's Opposite?
Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $1$. Each person is looking through the circle's center at the opposite person. \begin{center} {\small A sample of a circle of $6$ persons. The o...
The person with the number $a$ looks at the person with the number $b$ so the count of people standing to the left of $a$ between $a$ and $b$ is equal to the count of people standing to the right of $a$ between $a$ and $b$. Therefore, both counts are equal to $\frac{n - 2}{2}$, hence $n$ must be a solution of the equat...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int t; cin >> t; while (t--) { ll a, b, c; cin >> a >> b >> c; ll n = 2 * abs(a - b); if (a > n || b > n || c > n) cout << -1 << '\n'; else { ll d = n / 2 + c; while (d > n) d -= n; cout << d << '\n'; } ...
1560
C
Infinity Table
Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $1$, starting from the topmost one. The columns are numbered from $1$, starting from the leftmost one. Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $1$ and so on to the ...
Let's call a set of cells being filled from the topmost row to the leftmost column a layer. E. g. the $1$-st layer consists of the single number $1$, the $2$-nd layer consists of the numbers $2$, $3$ and $4$, the $3$-rd layer consists of the numbers $5$, $6$, $7$, $8$ and $9$, etc. The number of cells in layers forms a...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int k; cin >> k; int a = 1; int x = 1; int i = 1; while (k >= x + a) { x += a; a += 2; i += 1; } int m = k - x + 1; if (m <= i) cout << m << ' ' << i << '\n'; else cout << i << ' ' <<...
1560
D
Make a Power of Two
You are given an integer $n$. In $1$ move, you can do one of the following actions: - erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); - add one digit \textbf{to the right}. The actions may be performed in any order any ...
Suppose we must turn $n$ into some specific number $x$. In this case, we can use the following greedy algorithm. Consider the string forms - $s_n$ and $s_x$ - of the numbers $n$ and $x$, respectively. Let's make a pointer $p_n$ pointing at the first character of the string $s_n$ and a pointer $p_x$ pointing at the firs...
[ "greedy", "math", "strings" ]
1,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll P2LIM = (ll)2e18; int solve(string s, string t) { int tp = 0; int sp = 0; int taken = 0; while (sp < s.length() && tp < t.length()) { if(s[sp] == t[tp]) { taken++; tp++; } sp++; } return (int)s.length() - taken + (in...
1560
E
Polycarp and String Transformation
Polycarp has a string $s$. Polycarp performs the following actions until the string $s$ is empty ($t$ is initially an empty string): - he adds to the right to the string $t$ the string $s$, i.e. he does $t = t + s$, where $t + s$ is a concatenation of the strings $t$ and $s$; - he selects an arbitrary letter of $s$ an...
Suppose it's given a string $t$ for which the answer exists. Consider the last non-empty value of $s$. Only $1$ letter occurs in the value and the letter is the last removed letter. At the same time, the value of $s$ is a suffix of $t$ so the last character of $t$ is the last removed letter. Consider the second-last no...
[ "binary search", "implementation", "sortings", "strings" ]
1,800
#include <bits/stdc++.h> using namespace std; int cntsrc[26]; // don't forget to memset it but not cnt int* cnt = cntsrc - 'a'; // so cnt['a'] = cntsrc[0] and so on pair<string, string> decrypt(string s) { string order; reverse(s.begin(), s.end()); for (auto c : s) { if (!cnt[c]) order.push_back(c); cnt[c...
1560
F1
Nearest Beautiful Number (easy version)
It is a simplified version of problem F2. The difference between them is the constraints (F1: $k \le 2$, F2: $k \le 10$). You are given an integer $n$. Find the minimum integer $x$ such that $x \ge n$ and the number $x$ is $k$-beautiful. A number is called $k$-beautiful if its decimal representation having no leading...
Suppose the number $n$ contains $m$ digits. The desired number $x$ isn't greater than the number consisting of $m$ digits $9$. This number is $1$-beautiful whereas any $1$-beautiful number is at the same time $k$-beautiful, so $x$ contains at most $m$ digits. At the same time, $x \ge n$ so $x$ contains at least $m$ dig...
[ "binary search", "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; string solve1(string n) { string res(n.length(), '9'); for (char c = '8'; c >= '0'; c--) { string t(n.length(), c); if (t >= n) res = t; } return res; } string solve2(string n) { string res = solve1(n); for(char a = '0'; a <= '9'; a++) for (char b = a +...
1560
F2
Nearest Beautiful Number (hard version)
It is a complicated version of problem F1. The difference between them is the constraints (F1: $k \le 2$, F2: $k \le 10$). You are given an integer $n$. Find the minimum integer $x$ such that $x \ge n$ and the number $x$ is $k$-beautiful. A number is called $k$-beautiful if its decimal representation having no leadin...
Suppose the number $n$ contains $m$ digits and its decimal representation is $d_1d_2 \dots d_m$. The desired number $x$ isn't greater than the number consisting of $m$ digits $9$. This number is $1$-beautiful whereas any $1$-beautiful number is at the same time $k$-beautiful, so $x$ contains at most $m$ digits. At the ...
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dp", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; string solveFillingSuffix(string& n, char d, int from) { for (int i = from; i < n.length(); i++) n[i] = d; return n; } void decAt(map<char, int>& d, char c) { if (d.count(c)) { d[c]--; if (d[c] == 0) d.erase(c); } } string solve() { string n; int k; cin >>...
1561
A
Simply Strange Sort
You have a permutation: an array $a = [a_1, a_2, \ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd. Consider the following algorithm of sorting the permutation in increasing order. A helper procedure of the algorithm, $f(i)$, takes a single argument $i$ ($1 \le i \le n-1$) a...
The described sorting algorithm is similar to Odd-even sort. In this problem, it's enough to carefully implement the process described in the problem statement. Here is one sample implementation in C++: To estimate the complexity of this solution, we need to know the maximum number of iterations required to sort a perm...
[ "brute force", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt–) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } int ans = 0; while (!is_sorted(a.begin(), a.end())) { for (int i = ans % 2; i + 1 < n; i += 2) { ...
1561
C
Deep Down Below
In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor. On the current level, the hero is facing $n$ caves. To pass the level, the hero must enter all the caves in some order, e...
Consider a single cave $i$. Suppose that the hero enters the cave with power $x$. To beat the first monster, $x$ has to be greater than $a_{i, 1}$. After that, the hero's power will increase to $x+1$, and to beat the second monster, $x+1$ has to be greater than $a_{i, 2}$. Continuing this reasoning, we can write down $...
[ "binary search", "greedy", "sortings" ]
1,300
null
1562
A
The Miracle and the Sleeper
You are given two integers $l$ and $r$, $l\le r$. Find the largest possible value of $a \bmod b$ over all pairs $(a, b)$ of integers for which $r\ge a \ge b \ge l$. As a reminder, $a \bmod b$ is a remainder we get when dividing $a$ by $b$. For example, $26 \bmod 8 = 2$.
It's not hard to see that if $l \le \lfloor \frac{r}{2} \rfloor + 1$, then $r \bmod (\lfloor \frac{r}{2} \rfloor + 1) = \lfloor \frac{r-1}{2} \rfloor$. It can be shown that the maximal possible answer. At the same time, let the segment not contain number $\lfloor \frac{r}{2} \rfloor + 1$, that is, $l > \lfloor \frac{r}...
[ "greedy", "math" ]
800
#include <iostream> using namespace std; int l, r; void solve() { if (r < l * 2) { cout << r - l << endl; } else { cout << (r - 1) / 2 << endl; } } int main() { int t; cin >> t; while (t--) { cin >> l >> r; solve(); } }
1562
B
Scenes From a Memory
During the hypnosis session, Nicholas suddenly remembered a positive integer $n$, which \textbf{doesn't contain zeros in decimal notation}. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes \textbf{not prime}, that is, eithe...
Let's show that if a number has three digits, you can always remove at least one from it to get a number that is not prime. This can be proved by a simple brute-force search of all numbers with three digits, but we'll try to do it without a brute-force search. In fact, if a number contains the digits '1', '4', '6', '8'...
[ "brute force", "constructive algorithms", "implementation", "math", "number theory" ]
1,000
#include <iostream> using namespace std; int n; string s; bool prime[100]; void solve() { for (int i = 0; i < n; i++) { if (s[i] == '1' || s[i] == '4' || s[i] == '6' || s[i] == '8' || s[i] == '9') { cout << 1 << endl; cout << s[i] << endl; return; } } ...
1562
C
Rings
\begin{quote} {{\small Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents —there was a pile of different rings: gold and silver..."How am I to tell which is the One?!" the mage howled. "Throw them one by one into the Cracks of Doom and watch when Mordor falls!"}} \end{quote} Somewh...
Let us first consider the boundary case. Let a string (hereafter we will assume that the string length $n$) consists of only ones. Then we can output the numbers $1$ $n-1$ $2$ $n$ as the answer, since there will be the same substrings. Now let's figure out what to do in the other case. Let's call the substring [$1$ ......
[ "constructive algorithms", "math" ]
1,500
#include <iostream> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; bool solved = false; for (int i = 0; i < n; i++) { if (s[i] == '0') { solved = true; if (i >...
1562
D1
Two Hundred Twenty One (easy version)
\textbf{This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.} Stitch likes experimenting with different machines with his friend Spar...
Let's prove everything for a particular segment of length $n$. And at the end, we'll show how to quickly solve the problem for many segments. Let $n$ - the length of the segment, and let $a$ - the array corresponding to the segment ($a_i = 1$ if "+" is at the $i$th position in the segment, and $a_i = -1$ if "-" is at t...
[ "data structures", "dp", "math" ]
1,700
#include <iostream> using namespace std; int a[1000000 + 5], p[1000000 + 5]; int get_sum(int l, int r) { if (l > r) { return 0; } return (l % 2 == 1) ? p[r] - p[l - 1] : p[l - 1] - p[r]; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin>>t; while (...
1562
D2
Two Hundred Twenty One (hard version)
\textbf{This is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.} Stitch likes experimenting with different machines with his friend Sparky. ...
We will use the facts already obtained, given in the solution of problem D1. To quickly check the value of the sign-variable sum on the segment with deletion of one element, slightly modify the prefix-sum. We will not concentrate on this in detail; you can see how to make it in the solution. Now let's see how to search...
[ "data structures", "math" ]
2,200
#include <iostream> using namespace std; int a[1000000 + 5], p[1000000 + 5]; int get_sum(int l, int r) { if (l > r) { return 0; } return (l % 2 == 1) ? p[r] - p[l - 1] : p[l - 1] - p[r]; } int check_elimination(int l, int r, int m) { return ((m - l + 1) % 2 == 1) ? get_sum(l, m - 1) + ge...
1562
E
Rescue Niwen!
\begin{quote} {{\small Morning desert sun horizonRise above the sands of time...}} \hfill {\small Fates Warning, "Exodus"} \end{quote} After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light ...
The constraints on the problem were chosen so that solutions slower than $O(n^2 \cdot log(n))$ would not get AC, or would get with difficulty. The solution could be, for example, to sort all substrings by assigning numbers to them, and then find the largest increasing subsequence in the resulting array. Let us describe...
[ "dp", "greedy", "string suffix structures", "strings" ]
2,500
#include <iostream> using namespace std; int16_t lcp[10000 + 5][10000 + 5]; int dp[10000 + 5]; bool is_greater(const string& s, int x, int y) { if (lcp[x][y] == static_cast<int>(s.size()) - x) { return false; } return s[x + lcp[x][y]] > s[y + lcp[x][y]]; } int get_score(const string& s, int x, ...
1562
F
Tubular Bells
Do you know what tubular bells are? They are a musical instrument made up of cylindrical metal tubes. In an orchestra, tubular bells are used to mimic the ringing of bells. Mike has tubular bells, too! They consist of $n$ tubes, and each of the tubes has a length that can be expressed by a integer from $l$ to $r$ incl...
As I know, there are simpler solutions to this problem, but I will describe my solution. We can assume the whole array is randomly permutated, because we can make queries by renumbering it. We also pre-calculate all prime numbers smaller than $200000$. Let us denote something: $n$ - the number of numbers in the array, ...
[ "interactive", "math", "number theory", "probabilities" ]
2,900
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <ctime> #include <random> using namespace std; #define int long long mt19937 rnd(time(NULL)); int swnmb[1000000+5]; int swnmbr[1000000+5]; int b[1000000+5]; bool p[1000000+5]; vector<int> primes; int get_lcm(int x, int y) { ...
1566
A
Median Maximization
You are given two positive integers $n$ and $s$. Find the maximum possible median of an array of $n$ \textbf{non-negative} integers (not necessarily distinct), such that the sum of its elements is equal to $s$. A \textbf{median} of an array of integers of length $m$ is the number standing on the $\lceil {\frac{m}{2}} ...
Which numbers smaller than the median should be taken? Which numbers bigger than the median should be taken? Greedy algorithm. Let's consider the array of $n$ elements in non-decreasing order. We can make numbers before the median equal to zero, after that we have $m = \lfloor {\frac{n}{2}} \rfloor + 1$ numbers, which ...
[ "binary search", "greedy", "math" ]
800
t = int(input()) for test in range(t): n, s = map(int, input().split()) L = 0 R = 10**10 while R - L > 1: M = (L + R) // 2 m = n // 2 + 1 if m * M <= s: L = M else: R = M print(L)
1566
B
MIN-MEX Cut
A binary string is a string that consists of characters $0$ and $1$. Let $\operatorname{MEX}$ of a binary string be the smallest digit among $0$, $1$, or $2$ that does not occur in the string. For example, $\operatorname{MEX}$ of $001011$ is $2$, because $0$ and $1$ occur in the string at least once, $\operatorname{ME...
The answer is never greater than $2$. If a string consists only of $1$, then the answer is $0$. If all zeroes are consequent, then the answer is $1$. The answer is never greater than $2$, because $\text{MEX}$ of the whole string is not greater than $2$. The answer is $0$ only if there are no zeroes in the string. Now w...
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
800
t = int(input()) for test in range(t): s = input() zeroes = s.count('0') if zeroes == 0: print(0) continue first = s.find('0') last = s.rfind('0') if last - first + 1 == zeroes: print(1) else: print(2)
1566
C
MAX-MEX Cut
A binary string is a string that consists of characters $0$ and $1$. A bi-table is a table that has exactly two rows of equal length, each being a binary string. Let $\operatorname{MEX}$ of a bi-table be the smallest digit among $0$, $1$, or $2$ that does not occur in the bi-table. For example, $\operatorname{MEX}$ fo...
You can cut out the columns with both $0$ and $1$. Now in each column there are only $0$ or only $1$. We only need to solve the problem for a string because the columns can be replaced by one digit (they consist of equal elements). Let's be greedy, to each zero we will "join" not more than one $1$. Let's solve the same...
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
1,000
#include<bits/stdc++.h> using namespace std; int mex(string s){ int fl=0; for(auto &nx : s){ if(nx=='0'){fl|=1;} else if(nx=='1'){fl|=2;} } if(fl==3){return 2;} if(fl==1){return 1;} return 0; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t>0){ ...
1566
D2
Seating Arrangements (hard version)
\textbf{It is the hard version of the problem. The only difference is that in this version $1 \le n \le 300$.} In the cinema seats can be represented as the table with $n$ rows and $m$ columns. The rows are numbered with integers from $1$ to $n$. The seats in each row are numbered with consecutive integers from left t...
Each person can be seated on some subsegment of places with people with the same level of sight. If $n=1$ we should seat people on the maximal possible place. The places available for some person may be a subsegment of a row or a suffix of a row + some full rows + a prefix of a row. Let's consider all seats in increasi...
[ "data structures", "greedy", "implementation", "sortings", "two pointers" ]
1,600
#include <bits/stdc++.h> #define long long long int using namespace std; // @author: pashka void solve_test() { int n, m; cin >> n >> m; vector<pair<int, int>> a(n * m); for (int i = 0; i < n * m; i++) { cin >> a[i].first; a[i].second = i; } sort(a.begin(), a.end()); for ...
1566
E
Buds Re-hanging
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $v$ (different from root) is the previous to $v$ vertex on the shortest path from the root to the vertex $v$. Children of the vertex $v$ are all vertices for which $v$ is the parent. A vertex is a lea...
Re-hanging a bud to a leaf decreases the total amount of leaves by $1$. Buds can be re-hanged that way so in the end there is only a root, buds that are connected to the root and leaves connected to the root or to the buds. Now the answer depends only on the total amount of vertices, on the amount of buds and on the fa...
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; vector<vector<int>> g; vector<int> type; // -1 -- default, 0 -- root, 1 -- leaf, 2 -- bud void dfs(int v, int p) { bool leaves = false; for (auto to : g[v]) { if (to == p) continue; dfs(to, v); if (type[to] == 1) leaves = true; } i...
1566
F
Points Movement
There are $n$ points and $m$ segments on the coordinate line. The initial coordinate of the $i$-th point is $a_i$. The endpoints of the $j$-th segment are $l_j$ and $r_j$ — left and right endpoints, respectively. You can move the points. In one move you can move any point from its current coordinate $x$ to the coordin...
If a segment already contains a point then it can be thrown out of the consideration. If there is a segment that contains some segment, we can save only the smaller one. If you already know which segments will be visited by some point, how you should calculate the answer for this point? For some segment, which points s...
[ "data structures", "dp", "greedy", "implementation", "sortings" ]
2,600
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define ll long long const long long INFLL = 1e18; const int INF = 1e9 + 1; struct segment_tree { vector<int> t; segment_tree(int n) { ...
1566
G
Four Vertices
You are given an undirected weighted graph, consisting of $n$ vertices and $m$ edges. Some queries happen with this graph: - Delete an existing edge from the graph. - Add a non-existing edge to the graph. At the beginning and after each query, you should find four \textbf{different} vertices $a$, $b$, $c$, $d$ such ...
The answer always consists either of three edges with common end or of two edges that don't have any common ends. To find the answer of the second type you can leave in the graph only those edges that are in the list of three smallest edges for both ends. Let's consider those cases when the minimal edge is in the answe...
[ "constructive algorithms", "data structures", "graphs", "greedy", "implementation", "shortest paths" ]
3,100
#include<bits/stdc++.h> using namespace std; #define sz(a) (int) (a).size() const int N = 1e5; vector<pair<int, int>> g[N]; map<pair<int, int>, int> cost; set<pair<int, int>> a[N], b[N]; multiset<long long> dp; set<pair<int, pair<int, int>>> dp2; void solve() { auto minr = *dp2.begin(); long long ans = 1e18...
1566
H
Xor-quiz
\textbf{This is an interactive problem.} You are given two integers $c$ and $n$. The jury has a \textbf{randomly generated} set $A$ of distinct positive integers not greater than $c$ (it is generated from all such possible sets with equal probability). The size of $A$ is equal to $n$. Your task is to guess the set $A...
Numbers with the same set of prime divisors may be considered as the same numbers. The amount of distinct sets of prime divisors which multiplication does not exceed $C$ for such constraints does not exceed $\lceil 0.65 \cdot C \rceil$. How you should find the $xor$ of all numbers that have the same set of prime diviso...
[ "constructive algorithms", "dp", "interactive", "math", "number theory" ]
3,200
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define ll long long #define ld long double const long long INFLL = 1e18; const int INF = 1e9 + 1; const int MAXC = 1e6; mt19937 gen(time(0)); ve...
1567
A
Domino Disaster
Alice has a grid with $2$ rows and $n$ columns. She fully covers the grid using $n$ dominoes of size $1 \times 2$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino. Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of ...
If there is a vertical domino (either U or D) in the current slot, then the corresponding domino half in the other row must be a D or a U, respectively. Otherwise, we can just fill the rest of the row with copies of LR. Time complexity: $\mathcal{O}(n)$.
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s, res; cin >> s; for (int i = 0; i < n; i++) { if (s[i] == 'U') {res += 'D';} else if (s[i] == 'D') {res += 'U';} else {res += "LR";...
1567
B
MEXor Mixup
Alice gave Bob two integers $a$ and $b$ ($a > 0$ and $b \ge 0$). Being a curious boy, Bob wrote down an array of \textbf{non-negative} integers with $\operatorname{MEX}$ value of all elements equal to $a$ and $\operatorname{XOR}$ value of all elements equal to $b$. What is the shortest possible length of the array Bob...
First consider the MEX condition: the shortest array with MEX $a$ is the array $[0, 1, \dots, a - 1]$, which has length $a$. Now we'll consider the XOR condition. Let the XOR of the array $[0, 1, \dots, a - 1]$ be $x$. We have three cases. Case 1: $x = b$. Then we don't need to add any elements to the array, so the ans...
[ "bitmasks", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; const int MAX = 100007; const int MOD = 1000000007; void solve() { int a, b; cin >> a >> b; int pXor; if (a % 4 == 1) {pXor = a - 1;} else if (a % 4 == 2) {pXor = 1;} else if (a % 4 == 3) {pXor = a;} else {pXor = 0;} if (pXor == b) {c...
1567
C
Carrying Conundrum
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left. For example, the \textbf{regular} way to evaluate the sum $2039 + 2976$ would be as shown: However, Alice evaluates it as shown: In...
Note that in every other column, the addition Alice performs is correct. Therefore, we can take our number, split it into alternating digits, and then find the answer. For example, consider $n = 12345$. We split it into alternating digits: $1\underline{2}3\underline{4}5 \to 135, 24$. Now the problem is equivalent to fi...
[ "bitmasks", "combinatorics", "dp", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int dp[10][2][2]; void solve() { string s; cin>>s; int n=s.size(); for (int i=0;i<10;++i) for (int j=0;j<2;++j) for (int k=0;k<2;++k) dp[i][j][k]=0; dp[n][0][0]=1; for (int i=n-1;i>=0;--i) for (int j=0;...
1567
D
Expression Evaluation Error
On the board, Bob wrote $n$ positive integers in base $10$ with sum $s$ (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-$11$ integers and adds them up (in base $11$). What numbers should Bob write on the board, so Alice's sum is as large as possible...
Let's greedily construct the largest possible sum for Alice, digit by digit. That is, the leftmost position should have the largest value possible, then the second-leftmost position, and so on. The maximum value of the leftmost digit of Alice's sum is clearly equal to the leftmost digit of the number $s$, since it cann...
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; long long split(long long n) { long long pow10 = 1; while (pow10 <= n) { if (pow10 == n) {return pow10 / 10;} pow10 *= 10; } return pow10 / 10; } bool isPow10(long long n) { long long pow10 = 1; while (po...
1567
E
Non-Decreasing Dilemma
Alice has recently received an array $a_1, a_2, \dots, a_n$ for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too! However, soon Bob became curious, and as any sane friend would do, asked Alice to perform $q$ operations of two types on he...
Note that if there exists a non-decreasing array of length $x$, then it contains $\frac{x(x+1)}{2}$ non-decreasing subarrays. Therefore, we can break our solution down to counting the lengths of the non-decreasing "chains" within the queried subarray. We can solve this problem using a data structure called a segment tr...
[ "data structures", "divide and conquer", "math" ]
2,200
#include <bits/stdc++.h> #define ll long long using namespace std; const int N = 2e5+5; int a[N], k; ll seg[N*4][4], ans; /** Notes: 0: The total number of non-decreasing subarrays in this segment which are are not subarrays of the longest prefix/suffix of non-decreasing subarrays. 1: Length of longest non-decr...
1567
F
One-Four Overload
Alice has an empty grid with $n$ rows and $m$ columns. Some of the cells are marked, and \textbf{no marked cells are adjacent to the edge of the grid}. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: - every unmarked cell contai...
Let's look at the numbers in the grid modulo $5$. $1$ and $4$ are $1$ and $-1$ modulo $5$, and by definition each marked cell must be $0$ modulo $5$. This means that each marked cell must have an even number of unmarked neighbors, and there must be an equal number of $1$s and $4$s among those neighbors. In other words,...
[ "2-sat", "constructive algorithms", "dfs and similar", "dsu", "graphs", "implementation" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MAX = 507; char grid[MAX][MAX] = {}; bool vis[MAX][MAX] = {}; int val[MAX][MAX] = {}, res[MAX][MAX] = {}, color[MAX * MAX] = {}; set<int> graph[MAX * MAX] = {}; int ind = 0; void dfs(int x, int y) { vis[x][y] = true; vector<pair<int, int> > v; ...
1569
A
Balanced Substring
You are given a string $s$, consisting of $n$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $1$ to $n$. $s[l; r]$ is a continuous substring of letters from index $l$ to $r$ of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the ...
Any non-empty balanced string contains at least one letter 'a' and at least one letter 'b'. That implies that there's an 'a' adjacent to a 'b' somewhere in that string. Both strings "ab" and "ba" are balanced. Thus, any balanced string contains a balanced substring of length $2$. So the solution is to check all $n-1$ p...
[ "implementation" ]
800
for _ in range(int(input())): n = int(input()) s = input() for i in range(n - 1): if s[i] != s[i + 1]: print(i + 1, i + 2) break else: print(-1, -1)
1569
B
Chess Tournament
A chess tournament will be held soon, where $n$ chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players. Each of the players has their own expectations about the tournamen...
Since the chess players of the first type should not lose a single game, each game between two chess players of the first type should end in a draw (so that none of them gets defeated). And a game between a chess player of the first type and the second type should end either with a victory of the first or a draw. There...
[ "constructive algorithms" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n; string s; cin >> n >> s; vector<int> id; for (int i = 0; i < n; ++i) if (s[i] == '2') id.push_back(i); int k = id.size(); if (k...
1569
C
Jury Meeting
$n$ people gathered to hold a jury meeting of the upcoming competition, the $i$-th member of the jury came up with $a_i$ tasks, which they want to share with each other. First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $p$ of numbers from $1$ to $n$ (an ...
Note that if there are at least two members with the maximum value of $a_i$, then any permutation is nice. Now let's consider the case when there is only one maximum. Let's find out when the permutation is nice. Let $x$ be the index of the jury member with the maximum number of tasks. Then, during the $a_x$-th discussi...
[ "combinatorics", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; int mx = *max_element(a.begin(), a.end()); int cmx = c...
1569
D
Inconvenient Pairs
There is a city that can be represented as a square grid with corner points in $(0, 0)$ and $(10^6, 10^6)$. The city has $n$ vertical and $m$ horizontal streets that goes across the whole city, i. e. the $i$-th vertical streets goes from $(x_i, 0)$ to $(x_i, 10^6)$ and the $j$-th horizontal street goes from $(0, y_j)$...
Firstly, let's look at some point $(x_i, y_i)$. Let's find closest to it vertical and horizontal lines. We will name the closest vertical lines from left and right as $lx$ and $rx$ (and $ly$ and $ry$ as closest horizontal lines). So, $lx \le x \le rx$ and $ly \le y \le ry$ (we can also note that either $lx = rx$ or $ly...
[ "binary search", "data structures", "implementation", "sortings", "two pointers" ]
1,900
#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 all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out,...
1569
E
Playoff Restoration
$2^k$ teams participate in a playoff tournament. The tournament consists of $2^k - 1$ games. They are held as follows: first of all, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a ...
There are exactly $2^k-1$ games in the tournament, each game has only two possible outcomes. So it's possible to bruteforce all $2^k-1$ possible ways the tournament could go if $k$ is not large. In fact, this solution is fast enough when $k < 5$, so if we somehow can handle the case $k = 5$, we will have a working solu...
[ "bitmasks", "brute force", "hashing", "implementation", "meet-in-the-middle" ]
2,600
#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 & 1) z = mul(z, ...
1569
F
Palindromic Hamiltonian Path
You are given a simple undirected graph with $n$ vertices, $n$ is even. You are going to write a letter on each vertex. Each letter should be one of the first $k$ letters of the Latin alphabet. A path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads t...
Let's start with making some implications from the low constraints. What's the upper estimate on the number of answers? $12^{12}$. Too high, let's think of a better one. Using some combinatorics, we can normalize the answers in such a way that there are at most $12$-th Bell's number of them. The method basically define...
[ "brute force", "dfs and similar", "dp", "graphs", "hashing" ]
3,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; vector<vector<char>> g; map<long long, bool> dp; void brute(int n, vector<int> &p){ int x = find(p.begin(), p.end(), -1) - p.begin(); if (x == int(p.size())){ vector<vector<char>> dp2(1 << n, vector<char>(n)); ve...
1572
A
Book
You are given a book with $n$ chapters. Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list. Currently you don't understand any of the chapters. You are goi...
There are two main solutions in this task. The first solution simulates the process of reading the book. Let $r_i$ be the number of chapters that need to be understood in order to understand $i$-th chapter. We will keep this array updated during the simulation. Now we will simulate the process by keeping a set of chapt...
[ "binary search", "brute force", "data structures", "dp", "graphs", "implementation", "sortings" ]
1,800
null
1572
B
Xor of 3
You are given a sequence $a$ of length $n$ consisting of $0$s and $1$s. You can perform the following operation on this sequence: - Pick an index $i$ from $1$ to $n-2$ (inclusive). - Change all of $a_{i}$, $a_{i+1}$, $a_{i+2}$ to $a_{i} \oplus a_{i+1} \oplus a_{i+2}$ simultaneously, where $\oplus$ denotes the bitwise...
If the xor of all numbers in the array equals $1$ it is impossible to make everything equal to $0$, since the parity of all numbers doesn't change after an operation. From now on we will assume that the xor of all numbers equals $0$. Lets consider the case when $n$ is odd. We can perform operations on positions $1, 3, ...
[ "brute force", "constructive algorithms", "greedy", "two pointers" ]
2,500
null
1572
C
Paint
You are given a $1$ by $n$ pixel image. The $i$-th pixel of the image has color $a_i$. For each color, the number of pixels of that color is \textbf{at most} $20$. You can perform the following operation, which works like the bucket tool in paint programs, on this image: - pick a color — an integer from $1$ to $n$; -...
Firstly, we can notice that when we modify a segment of the form $[a, b, a]$ and change it to $[a, a, a]$ by performing the operation on the second element, as opposed to performing the operation first on the third element and then on the second element (like so $[a, b, a] \to [a, b, b] \to [a, a, a]$) we avoid using o...
[ "dp", "greedy" ]
2,700
null
1572
D
Bridge Club
There are currently $n$ hot topics numbered from $0$ to $n-1$ at your local bridge club and $2^n$ players numbered from $0$ to $2^n-1$. Each player holds a different set of views on those $n$ topics, more specifically, the $i$-th player holds a positive view on the $j$-th topic if $i\ \&\ 2^j > 0$, and a negative view ...
Let's make a graph in which the vertices are the players and there is an edge of weight $a_i + a_j$ between the $i$-th and the $j$-th player if they can play together. We can notice that the problem can then be solved by finding a matching of size at most $k$ with the biggest sum of weights in this graph. To solve this...
[ "flows", "graph matchings", "graphs", "greedy" ]
2,800
null
1572
E
Polygon
You are given a strictly convex polygon with $n$ vertices. You will make $k$ cuts that meet the following conditions: - each cut is a segment that connects two different nonadjacent vertices; - two cuts can intersect only at vertices of the polygon. Your task is to maximize the area of the smallest region that will ...
We are going to binary search the answer. Lets say that we want to check whether we can obtain $k+1$ regions with area of at least $w$. From now on a correct cut means a cut that will cut off a region with area of a least $w$. Lets consider some interval of vertices $(i, j)$. We will cut it off virtually using a cut fr...
[ "binary search", "dp", "geometry" ]
3,000
null
1572
F
Stations
There are $n$ cities in a row numbered from $1$ to $n$. The cities will be building broadcasting stations. The station in the $i$-th city has height $h_i$ and range $w_i$. It can broadcast information to city $j$ if the following constraints are met: - $i \le j \le w_i$, and - for each $k$ such that $i < k \le j$, th...
We will maintain the array $b$ on a range add/sum segment tree. Queries are done then in $O(\log n)$ per query. Now lets focus on the station rebuilds. Lets maintain an array $w$, which means how far a station can broadcast information including the fact that some stations might block the signal. When a station is rebu...
[ "data structures" ]
3,400
null
1573
A
Countdown
You are given a digital clock with $n$ digits. Each digit shows an integer from $0$ to $9$, so the whole clock shows an integer from $0$ to $10^n-1$. The clock will show leading zeroes if the number is smaller than $10^{n-1}$. You want the clock to show $0$ with as few operations as possible. In an operation, you can ...
Let $s$ be the sum of all digits. In one operation we can decrease $s$ by at most $1$ and we are finished iff $s = 0$. This leads us to a conclusion that it is always unoptimal to decrease the number on the clock, when the least significant digit shows $0$, since it will cost us at least $9$ more operations. Using this...
[ "greedy" ]
800
null
1573
B
Swaps
You are given two arrays $a$ and $b$ of length $n$. Array $a$ contains each \textbf{odd} integer from $1$ to $2n$ in an arbitrary order, and array $b$ contains each \textbf{even} integer from $1$ to $2n$ in an arbitrary order. You can perform the following operation on those arrays: - choose one of the two arrays - p...
Since the array $a$ has odd numbers and array $b$ has even numbers, then they will differ at the first position no matter how we perform the operations. It follows that in order to make the first array lexicographically smaller than the second one we need to make the first element of $a$ smaller than the first element ...
[ "greedy", "math", "sortings" ]
1,400
null
1574
A
Regular Bracket Sequences
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
There are many ways to solve this problem. The model solution does the following thing: start with the sequence ()()()()...; merge the first $4$ characters into one sequence to get (())()()...; merge the first $6$ characters into one sequence to get ((()))()...; and so on.
[ "constructive algorithms" ]
800
t = int(input()) for i in range(t): n = int(input()) for j in range(n): print("()" * j + "(" * (n - j) + ")" * (n - j))
1574
B
Combinatorics Homework
You are given four integer values $a$, $b$, $c$ and $m$. Check if there exists a string that contains: - $a$ letters 'A'; - $b$ letters 'B'; - $c$ letters 'C'; - no other letters; - exactly $m$ pairs of adjacent equal letters (exactly $m$ such positions $i$ that the $i$-th letter is equal to the $(i+1)$-th one).
Let's start with a simple assumption. For some fixed values $a, b, c$, the values of $m$ that the answers exist for, make up a range. So there's the smallest possible number of adjacent equal pairs one can construct and the largest one - everything in-between exists as well. The largest number is simple - put all A's, ...
[ "combinatorics", "greedy", "math" ]
1,100
for _ in range(int(input())): a, b, c, m = map(int, input().split()) a, b, c = sorted([a, b, c]) print("YES" if c - (a + b + 1) <= m <= a + b + c - 3 else "NO")
1574
C
Slay the Dragon
Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $n$ heroes, the strength of the $i$-th hero is equal to $a_i$. According to the rules of th...
It is enough to consider two cases: whether we will increase the strength of the hero who will kill the dragon or not. If you do not increase the hero's strength, then you have to choose such $i$ that $a_i \ge x$. Obviously, among such $i$, you have to choose with the minimum value $a_i$, because the strength of defend...
[ "binary search", "greedy", "sortings", "ternary search" ]
1,300
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<li> a(n); for (auto &x : a) cin >> x; sort(a.begin(), a.end()); li sum = accumulate(a.begin(), a.end(), 0LL); int m; cin >> m; while (m--) {...
1574
D
The Strongest Build
Ivan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has $n$ equipment slots. There is a list of $c_i$ items for the $i$-th slot, the $j$-th of them increases the hero strength by $a_{i,j}$. The items for each slot are pairwise distinct and are listed in the increasing or...
Consider the bruteforce solution. You start with a build that contains the most powerful item for each slot. In one move, you swap an item in some slot for the one that is the previous one by power. If a build is not banned, update the answer with its total power (banned builds can be stored in a set, maybe hashset if ...
[ "binary search", "brute force", "data structures", "dfs and similar", "graphs", "greedy", "hashing", "implementation" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n; vector<vector<int>> a; int m; vector<vector<int>> b; int main() { scanf("%d", &n); a.resize(n); forn(i, n){ int c; scanf("%d", &c); a[i].resize(c); forn(j, c) scanf("%d", &a[i][j]); } scanf("%d", &m...
1574
E
Coloring
A matrix of size $n \times m$, such that each cell of it contains either $0$ or $1$, is considered beautiful if the sum in every contiguous submatrix of size $2 \times 2$ is exactly $2$, i. e. every "square" of size $2 \times 2$ contains exactly two $1$'s and exactly two $0$'s. You are given a matrix of size $n \times...
For best understanding we replace the matrix with $0$ and $1$ with the matrix with black and white cells. At first let's consider matrix if there are two adjacent horizontal cell with same color (for example cells $(5, 5)$ and $(5, 6)$ are black). Then the cells $(4, 5)$, $(4, 6)$, $(6, 5)$ and $6, 6$ must have the opp...
[ "combinatorics", "constructive algorithms", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 1'000'009; int sum (int a, int b) { int res = a + b; if (res < 0) res += MOD; if (res >= MOD) res -= MOD; return res; } int n, m, k; map <pair <int, int>, char> c; int cntr[N][2], cntc[N][2]; int cntx[2]; set <int...
1574
F
Occurrences
A subarray of array $a$ from index $l$ to the index $r$ is the array $[a_l, a_{l+1}, \dots, a_{r}]$. The number of occurrences of the array $b$ in the array $a$ is the number of subarrays of $a$ such that they are equal to $b$. You are given $n$ arrays $A_1, A_2, \dots, A_n$; the elements of these arrays are integers ...
What does the condition "the number of occurrences of $A_i$ in the array $a$ is not less than the number of occurrences of each non-empty subarray of $A_i$ in $a$" mean? First, if $A_i$ contains two (or more) equal elements, then any occurrence of $A_i$ introduces at least two occurrences of that element; so any elemen...
[ "combinatorics", "dfs and similar", "dp", "dsu", "fft", "graphs" ]
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 main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); vector<vector<int>> ...
1575
A
Another Sorting Problem
Andi and Budi were given an assignment to tidy up their bookshelf of $n$ books. Each book is represented by the book title — a string $s_i$ numbered from $1$ to $n$, each with length $m$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending. Settling ...
Observe that the even-indexed character of the string can be transformed from A-Z to Z-A. E.g. for the first example: AA \rightarrow AZ AB \rightarrow AY BB \rightarrow BY BA \rightarrow BZ AZ \rightarrow AA Now, you can use any known algorithms to sort the string as usual. You can sort it in linear time with...
[ "data structures", "sortings", "strings" ]
1,100
null
1575
B
Building an Amusement Park
Mr. Chanek lives in a city represented as a plane. He wants to build an amusement park in the shape of a circle of radius $r$. The circle must \textbf{touch} the origin (point $(0, 0)$). There are $n$ bird habitats that can be a photo spot for the tourists in the park. The $i$-th bird habitat is at point $p_i = (x_i, ...
We can binary search the answer $r$ in this case. Here, bird's habitats are referred as points. First of all, define a function $c(x)$ as the maximum number of points that can be covered with a circle of radius $x$ through the origin. Define the park as a circle with radius $x$ and $\theta$, in a polar coordinate repre...
[ "binary search", "geometry" ]
2,300
null
1575
C
Cyclic Sum
Denote a cyclic sequence of size $n$ as an array $s$ such that $s_n$ is adjacent to $s_1$. The segment $s[r, l]$ where $l < r$ is the concatenation of $s[r, n]$ and $s[1, l]$. You are given an array $a$ consisting of $n$ integers. Define $b$ as the cyclic sequence obtained from concatenating $m$ copies of $a$. Note th...
Let a valid segment $[l, r]$ be a segment in $b$ where the sum of elements in the segment is divisible by $k$. We can try to solve a simpler problem: find the number of valid segments such that the right endpoint ends at $1$. That is, the valid segments $[l, 1]$ ($1 \leq l \leq n \cdot m$). Let $prefix(p) = \sum_{i=1}^...
[ "data structures", "fft", "number theory" ]
3,000
null