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
1660
C
Get an Even String
A string $a=a_1a_2\dots a_n$ is called even if it consists of a concatenation (joining) of strings of length $2$ consisting of the same characters. In other words, a string $a$ is even if two conditions are satisfied \textbf{at the same time}: - its length $n$ is even; - for all odd $i$ ($1 \le i \le n - 1$), $a_i = a...
We will act greedily: we will make an array $prev$ consisting of $26$ elements, in which we will mark $prev[i] = true$ if the letter is already encountered in the string, and $prev[i] = false$ otherwise. In the variable $m$ we will store the length of the even string that can be obtained from $s$. We will go through th...
[ "dp", "greedy", "strings" ]
1,300
#include<bits/stdc++.h> using namespace std; int sz = 26; void solve(){ string s; cin >> s; int m = 0, n = (int)s.size(); vector<bool>prev(sz, false); for(auto &i : s){ if(prev[i - 'a']){ m += 2; for(int j = 0; j < sz; j++) prev[j] = false; } else pr...
1660
D
Maximum Product Strikes Back
You are given an array $a$ consisting of $n$ integers. For each $i$ ($1 \le i \le n$) the following inequality is true: $-2 \le a_i \le 2$. You can remove any number (possibly $0$) of elements from the beginning of the array and any number (possibly $0$) of elements from the end of the array. You are allowed to delete...
First, we can always get a product value equal to $1$ if we remove all elements of the array. Then we need to know what maximal positive value of the product we can get. Consequently, the remaining array (after removing the corresponding prefix and suffix) should have no $0$ elements. We can find maxima in all sections...
[ "brute force", "implementation", "math", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() void solve() { int n; cin >> n; vector<int> a(n); forn(i, n) cin >> a[i]; int ans = 0; int ap = n, as = 0; for(int i = 0, l = -1; i <= n; i++) { ...
1660
E
Matrix and Shifts
You are given a binary matrix $A$ of size $n \times n$. Rows are numbered from top to bottom from $1$ to $n$, columns are numbered from left to right from $1$ to $n$. The element located at the intersection of row $i$ and column $j$ is called $A_{ij}$. Consider a set of $4$ operations: - Cyclically shift all rows up. ...
Count to the variable $sum$ the number of all ones in the matrix. Then consider pairs of diagonals, one of which starts in cell $A[i][0]$, and the other - in cell $A[0][n - i]$ (for $1 \le i \le n - 1$). Using cyclic shifts, we can assemble the main diagonal from this pair. Then among all such pairs (and the main diago...
[ "brute force", "constructive algorithms", "greedy", "implementation" ]
1,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back const int INF = INT_MAX >> 1; void solve() { int n; cin >> n; int cnt1 = 0; vector<int> cnt (n, 0); for (int i = ...
1660
F1
Promising String (easy version)
\textbf{This is the easy version of Problem F. The only difference between the easy version and the hard version is the constraints.} We will call a non-empty string \textbf{balanced} if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" ...
Note the fact that if the number of minus signs is greater than the number of plus signs by at least $2$, then there is sure to be a pair of standing next to minus signs (according to the Dirichlet principle). When we apply the operation of replacing two adjacent minus signs with a plus sign, the balance (the differenc...
[ "brute force", "implementation", "math", "strings" ]
1,700
tst = int(input()) for _ in range(tst): n = int(input()) s = input() b = [0 for i in range(n+1)] bal = n b[0] = bal ans = 0 for i in range(1,n+1): if s[i-1] == '+': bal += 1 else: bal -= 1 b[i] = bal for j in range(i): if b[...
1660
F2
Promising String (hard version)
\textbf{This is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.} We will call a non-empty string \textbf{balanced} if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" ...
Now we need to quickly find for a given balance value (on the prefix), the number of matching left boundaries. The boundary is suitable if the balance on the boundary is comparable modulo $3$ to the current balance and the current balance is less than the balance on the boundary, since we need the balance on the segmen...
[ "data structures", "implementation", "math", "strings" ]
2,100
tst = int(input()) for _ in range(tst): n = int(input()) s = input() f = [0 for i in range(3)] cur_bal = n cnt_bal = [0 for i in range(2 * n + 1)] cnt_bal[cur_bal] += 1 f[cur_bal % 3] += 1 ans = 0 for i in range(n): #print(f) #print(cur_bal, ans) new_bal = cur...
1661
A
Array Balancing
You are given two arrays of length $n$: $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$. You can perform the following operation any number of times: - Choose integer index $i$ ($1 \le i \le n$); - Swap $a_i$ and $b_i$. What is the minimum possible sum $|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$ $+$ $|b_...
Let's look at our arrays $a$ and $b$. Note that for any position $p$ such that $|a_{p-1} - a_p| + |b_{p-1} - b_p| > |a_{p-1} - b_p| + |b_{p-1} - a_p|$ we can always "fix it" by swapping all positions $i$ from $p$ to $n$. In that case, contribution from all $i < p$ won't change, contribution of pair $(p - 1, p)$ will de...
[ "greedy", "math" ]
800
import kotlin.math.abs fun sum(a1: Int, a2: Int, b1: Int, b2: Int) = abs(a1 - a2) + abs(b1 - b2) fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray() val b = readLine()!!.split(' ').map { it.toInt() }.toInt...
1661
B
Getting Zero
Suppose you have an integer $v$. In one operation, you can: - either set $v = (v + 1) \bmod 32768$ - or set $v = (2 \cdot v) \bmod 32768$. You are given $n$ integers $a_1, a_2, \dots, a_n$. What is the minimum number of operations you need to make each $a_i$ equal to $0$?
Note that $32768 = 2^{15}$, so you can make any value equal to $0$ by multiplying it by two $15$ times, since $(v \cdot 2^{15}) \bmod 2^{15} = 0$. So, the answer for each value $a_i$ is at most $15$. Now, let's note that there is always an optimal answer that consists of: at first, add one $cntAdd$ times, then multiply...
[ "bitmasks", "brute force", "dfs and similar", "dp", "graphs", "greedy", "shortest paths" ]
1,300
fun main() { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray() for (v in a) { var ans = 20 for (cntAdd in 0..15) { for (cntMul in 0..15) { if (((v + cntAdd) shl cntMul) % 32768 == 0) ans = minOf(ans, ...
1661
C
Water the Trees
There are $n$ trees in a park, numbered from $1$ to $n$. The initial height of the $i$-th tree is $h_i$. You want to water these trees, so they all grow to the \textbf{same} height. The watering process goes as follows. You start watering trees at day $1$. During the $j$-th day you can: - Choose a tree and water it....
The first observation we need to solve this problem: the required height is either $max$ or $max + 1$, where $max$ is the maximum initial height of some tree. We don't need heights greater than $max + 1$, because, for example, if the height is $max + 2$, we can remove some moves and get the answer for the height $max$....
[ "binary search", "greedy", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) int main(){ int tc; scanf("%d", &tc); while (tc--) { int n; scanf("%d", &n); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); long long ans = 1e18; int mx = *m...
1661
D
Progressions Covering
You are given two arrays: an array $a$ consisting of $n$ zeros and an array $b$ consisting of $n$ integers. You can apply the following operation to the array $a$ an arbitrary number of times: choose some subsegment of $a$ of length $k$ and add the arithmetic progression $1, 2, \ldots, k$ to this subsegment — i. e. ad...
Let's solve the problem greedily. But not from the beginning, because if we solve it from the beginning, we can't be sure what option is more optimal for the next elements (e.g. for the second element it is not clear if we need to add $2$ to it starting our segment from the first position or add $1$ to it starting our ...
[ "data structures", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); vector<long long> b(n); for (auto &it : b) { scanf("%lld", &it); } vector<long long> clo...
1661
E
Narrow Components
You are given a matrix $a$, consisting of $3$ rows and $n$ columns. Each cell of the matrix is either free or taken. A free cell $y$ is reachable from a free cell $x$ if at least one of these conditions hold: - $x$ and $y$ share a side; - there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is rea...
Consider the naive approach to the problem. Cut off the columns directly and count the connected components. There are two main solutions to this problem: either DFS (or BFS) or DSU. I personally found the DSU method easier to adjust to the full problem. So, to count connected components with DSU, you should do the fol...
[ "brute force", "data structures", "dp", "dsu", "math", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) int main(){ cin.tie(0); iostream::sync_with_stdio(false); int n; cin >> n; vector<string> s(3); forn(i, 3) cin >> s[i]; vector<int> pr(n + 1); forn(i, n){ pr[i + 1] += pr[i]; forn(j, 3) pr[i + 1] += (s[j]...
1661
F
Teleporters
There are $n+1$ teleporters on a straight line, located in points $0$, $a_1$, $a_2$, $a_3$, ..., $a_n$. It's possible to teleport from point $x$ to point $y$ if there are teleporters in \textbf{both} of those points, and it costs $(x-y)^2$ energy. You want to install some additional teleporters so that it is possible ...
Initial $n+1$ portals divide the path from $0$ to $a_n$ into $n$ separate sections. If we place a new portal between two given ones, it only affects the section between these two portals. Let's suppose we want to place $k$ new portals into a section of length $x$. This will divide it into $(k+1)$ sections, and it's qui...
[ "binary search", "greedy" ]
2,600
#include <bits/stdc++.h> using namespace std; int n; vector<int> lens; long long sqr(int x) { return x * 1ll * x; } long long eval_split(int len, int k) { return sqr(len / k) * (k - len % k) + sqr(len / k + 1) * (len % k); } pair<int, long long> eval_segment(int len, long long bound) { // only tak...
1662
A
Organizing SWERC
Gianni, SWERC's chief judge, received a huge amount of high quality problems from the judges and now he has to choose a problem set for SWERC. He received $n$ problems and he assigned a beauty score and a difficulty to each of them. The $i$-th problem has beauty score equal to $b_i$ and difficulty equal to $d_i$. The ...
This is the ice breaker problem of the contest. To solve it one shall implement what is described in the statement. One way to implement it is to keep an array $\texttt{beauty}[1\dots10]$ (initialized to $0$), so that, for $1\le \texttt{diff}\le 10$, the value $\texttt{beauty}[\texttt{diff}]$ corresponds to the maximum...
[ "brute force", "implementation" ]
null
null
1662
B
Toys
Vittorio has three favorite toys: a teddy bear, an owl, and a raccoon. Each of them has a name. Vittorio takes several sheets of paper and writes a letter on each side of every sheet so that it is possible to spell any of the three names by arranging some of the sheets in a row (sheets can be reordered and flipped as ...
Toys is one of the most challenging problems of the contest, but no particular knowledge of algorithms and data structures is required to solve it. We propose two greedy solutions that start with a common reformulation of the problem statement. The limit to the length of the three names is very permissive ($\leq 1000$)...
[ "greedy", "strings" ]
null
null
1662
C
European Trip
The map of Europe can be represented by a set of $n$ cities, numbered from $1$ through $n$, which are connected by $m$ bidirectional roads, each of which connects two distinct cities. A trip of length $k$ is a sequence of $k+1$ cities $v_1, v_2, \ldots, v_{k+1}$ such that there is a road connecting each consecutive pai...
Warm-up problem Let us consider a related simpler problem first. Let $G$ be the graph that represents the cities and roads in the problem statement and let $A$ be its adjacency matrix. Suppose that instead of special trips we wanted to compute the number of distinct trips of length $k$ that begin and end in the same ci...
[ "dp", "graphs", "math", "matrices" ]
null
null
1662
D
Evolution of Weasels
A wild basilisk just appeared at your doorstep. You are not entirely sure what a basilisk is and you wonder whether it evolved from your favorite animal, the weasel. How can you find out whether basilisks evolved from weasels? Certainly, a good first step is to sequence both of their DNAs. Then you can try to check wh...
To solve the problem we need the following observations. Every mutation is reversible. Hence, instead of trying to find a sequence of mutations of the string $u$ to get to the string $v$, we can try to find a sequence of mutations of the string $u$ and a sequence of mutations of the string $v$ such that both of them ar...
[ "greedy", "implementation", "strings" ]
null
null
1662
E
Round Table
There are $n$ people, numbered from $1$ to $n$, sitting at a round table. Person $i+1$ is sitting to the right of person $i$ (with person $1$ sitting to the right of person $n$). You have come up with a better seating arrangement, which is given as a permutation $p_1, p_2, \dots, p_n$. More specifically, you want to c...
Main assumption After playing a bit with the second sample test case one can notice that there are many sequences of swaps of the same length that achieve the same result, and as long as we always swap two people such that the person with a larger number is on the left before the swap, then we always achieve the goal i...
[ "math" ]
null
null
1662
F
Antennas
There are $n$ equidistant antennas on a line, numbered from $1$ to $n$. Each antenna has a power rating, the power of the $i$-th antenna is $p_i$. The $i$-th and the $j$-th antenna can communicate directly if and only if their distance is at most the minimum of their powers, i.e., $|i-j| \leq \min(p_i, p_j)$. Sending ...
Let's model the problem as an undirected graph, where the vertex $i$ corresponds to the antenna $i$ and vertices $i$ and $j$ are connected with an edge if and only if the corresponding antennas are able to communicate directly, that is $|i - j| \leq \min(p_i, \, p_j)$. In this formulation, the answer to the question po...
[ "data structures", "dfs and similar", "graphs", "implementation", "shortest paths" ]
null
null
1662
G
Gastronomic Event
SWERC organizers want to hold a gastronomic event. The location of the event is a building with $n$ rooms connected by $n-1$ corridors (each corridor connects two rooms) so that it is possible to go from any room to any other room. In each room you have to set up the tasting of a typical Italian dish. You can choose ...
This is a classical problem in which one must find a "simple" characterization of what the optimal solution looks like, and then restrict the search for the maximum to the (much smaller, much more regular) family of instances that satisfy the characterization. In our specific case, the first part of this paradigm is by...
[ "dp", "greedy", "trees" ]
null
null
1662
H
Boundary
Bethany would like to tile her bathroom. The bathroom has width $w$ centimeters and length $l$ centimeters. If Bethany simply used the basic tiles of size $1 \times 1$ centimeters, she would use $w \cdot l$ of them. However, she has something different in mind. - On the interior of the floor she wants to use the $1 \...
First, observe that we can tile any rectangle with tiles of size $1 \times 1$. From now on, we will consider a fixed $a > 1$. Let's investigate what happens in the corners of the rectangle. Each corner is covered either by a tile that is placed horizontally, or by a tile that is placed vertically. Below is an example o...
[ "brute force", "math" ]
null
null
1662
I
Ice Cream Shop
On a beach there are $n$ huts in a perfect line, hut $1$ being at the left and hut $i+1$ being $100$ meters to the right of hut $i$, for all $1 \le i \le n - 1$. In hut $i$ there are $p_i$ people. There are $m$ ice cream sellers, also aligned in a perfect line with all the huts. The $i$-th ice cream seller has their s...
Suppose there are ice cream shops located $a$ and $b$ meters to the right of the first hut, such that $a < b$. If we place our ice cream shop in any location in the interval $[a, \, b]$ it can only be strictly closer to huts located in the interval $(a, \, b)$, since any hut located at or before $a$ will be closer to t...
[ "brute force", "implementation", "sortings" ]
null
null
1662
J
Training Camp
You are organizing a training camp to teach algorithms to young kids. There are $n^2$ kids, organized in an $n$ by $n$ grid. Each kid is between $1$ and $n$ years old (inclusive) and any two kids who are in the same row or in the same column have different ages. You want to select exactly $n$ kids for a programming co...
In this task, you are given the ages of $n^2$ kids as a Latin square $S$ ($n \times n$ grid such that each row and each column contains all the integers from $1$ to $n$), and you are asked to find a subset containing exactly one kid from each row/column, satisfying a certain "stability" constraint, and maximizing the n...
[ "flows", "graphs" ]
null
null
1662
K
Pandemic Restrictions
After a long time living abroad, you have decided to move back to Italy and have to find a place to live, but things are not so easy due to the ongoing global pandemic. Your three friends Fabio, Flavio and Francesco live at the points with coordinates $(x_1, y_1), (x_2, y_2)$ and $(x_3, y_3)$, respectively. Due to the...
Let us start with some definitions that will make the presentation clearer. Given three points $X, Y$ and $Z$ in the plane, let $f(X, \, Y, \, Z)$ be the minimum of $\overline{XP}+\overline{YP}+\overline{ZP}$ over all points $P$. It is well known that this minimum actually exists and is achieved at a unique point calle...
[ "geometry", "ternary search" ]
null
null
1662
L
Il Derby della Madonnina
The derby between Milan and Inter is happening soon, and you have been chosen as the assistant referee for the match, also known as linesman. Your task is to move along the touch-line, namely the side of the field, always looking very carefully at the match to check for offside positions and other offences. Football i...
Let $x_i := v t_i - a_i$ and $y_i := v t_i + a_i$ for $i = 1, \, \ldots, \, n$. The main observation to solve this problem is that a sequence of kicks with indices $i_1, \, \ldots, \, i_k$ can be seen (in this order and starting from the first one) if and only if both sequences $x_{i_1}, \, \ldots, \, x_{i_k}$ and $y_{...
[ "data structures", "dp", "math" ]
null
null
1662
N
Drone Photo
Today, like every year at SWERC, the $n^2$ contestants have gathered outside the venue to take a drone photo. Jennifer, the social media manager for the event, has arranged them into an $n\times n$ square. Being very good at her job, she knows that the contestant standing on the intersection of the $i$-th row with the ...
For each $i = 1, \, \ldots, \, n^2$, let: $s_i$ denote the $i$-year-old contestant; $u_i$ be the number of contestants on the same row as $s_i$ who are (strictly) under $i$ years old; $v_i$ be the number of contestants on the same column as $s_i$ who are (strictly) under $i$ years old. Let $A$ be the answer to the prob...
[ "combinatorics", "math", "sortings" ]
null
null
1662
O
Circular Maze
You are given a circular maze such as the ones shown in the figures. Determine if it can be solved, i.e., if there is a path which goes from the center to the outside of the maze which does not touch any wall. The maze is described by $n$ walls. Each wall can be either circular or straight. - Circular walls are descr...
In this task, you are given circular mazes described by collections of walls, which can be either circular (constant radius) or straight (constant angle). The goal is to determine if a maze can be solved, that is, if there is a path from the center to the outside which does not cross any wall. Reducing the problem to a...
[ "brute force", "dfs and similar", "graphs", "implementation" ]
null
null
1665
A
GCD vs LCM
You are given a positive integer $n$. You have to find $4$ \textbf{positive} integers $a, b, c, d$ such that - $a + b + c + d = n$, and - $\gcd(a, b) = \operatorname{lcm}(c, d)$. If there are several possible answers you can output any of them. It is possible to show that the answer always exists. In this problem $\...
In this problem it is enough to print $n - 3$, $1$, $1$, $1$. It is easy to see that this answer is correct for any $n \ge 4$.
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T --> 0) { int n; cin >> n; cout << n - 3 << ' ' << 1 << ' ' << 1 << ' ' << 1 << '\n'; } return 0; }
1665
B
Array Cloning Technique
You are given an array $a$ of $n$ integers. Initially there is only one copy of the given array. You can do operations of two types: - Choose any array and clone it. After that there is one more copy of the chosen array. - Swap two elements from \textbf{any} two copies (maybe in the same copy) on any positions. You ...
We will use a greedy technique. Let's find the most common element in the array. Let it be $x$ and let it occur $k$ times in the array. Then let's make a copy where all elements are $x$. To do that we can make a copy of the given array and put all $x$ in one array. Now we will repeat the algorithm for the new array unt...
[ "constructive algorithms", "greedy", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int T; cin >> T; while (T --> 0) { int n; cin >> n; map<int, int> q; for (int i = 0; i < n; ++i) { int x; cin...
1665
C
Tree Infection
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. You are given a r...
Firstly, we can see that for any two different vertices, their children are independent. It means that infection can not spread from children of one vertex to children of another. Also it does not matter how the infection spreads among the children of some vertex, so we only need to know the amount of vertices with the...
[ "binary search", "greedy", "sortings", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; int ans; void proc(vector<int>& a) { if (a.empty()) return; int n = a.size(); int last = 0; for (int i = 0; i < n; ++i) { if (a[i] == a[0]) { last = i; } else { break; } } --a[last]; for (int i = ...
1665
D
GCD Guess
\textbf{This is an interactive problem.} There is a positive integer $1 \le x \le 10^9$ that you have to guess. In one query you can choose two positive integers $a \neq b$. As an answer to this query you will get $\gcd(x + a, x + b)$, where $\gcd(n, m)$ is the greatest common divisor of the numbers $n$ and $m$. To ...
Solution 1 Let's iteratively find the remainder of $x \bmod$ each power of $2$. Initially, we know that $x \bmod 2^0 = x \bmod 1 = 0$. If we know that $x \bmod 2^k = r$, then how do we find $x \bmod 2^{k + 1}$? To do that let's ask $\gcd(x + 2^k - r, 2^{k + 1}) = \gcd(x + 2^k - r, x + 2^k - r + 2^{k + 1})$. If $\gcd = ...
[ "bitmasks", "chinese remainder theorem", "constructive algorithms", "games", "interactive", "math", "number theory" ]
2,000
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 998244353 #define maxn 110 #define lc 1338557220 ll i, i1, j, k, k1, t, n, m, res, flag[10], a, b; ll x, rs[maxn], p; vector<ll> pw = {23, 19...
1665
E
MinimizOR
You are given an array $a$ of $n$ non-negative integers, numbered from $1$ to $n$. Let's define the cost of the array $a$ as $\displaystyle \min_{i \neq j} a_i | a_j$, where $|$ denotes the bitwise OR operation. There are $q$ queries. For each query you are given two integers $l$ and $r$ ($l < r$). For each query you...
The key idea for the solution is that the answer always lies among no more than 31 minimal numbers. According to this idea, it is possible to build a segment tree for minimum on a segment. After that we only need to find no more than 31 minimums on the segment (each time we find one we change it to $\infty$) and, final...
[ "bitmasks", "brute force", "data structures", "divide and conquer", "greedy", "implementation", "two pointers" ]
2,500
#include <bits/stdc++.h> #define F first #define S second #define all(a) a.begin(), a.end() using namespace std; using ll = long long; template<class T> bool ckmin(T &a, T b) { return a > b ? a = b, true : false; } template<class T> bool ckmax(T &a, T b) { return a < b ? a = b, true : false; } void solve() { ...
1667
A
Make it Increasing
You are given an array $a$ consisting of $n$ positive integers, and an array $b$, with length $n$. Initially $b_i=0$ for each $1 \leq i \leq n$. In one move you can choose an integer $i$ ($1 \leq i \leq n$), and add $a_i$ to $b_i$ or subtract $a_i$ from $b_i$. What is the minimum number of moves needed to make $b$ inc...
If the final array, is $b_1$, $b_2$ ... $b_n$, than the solution is surely unoptimal if there is an $2 \le i \le n$, when $b_i>0$, and $b_i-a_i>b_{i-1}$, or $b_1>0$. Because there was one unnecessary move on $b_i$ or on $b_1$. Similarly it is unoptimal, if $b_i<0$ and $b_i+a_i<b_{i+1}$ or $b_n<0$. We can see, that ther...
[ "brute force", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; long long n, a[5005], ans=1e18; int main() { cin >> n; for (int i=1; i<=n; i++) { cin >> a[i]; } for (int pos=1; pos<=n; pos++) { long long prev=0, sum=0; for (int i=pos-1; i>=1; i--) { prev+=a[i]-prev%a[i]; ...
1667
B
Optimal Partition
You are given an array $a$ consisting of $n$ integers. You should divide $a$ into continuous non-empty subarrays (there are $2^{n-1}$ ways to do that). Let $s=a_l+a_{l+1}+\ldots+a_r$. The value of a subarray $a_l, a_{l+1}, \ldots, a_r$ is: - $(r-l+1)$ if $s>0$, - $0$ if $s=0$, - $-(r-l+1)$ if $s<0$. What is the maxi...
Let $dp_i$ be the answer for the first $i$ elements, and $v_{(i, j)}$ the value of the subarray $[i, j]$. With prefix sums it is easy to calculate $v_{(i, j)}$ quickly. With this we can get a $n^2$ solution: $dp_i=max(dp_j+v_{(j+1, i)})$ for $j<i$. Lets call a segment winning, drawing, or losing, if the value of it is ...
[ "data structures", "dp" ]
2,100
#include <bits/stdc++.h> using namespace std; const int max_n=500005, inf=10000000; int t, n, a[max_n], dp[max_n], ord[max_n], fen[max_n]; long long pref[max_n]; // Fenwick tree with prefix maximum int lsb(int a) { return (a & -a); } void add(int pos, int val) { while (pos<=n) { fen[pos]=max(fen[pos]...
1667
C
Half Queen Cover
You are given a board with $n$ rows and $n$ columns, numbered from $1$ to $n$. The intersection of the $a$-th row and $b$-th column is denoted by $(a, b)$. A half-queen attacks cells in the same row, same column, and on one diagonal. More formally, a half-queen on $(a, b)$ attacks the cell $(c, d)$ if $a=c$ or $b=d$ o...
Let's assume that there is a solution for $k$ half-queens. There are at least $n-k$ rows, and columns, which contains no half-queen. If the uncovered rows are $r_1, r_2, ... r_a$, and the columns are $c_1, c_2, ... c_b$, (in increasing order), each diagonal (when the difference is a constant) contains at most one of th...
[ "constructive algorithms", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; cout << n/3+(n+2)/3 << "\n"; if (n==1) { cout << 1 << " " << 1 << "\n"; return 0; } while (n%3!=2) { cout << n << " " << n << "\n"; n--; } int a=(n+1)/3; for (int i=1; i...
1667
D
Edge Elimination
You are given a tree (connected, undirected, acyclic graph) with $n$ vertices. Two edges are adjacent if they share exactly one endpoint. In one move you can remove an arbitrary edge, if that edge is adjacent to an even number of remaining edges. Remove all of the edges, or determine that it is impossible. If there ar...
When an edge is removed, the two neighbouring vertex have the same parity of edges. We say that an edge is odd, if the parity is odd, and the edge is even otherwise. One can see, that a vertex with even degree will have the same amount of odd and even edges. For a vertex with odd degree, there will be one more odd edge...
[ "constructive algorithms", "dfs and similar", "dp", "trees" ]
2,900
#include <bits/stdc++.h> using namespace std; const int c=200005; int t, n, up[c]; bool parity[c], vis[c], no_sol; vector<int> edges[c]; void dfs(int a) { vis[a]=true; int cnt[2]={0, 0}; for (auto x:edges[a]) { if (!vis[x]) { up[x]=a; dfs(x); cnt[parity[x]]++; ...
1667
E
Centroid Probabilities
Consider every tree (connected undirected acyclic graph) with $n$ vertices (\textbf{$n$ is odd}, vertices numbered from $1$ to $n$), and for each $2 \le i \le n$ the $i$-th vertex is adjacent to exactly one vertex with a smaller index. For each $i$ ($1 \le i \le n$) calculate the number of trees for which the $i$-th v...
Let $S=\frac{n+1}{2}$, $binom_{i, j}=\frac{i!}{j! \cdot (i-j)!}$, $dp_i$ the result of some precalculation (see below) and $ans_i$ the final answer for the $i$-th vertex. Root the tree in vertex $1$. It is easy to see that in the possible trees the parent of vertex $2 \le i \le n$ is smaller than $i$. The cetroid will ...
[ "combinatorics", "dp", "fft", "math" ]
3,000
#include <bits/stdc++.h> using namespace std; // ntt - this code is not mine const int _ = 1 << 20 , mod = 998244353 , G = 3; int upd(int x) { return x + (x >> 31 & mod); } int add(int x , int y) { return upd(x + y - mod); } int sub (int x , int y){ return upd(x - y); } int mul (int a, int b) { ...
1667
F
Yin Yang
You are given a rectangular grid with $n$ rows and $m$ columns. $n$ and $m$ are divisible by $4$. Some of the cells are already colored black or white. It is guaranteed that no two colored cells share a corner or an edge. Color the remaining cells in a way that both the black and the white cells becomes orthogonally c...
Border: cells in the first or last row or first or last column. One can see that on the border both the black and the white part is connected. So there is no solution if there is a BWBW subsequence on the border. Otherwise there is a solution. Solve an easier task first. Assume that there is no colored cell on the bord...
[ "implementation" ]
3,500
#include <bits/stdc++.h> using namespace std; const int c=505; int t, n, m, fix[c][c], ans[c][c], rotcnt, change, old_cl, new_cl; int fix2[c][c], ans2[c][c]; void color_boundary() { for (int cnt=1; cnt<=2; cnt++) { for (int j=2; j<=m; j++) { if (!ans[1][j]) ans[1][j]=ans[1][j-1]; i...
1668
A
Direction Change
You are given a grid with $n$ rows and $m$ columns. Rows and columns are numbered from $1$ to $n$, and from $1$ to $m$. The intersection of the $a$-th row and $b$-th column is denoted by $(a, b)$. Initially, you are standing in the top left corner $(1, 1)$. Your goal is to reach the bottom right corner $(n, m)$. You ...
The moves are symmetrical, so we can assume that $n \ge m$. There is no solution if $m=1$ and $n \ge 3$, because one can only move up and down, but two consecutive down moves is required to reach $(n, 1)$. Otherwise, there is a solution. One should move downwards at least $n-1$ times, and it is forbidden to do that twi...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int t, n, m; int main() { ios_base::sync_with_stdio(false); cin >> t; while (t--) { cin >> n >> m; if (n<m) { swap(n, m); } if (m==1 && n>=3) { cout << -1 << "\n"; } else { cout << 2*n...
1668
B
Social Distance
$m$ chairs are arranged in a circle sequentially. The chairs are numbered from $0$ to $m-1$. $n$ people want to sit in these chairs. The $i$-th of them wants at least $a[i]$ empty chairs both on his right and left side. More formally, if the $i$-th person sits in the $j$-th chair, then no one else should sit in the fo...
If there is no one between the $i$-th and $j$-th person then $max(a_i, a_j)$ free chairs should be between them. So we should find a permutation $p$ of the array $a$, when $max(p_1, p_2)+max(p_2, p_3) ... +max(p_{n-1}, p_n)+max(p_n, p_1)$ is minimal. We can assume that the array is non-decreasing ($a_i \leq a_{i+1}$). ...
[ "greedy", "math", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); int t; cin >> t; while (t--) { long long n, m; cin >> n >> m; long long sum=0, min_val=1e9, max_val=0; for (int i=1; i<=n; i++) { long long x; cin >> x...
1669
A
Division?
Codeforces separates its users into $4$ divisions by their rating: - For Division 1: $1900 \leq \mathrm{rating}$ - For Division 2: $1600 \leq \mathrm{rating} \leq 1899$ - For Division 3: $1400 \leq \mathrm{rating} \leq 1599$ - For Division 4: $\mathrm{rating} \leq 1399$ Given a $\mathrm{rating}$, print in which divis...
For this problem you just need to implement what it asks you. To be able to implement it you need to know about the "if" statement.
[ "implementation" ]
800
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--) { int x; cin >> x; if(x < 1400) cout << "Division 4\n"; else if(x < 1600) cout << "Division 3\n"; else if(x < 1900) cout << "Division 2\n"; else cout << "Division 1\n"; } }
1669
B
Triple
Given an array $a$ of $n$ elements, print any value that appears at least three times or print -1 if there is no such value.
Approach 1: Sort the array using an efficient sorting algorithm. For every element check if the next two in the array are equal to it. If you find such an element output it. Time complexity is $\mathcal{O}(n \log n)$. Approach 2: Notice that elements have an upper bound of $n$, you can use an auxiliary array to store t...
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<int> cnt(n + 1, 0); int ans = -1; for(int i = 0; i < n; i++) { int x; cin >> x; if(++cnt[x] >= 3) { ans = x; } } cout << ans << endl; } }
1669
C
Odd/Even Increments
Given an array $a=[a_1,a_2,\dots,a_n]$ of $n$ positive integers, you can do operations of two types on it: - Add $1$ to \textbf{every} element with an \textbf{odd} index. In other words change the array as follows: $a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \dots$. - Add $1$ to \textbf{every} element with an \textb...
Note is that after doing two operations of the same type, they are "cancelled out" in terms of parity, since we would change the parity of all elements once, then change it back again. So, we know that we will do each operation exactly $0$ or $1$ time. It is possible to check all possible cases just by simulating, or w...
[ "greedy", "implementation", "math" ]
800
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a(n); int even1 = 0, even2 = 0, odd1 = 0, odd2 = 0; for(int i = 0; i < n; ++i) { cin >> a[i]; if(i % 2 == 0) { if(a[i] ...
1669
D
Colorful Stamp
A row of $n$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $\textcolor{blue}{B}\textcolor{red}{R}$ and as $\textcolor{red}{R}\textcolor{blue}{B}$. During use,...
First note that parts of the picture separated by $\texttt{W}$ are independent. That is, any stamps used on one part doesn't have any impact on the other, since a character $\texttt{W}$ means no stamp has been placed on that cell. So let's split the string by $\texttt{W}$s (for example, with split() method in Python), ...
[ "implementation" ]
1,100
for i in range(int(input())): n = int(input()) l = input().split('W') bad = False for s in l: b1 = 'R' in s b2 = 'B' in s if (b1 ^ b2): bad = True print("NO" if bad else "YES")
1669
E
2-Letter Strings
Given $n$ strings, each of length $2$, consisting of lowercase Latin alphabet letters \textbf{from 'a' to 'k}', output the number of pairs of indices $(i, j)$ such that $i < j$ and the $i$-th string and the $j$-th string differ in exactly one position. In other words, count the number of pairs $(i, j)$ ($i < j$) such ...
One solution is to go through all given strings, generate all strings that differ in exactly one position, and count the number of times these strings occur in the array. A possible way to count them is by using either the map/dictionary data structure or even simpler - a frequency array. Depending on the implementatio...
[ "data structures", "math", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<vector<int>> cnt(12, vector<int>(12, 0)); long long ans = 0; for(int i = 0;i < n; ++i) { string s; cin >> s; for(int j = 0;j < 2; ++...
1669
F
Eating Candies
There are $n$ candies put from left to right on a table. The candies are numbered from left to right. The $i$-th candy has weight $w_i$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he c...
We can solve the problem with a two pointers technique. Let $i$ be the left pointer, initially at $1$, and $j$ be the right pointer, initially at $n$. Let's store Alice and Bob's current totals as $a$ and $b$. Let's iterate $i$ from the left to the right. For each $i$, we should do the following. Increase $a$ by $a_i$ ...
[ "binary search", "data structures", "greedy", "two pointers" ]
1,100
t = int(input()) for test in range(t): n = int(input()) a = list(map(int, input().split())) l = 0 r = n - 1 suml = a[0] sumr = a[n-1] ans = 0 while l < r: if suml == sumr: ans = max(ans, l + 1 + n - r) if suml <= sumr: l+=1 suml+=a[l] ...
1669
G
Fall Down
There is a grid with $n$ rows and $m$ columns, and three types of cells: - An empty cell, denoted with '.'. - A stone, denoted with '*'. - An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. ...
Note that the columns don't affect each other, so we can solve for each column by itself. For each column, go from the bottom to the top, and keep track of the row of the last obstacle seen; call it $\mathrm{last}$. Note that initially, $\mathrm{last}=n+1$, since we treat the floor as the $n+1$th row of obstacles. When...
[ "dfs and similar", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n, m; cin >> n >> m; char g[n + 7][m + 7]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> g[i][j]; } } for (int j = 0; j < m; j++) { int last = n - 1; for (int i =...
1669
H
Maximal AND
Let $\mathsf{AND}$ denote the bitwise AND operation, and $\mathsf{OR}$ denote the bitwise OR operation. You are given an array $a$ of length $n$ and a non-negative integer $k$. You can perform \textbf{at most} $k$ operations on the array of the following type: - Select an index $i$ ($1 \leq i \leq n$) and replace $a_...
The optimal strategy is to greedily take the highest bit we have enough operations to set in every array element. To do this, we maintain a count for each bit with the number of elements that have it set already. The cost to set the $i$-th bit will be $n-\mathrm{count}_i$. We go from the highest bit to the lowest: If w...
[ "bitmasks", "greedy", "math" ]
1,300
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--) { int n, k; cin >> n >> k; vector<int> cnt(31, 0), a(n); for(int i = 0;i < n; ++i) { cin >> a[i]; for(int j = 30; j >= 0; --j) { if(a[i] & (1 << j)) ++cnt[j]; ...
1670
A
Prof. Slim
{One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were \sout{happy} sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder on...
We can notice that to make the array sorted we must move all the negative signs to the beginning of the array. So let's say the number of negative elements is $k$. Then we must check that the first $k$ elements are non-increasing and the remaining elements are non-decreasing. Complexity is $O(n)$.
[ "greedy", "implementation", "sortings" ]
800
import java.io.*; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tc = sc.nextInt(); for (int test = 1; test <= tc; test++) { ...
1670
B
Dorms War
Hosssam decided to sneak into Hemose's room while he is sleeping and change his laptop's password. He already knows the password, which is a string $s$ of length $n$. He also knows that there are $k$ special letters of the alphabet: $c_1,c_2,\ldots, c_k$. Hosssam made a program that can do the following. - The progra...
Let's consider the non-special characters as '0' and special characters as '1' since they are indistinguishable. So now the problem is that we have a binary string, where each '1' character removes the character before it each time the program is run. The trivial case is when there is only one '1' character, the answer...
[ "brute force", "implementation", "strings" ]
1,100
import java.io.*; import java.util.StringTokenizer; public class B{ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tests = sc.nextInt(); for (int test = 0; test < tests; test++) ...
1670
C
Where is the Pizza?
While searching for the pizza, baby Hosssam came across two permutations $a$ and $b$ of length $n$. Recall that a permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the arr...
Let's first solve the version where the array $d$ is filled with $0$'s (in other words there is no constrain on the permutation $c$ that needs to be formed). Let's say we have the permutation $[1,2,3,4]$ as $a$ and the permutation $[3,1,2,4]$ as $b$. Suppose that we have chosen the first element of the array $c$ to be ...
[ "data structures", "dfs and similar", "dsu", "graphs", "implementation", "math" ]
1,400
import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; public class C{ static int mod = (int) 1e9 + 7; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tests = s...
1670
D
Very Suspicious
Sehr Sus is an infinite hexagonal grid as pictured below, controlled by MennaFadali, ZerooCool and Hosssam. They love equilateral triangles and want to create $n$ equilateral triangles on the grid by adding some straight lines. The triangles must all be empty from the inside (in other words, no straight line or hexago...
We can notice that there are $3$ different slopes in which we can draw a line, and we can also notice that drawing the lines exactly on the edges of the hexagons will result in the creation of $2$ equilateral triangles at each intersection of $2$ lines, so we can say that: Number of equilateral triangles = 2 *( number ...
[ "binary search", "brute force", "geometry", "greedy", "implementation", "math" ]
1,700
import java.util.*; import java.io.*; public class D{ public static void main(String[] args) throws Exception { int t=sc.nextInt(); while(t-->0) { pw.println(sol(sc.nextInt())); } pw.close(); } public static int sol(int n) { int low=0; int high=(int)1e9; int mid=(low+high)/2; while(low<=high) ...
1670
E
Hemose on the Tree
After the last regional contest, Hemose and his teammates finally qualified to the ICPC World Finals, so for this great achievement and his love of trees, he gave you this problem as the name of his team "Hemose 3al shagra" (Hemose on the tree). You are given a tree of $n$ vertices where $n$ is a power of $2$. You hav...
Let's look at the minimum maximum value that we can get if we have an array of numbers from $[1,2^{(p+1)}-1]$ and we are trying to get any prefix xor, the answer will be $2^p$ because you can stop at the first integer that will have the bit $p$ so the answer will be $\geq 2^p$. We can apply the same concept here, for a...
[ "bitmasks", "constructive algorithms", "dfs and similar", "trees" ]
2,200
import java.util.*; import java.io.*; public class E{ static ArrayList<int[]>[] adj; static int[] nodeval, edgeval; static int count, N; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); ...
1670
F
Jee, You See?
{During their training for the ICPC competitions, team "Jee You See" stumbled upon a very basic counting problem. After many "Wrong answer" verdicts, they finally decided to give up and \sout{destroy} turn-off the PC. Now they want your help in up-solving the problem.} You are given 4 integers $n$, $l$, $r$, and $z$. ...
Let's put aside the XOR constraint and only focus on the sum constraint. let $G(X)$ be the number of ways to construct $n$ integers such that their sum is at most $X$. We will construct each bit of the $n$ integers at the same time, we want to guarantee that the contribution of the sum of the bits generated at each pos...
[ "bitmasks", "combinatorics", "dp" ]
2,400
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class F { static final int mod = (int) 1e9 + 7; static int n; static long l, r, z; static long[][] memo; static long[][] memo2; public static long nCr(int n, int r) { if (r == 0) return 1;...
1671
A
String Building
You are given a string $s$. You have to determine whether it is possible to build the string $s$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order. For example: - aaaabbb can be built as aa $+$ aa $+$ bbb; - bbaaaaabbb can ...
Every character in strings aa, aaa, bb and bbb has at least one character adjacent to it that is the same. So, if there is an isolated character in our string (a character that has no neighbors equal to it), we cannot build it. It's easy to see that in the other case, we can build the string: we can split it into block...
[ "implementation" ]
800
t = int(input()) for i in range(t): s = input() ans = True n = len(s) for j in range(n): if (j == 0 or s[j] != s[j - 1]) and (j == n - 1 or s[j] != s[j + 1]): ans = False print('YES' if ans else 'NO')
1671
B
Consecutive Points Segment
You are given $n$ points with integer coordinates on a coordinate axis $OX$. The coordinate of the $i$-th point is $x_i$. All points' coordinates are distinct and given in strictly increasing order. For each point $i$, you can do the following operation \textbf{no more than once}: take this point and move it by $1$ to...
We can see that the answer is YES if and only if there are no more than two gaps of length $1$ between the given points. If there is no gap, the answer is obviously YES. If there is only one gap of length $1$, we can just move the left (or the right) part of the set to this gap. When there are two gaps, we can move the...
[ "brute force", "math", "sortings" ]
1,000
for i in range(int(input())): n = int(input()) x = list(map(int, input().split())) print('YES' if x[-1] - x[0] - n + 1 <= 2 else 'NO')
1671
C
Dolce Vita
Turbulent times are coming, so you decided to buy sugar in advance. There are $n$ shops around that sell sugar: the $i$-th shop sells one pack of sugar for $a_i$ coins, but only \textbf{one pack to one customer} each day. So in order to buy several packs, you need to visit several shops. Another problem is that prices...
Firstly, note that if we want to buy as many packs as possible, then it's optimal to buy the cheapest packs. In other words, if we sort all packs, we'll always buy a prefix of array $a$. Next, note that each day we buy some number of packs $i \in [1, n]$, so, instead of iterating through the days, we can iterate throug...
[ "binary search", "brute force", "greedy", "math" ]
1,200
fun main() { repeat(readLine()!!.toInt()) { val (n, x) = readLine()!!.split(' ').map { it.toInt() } val a = readLine()!!.split(' ').map { it.toInt() }.sorted() var sum = a.sumOf { it.toLong() } var prevDay = -1L var ans = 0L for (i in n - 1 downTo 0) { va...
1671
D
Insert a Progression
You are given a sequence of $n$ integers $a_1, a_2, \dots, a_n$. You are also given $x$ integers $1, 2, \dots, x$. You are asked to insert each of the extra integers into the sequence $a$. Each integer can be inserted at the beginning of the sequence, at the end of the sequence, or between any elements of the sequence...
Observe the cost of inserting a single element. Notice that inserting any value between the minimum of the sequence and the maximum of the sequence is free. Why is this true? The argument is similar to the algorithm of finding some $x$ such that $f(x) = 0$ for a continous function $f$ if you know some $x_1$ such that $...
[ "brute force", "constructive algorithms", "greedy" ]
1,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int t; scanf("%d", &t); forn(_, t){ int n, x; scanf("%d%d", &n, &x); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); long long ans = 1e18; long ...
1671
E
Preorder
You are given a rooted tree of $2^n - 1$ vertices. Every vertex of this tree has either $0$ children, or $2$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect...
In terms of preorder strings, the operation "swap two children of some vertex" means "swap two substrings of equal length in some specific location". This operation can be inverted by applying it an additional time, so for every positive integer $k$, all of the strings of length $2^k-1$ are split into equivalence class...
[ "combinatorics", "divide and conquer", "dp", "dsu", "hashing", "sortings", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; mt19937 rnd(42); const int MOD = 998244353; const int K = 3; int add(int x, int y, int mod = MOD) { x += y; while(x >= mod) x -= mod; while(x < 0) x += mod; return x; } int sub(int x, int y, int mod = MOD) { return add(x, -y, mod); } int mul...
1671
F
Permutation Counting
Calculate the number of permutations $p$ of size $n$ with exactly $k$ inversions (pairs of indices $(i, j)$ such that $i < j$ and $p_i > p_j$) and exactly $x$ indices $i$ such that $p_i > p_{i+1}$. Yep, that's the whole problem. Good luck!
A lot of solutions which were written during the contest use Berlekamp-Messey or some other algorithms related to analyzing linear recurrences, but the model solution is based on other principles. First of all, if the number of inversions is at most $11$, it means that most elements of the permutation will stay at thei...
[ "brute force", "combinatorics", "dp", "fft", "math" ]
2,700
#include <bits/stdc++.h> using namespace std; const int K = 13; const int MOD = 998244353; int n, k, x; int cnt[K][K][K]; int dp[K][2 * K][K][K]; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int sub(int x, int y) { return add(x, -y); } in...
1672
A
Log Chopping
There are $n$ logs, the $i$-th log has a length of $a_i$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game. errorgorn and maomao90 will take turns chopping the logs with \textbf{errorgorn chopping first}. On his turn, the player will pick a log and chop it into $2$ pieces. ...
No matter what move each player does, the result of the game will always be the same. Count the number of moves. Let us consider the ending state of the game. It turns out that at the ending state, we will only have logs of $1$ meter. Otherwise, players can make a move. Now, at the ending state of the game, we will hav...
[ "games", "implementation", "math" ]
800
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define int long long #define ll long lo...
1672
B
I love AAAB
Let's call a string \textbf{good} if its length is at least $2$ and all of its characters are $A$ except for the last character which is $B$. The good strings are $AB,AAB,AAAB,\ldots$. Note that $B$ is \textbf{not} a good string. You are given an initially empty string $s_1$. You can perform the following operation a...
Pretend that we can only insert $\texttt{AB}$. What if we replaced $\texttt{A}$ and $\texttt{B}$ with $\texttt{(}$ and $\texttt{)}$? Claim: The string is obtainable if it ends in $\texttt{B}$ and every prefix of the string has at least as many $\texttt{A}$ as $\texttt{B}$. An alternative way to think about the second c...
[ "constructive algorithms", "implementation" ]
800
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define int long long #define ll long lo...
1672
C
Unequal Array
You are given an array $a$ of length $n$. We define the \textbf{equality} of the array as the number of indices $1 \le i \le n - 1$ such that $a_i = a_{i + 1}$. We are allowed to do the following operation: - Select two integers $i$ and $x$ such that $1 \le i \le n - 1$ and $1 \le x \le 10^9$. Then, set $a_i$ and $a_{...
If the array is $a=[1,1,\ldots,1]$. We will need $0$ moves if $n \leq 2$ and will need $\max(n-3,1)$ moves. The only way to reduce the number of $i$ such that $a_i = a_{i+1}$ is when $a_i = a_{i+1}$ and $a_{i+2} = a_{i+3}$, and you apply the operation on $a_{i+1}$ and $a_{i+2}$. Suppose $l$ is the smallest index where ...
[ "constructive algorithms", "greedy", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; template <class T> inline bool mnto(T& a, T b) {return a > b ? a = b, 1 : 0;} template <class T> inline bool mxto(T& a, T b) {return a < b ? a = b, 1: 0;} #define REP(i, s, e) for (int i = s; i < e; i++) #define RREP(i, s, e) for (int i = s; i >= e; i--) typedef long long...
1672
D
Cyclic Rotation
There is an array $a$ of length $n$. You may perform the following operation any number of times: - Choose two indices $l$ and $r$ where $1 \le l < r \le n$ and $a_l = a_r$. Then, set $a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$. You are also given another array $b$ of length $n$ which is a permutation of $...
The operation of cyclic shift is equivalent to deleting $a_i$ and duplicating $a_j$ where $a_i = a_j$. Reverse the process. We will solve the problem by reversing the steps and transform array $b$ to array $a$. We can do the following operation on $b$: pick index $i<j$ such that $b_j=b_{j+1}$ and remove $b_{j+1}$ and i...
[ "constructive algorithms", "greedy", "implementation", "two pointers" ]
1,700
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define int long long #define ll long lo...
1672
E
notepad.exe
\textbf{This is an interactive problem.} There are $n$ words in a text editor. The $i$-th word has length $l_i$ ($1 \leq l_i \leq 2000$). The array $l$ is hidden and only known by the grader. The text editor displays words in lines, splitting each two words in a line with at least one space. Note that a line does not...
Find the sum of lengths of words. Given a height, how many "good" widths are there. The first idea that we have is that we want to be able to find the minimum possible width of the text editor for a specific height. We can do this in $n\log (n \cdot 2000)$ queries using binary search for each height. This is clearly no...
[ "binary search", "constructive algorithms", "greedy", "interactive" ]
2,200
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define int long long #define ll long lo...
1672
F2
Checker for Array Shuffling
oolimry has an array $a$ of length $n$ which he really likes. Today, you have changed his array to $b$, a permutation of $a$, to make him sad. Because oolimry is only a duck, he can only perform the following operation to restore his array: - Choose two integers $i,j$ such that $1 \leq i,j \leq n$. - Swap $b_i$ and $...
The number of occurances of the most frequent element is important. Let $X$ be the number of occurances of the most common element. The maximal sadness is $N-X$. For every minimal sequence of swaps, we have duality of maximal number of cycles when considering the graph with edges $a_i \to b_i$. Let $N$ be the length of...
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,800
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define int long long #define ll long lo...
1672
G
Cross Xor
There is a grid with $r$ rows and $c$ columns, where the square on the $i$-th row and $j$-th column has an integer $a_{i, j}$ written on it. Initially, all elements are set to $0$. We are allowed to do the following operation: - Choose indices $1 \le i \le r$ and $1 \le j \le c$, then replace all values on the same ro...
We need to consider $4$ cases based on the parity of $r$ and $c$. Let $R_i$ and $C_j$ denote $\bigotimes\limits_{j=1}^c a_{i,j}$ and $\bigotimes\limits_{i=1}^r a_{i,j}$ respectively, or the xor-sum of the $i$-th row and the xor-sum of the $j$-th column respectively. For some cases, $R$ and $C$ will be constant sequence...
[ "constructive algorithms", "graphs", "math", "matrices" ]
3,200
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define int long long #define ll long lo...
1672
H
Zigu Zagu
You have a binary string $a$ of length $n$ consisting only of digits $0$ and $1$. You are given $q$ queries. In the $i$-th query, you are given two indices $l$ and $r$ such that $1 \le l \le r \le n$. Let $s=a[l,r]$. You are allowed to do the following operation on $s$: - Choose two indices $x$ and $y$ such that $1 ...
We will always remove a maximal segment, or in other words we will select $l$ and $r$ such that $A_{l-1} = A_l$ and $A_r = A_{r+1}$. Try to find an invariant. We can first split string $A$ into the minimum number of sections of $\texttt{010101}\ldots$ and $\texttt{101010}\ldots$. Let the number of sections be $K$. Sinc...
[ "constructive algorithms", "data structures", "greedy" ]
2,700
#include <bits/stdc++.h> using namespace std; int n,q; string s; int l[200005]; int r[200005]; int psum[200005]; int balance[200005]; signed main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin.exceptions(ios::badbit | ios::failbit); cin>>n>>q; cin>>s; s=s[0]+s+s[n-1]; for (int x=1;x<=n;x++){ ...
1672
I
PermutationForces
You have a permutation $p$ of integers from $1$ to $n$. You have a strength of $s$ and will perform the following operation some times: - Choose an index $i$ such that $1 \leq i \leq |p|$ and $|i-p_i| \leq s$. - For all $j$ such that $1 \leq j \leq |p|$ and $p_i<p_j$, update $p_j$ to $p_j-1$. - Delete the $i$-th elem...
When removing an element, consider how the costs of other elements change? When removing an element, consider the elements whose cost increase. What are their properties? Is there a greedy algorithm? Yes there is. How to make it run fast? Use monotonicity to reduce one dimension Let us rephrase the problem. Let $x$ and...
[ "data structures", "greedy" ]
3,000
// Super Idol的笑容 // 都没你的甜 // 八月正午的阳光 // 都没你耀眼 // 热爱105°C的你 // 滴滴清纯的蒸馏水 #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/rope> using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx; #define ii pair<int,int> #define fi firs...
1673
A
Subtle Substring Subtraction
Alice and Bob are playing a game with strings. There will be $t$ rounds in the game. In each round, there will be a string $s$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. \textbf{Alice is allowed to remove any substring of even length (possibly empty) and Bob i...
Greedy The answer depends on whether the length of $s$ is even or odd and on the first and last characters of $s$ if the length is odd. The problem can be solved greedily. Let $n$ be the length of the given string. If the $n$ is even, it is always optimal for Alice to remove the whole string. If the $n$ is odd, it is a...
[ "games", "greedy", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while(tc--) { string s; cin >> s; int n=s.length(),alice=0; for(int i=0;i<n;i++) alice += s[i]-'a'+1; if(n%2==0) cout << "Alice " << alice << '\n'; else ...
1673
B
A Perfectly Balanced String?
Let's call a string $s$ perfectly balanced if for all possible triplets $(t,u,v)$ such that $t$ is a non-empty substring of $s$ and $u$ and $v$ are characters present in $s$, the difference between the frequencies of $u$ and $v$ in $t$ is not more than $1$. For example, the strings "aba" and "abc" are perfectly balanc...
The string is perfectly balanced if it is periodic and the repeating pattern contains all distinct alphabets. Let the number of distinct characters in $s$ be $k$ and length of $s$ be $n$. Then, $s$ will be perfectly balanced if and only if $s_{i}, s_{i+1}, \ldots, s_{i+k-1}$ are all pairwise distinct for every $i$ in t...
[ "brute force", "greedy", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while(tc--) { string s; cin >> s; int n = s.length(); set<char> c; bool ok = true; int k; for(k=0;k<n;k++) { if(c.find(s[k])==c.end()) ...
1673
C
Palindrome Basis
You are given a positive integer $n$. Let's call some positive integer $a$ without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express $n$ as a sum of positive palindromic integers. Two ways are considered different if the frequency of a...
The number of palindromes less than $4\cdot 10^4$ is relatively small. The rest of the problem is quite similar to the classical partitions problem. First, we need to observe that the number of palindromes less than $4\cdot 10^4$ is relatively very small. The number of $5$-digit palindromes are $300$ (enumerate all $3$...
[ "brute force", "dp", "math", "number theory" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 40004, M = 502; const long long MOD = 1000000007; long long dp[N][M]; int reverse(int n) { int r=0; while(n>0) { r=r*10+n%10; n/=10; } return r; } bool palindrome(int n) { return (reverse(n)==n); } int main() { ...
1673
D
Lost Arithmetic Progression
Long ago, you thought of two finite arithmetic progressions $A$ and $B$. Then you found out another sequence $C$ containing all elements common to both $A$ and $B$. It is not hard to see that $C$ is also a finite arithmetic progression. After many years, you forgot what $A$ was but remember $B$ and $C$. You are, for so...
First check if all elements of $C$ are present in $B$ or not. If not, the answer is $0$. Then check if the answer is infinite or not. It depends on only the first and last elements of $B$ and $C$. If $p$ is the common difference of $A$ then $lcm(p,q)=r$. $p$ must necessarily be a factor of $r$ and $\mathcal{O}(\sqrt n)...
[ "combinatorics", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; const long long MOD = 1000000007; long long gcd(long long a,long long b) { if(b==0) return a; else return gcd(b,a%b); } long long lcm(long long a,long long b) { long long g = gcd(a,b); return (a*b)/g; } int main() { int tc; cin >>...
1673
E
Power or XOR?
The symbol $\wedge$ is quite ambiguous, especially when used without context. Sometimes it is used to denote a power ($a\wedge b = a^b$) and sometimes it is used to denote the XOR operation ($a\wedge b=a\oplus b$). You have an ambiguous expression $E=A_1\wedge A_2\wedge A_3\wedge\ldots\wedge A_n$. You can replace each...
All numbers in $A$ are powers of $2$ and the modulo is also a power of $2$ and $B_i\geq 1$. Fix all operators in a particular subsegment as $\texttt{Power}$ and fix the operators around the segment as $\texttt{XOR}$. Find the contribution of this segment independent of other segments. Maximum possible length for such a...
[ "bitmasks", "combinatorics", "math", "number theory" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 1048576; long long b[N]; char ans[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,k; cin >> n >> k; for(int i=0;i<n;i++) { cin >> b[i]; } for(int i=0;i<1048576;i++) ans[i]='0'; for(i...
1673
F
Anti-Theft Road Planning
This is an interactive problem. A city has $n^2$ buildings divided into a grid of $n$ rows and $n$ columns. You need to build a road of some length $D(A,B)$ of your choice between each pair of adjacent by side buildings $A$ and $B$. Due to budget limitations and legal restrictions, the length of each road must be a po...
The main goal is to assign numbers $A_{i,j}$ from $0$ to $1023$ to all buildings such that all buildings get distinct numbers and assign the road lengths between buildings $B_{x_1,y_1}$ and $B_{x_2,y_2}$ as $A_{x_1,y_1}\oplus A_{x_2,y_2}$. Among all such assignments, try to find the one which has the least sum of road ...
[ "bitmasks", "constructive algorithms", "divide and conquer", "greedy", "interactive", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 32; int maxpower2(int n) { int p=1; while(n%2==0) { p*=2; n/=2; } return p; } int main() { int n,k; cin >> n >> k; int h[N][N-1]; for(int i=0;i<N;i++) { for(int j=1;j<=N-1;j++) { ...
1674
A
Number Transformation
You are given two integers $x$ and $y$. You want to choose two \textbf{strictly positive} (greater than zero) integers $a$ and $b$, and then apply the following operation to $x$ \textbf{exactly} $a$ times: replace $x$ with $b \cdot x$. You want to find two positive integers $a$ and $b$ such that $x$ becomes equal to $...
The process in the statement can be rephrased as "multiply $x$ by $b^a$". $x \cdot b^a$ will be divisible by $x$, so if $y$ is not divisible by $x$, there is no answer. Otherwise, $a = 1$ and $b = \frac{y}{x}$ can be used.
[ "constructive algorithms", "math" ]
800
t = int(input()) for i in range(t): x, y = map(int, input().split()) if y % x != 0: print(0, 0) else: print(1, y // x)
1674
B
Dictionary
The Berland language consists of words having \textbf{exactly two letters}. Moreover, \textbf{the first letter of a word is different from the second letter}. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland langua...
There are many different ways to solve this problem: generate all Berland words with two for-loops and store them in an array, then for each test case, go through the array of words to find the exact word you need; generate all Berland words with two for-loops and store them in a dictionary-like data structure (map in ...
[ "combinatorics", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { string w = "aa"; map<string, int> idx; int i = 1; for(w[0] = 'a'; w[0] <= 'z'; w[0]++) for(w[1] = 'a'; w[1] <= 'z'; w[1]++) if(w[0] != w[1]) idx[w] = i++; int t; cin >> t; for(int i = 0; i < t...
1674
C
Infinite Replacement
You are given a string $s$, consisting only of Latin letters 'a', and a string $t$, consisting of lowercase Latin letters. In one move, you can replace any letter 'a' in the string $s$ with a string $t$. Note that after the replacement string $s$ might contain letters other than 'a'. You can perform an arbitrary numb...
Let's consider some cases. If there are letters 'a' in string $t$, then the moves can be performed endlessly. If $t$ itself is equal to "a", then the string won't change, so the answer is $1$. Otherwise, the length of $t$ is least $2$, so string $s$ will be increasing in length after each move, and the answer is -1. If...
[ "combinatorics", "implementation", "strings" ]
1,000
for _ in range(int(input())): s = input() t = input() if t == "a": print(1) elif t.count('a') != 0: print(-1) else: print(2**len(s))
1674
D
A-B-C Sort
You are given three arrays $a$, $b$ and $c$. Initially, array $a$ consists of $n$ elements, arrays $b$ and $c$ are empty. You are performing the following algorithm that consists of two steps: - Step $1$: while $a$ is not empty, you take the last element from $a$ and move it in the middle of array $b$. If $b$ current...
Let's look at elements $a_n$ and $a_{n - 1}$. After the first step, they will always move to positions $b_1$ and $b_n$ (it's up to you to choose: $a_n \to b_1$ and $a_{n-1} \to b_n$ or vice versa) because all remaining $a_i$ for $i < n - 1$ will be placed between $a_n$ and $a_{n-1}$. After the second step, elements $b_...
[ "constructive algorithms", "implementation", "sortings" ]
1,200
fun main() { repeat(readLine()!!.toInt()) { val n = readLine()!!.toInt() val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray() for (i in (n % 2) until n step 2) { if (a[i] > a[i + 1]) a[i] = a[i + 1].also { a[i + 1] = a[i] } } var sorted ...
1674
E
Breaking the Wall
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall. The wall consists of $n$ sections, aligned in a row. The $i$-th section initi...
Let's analyze three cases based on the distance between two sections we are going to break: break two neighboring sections ($i$ and $i+1$); break two sections with another section between them ($i$ and $i+2$); break two sections with more than one section between them. Why exactly these cases? Because the damage from t...
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
2,000
#include <iostream> #include <sstream> #include <cstdio> #include <vector> #include <cmath> #include <queue> #include <string> #include <cstring> #include <cassert> #include <iomanip> #include <algorithm> #include <set> #include <map> #include <ctime> #include <cmath> #define forn(i, n) for(int i=0;i<n;++i) #define fo...
1674
F
Desktop Rearrangement
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $n \times m$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon). The desktop is called \textbf{good} if all its icons are occupying some prefix of full columns and, possibl...
I've seen a lot of data structures solutions for this problem, but author's solution doesn't use them and works in $O(nm + q)$. Firstly, let's change our matrix to a string $s$, because it will be easier to work with a string than with a matrix. The order of characters will be from top to bottom, from left to right (i....
[ "data structures", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; static char buf[1010]; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m, q; scanf("%d %d %d", &n, &m, &q); vector<string> tmp(n); string s; int sum = 0; for (int i = 0; i...
1674
G
Remove Directed Edges
You are given a directed acyclic graph, consisting of $n$ vertices and $m$ edges. The vertices are numbered from $1$ to $n$. There are no multiple edges and self-loops. Let $\mathit{in}_v$ be the number of incoming edges (indegree) and $\mathit{out}_v$ be the number of outgoing edges (outdegree) of vertex $v$. You ar...
Let's solve the problem in reverse. Imagine we have already removed some edges, so that the conditions hold. When is some set of vertices considered cute? Since the graph is acyclic, we can topologically sort the vertices in the set. The vertices are reachable from each other, so there exists a path from the $i$-th ver...
[ "dfs and similar", "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 INF = 1e9; vector<int> in, out; vector<vector<int>> g; vector<int> dp; int calc(int v){ if (dp[v] != -1) return dp[v]; if (in[v] >= 2 && out[v] >= 2){ dp[v] = 1; for (int u : g[v...
1675
A
Food for Animals
In the pet store on sale there are: - $a$ packs of dog food; - $b$ packs of cat food; - $c$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $x$ dogs and $y$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cat...
Obviously, the best way to buy food for every pet is to buy maximum possible food for dogs and cats, then $max(0, x - a)$ dogs and $max(0, y - b)$ cats will not get food. We will buy universal food for these dogs and cats. Then the answer is YES, if $max(0, x - a) + max(0, y - b) \le c$, and NO else.
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int a, b, c, x, y; cin >> a >> b >> c >> x >> y; int ax = min(a, x); int by = min(b, y); a -= ax; x -= ax; ...
1675
B
Make It Increasing
Given $n$ integers $a_1, a_2, \dots, a_n$. You can perform the following operation on them: - select any element $a_i$ ($1 \le i \le n$) and divide it by $2$ (round down). In other words, you can replace any selected element $a_i$ with the value $\left \lfloor \frac{a_i}{2}\right\rfloor$ (where $\left \lfloor x \right...
We will process the elements of the sequence starting from the end of the sequence. Each element $a_i$ ($1 \le i \le n - 1$) will be divided by $2$ until it is less than $a_{i+1}$. If at some point it turns out that $a_{i + 1} = 0$, it is impossible to obtain the desired sequence.
[ "greedy", "implementation" ]
900
#include<bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int>a(n); for(auto &i : a) cin >> i; int ans = 0; for(int i = n - 2; i >= 0; i--){ while(a[i] >= a[i + 1] && a[i] > 0){ a[i] /= 2; ans++; } if(a[i] == a[i+1]){ ...
1675
C
Detective Task
Polycarp bought a new expensive painting and decided to show it to his $n$ friends. He hung it in his room. $n$ of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on. It is kno...
First, let's note that we will have a transition from $1$ to $0$ only once, otherwise it turns out that first the picture disappeared, then it appeared and disappeared back, but we can consider that a friend in the middle, who answered $1$ lied to us, but this is not true, because even before him the picture disappeare...
[ "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { string s; cin >> s; int n = s.length(); vector<bool> a(n + 1); a[0] = true; forn(i, n) a[i + 1] = a[i] ...
1675
D
Vertical Paths
You are given a rooted tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. Any vertex can be the root of a tree. A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. The tree is specified by an array of parents $p$ contain...
Let's find a set of leaves of a given tree. From each leaf we will climb up the tree until we meet a vertex already visited. Having met such a vertex, start a new path from the next leaf. The sequence of vertices in the found paths must be deduced in reverse order, because the paths must go from bottom to top. It also ...
[ "graphs", "implementation", "trees" ]
1,300
#include<bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int>b(n + 1); vector<bool>leaf(n + 1, true); for(int i = 1; i <= n; i++) { cin >> b[i]; leaf[b[i]] = false; } if(n == 1){ cout << "1\n1\n1\n\n"; return; } vector<int>...
1675
E
Replace With the Previous, Minimize
You are given a string $s$ of lowercase Latin letters. The following operation can be used: - select one character (from 'a' to 'z') that occurs at least once in the string. And replace all such characters in the string with the previous one in alphabetical order on the loop. For example, replace all 'c' with 'b' or ...
Greedy idea. To minimize the string, we will go from left to right and maintain a variable $mx$ = maximal character, from which we will reduce everything to 'a'. Initially it is 'a' and we spend $0$ of operations on it. Then, at the next symbol, we can either reduce it to 'a' in no more than $k$ operations, or reduce t...
[ "dsu", "greedy", "strings" ]
1,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back template <class T> bool ckmax(T &a, T b) {return a<b ? a=b, true : false;} void solve() { int n,k; cin >> n >> k; string s; ...
1675
F
Vlad and Unfinished Business
Vlad and Nastya live in a city consisting of $n$ houses and $n-1$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree. Vlad lives in a house with index $x$, and Nastya lives in a house with index $y$. Vlad decided to visit Nastya. However, he remembered that he h...
To begin with, we will hang the tree by the vertex $x$. In fact, we want to go from the root to the top of $y$, going off this path to do things and coming back. At one vertex of the path, it is advantageous to get off it in all the necessary directions and follow it further. So we will go $1$ once for each edge leadin...
[ "dfs and similar", "dp", "greedy", "trees" ]
1,800
#include <bits/stdc++.h> using namespace std; //#define int long long #define ll long long //#define double long double #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() const int MOD = 1e9 + 7; const int maxN = 5e3 + 1; const int INF = 2e9; const int MB = 20; vector<vector<int>> g; vector<bool...
1675
G
Sorting Pancakes
Nastya baked $m$ pancakes and spread them on $n$ dishes. The dishes are in a row and numbered from left to right. She put $a_i$ pancakes on the dish with the index $i$. Seeing the dishes, Vlad decided to bring order to the stacks and move some pancakes. In one move, he can shift one pancake from any dish to the closes...
For convenience, we will calculate the prefix sums on the array $a$, we will also enter the array $b$ containing the indexes of all pancakes and calculate the prefix sums on it. Let's use dynamic programming. Let's define $dp[i][last][sum]$ as the required number of operations to correctly lay out the $i$-th prefix, wi...
[ "dp" ]
2,300
#include <bits/stdc++.h> //#define int long long #define mp make_pair #define x first #define y second #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(143); const ll inf = 1e9 + 7; const ll M = 998'244'353...
1676
A
Lucky?
A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.
We need to check if the sum of the first three digits is equal to the sum of the last three digits. This is doable by scanning the input as a string, then comparing the sum of the first three characters with the sum of the last three characters using the if statement and the addition operation.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { string s; cin >> s; if(s[0]+s[1]+s[2] == s[3]+s[4]+s[5]) { cout << "YES" << endl; } else { cout << "NO" << endl; } } int main() { int t = 1; cin >> t; while (t--) { solve(); } }
1676
B
Equal Candies
There are $n$ boxes with different quantities of candies in each of them. The $i$-th box has $a_i$ candies inside. You also have $n$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none)...
Because we can only eat candies from boxes. The only way to make all boxes have the same quantity of candies in them would be to make all candies contain a number of candies equal to the minimum quantity of candies a box initially has. So, we should find this minimum number, let's denote it as $m$, and then for each bo...
[ "greedy", "math", "sortings" ]
800
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a(n); int mn = INT_MAX, ans = 0; for(int i = 0; i < n; ++i) { cin >> a[i]; mn = min(mn, a[i]); } for(int i = 0; i < n; ++...
1676
C
Most Similar Words
You are given $n$ words of \textbf{equal} length $m$, consisting of lowercase Latin alphabet letters. The $i$-th word is denoted $s_i$. In one move you can choose \textbf{any position in any single word} and change the letter at that position to the previous or next letter in alphabetical order. For example: - you ca...
Firstly, given any pair of strings of length $m$, we should be able to tell the difference between them. It's enough to find the sum of absolute differences between each character from the same position. Now, we should go through all possible pairs and pick the minimum value over all of them using the function we use t...
[ "brute force", "greedy", "implementation", "math", "strings" ]
800
#include "bits/stdc++.h" using namespace std; int cost(string& a, string& b) { int val = 0; for(int i = 0; i < a.size(); ++i) { val += abs(a[i] - b[i]); } return val; } int main() { int t; cin >> t; while(t--) { int n, m; cin >> n >> m; vector<string> s(n); for(...
1676
D
X-Sum
Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $a$ with $n$ rows and $m$ columns with each cell having a \textbf{non-negative} integer written on it. Timur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is \textbf...
The solution is to check the sum over all diagonals for each cell. For a cell ($i,j$) we can iterate over all elements in all its diagonals. This will be in total $O(max(n, m))$ elements. The complexity will be $O(n \cdot m \cdot max(n, m))$. $O(n \cdot m)$ solutions involving precomputation are also possible but aren'...
[ "brute force", "greedy", "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve() { int n, m; cin >> n >> m; int a[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cin >> a[i][j]; } } int mx = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { int now = 0; int ci = i, cj = j; while(c...
1676
E
Eating Queries
Timur has $n$ candies. The $i$-th candy has a quantity of sugar equal to $a_i$. So, by eating the $i$-th candy, Timur consumes a quantity of sugar equal to $a_i$. Timur will ask you $q$ queries regarding his candies. For the $j$-th query you have to answer what is the \textbf{minimum} number of candies he needs to eat...
Let's solve the problem with just one query. Greedily, we should pick the candies with the most sugar first, since there is no benefit to picking a candy with less sugar. So the solution is as follows: sort the candies in descending order, and then find the prefix whose sum is $\geq x$. This is $\mathcal{O}(n)$ per que...
[ "binary search", "greedy", "sortings" ]
1,100
#include "bits/stdc++.h" using namespace std; int main() { int t; cin >> t; while(t--) { int n, q; cin >> n >> q; vector<long long> a(n), p(n); for(int i = 0; i < n; ++i) { cin >> a[i]; } sort(a.rbegin(), a.rend()); for(int i = 0; i < n; ++i) { ...
1676
F
Longest Strike
Given an array $a$ of length $n$ and an integer $k$, you are tasked to find any two numbers $l$ and $r$ ($l \leq r$) such that: - For each $x$ $(l \leq x \leq r)$, $x$ appears in $a$ at least $k$ times (i.e. $k$ or more array elements are equal to $x$). - The value $r-l$ is maximized. If no numbers satisfy the condit...
Let's call a value good if it appears at least $k$ times. For example, if $a=[1,1,2,2,3,4,4,4,5,5,6,6]$ and $k=2$, then good values are $[1,2,4,5,6]$. So we need to find the longest subarray of this array in which all values are consecutive. For example, the subarray $[4,5,6]$ is the answer, because all values are good...
[ "data structures", "greedy", "implementation", "sortings", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n, k; cin >> n >> k; int a[n]; map<int, int> mp; for(int i = 0; i < n; i++) { cin >> a[i]; mp[a[i]]++; } vector<int> c; for(auto x : mp) { if(x.second >= k) { c.push_back(x.first); } } if(c.size() == 0) { cout << -1 << endl; ...
1676
G
White-Black Balanced Subtrees
You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root is vertex $1$. There is also a string $s$ denoting the color of each vertex: if $s_i = B$, then vertex $i$ is black, and if $s_i = W$, then vertex $i$ is white. A subtree of the tree is called balanced if the number of white vert...
Let's run a dynamic programming from the leaves to the root. For each vertex store the values of the number of balanced subtrees, as well as the number of white and black vertices in it. Then from a vertex we can count the total number of white vertices in its subtree as well as the black vertices in its subtree, and u...
[ "dfs and similar", "dp", "graphs", "trees" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; vector<int> child[n + 7]; for (int i = 2; i <= n; i++) { int x; cin >> x; child[x].push_back(i); } string s; cin >> s; int res = 0; function<int(int)> dp = [&] (int x) { ...
1676
H1
Maximum Crossings (Easy Version)
The only difference between the two versions is that in this version $n \leq 1000$ and the sum of $n$ over all test cases does not exceed $1000$. A terminal is a row of $n$ equal segments numbered $1$ to $n$ in order. There are two terminals, one above the other. You are given an array $a$ of length $n$. For all $i =...
Let's look at two wires from $i \to a_i$ and $j \to a_j$. If $a_i < a_j$, there can never be any intersection. If $a_i > a_j$, there has to be an intersection. If $a_i = a_j$, it is possible that there is an intersection or not, depending on how we arrange the wires on the bottom terminal. Since we want to maximize the...
[ "brute force" ]
1,400
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } int res = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[i] >= a[j]) {res++;} } } cout <...
1676
H2
Maximum Crossings (Hard Version)
The only difference between the two versions is that in this version $n \leq 2 \cdot 10^5$ and the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. A terminal is a row of $n$ equal segments numbered $1$ to $n$ in order. There are two terminals, one above the other. You are given an array $a$ of length $...
Read the solution of the easy version. We want to count the number of pairs $(i,j)$ such that $i<j$ and $a_i \geq a_j$. This is a standard problem, and we can do this we can use a segment tree or BIT, for example. Insert the $a_j$ from $j=1$ to $n$, and then for each $a_j$ count the number of $a_i \leq a_j$ using a BIT...
[ "data structures", "divide and conquer", "sortings" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; long long merge(int a[], int temp[], int left, int mid, int right) { int i, j, k; long long count = 0; i = left; j = mid; k = left; while ((i <= mid - 1) && (j <= right)) { if (a[i] <= a[j]){ ...
1677
A
Tokitsukaze and Strange Inequality
Tokitsukaze has a permutation $p$ of length $n$. Recall that a permutation $p$ of length $n$ is a sequence $p_1, p_2, \ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \leq p_i \leq n$). She wants to know how many different indices tuples $[a,b,c,d]$ ($1 \leq a < b < c < d \leq n$) in...
We can calculate the answer in two steps. The first step, for each $b$, let $f_b$ represents the number of $p_d$ where $p_b > p_d$ in the interval $[b+1,n]$. We can calculate $f$ in $\mathcal{O}(n^2)$. The second step, calculate the answer. First we enumerate $c$ from $1$ to $n$, and then enumerate $a$ from $1$ to $c-1...
[ "brute force", "data structures", "dp" ]
1,600
#include <bits/stdc++.h> using namespace std; /************* debug begin *************/ string to_string(string s){return '"'+s+'"';} string to_string(const char* s){return to_string((string)s);} string to_string(const bool& b){return(b?"true":"false");} template<class T>string to_string(T x){ostringstream sout;sout<<x...
1677
B
Tokitsukaze and Meeting
Tokitsukaze is arranging a meeting. There are $n$ rows and $m$ columns of seats in the meeting hall. There are exactly $n \cdot m$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $1$ to $n\cdot m$. The students will enter the meeting hall...
Obviously, we can calculate the answers of rows and columns separately. For the answers of columns, we can observe that since there are only $n \cdot m$ students in total, no students will leave, and every time a new student entering the meeting hall, all columns will move one step to the right circularly, so the answe...
[ "data structures", "implementation", "math" ]
1,700
#include<bits/stdc++.h> using namespace std; int rownum[1000100]; int col[1000100]; int n,m; void init(){ for(int i = 0;i <= max(n,m);i++) { rownum[i] = col[i] = 0; } } void solve(){ scanf("%d%d",&n,&m); init(); int las = -n*m; int colnum = 0; char tmp; for(int i = 0;i < n*m;i++) { scanf(" %c",&tmp); tmp ...
1677
C
Tokitsukaze and Two Colorful Tapes
Tokitsukaze has two colorful tapes. There are $n$ distinct colors, numbered $1$ through $n$, and each color appears exactly once on each of the two tapes. Denote the color of the $i$-th position of the first tape as $ca_i$, and the color of the $i$-th position of the second tape as $cb_i$. Now Tokitsukaze wants to sel...
First, find the cycle directly, take out all the cycles, and then fill each cycle in the order: maximum, minimum, maximum, minimum $\ldots$. Note that when you encounter an odd cycle, the last one should be empty and fill in the middle value. For example, in a ternary cycle, if the first and the second position are fil...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; int n,col[2][MAXN],col_to_pos_1[MAXN]; long long output; bool vis_0[MAXN]; int T,cnt; long long c; void dfs(int pos) { if(vis_0[pos])return; vis_0[pos]=true; ++cnt; dfs(col_to_pos_1[col[0][pos]]); } int main(int argc, char const *argv[]) { scan...
1677
D
Tokitsukaze and Permutations
Tokitsukaze has a permutation $p$. She performed the following operation to $p$ \textbf{exactly} $k$ times: in one operation, for each $i$ from $1$ to $n - 1$ in order, if $p_i$ > $p_{i+1}$, swap $p_i$, $p_{i+1}$. After exactly $k$ times of operations, Tokitsukaze got a new sequence $a$, obviously the sequence $a$ is a...
Consider finding out the relationship between sequence $v$ and permutation $p$. It can be observed that the permutation $p$ have bijective relationship with sequence $c$. That is to say, sequence $c$ will only correspond to one permutation $p$, as it can be proved: Let $S={1,2,\ldots,n}$, and find that the last number ...
[ "dp", "math" ]
2,500
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<queue> #include<map> #include<ctime> #include<cmath> #include<unordered_map> using namespace std; #define LL long long #define pp pair<int,pair<int,int>> #define mp make_pair #define fi first #define se second.first #define th second.s...