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
1102
C
Doors Breaking and Repairing
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are $n$ doors, the $i$-th door initially has durability equal to $a_i$. During your move you can try...
Let's consider two cases: If $x > y$ then the answer is $n$ because we can make opposite moves to the Slavik's moves and it always will reduce durability of some door (so at some point we will reach the state when all doors will have durability $0$). Otherwise $x \le y$ and we have to realize the optimal strategy for u...
[ "games" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, x, y; cin >> n >> x >> y; int cnt = 0; for (int i = 0; i < n; ++i) { int cur; cin >> cur; if (cur <= x) { ++cnt; } } if (x > y) { cout...
1102
D
Balanced Ternary String
You are given a string $s$ consisting of exactly $n$ characters, and each character is either '0', '1' or '2'. Such strings are called \textbf{ternary strings}. Your task is to \textbf{replace minimum number of characters} in this string with other characters to obtain a balanced ternary string (balanced ternary strin...
Let's count how many characters '0', '1' and '2' we have in the string $s$ and store it in the array $cnt$. Also let's count our "goal" array $cur$. Firstly, the array $cur$ is $[\frac{n}{3}, \frac{n}{3}, \frac{n}{3}]$. The main idea of this problem is a pretty standard lexicographically greedy approach. We go from lef...
[ "greedy", "strings" ]
1,500
n = int(input()) s = [ord(x) - ord('0') for x in input()] cnt = [s.count(x) for x in [0, 1, 2]] def forw(x): for i in range(n): if (cnt[x] < n // 3 and s[i] > x and cnt[s[i]] > n // 3): cnt[x] += 1 cnt[s[i]] -= 1 s[i] = x def back(x): for i in range(n - 1, -1, -1): if (cnt[x] < n // 3 and s[i] < x and cn...
1102
E
Monotonic Renumeration
You are given an array $a$ consisting of $n$ integers. Let's denote monotonic renumeration of array $a$ as an array $b$ consisting of $n$ integers such that all of the following conditions are met: - $b_1 = 0$; - for every pair of indices $i$ and $j$ such that $1 \le i, j \le n$, if $a_i = a_j$, then $b_i = b_j$ (note...
We are interested in such subsegments of the array $a$ that for every value belonging to this segment all occurences of this value in the array are inside this segment. Let's call such segments closed segments. For example, if $a = [1, 2, 1, 2, 3]$, then $[1, 2, 1, 2]$, $[3]$ and $[1, 2, 1, 2, 3]$ are closed segments. ...
[ "combinatorics", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int main() { int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); map<int, int> lst; vector<int> last_pos(n); for(int i = n - 1; i >= 0; i--) { if(!lst.count(a[i])) lst[a[i]] = i; ...
1102
F
Elongated Matrix
You are given a matrix $a$, consisting of $n$ rows and $m$ columns. Each cell contains an integer in it. You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following w...
Really low constraints, choosing some permutation... Surely, this will be some dp on subsets! At first, let's get rid of $m$. For each two rows calculate the minimum difference between the elements of the same columns - let's call this $mn1_{i, j}$ for some rows $i$, $j$. This will be used to put row $j$ right after ro...
[ "binary search", "bitmasks", "brute force", "dp", "graphs" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 18; const int M = 100 * 1000 + 13; const int INF = 1e9; int used[1 << N]; char dp[1 << N]; int g[1 << N]; int n, m; int a[N][M]; int mn1[N][N], mn2[N][N]; bool calc(int mask){ if (dp[mask] != -1) ret...
1103
A
Grid game
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in...
One possible solution is to place vertical tiles into lower-left corner and place horizontal tiles into upper-right corner.If some tile comes, but there is already a tile of the same type, than we will place the new tile into upper-left corner. So both tiles will be cleared and only them.
[ "constructive algorithms", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(0); string s; cin>>s; bool occv=false, occh=false; for(auto& x:s){ if(x=='0'){ if(occv) cout<<"3 4\n"; else cout<<"1 4\n"; occv=!occv; } else { if (occh) cout<<"4 3\n"; else cout<<...
1103
B
Game with modulo
\textbf{This is an interactive problem.} Vasya and Petya are going to play the following game: Petya has some positive integer number $a$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $(x, y)$. Petya will answer him: - "x", if $(x \bmod a) ...
Let's ask this pairs of numbers: $(0, 1), (1, 2), (2, 4), (4, 8), \ldots, (2^{29}, 2^{30})$. Let's find the first pair in this list with the answer "x". This pair exists and it will happen for the first pair $(l_0, r_0)$, that satisfy the inequality $l_0 < a \leq r_0$. We can simply find this pair using $\leq 30$ or $\...
[ "binary search", "constructive algorithms", "interactive" ]
2,000
null
1103
C
Johnny Solving
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with $n$ vertices without loops and multiedges, such that a degree of any vertex is at least $3$, and also he...
Let's build a dfs spanning tree from the vertex $1$ and find the depth of the tree. If the depth is at least $\frac{n}{k}$ then we can just print the path from the root to the deepest vertex. Otherwise, there will be at least $k$ leaves in the tree. Let's prove it. Consider a tree with $c$ leaves, after that consider a...
[ "constructive algorithms", "dfs and similar", "graphs", "math" ]
2,700
null
1103
D
Professional layer
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are $n$ judges now in the layer and you are trying to pass the entrance exam. You have a number $k$ — your skill in Cardbluff. Each judge has a number $a_i$ — an indicator of uncertainty ...
We supposed this as the author solution: Let's find $gcd$ and factorize it. $gcd = p_1^{\alpha_1} \cdot \ldots \cdot p_m^{\alpha_m}$, where $p_i$ $i$-th prime number in factorization ($p_i < p_{i+1}$) and $\alpha_i > 0$ - number of occurrences of this prime. It's clear, that $m \leq 11$ in our constraints, because $a_i...
[ "bitmasks", "dp" ]
3,100
null
1103
E
Radix sum
Let's define \textbf{radix sum} of number $a$ consisting of digits $a_1, \ldots ,a_k$ and number $b$ consisting of digits $b_1, \ldots ,b_k$(we add leading zeroes to the shorter number to match longer length) as number $s(a,b)$ consisting of digits $(a_1+b_1)\mod 10, \ldots ,(a_k+b_k)\mod 10$. The \textbf{radix sum} of...
After reading the problem statement, it is pretty clear that you should apply something like Hadamard transform, but inner transform should have size ten instead of two. There is no $10$-th root of one modulo $2^{58}$ (except $5$-th and $2$-th roots), so it is not possible to solve the problem just calculating all valu...
[ "fft", "math", "number theory" ]
3,400
#include <bits/stdc++.h> using namespace std; typedef unsigned long long ull; const int two = 2; const int M = 1e5; const int L = 7; const int X = 2e5 + 1e3; const int fr = 4; const int ten = 10; const ull cs = 6723469279985657373; const ull RT = (1LL << 58LL) - 1; ull f[X][fr], bf[L]; int cur; inline int sum...
1104
A
Splitting into digits
Vasya has his favourite number $n$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $d_1, d_2, \ldots, d_k$, such that $1 \leq d_i \leq 9$ for all $i$ and $d_1 + d_2 + \ldots + d_k = n$. Vasya likes beauty in everything, so he wants to find any solution with the minimal poss...
It was a joke :). Let's split number $n$ to $n$ digits, equal to $1$. Their sum is $n$ and the number of different digits is $1$. So, it can be found as the answer.
[ "constructive algorithms", "implementation", "math" ]
800
null
1104
B
Game with string
Two people are playing a game with a string $s$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A p...
It can be shown that the answer does not depend on the order of deletions. Let's remove letters from left to right, storing a stack of letters, remaining in the left. When we process a letter, it will be deleted together with the last letter in the stack if they are equal or will be pushed to the stack. Let's calculate...
[ "data structures", "implementation", "math" ]
1,200
null
1105
A
Salem and Sticks
Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \ldots, a_n$. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $a$ to $b$ is $|a - b|$, where $|x|$ means the absolute value of $x$. A ...
Firstly, we must find the value of $t$ and it can easily proven that $t$ is less than or equal to $100$, so we can iterate over all possible value of $t$ from $1$ to $100$ and calculate the cost of making all the sticks almost good for that $t$. That works in $100 \cdot n$.
[ "brute force", "implementation" ]
1,100
null
1105
B
Zuhair and Strings
Given a string $s$ of length $n$ and integer $k$ ($1 \le k \le n$). The string $s$ has a level $x$, if $x$ is largest non-negative integer, such that it's possible to find in $s$: - $x$ \textbf{non-intersecting} (non-overlapping) substrings of length $k$, - all characters of these $x$ substrings are the same (i.e. eac...
Since all the substrings of length $k$ must be of the same latter, we can iterate over all letters from 'a' to 'z' and for each letter count the number of disjoint substrings of length $k$ and take the maximum one.
[ "brute force", "implementation", "strings" ]
1,100
null
1105
C
Ayoub and Lost Array
Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties: - All the integers in the array were between $l$ and $r$ (inclusive). - The sum of all the elements was divisible by $3$. Unfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l...
Since we need the sum of the array to be divisible by $3$, we don't care about the numbers themselves: We care about how many numbers $x$ such that $x \pmod{3} = 0$ or $1$ or $2$ and we count them by simple formulas. For example, let's count the number of $x$ with remainder $1$ modulo $3$, hence $x = 3k + 1$ for some i...
[ "combinatorics", "dp", "math" ]
1,500
null
1105
D
Kilani and the Game
Kilani is playing a game with his friends. This game can be represented as a grid of size $n \times m$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell). The game is played in rounds. In each round players expand turn by turn: fir...
This problem can be solved in many ways, one of them uses a bfs. Let's process the first round. Iterate over players and use a multi-source bfs for each player from his starting castles to find cells reachable in at most s[i] moves. A multi-source bfs works just like regular one, except you push more vertices in the qu...
[ "dfs and similar", "graphs", "implementation", "shortest paths" ]
1,900
null
1105
E
Helping Hiasat
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle. Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequen...
Let's change this problem to a graph problem first. Let's say, that each action of the first type is a "border". Consider all friends visiting our profile after this "border" but before the next one. Clearly, we can satisfy at most one of them. Let's change the friends into graph nodes and add edges between every two f...
[ "bitmasks", "brute force", "dp", "meet-in-the-middle" ]
2,200
null
1106
A
Lunar New Year and Cross Counting
Lunar New Year is approaching, and you bought a matrix with lots of "crosses". This matrix $M$ of size $n \times n$ contains only 'X' and '.' (without quotes). The element in the $i$-th row and the $j$-th column $(i, j)$ is defined as $M(i, j)$, where $1 \leq i, j \leq n$. We define a cross appearing in the $i$-th row...
The solution is simple: Just check if crosses can appear in every positions. Two nesting for-loops will be enough to solve this problem. Time complexity: $\mathcal{O}(n^2)$
[ "implementation" ]
800
#include <bits/stdc++.h> #define N 510 using namespace std; char a[N][N]; int n; int main(){ scanf("%d", &n); for (int i = 1; i <= n; i++){ scanf("%s", a[i] + 1); } int ans = 0; for (int i = 2; i < n; i++){ for (int j = 2; j < n; j++){ if (a[i][j] == 'X' && a[i - 1][j - 1] == 'X' && a[i - 1][j + 1] == 'X...
1106
B
Lunar New Year and Food Ordering
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's". The restaurant "Alice's" serves $n$ kinds of food. The cost for the $i$-th kind is always $c_i$. Initially, the restaurant has enough ingredients for serving exactly $a_i$ dishes of the $i$-th kind. In the New Year's Eve, $m$...
The implementation of the problem is easy: Just do what Bob tells you to do. The only difficulty, if it is, is to handle the cheapest dish. This can be done by a pointer or a priority queue. The details can be found in the code. Time complexity: $\mathcal{O}(m + n \log n)$
[ "data structures", "implementation" ]
1,500
#include <bits/stdc++.h> #define N 300010 #define PII pair<int, int> using namespace std; typedef long long LL; int n, m, a[N], c[N], t, d; LL ans = 0; priority_queue<PII, vector<PII>, greater<PII> > Q; int main(){ scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++){ scanf("%d", &a[i]); } for (int i = 1; i...
1106
C
Lunar New Year and Number Division
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem. There are $n$ positive integers $a_1, a_2, \ldots, a_n$ on Bob's homework paper, where $n$ is always an \textbf{even} number. Bob is asked to divide those numbers into groups, where each group must contain at least $2$ ...
This problem is easy as it looks like, and it is proved to be simple. As $n$ is even, the optimal grouping policy is to group the smallest with the largest, the second smallest with the second largest, etc. First, it is easy to prove that it is optimal to group these numbers $2$ by $2$, so the proof is given as an exer...
[ "greedy", "implementation", "math", "sortings" ]
900
#include <bits/stdc++.h> #define N 300010 using namespace std; typedef long long LL; int n, a[N]; LL ans = 0; int main(){ scanf("%d", &n); for (int i = 1; i <= n; i++){ scanf("%d", &a[i]); } sort(a + 1, a + n + 1); for (int i = 1; i <= n / 2; i++){ ans += 1LL * (a[i] + a[n - i + 1]) * (a[i] + a[n - i + 1]);...
1106
D
Lunar New Year and a Wander
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with $n$ nodes and $m$ bidirectional edges. Initially Bob is at the node $1$ and he records $1$ on his notebook. He can wander from one node to another through those bidirectional edges. W...
In fact, you don't really need to consider the path Bob wanders. A priority queue is enough for this problem. When Bob visits a node, add its adjacent nodes into the priority queue. Every time he visits a new node, it will be one with the smallest index in the priority queue. Time complexity: $\mathcal{O}(m \log n)$
[ "data structures", "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,500
#include <bits/stdc++.h> #define N 300010 using namespace std; typedef long long LL; priority_queue<int, vector<int>, greater<int> > Q; vector<int> e[N]; vector<int> seq; bool vis[N]; int n, m; int main(){ scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++){ int u, v; scanf("%d%d", &u, &v); e[u].push_back(v)...
1106
E
Lunar New Year and Red Envelopes
Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself. Let's describe this problem in a mathematical way. Consider a timeline from time $1$ to $n$. The $i$-th red envelope will be available from tim...
Yes, this is where Alice shows up and ... probably the problem is not related to Game Theory. Let's divide the problem into two parts: The first is to obtain the maximum coins Bob can get from time points $1$ to $n$, and the second is to decide when to disturb Bob. For the first part, we apply event sorting to those ti...
[ "data structures", "dp" ]
2,100
#include <bits/stdc++.h> #define N 100010 using namespace std; typedef long long LL; struct Event{ int d, w, t; bool operator < (const Event &e) const { return w > e.w || (w == e.w && d > e.d); } }; vector<Event> e[N]; Event a[N]; map<Event, int> cur; int n, m, k; LL f[2][N], ans = 0x3f3f3f3f3f3f3f3fLL; voi...
1106
F
Lunar New Year and a Recursive Sequence
Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it. Let $f_1, f_2, \ldots, f_i, \ldots$ be an infinite sequence of positive integers. Bob knows that for $i > k$, $f_i$ can be obtained by the following recurs...
This problem seems weird first looking at it, but we can rewrite it into a linear recursive equation. The most important thing you should know is that $g = 3$ is a primitive root of $p = 998\,244\,353$. Briefly speaking, the primitive $g$ is called a primitive root of $p$ if and only if the following two constraints ar...
[ "math", "matrices", "number theory" ]
2,400
#include <bits/stdc++.h> #define N 210 using namespace std; typedef long long LL; const LL p = 998244353; const LL g = 3; int k; LL n, m, b[N]; struct Matrix{ int n; LL mat[N][N]; Matrix(){ n = 0; memset(mat, 0, sizeof(mat)); } Matrix(int _n, LL diag){ n = _n; memset(mat, 0, sizeof(mat)); for (int...
1107
A
Digits Sequence Dividing
You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$. You have to divide it into \textbf{at least two} segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that \textbf{each element belongs to exactl...
The only case when the answer is "NO" - $n=2$ and $s_1 \ge s_2$. Then you cannot divide the initial sequence as needed in the problem. Otherwise you always can divide it into two parts: the first digit of the sequence and the remaining sequence.
[ "greedy", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { int n; string s; cin >> n >> s; if (n == 2 && s[0] >= s[1]) { cout << "NO" << endl; } else { cou...
1107
B
Digital root
Today at the lesson of mathematics, Petya learns about the digital root. The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d...
Let's derive the formula $S(x) = (x-1)~mod~9 + 1$ from the digital root properties (that's a known fact but I could only find a link to some russian blog about it). Using that formula, you can easily get that $k$-th number with the digital root of $x$ is $(k-1) \cdot 9 + x$.
[ "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { long long k, x; cin >> k >> x; cout << (k - 1) * 9 + x << endl; } }
1107
C
Brutality
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on button...
All you need in this problem is two simple technique: two pointers and sorting. Let's consider maximum by inclusion segments of equal letters in the initial string. Let the current segment be $[l; r]$ and its length is $len = r - l + 1$. If $len < k$ then we can press all buttons and deal all damage corresponding to th...
[ "greedy", "sortings", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } string s; cin >> s; long long ans = 0; for (int i = 0; i < n;...
1107
D
Compression
You are given a binary matrix $A$ of size $n \times n$. Let's denote an $x$-compression of the given matrix as a matrix $B$ of size $\frac{n}{x} \times \frac{n}{x}$ such that for every $i \in [1, n], j \in [1, n]$ the condition $A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$ is met. Obviously, $x$-...
It is very easy to decompress the input (the input was given in the compressed form to make the constraints bigger but less dependent of the time to read the data). The authors solution is the following: Let $x$ be the answer to the problem and initially it equals to $n$. Let's iterate over all rows of the matrix and c...
[ "dp", "implementation", "math", "number theory" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 5200; int n; bool a[N][N]; void parse_char(int x, int y, char c) { int num = -1; if (isdigit(c)) { num = c - '0'; } else { num = c - 'A' + 10; } for (int i = 0; i < 4; ++i) { a[x][y + 3 - i] = num & 1; num >>= 1; } } int main() { #ifdef _DEB...
1107
E
Vasya and Binary String
Vasya has a string $s$ of length $n$ consisting only of digits 0 and 1. Also he has an array $a$ of length $n$. Vasya performs the following operation until the string becomes empty: choose some \textbf{consecutive} substring of \textbf{equal characters}, erase it from the string and glue together the remaining parts ...
We will solve the problem with dynamic programming. Let $ans_{l, r}$ be the answer for substring $s_{l, l + 1, \dots r}$. If sequence is empty ($l > r$) then $ans_{l, r} = 0$. Let $dp_{dig, l, r, cnt}$ be the maximum score that we can get if we reduce the substring $s_{l, l + r, \dots r}$ into $cnt$ digits equal to $di...
[ "dp" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 102; const long long INF = 1e12; int n; string s; int a[N]; long long ans[N][N]; long long dp[2][N][N][N]; long long calcDp(int c, int l, int r, int cnt); long long calcAns(int l, int r){ if(l >= r) return 0; long long &res = ans[l][r]; if(res != -1) ...
1107
F
Vasya and Endless Credits
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles. However, the local bank has $n$ credit offers. Each offer can be described with three numbers $a_i$, $b_i$ and $k_i$. Offers are numbered from $1$ to $n$. If Vasya takes the $i$-th offer, then the bank giv...
Let create the following matrix (zero-indexed): $mat_{i, j} = a_j - min(i, k_j) \cdot b_j$. $i$-th row of this matrix contains Vasya's profits for credit offers as if they were taken $i$ months before the purchase. We need to choose elements from this matrix so that there is no more than one element taken in each row a...
[ "dp", "flows", "graph matchings", "graphs", "sortings" ]
2,600
#include <bits/stdc++.h> using namespace std; const int N = 505; const long long INF = 1e18; int n; long long a[N][N]; int up[N], down[N], k[N]; long long u[N], v[N]; int p[N], way[N]; int main(){ cin >> n; for(int i = 0; i < n; ++i) cin >> up[i] >> down[i] >> k[i]; for(int i = 0; i < n; ++i) for(int j = 0...
1107
G
Vasya and Maximum Profit
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit. Vasya has $n$ problems to choose from. They are numbered from $1$ to $n$. The difficulty of the $i$-th problem is $d_i$. Moreover, the problems are given in the increasing or...
It is clear that $gap(l, r) \le gap(l, r + 1)$ and $gap(l, r) \le gap(l - 1, r)$. Sort all indices $2, 3, \dots, n$ with comparator based on the value of $d_i - d_{i-1}$. Let's consider all indices in the order discussed above and for fixed index $i$ find the best answer among such segments $(l, r)$ that $gap(l, r) \le...
[ "binary search", "constructive algorithms", "data structures", "dp", "dsu" ]
2,400
#include<bits/stdc++.h> using namespace std; const int N = int(3e5) + 99; struct node{ long long sum, ans, pref, suf; node () {} node(int x){ sum = x; x = max(x, 0); pref = suf = ans = x; } }; node merge(const node &a, const node &b){ node res; res.sum = a.sum + b.sum; res.pref = max(a.pref, a.sum + ...
1108
A
Two distinct points
You are given two segments $[l_1; r_1]$ and $[l_2; r_2]$ on the $x$-axis. It is guaranteed that $l_1 < r_1$ and $l_2 < r_2$. Segments \textbf{may intersect, overlap or even coincide with each other}. \begin{center} {\small The example of two segments on the $x$-axis.} \end{center} Your problem is to find two \textbf{...
One of the possible answers is always a pair of endpoints of the given segments. So we can add all endpoints to the array and iterate over all pairs of elements of this array and check if the current pair is suitable or not.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { int l1, r1, l2, r2; cin >> l1 >> r1 >> l2 >> r2; vector<int>a({l1, r1, l2, r2}); int ans1 = 0, ans2 = 0; for (auto it : a) for (auto jt : a) { if (l1 <= it && it <= r1 && l2 <= jt && jt <= r2 && i...
1108
B
Divisors of Two Integers
Recently you have received two \textbf{positive} integer numbers $x$ and $y$. You forgot them, but you remembered a \textbf{shuffled} list containing all divisors of $x$ (including $1$ and $x$) and all divisors of $y$ (including $1$ and $y$). If $d$ is a divisor of both numbers $x$ and $y$ at the same time, there are t...
Let's take a look on the maximum element of the given array. Suddenly, this number is $x$ (or $y$, the order doesn't matter). Okay, what would we do if we know $x$ and merged list of divisors of $x$ and $y$? Let's remove all divisors of $x$ and see what we got. The maximum element in the remaining array is $y$. So, the...
[ "brute force", "greedy", "math", "number theory" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; multiset<int> a; for (int i = 0; i < n; ++i) { int x; cin >> x; a.insert(x); } int x = *prev(a.end()); for (int i = 1; i <= x; ++i...
1108
C
Nice Garland
You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained ...
It is easy to see that any nice garland has one of the following $6$ patterns: "BGRBGR ... BGR"; "BRGBRG ... BRG"; "GBRGBR ... GBR"; "GRBGRB ... GRB"; "RBGRBG ... RBG"; "RGBRGB ... RGB"; We can hard-code all all this patterns or iterate over all these permutations of letters "BGR" using three nested loops or standard l...
[ "brute force", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; vector<int> p(3); iota(p.begin(), p.end(), 0); string colors = "RGB"; string res = ""; int ans = 1e9; do { string...
1108
D
Diverse Garland
You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained ...
Let's divide the initial string into blocks of consecutive equal letters. For example, if we have the string "GGBBBRRBBBB" then have $4$ blocks: the first block is two letters 'G', the second one is three letters 'B', the third one is two letters 'R' and the last one is four letters 'B'. Let's see at the current block ...
[ "constructive algorithms", "dp", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; string s; cin >> n >> s; int ans = 0; for (int i = 0; i < n; ++i) { int j = i; while (j < n && s[i] == s[j]) { ++j; } string q = "RGB"; ...
1108
E1
Array and Segments (Easy version)
\textbf{The only difference between easy and hard versions is a number of elements in the array}. You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$. You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$....
Let's divide all segments to four classes. The first class contains segments which covers both minimum and maximum values (the answer) of the resulting array, the second class contains segments which covers only minimum value of the resulting array, the third class contains segments which covers only maximum value of t...
[ "brute force", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; mt19937 rnd(time(NULL)); const int INF = 1e9; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<pair<int, i...
1108
E2
Array and Segments (Hard version)
\textbf{The only difference between easy and hard versions is a number of elements in the array}. You are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$. You are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \le l_j \le r_j \le n$....
This tutorial is based on the previous problem (easy version) tutorial. At first, I want to say I know that this problem and this approach can be implemented in $O(m \log n)$ with segment tree. So, we iterate over all supposed maximums in the array and trying to apply all segments not covering our current element. How ...
[ "data structures", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; mt19937 rnd(time(NULL)); const int INF = 1e9; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector<pair<int,...
1108
F
MST Unification
You are given an undirected weighted \textbf{connected} graph with $n$ vertices and $m$ edges \textbf{without loops and multiple edges}. The $i$-th edge is $e_i = (u_i, v_i, w_i)$; the distance between vertices $u_i$ and $v_i$ along the edge $e_i$ is $w_i$ ($1 \le w_i$). The graph is \textbf{connected}, i. e. for any ...
The first (and the most straight-forward) approach is to construct MST with any suitable algorithm, build LCA with the maximum edge on a path with binary lifting technique and then we have to increase the answer for each edge $e_i = (u_i, v_i, w_i)$ such that $w_i$ equals to the maximum edge on a path between $u_i$ and...
[ "binary search", "dsu", "graphs", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; #define x first #define y second vector<int> p, rk; int getp(int v) { if (v == p[v]) return v; return p[v] = getp(p[v]); } bool merge(int v, int u) { u = getp(u); v = getp(v); if (u == v) return false; if (rk[u] < rk[v]) swap(u, v); rk[u] += rk[v]; p[v] =...
1109
A
Sasha and a Bit of Relax
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
Notice, that if $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$ then $a_l \oplus a_{l+1} \oplus \ldots \oplus a_r = 0$ (it comes from the fact that for some integers $A$, $B$, $C$ if $A \oplus B = C$ then $A = B \oplus C$). Now we have another task. How many a...
[ "dp", "implementation" ]
1,600
"#include <bits/stdc++.h>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nconst int maxn = (int)3e5 + 3;\nconst int maxa = (1 << 20) + 3;\n\n\nint n;\nint a[maxn];\nint cnt[2][maxa];\n\n\nint32_t main() {\n std::ios_base::sync_with_stdio(false);\n\n cin >> n;\n for(int i = 0; i < n; ++i) {\n c...
1109
B
Sasha and One More Name
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in t...
Let's $s$ be the given string, $n$ - it's length. If $s$ consists of $n$ or $n - 1$ (when $n$ is odd) equal characters, then there is no way to get the answer. Otherwise, let's prove that the answer can be always reached in two cuttings. Let's the longest prefix of $s$, that consists of equal characters has the length ...
[ "constructive algorithms", "hashing", "strings" ]
1,800
"#include <bits/stdc++.h>\nusing namespace std;\n\nbool isPalindrome(const string& s) {\n for(int i = 0; i < s.length(); ++i) {\n if (s[i] != s[s.length() - i - 1]) \n return false;\n }\n return true;\n}\n\nbool solve1(string s) {\n string t = s;\n for(int i = 0; i < s.length(); ++i) {\...
1109
C
Sasha and a Patient Friend
Fedya and Sasha are friends, that's why Sasha knows everything about Fedya. Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let $v$ be the number of liters of Fedya's patience, and, as soon as $v$ becomes \textbf{equal} to $0$, the bowl will burs...
Let's keep not deleted pairs ($t, s$) in a treap where $t$ will be the key of some node. Also we need some auxiliary variables. So each node in the treap will store that: $time$ - time of the event $speed$ - speed of the tap since second $time$ $tL$, $tR$ - the minimum and the maximum $time$ in the subtree of that node...
[ "binary search", "data structures", "implementation" ]
2,800
"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n//mt19937 gen(time(NULL));\nmt19937 gen(200);\n\nstruct node {\n pair<int, int> f, s;\n node *le, *ri;\n ll mn, res;\n int tl, tr;\n node() {\n mn = 228;\n }\n node(int l, int r) {\n tl = l; tr = r;\n mn ...
1109
D
Sasha and Interesting Fact from Graph Theory
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the num...
Let's fix $edges$ - the number of edges on the path between $a$ and $b$. Then on this path there are $edges-1$ vertices between $a$ and $b$, and they can be choosen in $A(n - 2, edges - 1)$ ways. The amount of ways to place numbers on edges in such a way, that their sum is equal to $m$, is $\binom{m-1}{edges-1}$ (stars...
[ "brute force", "combinatorics", "dp", "math", "trees" ]
2,400
"import java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) {\n InputReader in = new InputReader(System.in);\n OutputWriter out = new OutputWriter(System.out);\n TaskC solver = new TaskC(in, out);\n solver.solve();\n out.close();\n }...
1109
E
Sasha and a Very Easy Test
Egor likes math, and not so long ago he got the highest degree of recognition in the math community — Egor became a red mathematician. In this regard, Sasha decided to congratulate Egor and give him a math test as a present. This test contains an array $a$ of integers of length $n$ and exactly $q$ queries. Queries were...
The main idea: Let's factorize $x$ in every query of the $1$-st and the $2$-nd type. Now $x$ can be presented as $p_1^{\alpha_1} \cdot p_2^{\alpha_2} \cdot \ldots \cdot p_k^{\alpha_k}$, where $p_i$ is a prime divisor of $x$. Then let's split $p_i$ into two sets: those which are divisors of $mod$ and those which are not...
[ "data structures", "number theory" ]
2,700
"#include <bits/stdc++.h>\nusing namespace std;\n\nint phi(int n) {\n\tint res = n;\n\tfor (int i = 2; i*i <= n; ++i)\n\t\tif (n % i == 0) {\n\t\t\twhile (n % i == 0)\n\t\t\t\tn /= i;\n\t\t\tres -= res / i;\n\t\t}\n\tif (n > 1)\n\t\tres -= res / n;\n\treturn res;\n}\n\nvector <int> factorize(int x) {\n vector <int> ...
1109
F
Sasha and Algorithm of Silence's Sounds
One fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Le...
A range $[l \ldots r]$ - a tree, if the graph formated by it doen't have any cycle and there is only one connected component in this graph. Let's $t_r$ be such minimal position, that $[t_r \ldots r]$ doen't contain cycles (forest). It is obvous that $t_r \leq t_{r+1}$. Suppose for each $r$ we find $t_r$. Then the task ...
[ "data structures", "trees" ]
3,200
"import java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n public static void main(String[] args) {\n InputReader in = new InputReader(System.in);\n OutputWriter out = new OutputWriter(System.out);\n TaskD solver = new TaskD(in, out);\n solver.solve();\n out.close();\n }...
1110
A
Parity
You are given an integer $n$ ($n \ge 0$) represented with $k$ digits in base (radix) $b$. So, $$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$ For example, if $b=17, k=3$ and $a=[11, 15, 7]$ then $n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$. Determine whether $n$ is even or odd.
If $b$ is even, then only the last digit matters. Otherwise $b^k$ is odd for any $k$, so each digit is multiplied by odd number. A sum of several summands is even if and only if the number of odd summands is even. So we should just compute the number of even digits.
[ "math" ]
900
null
1110
B
Tape
You have a long stick, consisting of $m$ segments enumerated from $1$ to $m$. Each segment is $1$ centimeter long. Sadly, some segments are broken and need to be repaired. You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise,...
Let's start with $n$ pieces of length $1$ covering only broken segments and then decrease the number of pieces used. After reducing the number of segments by $x$, some $x$ of long uncovered initial segments of unbroken places will be covered. It's easy to see that you should cover the shortest $x$ segments. Thus, to ma...
[ "greedy", "sortings" ]
1,400
null
1110
C
Meaningless Operations
Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer $a$. You want to choose some integer $b$ from $1$ to $a - 1$ inclusive in such a way that the greatest common divisor (GCD) of integers $a \oplus b$ and $a \> \& ...
Denote the highest bit of $a$ as $x$ (that is largest number $x$, such that $2^x \le a$) and consider $b = (2^x - 1) \> \oplus a$. It's easy to see that if $a \neq 2^x - 1$ then $0 < b < a$ holds. In this, $gcd$ is maximum possible, because $a \> \& b = 0$ and $gcd(2 ^ x - 1, 0) = 2^x - 1$. Now consider the case when $...
[ "constructive algorithms", "math", "number theory" ]
1,500
null
1110
D
Jongmah
You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have $n$ tiles in your hand. Each tile has an integer between $1$ and $m$ written on it. To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on th...
First thing to note is that one can try solving this problem with different greedy approaches, but authors don't know any correct greedy. To solve this problem, note that you can always replace $3$ triples of type $[x, x + 1, x + 2]$ with triples $[x, x, x]$, $[x + 1, x + 1, x + 1]$ and $[x + 2, x + 2, x + 2]$. So we c...
[ "dp" ]
2,200
null
1110
E
Magic Stones
Grigory has $n$ magic stones, conveniently numbered from $1$ to $n$. The charge of the $i$-th stone is equal to $c_i$. Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index $i$, where $2 \le i \le n - 1$), and after that synchronizes it with neighboring stones. After that, the chose...
Consider the difference array $d_1, d_2, \ldots, d_{n - 1}$, where $d_i = c_{i + 1} - c_i$. Let's see what happens if we apply synchronization. Pick an arbitrary index $j$ and transform $c_j$ to $c_j' = c_{j + 1} + c_{j - 1} - c_j$. Then: $d_{j - 1}' = c_j' - c_{j - 1} = (c_{j + 1} + c_{j - 1} - c_j) - c{j - 1} = c_{j ...
[ "constructive algorithms", "math", "sortings" ]
2,200
null
1110
F
Nearest Leaf
Let's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number $1$ ...
Let's answer the queries offline: for each vertex we'll remember all queries for it. Let's make vertex $1$ root and find distances from it to all leaves using DFS. Now for answering queries for vertex $1$ we should simply answer some range minimum queries, so we'll build a segment tree for it. For answering queries for...
[ "data structures", "trees" ]
2,600
null
1110
G
Tree-Tac-Toe
The tic-tac-toe game is starting on a tree of $n$ vertices. Some vertices are already colored in white while the remaining are uncolored. There are two players — white and black. The players make moves alternatively. The white player starts the game. In his turn, a player must select one uncolored vertex and paint it ...
To start with, let's notice that the white vertices are not necessary. Actually, you can solve the problem analyzing the cases with the whites as well, but there is an easy way to get rid of them: Examine the following construction: That is, replace the white $A$ with some set of four non-white vertices. One can notice...
[ "constructive algorithms", "games", "trees" ]
3,100
null
1110
H
Modest Substrings
You are given two integers $l$ and $r$. Let's call an integer $x$ modest, if $l \le x \le r$. Find a string of length $n$, consisting of digits, which has the largest possible number of substrings, which make a modest integer. Substring having leading zeros are not counted. If there are many answers, find lexicograph...
Set of modest numbers could be represented by set of size approximately $(|l| + |r|) \cdot 10$ of regular expressions of form $d_0 d_1 d_2 \dots d_{k - 1} [0-9]\{e\}$, where $|l|$ and $|r|$ are lengths of numbers $l$ and $r$ correspondingly, and $d_i$ are digits. Set of regular expressions can be build in the following...
[ "dp", "strings" ]
3,500
null
1111
A
Superhero Transformation
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $s$ can transform to another superhero with name $t$ if $s$ can be made equal to $t$ by changing any vowel in $s$ to any other vowel and any consonant in $s$ to an...
Check lengths of $s$ and $t$. If they are different, $s$ can never be converted to $t$ and answer is "No". If for all indexes $i$ either both $s[i]$ and $t[i]$ are vowels or both $s[i]$ and $t[i]$ are consonants, then answer is "Yes", else answer is "No".
[ "implementation", "strings" ]
1,000
#include "bits/stdc++.h" using namespace std; // Checking if a character is vowel bool isVowel(char a) { if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return true; return false; } int main() { string S, T; cin >> S; cin >> T; // Answer is no if size of strings is differe...
1111
B
Average Superhero Gang Power
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations. Initially, there are $n$ superheroes in avengers team having powers $a_1, a_2, \ldots, a_n$, respectively. In one operation, t...
If we want to remove an element to increase the average it should be the smallest element in our current set. For each deletion, $1$ operation is used. Lets try finding $f(i)$ = maximum average by deleting $i$ smallest elements. If we delete $i$ elements, then for the remaining $n-i$ elements the maximum increase can b...
[ "brute force", "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; const long long N = 100010; long long a[N]; int main() { long long n, k, m, i, sum=0, tp; long double mx; cin>>n>>k>>m; for(int i=1;i<=n;i++) { cin>>a[i]; sum += a[i]; } // Sorting the array sort(a+1, a+n+1); // Checking...
1111
C
Creative Snap
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base. Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $2$. Thanos wants to destroy t...
Make a recursive function rec($l,r$) where l and r are start and end indexes of subarray to be considered. Start with $l=1$ and $r=2^n$. If there is no avenger in l to r return A (power consumed). Else either power consumed to burn it directly is $b*x*len$ (where x is number of avengers in l to r and len is length of a...
[ "binary search", "brute force", "divide and conquer", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; vector<long long> avengers; long long n,k,A,B; // rec(l,r) returns minimum power needed to destroy l to r (inclusive) long long rec(long long l, long long r) { long long i=lower_bound(avengers.begin(),avengers.end(),l)-avengers.begin(); long long j=upper_bound(avengers....
1111
D
Destroy the Colony
There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain. Each colony arrangement can be expressed as a string of \textbf{even} length, where the $i$-th character of the string represents the type of villain in the $i$-th hole. Iron Man can destroy a colony only ...
The question reduces to the following. Given a string s with lowercase and uppercase characters,a good string is one which can be generated by reshuffling characters, such that all occurences of a particular alphabet are in the same half. ( (1 to n/2) or (n/2+1 to n)) and this condition is true for all alphabets. Now g...
[ "combinatorics", "dp", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; #define pb push_back #define fr(i,n) for(i=0;i<n;i++) #define rep(i,st,en) for(i=st;i<=en;i++) typedef long long ll; typedef pair<int,int> pii; const int N = 100010; ll mod = 1e9+7; ll fmod(ll b,ll exp){ ll res =1; while(exp){if(exp&1ll)res=(res*b)%mod; b =(b*b)...
1111
E
Tree
You are given a tree with $n$ nodes and $q$ queries. Every query starts with three integers $k$, $m$ and $r$, followed by $k$ nodes of the tree $a_1, a_2, \ldots, a_k$. To answer a query, assume that the tree is rooted at $r$. We want to divide the $k$ given nodes into \textbf{at most} $m$ groups such that the followi...
Assume that we didn't have to root at Y in each query. Lets first solve the problem for all queries having root at 1. While processing the query, let's sort the given set of nodes according to the dfs order. Let dp[i][j] denotes the number of ways to divide the first i nodes in the set into j non-empty groups. For a no...
[ "data structures", "dfs and similar", "dp", "graphs", "trees" ]
2,500
#include<bits/stdc++.h> using namespace std; #define pb push_back #define rep(i,st,en) for(i=st;i<=en;i++) typedef long long ll; typedef pair<int,int> pii; const int N = 200010; const int LN = 20; ll mod = 1e9+7; ll fmod(ll b,ll exp){ ll res =1; while(exp){if(exp&1ll)res=(res*b)%mod; b =(b*b)%mod;exp/=...
1113
A
Sasha and His Trip
Sasha is a very happy guy, that's why he is always on the move. There are $n$ cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from $1$ to $n$ in increasing order. The distance between any two adjacent cities is equal to $1$ kilometer. Since all ...
When $n - 1 < v$ the answer is $n - 1$. Else you must notice, that it is optimal to fill the tank as soon as possible, because if you don't do that, you will have to spend more money in future. So to drive first $v - 1$ kilometers just buy $v - 1$ liters in the first city, then to drive between cities with numbers $i$ ...
[ "dp", "greedy", "math" ]
900
"#include <bits/stdc++.h>\nusing namespace std;\n\n\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr), cout.tie(nullptr);\n \n int n, v;\n cin >> n >> v;\n if (n-1 <= v) {\n cout << n-1 << endl;\n return 0;\n }\n int result = v - 1;\n for(int i = 1; i <= n...
1113
B
Sasha and Magnetic Machines
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$. This year 2D decided to cultivate a new culture, but what exactly...
First notice that if we divide some number by $x$, then to get the minimal sum, it is optimal to multiply by $x$ the smallest number in the array. So now precalculate the sum of the initial array and the minimal $a_i$, then you can check all possible $x$ for every $a_i$, and choose the best variant. So the complexity i...
[ "greedy", "number theory" ]
1,300
"#include <bits/stdc++.h>\nusing namespace std;\n\n\nint32_t main() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr), cout.tie(nullptr);\n \n int n;\n cin >> n;\n vector<int> a(n);\n for(int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n int mn = *min_element(a.begin(), a.end());\n ...
1114
A
Got Any Grapes?
\begin{quote} The Duck song \end{quote} For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen: - ...
First of all, we can see the grape preference is hierarchically inclusive: the grapes' types Andrew enjoys are some of those that Dmitry does, and Dmitry's favorites are included in Michal's. Let's distribute the grapes to satisfy Andrew first, then to Dmitry, then Michal. If any of the following criteria is not satisf...
[ "brute force", "greedy", "implementation" ]
800
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' int x, y, z, a, b, c; void Input() { cin >> x >> y >> z; cin >> a >> b >> c; } void Solve() { if (x > a) {cout << "NO\n"; return;} if (x + y > a + b) {cout << "NO\n"; return...
1114
B
Yet Another Array Partitioning Task
An array $b$ is called to be a subarray of $a$ if it forms a continuous subsequence of $a$, that is, if it is equal to $a_l$, $a_{l + 1}$, $\ldots$, $a_r$ for some $l, r$. Suppose $m$ is some known constant. For any array, having $m$ or more elements, let's define it's beauty as the sum of $m$ largest elements of that...
In a perfect scenario, the maximum beauty of the original array is just a sum of $m \cdot k$ largest elements. In fact, such scenario is always available regardless of the elements. Let's denote $A$ as the set of these $m \cdot k$ largest elements. The solution for us will be dividing the array into $k$ segments, such ...
[ "constructive algorithms", "greedy", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); int n, m, k; cin >> n >> m >> k; vector<pii> a(n); for(int i = 0; i < n; ++i) { cin >> a[i].first; a[i].second = i; } ...
1114
C
Trailing Loves (or L'oeufs?)
\begin{quote} The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis. \end{quote} Aki is fond of numbers, especially those with trailing zeros. For example, the number $9200$ has two trailing zeros. Aki thinks the mo...
The problem can be reduced to the following: finding the maximum $r$ that $n !$ is divisible by $b^{r}$. By prime factorization, we will have the following: $b = p_{1}^{y1} \cdot p_{2}^{y2} \cdot ... \cdot p_{m}^{ym}$. In a similar manner, we will also have: $n ! = p_{1}^{x1} \cdot p_{2}^{x2} \cdot ... \cdot p_{m}^{xm}...
[ "brute force", "implementation", "math", "number theory" ]
1,700
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' long long n, b; void Input() { cin >> n >> b; } void Solve() { long long ans = 1000000000000000000LL; for (long long i=2; i<=b; i++) { if (1LL * i * i > b) i = b; int cnt...
1114
D
Flood Fill
You are given a line of $n$ colored squares in a row, numbered from $1$ to $n$ from left to right. The $i$-th square initially has the color $c_i$. Let's say, that two squares $i$ and $j$ belong to the same connected component if $c_i = c_j$, and $c_i = c_k$ for all $k$ satisfying $i < k < j$. In other words, all squa...
This problem was inspired by the game Flood-it. It is apparently NP-hard. You can try out the game here. https://www.chiark.greenend.org.uk/\%7Esgtatham/puzzles/js/flood.html The first solution is rather straightforward. Suppose squares $[L, R]$ are flooded, then they are either of color $c_{L}$ or $c_{R}$. We can defi...
[ "dp" ]
1,900
#include <bits/stdc++.h> using namespace std; const int maxN = 5008; int n; int dp[maxN][maxN]; vector<int> a(1), b; vector<int> ans; void input() { cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; if (x != a.back()) a.push_back(x); } n = a.size() - 1; b = a; reverse(b.begin() + 1, b.end()); } vo...
1114
E
Arithmetic Progression
This is an interactive problem! An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($x_i - x_{i - 1}$, where $i \ge 2$) is constant — such difference is called a common difference of the sequence. That is, an arithmetic progression...
The > query type allows you to find the max value of the array through binary searching, which will cost $\lceil\log_{2}(10^{9})\rceil=30$ queries. The remaining queries will be spent for the queries of the ? type to get some random elements of the array. $d$ will be calculated as greatest common divisors of all differ...
[ "binary search", "interactive", "number theory", "probabilities" ]
2,200
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; #define endl '\n' mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count()); int n, Max = -1000000000, d = 0; int queryRemaining = 60; vector<int> id; void findMax() { int top = -1000...
1114
F
Please, another Queries on Array?
You are given an array $a_1, a_2, \ldots, a_n$. You need to perform $q$ queries of the following two types: - "MULTIPLY l r x" — for every $i$ ($l \le i \le r$) multiply $a_i$ by $x$. - "TOTIENT l r" — print $\varphi(\prod \limits_{i=l}^{r} a_i)$ taken modulo $10^9+7$, where $\varphi$ denotes Euler's totient function...
There's a few fundamentals about Euler's totient we need to know: $ \phi (p) = p - 1$ and $ \phi (p^{k}) = p^{k - 1} \cdot (p - 1)$, provided $p$ is a prime number and $k$ is a positive integer. You can easily prove these equations through the definition of the function itself. Euler's totient is a multiplicative funct...
[ "bitmasks", "data structures", "divide and conquer", "math", "number theory" ]
2,400
#define _CRT_SECURE_NO_WARNINGS #pragma GCC optimize("unroll-loops") #include <iostream> #include <algorithm> #include <vector> #include <ctime> #include <unordered_set> #include <string> #include <map> #include <unordered_map> #include <random> #include <set> #include <cassert> #include <functional> #include <iomanip>...
1117
A
Best Subsegment
You are given array $a_1, a_2, \dots, a_n$. Find the subsegment $a_l, a_{l+1}, \dots, a_r$ ($1 \le l \le r \le n$) with maximum arithmetic mean $\frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i}$ (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the \textbf{longest} one.
There is a property of arithmetic mean: $\frac{1}{k}\sum\limits_{i=1}^{k}{c_i} \le \max\limits_{1 \le i \le k}{c_i}$ and the equality holds when $c_1 = c_2 = \dots = c_k$. Obviously, we can always gain maximum arithmetic mean equal to $\max\limits_{1 \le i \le n}{a_i}$ by taking single maximum element from $a$. Conside...
[ "implementation", "math" ]
1,100
#include<iostream> using namespace std; int main() { int n; cin >> n; int mx = -1, lenMx = 0; int curEl = -1, curLen = 0; for(int i = 0; i < n; i++) { int a; cin >> a; if(curEl != a) curEl = a, curLen = 0; curLen++; if(mx < curEl) mx = curEl, lenMx = 0; if(mx == curEl) lenMx = max(lenMx,...
1117
B
Emotes
There are $n$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $i$-th emote increases the opponent's happiness by $a_i$ units (we all know that emotes in this game are used to make opponents happy). You have time to use some emotes only $m$ times. You are a...
It is obvious that we always can use only two emotes with maximum $a_i$. Let their values be $x$ and $y$ ($x \ge y$). We have to solve the problem by some formula. The best way to use emotes - use the emote with the value $x$ $k$ times, then use the emotion with the value $y$, then again use the emote with value $x$ $k...
[ "greedy", "math", "sortings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, k; cin >> n >> m >> k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); cout << m / (k + 1) * 1ll...
1117
C
Magic Ship
You a captain of a ship. Initially you are standing in a point $(x_1, y_1)$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $(x_2, y_2)$. You know the weather forecast — the string $s$ of length $n$, consisting only of letters U, D, L and R. The letter corres...
Note, that if we can reach the destination in $x$ days, so we can reach it in $y \ge x$ days, since we can stay in the destination point by moving to the opposite to the wind direction. So, we can binary search the answer. To check the possibility to reach the destination point $(x_2, y_2)$ in $k$ days we should at fir...
[ "binary search" ]
1,900
#include <bits/stdc++.h> using namespace std; #define x first #define y second const int N = 100009; pair<int, int> st, fi; int n; string s; string mv = "UDLR"; int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; pair<int, int> d[N]; int main(){ cin >> st.x >> st.y >> fi.x >> fi.y; cin >> n >> s; for(int i...
1117
D
Magic Gems
Reziba has many magic gems. Each magic gem can be split into $M$ normal gems. The amount of space each magic (and normal) gem takes is $1$ unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is $N$ units. If a m...
Let's reformulate the solution to the form of dynamic programming. $dp_n$ - the number of ways to split the gems so that the total amount of space taken is $n$. Then there are obvious transitions of either splitting the last gem or not. $dp_n = dp_{n - m} + dp_{n - 1}$. And that can be easily rewritten in such a way th...
[ "dp", "math", "matrices" ]
2,100
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second #define MOD 1000000007 #define MOD9 1000000009 #define pi 3.1415926535 #define ms(s, n) memset(s, n, sizeof(s)) #define prec(n) fixed<<setprecision(n) #define eps 0.000001 #define all(v) v.begin(), v.end() #define allr(...
1117
E
Decypher the String
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentati...
Since a sequence of swaps denotes some permutation, let's try to restore the permutation $p$ that was used to transform $s$ into $t$, and then get $s$ by applying inverse permutation. If $n$ was $26$ or less, then we could get $p$ just by asking one query: send a string where no character occurs twice, and the resultin...
[ "bitmasks", "chinese remainder theorem", "constructive algorithms", "interactive", "math" ]
2,200
#include <bits/stdc++.h> using namespace std; int main() { string t; cin >> t; int n = t.size(); string s1(n, 'a'), s2(n, 'a'), s3(n, 'a'); for(int i = 0; i < n; i++) { s1[i] = char('a' + (i % 26)); s2[i] = char('a' + ((i / 26) % 26)); s3[i] = char('a' + ((i / 26 / 26) % 26)); } cout << "? " << s1 << en...
1117
F
Crisp String
You are given a string of length $n$. Each character is one of the first $p$ lowercase Latin letters. You are also given a matrix $A$ with binary values of size $p \times p$. This matrix is symmetric ($A_{ij} = A_{ji}$). $A_{ij} = 1$ means that the string can have the $i$-th and $j$-th letters of Latin alphabet adjace...
Each state of the string can be denoted as the set of characters we deleted from it, and each such set can be represented as a $p$-bit binary mask, where $i$-th bit is equal to $0$ if $i$-th character of the alphabet is already deleted, and $1$ otherwise. Let's call a mask bad if the string formed by this mask is not c...
[ "bitmasks", "dp" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 100 * 1000 + 13; const int P = 17; int n, p; string s; int A[P][P]; vector<int> pos[P]; int pr[P][N]; bitset<(1 << P)> legal, cur, dp; int cnt[P]; int main() { scanf("%d%d", &n, &p); char buf[N]; scan...
1117
G
Recursive Queries
You are given a permutation $p_1, p_2, \dots, p_n$. You should answer $q$ queries. Each query is a pair $(l_i, r_i)$, and you should calculate $f(l_i, r_i)$. Let's denote $m_{l, r}$ as the position of the maximum in subsegment $p_l, p_{l+1}, \dots, p_r$. Then $f(l, r) = (r - l + 1) + f(l, m_{l,r} - 1) + f(m_{l,r} + 1...
Let's denote $fl(l, r) = (m_{l,r} - l) + fl(l, m_{l,r} - 1) + fl(m_{l,r} + 1, r)$ and, analogically, $fr(l, r) = (r - m_{l,r}) + fr(l, m_{l,r} - 1) + fr(m_{l,r} + 1, r)$. Then, we can note that $f(l, r) = (r - l + 1) + fl(l, r) + fr(l, r)$. So we can switch to calculating $fl$ (and $fr$). Let's $lf[i]$ be the closest f...
[ "data structures" ]
2,500
#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; int n, q; vector<int> a; vector< pair<pt, int> > qs; inline bool read() { if(!(cin >> n >> q)) r...
1118
A
Water Buying
Polycarp wants to cook a soup. To do it, he needs to buy exactly $n$ liters of water. There are only two types of water bottles in the nearby shop — $1$-liter bottles and $2$-liter bottles. There are infinitely many bottles of these two types in the shop. The bottle of the first type costs $a$ burles and the bottle o...
The answer can be calculated by easy formula: $\lfloor\frac{n}{2}\rfloor \cdot min(2a, b) + (n~ \%~ 2) \cdot a$, where $\lfloor\frac{x}{y}\rfloor$ is $x$ divided by $y$ rounded down and $x~ \%~ y$ is $x$ modulo $y$.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int q; cin >> q; for (int i = 0; i < q; ++i) { long long n; int a, b; cin >> n >> a >> b; cout << (n / 2) * min(2 * a, b) + (n % 2) * a << endl; } ...
1118
B
Tanya and Candies
Tanya has $n$ candies numbered from $1$ to $n$. The $i$-th candy has the weight $a_i$. She plans to eat exactly $n-1$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, \textbf{exactly one candy per day}. Your task is to find the number of such candies $i$ (let's...
Let's maintain four variables $oddPref$, $evenPref$, $oddSuf$ and $evenSuf$, which will mean the sum of $a_i$ with odd $i$ on prefix, even $i$ on prefix, odd $i$ on suffix and even $i$ on suffix. Initially, $oddPref$ and $evenPref$ are $0$, $oddSuf$ equals to the sum of $a_i$ with odd $i$ in a whole array and $evenSuf$...
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; vector<int> a(n); int ePref = 0, oPref = 0, eSuf = 0, oSuf = 0; for (int i = 0; i < n; ++i) { cin >> a[i]; if (i & 1) eSuf += a[i]; ...
1118
C
Palindromic Matrix
Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed. For example, the following matrices are \textbf{palindromic}: The following matrices are \textbf{not palindromic} because th...
Basically, what does the matrix being palindromic imply? For each $i, j$ values in cells $(i, j)$, $(i, n - j - 1)$, $(n - i - 1, j)$ and $(n - i - 1, n - j - 1)$ are equal (all zero-indexed). You can easily prove it by reversing the order of rows or columns and checking the overlapping cells in them. Thus, all cells c...
[ "constructive algorithms", "implementation" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef pair<int, int> pt; const int N = 1000 + 7; int cnt[N]; int a[20][20]; int main() { int n; scanf("%d", &n); forn(i, n * n){ int x; scanf("%d", &x); ++cnt[x]; } vector<pair<int, pt>> cells; forn(i...
1118
D1
Coffee and Coursework (Easy version)
\textbf{The only difference between easy and hard versions is the constraints}. Polycarp has to write a coursework. The coursework consists of $m$ pages. Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He...
Since the number of days doesn't exceed $n$, let's iterate over this value (from $1$ to $n$). So now we have to check (somehow), if the current number of days is enough to write a coursework. Let the current number of days be $k$. The best way to distribute first cups of coffee for each day is to take $k$ maximums in t...
[ "brute force", "greedy" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); for (int i = 1; i <= n; ++i) { ...
1118
D2
Coffee and Coursework (Hard Version)
\textbf{The only difference between easy and hard versions is the constraints}. Polycarp has to write a coursework. The coursework consists of $m$ pages. Polycarp also has $n$ cups of coffee. The coffee in the $i$-th cup Polycarp has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than ...
Well, the main idea is described in the previous (D1) problem editorial. Read it firstly. So, now we have to improve our solution somehow. How can we do it? Wait... What is it? We iterate over all numbers of days... And the number of pages Polycarp can write when we consider $k+1$ days instead of $k$ is strictly increa...
[ "binary search", "greedy" ]
1,700
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> a; bool can(int i) { long long sum = 0; // there can be a bug for (int j = 0; j < n; ++j) { sum += max(a[j] - j / i, 0); } return sum >= m; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout);...
1118
E
Yet Another Ball Problem
The king of Berland organizes a ball! $n$ pair are invited to the ball, they are numbered from $1$ to $n$. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from $1$ to $k$, inclusive. Let $b_i$ be the color o...
The first observation: we cannot construct more than $k(k-1)$ pairs at all due to second and third rules. The second observation: we always can construct an answer which will contain all $k(k-1)$ pairs (and get some prefix of this answer if we need less than $k(k-1)$ pairs). Ho do we do that? Let man's costumes colors ...
[ "constructive algorithms", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; cin >> n >> k; if (n > k * 1ll * (k - 1)) { cout << "NO" << endl; } else { cout << "YES" << endl; int cur = 0; for (int i = 0; i < n; ++i)...
1118
F1
Tree Cutting (Easy Version)
You are given an undirected tree of $n$ vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. L...
Let's root the tree by some vertex. The edge $(v, u)$, where $v$ is the parent of $u$, is now nice if and only if the subtree of $u$ contains either all red vertices of the tree and no blue vertices or all blue vertices of the tree and no red vertices. That's because removing that edge splits the tree into the subtree ...
[ "dfs and similar", "trees" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 300 * 1000 + 13; int n; int a[N]; vector<int> g[N]; int red, blue; int ans; pair<int, int> dfs(int v, int p = -1){ int r = (a[v] == 1), b = (a[v] == 2); for (auto u : g[v]) if (u != p){ auto tmp = df...
1118
F2
Tree Cutting (Hard Version)
You are given an undirected tree of $n$ vertices. Some vertices are colored one of the $k$ colors, some are uncolored. It is guaranteed that the tree contains at least one vertex of each of the $k$ colors. There might be no uncolored vertices. You choose a subset of \textbf{exactly $k - 1$ edges} and remove it from t...
Okay, this solution is really complicated and I would like to hear nicer approaches from you in comments if you have any. However, I still feel like it's ok to have this problem in a contest specifically as a harder version of F1. Let's start with the following thing. Root the tree by some vertex. For each color take a...
[ "combinatorics", "dfs and similar", "dp", "trees" ]
2,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 300 * 1000 + 13; const int LOGN = 19; const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b...
1119
A
Ilya and a Colorful Walk
Ilya lives in a beautiful city of Chordalsk. There are $n$ houses on the street Ilya lives, they are numerated from $1$ to $n$ from left to right; the distance between every two neighboring houses is equal to $1$ unit. The neighboring houses are $1$ and $2$, $2$ and $3$, ..., $n-1$ and $n$. The houses $n$ and $1$ are ...
It is enough to find the last color different from the $c_1$ and the first color different from $c_n$ and print the maximum of the two distances.
[ "greedy", "implementation" ]
1,100
null
1119
B
Alyona and a Narrow Fridge
Alyona has recently bought a miniature fridge that can be represented as a matrix with $h$ rows and $2$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space ...
For a fixed set of bottles the optimal way to put them in the fridge is to sort them in decreasing order and then put the tallest next to the second tallest, the third next to the fourth and so on. The total required height is then $h_1 + h_3 + h_5 + \ldots$, where $h$ is the sorted array of heights. Now just try all p...
[ "binary search", "flows", "greedy", "sortings" ]
1,300
[n, k], arr = [int(i) for i in input().split()], [int(i) for i in input().split()] print([i for i in range(n + 1) if sum(sorted(arr[0:i])[::-2]) <= k][-1])
1119
C
Ramesses and Corner Inversion
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task. You are given two matrices $A$ and $B$ of size $n \times m$, each of which consists of $0$ and $1$ only. You can apply the following operation to the matrix $A$ arbitrary number of time...
One can notice that the operation does not change the total parity of the matrix. So, if the total parity of $A$ and $B$ do not match, then the answer is No. However, this is not the only case when the answer is no. You can also notice that the operation does not change the total parity of each row/column independently...
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,500
null
1119
D
Frets On Fire
Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day. In return, the fleas made a bigger ukulele for her: it has $n$ strings, and each string has $(10^{18} + 1)$ frets numerated from $0$ to $10^{18}$. The fleas use the array $s_...
Let's sort all $s_i$'s in ascending order. This does not affect the answers, but now we notice that for some $i$, as soon as $r - l$ exceeds $s_{i+1} - s_i$ we don't need to consider row $i$ any more. This is because from then on, any integer that appears in row $i$ also appears in row $i + 1$. Taking this observation ...
[ "binary search", "sortings" ]
1,800
#include <cstdio> #include <algorithm> static const int MAXN = 1e5; static int n, q; static long long s[MAXN]; static long long t[MAXN]; int main() { scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%lld", &s[i]); std::sort(s, s + n); for (int i = 0; i < n - 1; ++i) s[i] = s[i + 1] - s[i]; st...
1119
E
Pavel and Triangles
Pavel has several sticks with lengths equal to powers of two. He has $a_0$ sticks of length $2^0 = 1$, $a_1$ sticks of length $2^1 = 2$, ..., $a_{n-1}$ sticks of length $2^{n-1}$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each st...
First, possible triangles have sides $(2^i, 2^j, 2^j)$ where $i \le j$. There are several correct greedies to finish the solution, let's discuss one of them. The greedy is to loop through the values of $j$ in increasing order, then first try to match as many pairs $(j, j)$ to some unmatched $i$ as possible, after that ...
[ "brute force", "dp", "fft", "greedy", "ternary search" ]
1,900
null
1119
F
Niyaz and Small Degrees
Niyaz has a tree with $n$ vertices numerated from $1$ to $n$. A tree is a connected graph without cycles. Each edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex. Niyaz does not like when vertices in the tree have too large degrees. For each $x$...
First, let's learn how to solve for a fixed $x$ in $O(n \log n)$. We can calculate the dp on subtrees, $dp_{v, flag}$, denoting the minimum total weight of edges to be removed, if we consider the subtree of the vertex $v$, and $flag$ is zero, if the vertex has the degree $\leq x$, and one, if $\leq x+1$. Then to recalc...
[ "data structures", "dp", "trees" ]
3,400
null
1119
G
Get Ready for the Battle
Recently Evlampy installed one interesting computer game, one of aspects of which is to split army into several groups and then fight with enemy's groups. Let us consider a simplified version of the battle. In the nearest battle Evlampy should fight an enemy army that consists of $m$ groups, the $i$-th of which has $h...
Note that on each turn the total health of enemy groups decreases by $n$. When all groups are destroyed, their health does not exceed $0$, and thus the answer is at least $\left\lceil{\frac{\sum_{i=1}^n hp_i}{n}}\right\rceil$. Now let's construct a way to win in this number of steps. Let's emulate the battle and split ...
[ "constructive algorithms", "implementation" ]
3,100
null
1119
H
Triple
You have received your birthday gifts — $n$ triples of integers! The $i$-th of them is $\lbrace a_{i}, b_{i}, c_{i} \rbrace$. All numbers are greater than or equal to $0$, and strictly smaller than $2^{k}$, where $k$ is a fixed integer. One day, you felt tired playing with triples. So you came up with three new intege...
If we form $n$ arrays, $i$-th of them is $F_{i}$, and set $F_{i,A_{i}}=a$, $F_{i,B_{i}}=b$, $F_{i,C_{i}}=c$ and others zero. It's easy to find that the xor-convolution of all the arrays is the answer we want. Implementation with the Fast Walsh-Hadamard Transform works in $O(n \times 2^{k} \times k)$, this is too slow. ...
[ "fft", "math" ]
3,200
null
1120
A
Diana and Liana
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $k$ flowers. The work material for the wreaths for all $n$ citizens of Shortriver is cut from the longest flowered liana that grew in the...
First of all, let's learn how to check if a perfect wreath can be obtained from the subsegment $[l, r]$ of our liana (that is, if we can remove some flowers so that the remaining ones on $[l, r]$ represent a perfect wreath, and this whole wreath will be cut). First, the number of other wreaths must be $n - 1$, so the i...
[ "greedy", "implementation", "two pointers" ]
1,900
null
1120
B
Once in a casino
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow. A positive integer $a$ is initially on the screen. The player can put a coin into the machine and then add $1$ to or subtract $1$ from any two adjacent digits. All digits must remain from $0$ to $9$ af...
Since each operation saves the alternating series of the digits, if it's different for $a$ and $b$, then the answer is '-1'. Now we prove that otherwise it's possible to win. Let's imagine that digits can be negative or bigger than 9 (that is, for example, number 19 can become the number with digits 2 and 10). Denote b...
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,700
null
1120
C
Compress String
Suppose you are given a string $s$ of length $n$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins. To compress the string, you have to represent $s$ as a concatenation of several non-empty strings: $s = t_{1} t_{2} \ldots t_{k}$. The $i$-th of these strings s...
Let's say that $dp[p]$ is the minimal cost to encode the prefix of $s$ with length $p$, the answer is $dp[n]$. If we want to encode the prefix with length $p$ then the last symbol in our encoded string either equals $s_p$, or represents some substring $s_{[l,p]}$ so that it occurs in the prefix of length $l - 1$. There...
[ "dp", "strings" ]
2,100
null
1120
D
Power Tree
You are given a rooted tree with $n$ vertices, the root of the tree is the vertex $1$. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree $1$. Arkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empt...
One can see that the problem doesn't change if we want to be able to obtain any possible combination of numbers in leaves from the all-zero combination. Solution 1. Let $v_1$, $v_2$, ..., $v_l$ be the indices of all leaves in the order of any Euler tour. Let $a_i$ be the number written in $v_i$. We say that $v_0 = v_{l...
[ "dfs and similar", "dp", "dsu", "graphs", "greedy", "trees" ]
2,500
null
1120
E
The very same Munchhausen
A positive integer $a$ is given. Baron Munchausen claims that he knows such a positive integer $n$ that if one multiplies $n$ by $a$, the sum of its digits decreases $a$ times. In other words, $S(an) = S(n)/a$, where $S(x)$ denotes the sum of digits of the number $x$. Find out if what Baron told can be true.
Define the balance of a number $x$ as $S(nx) \cdot n - S(x)$. By the balance of a digit string we mean the balance of the corresponding number. Solution 1. We are gonna do the following: Find out if the solution exists. If no, print -1 and exit. Find any string with negative balance. Find any string with positive balan...
[ "brute force" ]
2,600
null
1120
F
Secret Letters
Little W and Little P decided to send letters to each other regarding the most important events during a day. There are $n$ events during a day: at time moment $t_i$ something happens to the person $p_i$ ($p_i$ is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to ...
Consider any optimal solution. Consider all letters of W between two times when P visits R. It's clear that maybe the first of these messages is sent via R, some of the last messages are also sent via R, all other messages are sent via O. The sense behind shipping the first message via R is to obtain all messages which...
[ "data structures", "dp", "greedy" ]
3,100
null
1121
A
Technogoblet of Fire
Everybody knows that the $m$-coder Tournament will happen soon. $m$ schools participate in the tournament, and only one student from each school participates. There are a total of $n$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of ...
First of all, each time we move someone to another school the number of schools which contain at least one Chosen One can increase at most by one. Second, if a school contains $c > 0$ Chosen Ones, but the strongest guy in this school is not one of them, then we need to move someone at least $c$ times to make all these ...
[ "implementation", "sortings" ]
1,100
null
1121
B
Mike and Children
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child \textbf{two} sweets. Mike has $n$ sweets with sizes $a_1, a_2, \ldots, a_n$. All his sweets have \textbf{different} sizes. That...
Notice that the sum of sweets each child gets cannot exceed $2\cdot 10^5$, so for each of numbers no more than this threshold we can store the number of ways to obtain it as the sum of two sweets. It can be done just by considering all possible (unordered) pairs of sweets and printing the maximal obtained number (of wa...
[ "brute force", "implementation" ]
1,200
null
1121
C
System Testing
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab. There are $n$ solutions, the $i$-th of them should be tested on $a_i$ tests, testing one solution on one test takes $1$ second. The solutions are judged in the order from $1$ to $n$. There are...
Let's determine for each solution when it begins being tested. It can be done, for example, by the following algorithm: let's store for each testing process the time when it becomes free to test something (initially all these $k$ numbers are zeroes), then iterate over all solutions in the queue and for each of them we ...
[ "implementation" ]
1,600
null
1129
A2
Toy Train
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visi...
We can consider the pickup requests from each station individually. The overall answer for some fixed starting station is simply the maximum time needed to fulfill deliveries among all pickup stations. Suppose the starting station for the train is fixed at some station $s$ ($1 \leq s \leq n$). Consider some station $i$...
[ "brute force", "greedy" ]
1,800
null
1129
B
Wrong Answer
Consider the following problem: given an array $a$ containing $n$ integers (indexed from $0$ to $n-1$), find $\max\limits_{0 \leq l \leq r \leq n-1} \sum\limits_{l \leq i \leq r} (r-l+1) \cdot a_i$. In this problem, $1 \leq n \leq 2\,000$ and $|a_i| \leq 10^6$. In an attempt to solve the problem described, Alice quick...
Suppose $a_0 = -1$ and $a_i \geq 1$ for each $1 \leq i < n$. Let $S = \sum\limits_{i=0}^{n-1} a_i$. Assume also that $n \geq 2$. It is easy to see that Alice's algorithm produces $(n-1)(S+1)$ as the answer. Meanwhile, there are two possible correct answers: either $nS$ or $(n-1)(S+1)$, whichever is greater. Assume furt...
[ "constructive algorithms" ]
2,000
null
1129
C
Morse Code
In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1". Because there are $2^1+2^2+2^3+2^4 = 30$ strings w...
We will be computing the answers offline instead of doing so immediately after each modification. Let $T = S_{reversed}$. Now, we need to find the number of English sequences that, if considered backward, would translate into some substring of each suffix of T. Let $f(l, r)$ be the number of English sequences that tran...
[ "binary search", "data structures", "dp", "hashing", "sortings", "string suffix structures", "strings" ]
2,400
null
1129
D
Isolation
Find the number of ways to divide an array $a$ of $n$ integers into any number of disjoint non-empty segments so that, in each segment, there exist at most $k$ distinct integers that appear exactly once. Since the answer can be large, find it modulo $998\,244\,353$.
Let $f(l, r)$ be the number of integers that appear exactly once in the segment $a[l..r]$. We can use the following recurrence to compute the answer: $dp(n) = \sum\limits_{0 \leq i < n \wedge f(i+1, n) \leq k} dp(i)$, where $dp(0) = 1$. A naive $\mathcal{O}(n^2)$ implementation will definitely be too slow. To compute t...
[ "data structures", "dp" ]
2,900
null
1129
E
Legendary Tree
This is an interactive problem. A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster. To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains $n$ vertices, enumerated from $1$ through $n$. ...
In this analysis, let $V$ be the set of all vertices. We will use tuples of the form $(S, T, v)$ to represent queries. First, we will root the tree at vertex $1$. The size of each subtree can be found in $n-1$ queries by asking $(\{1\}, \{2, 3, \ldots, n\}, i)$, for each $1 \leq i \leq n$. Suppose $sz(i)$ denotes the s...
[ "binary search", "interactive", "trees" ]
3,100
null