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
1801
G
A task for substrings
Philip is very fond of tasks on the lines. He had already solved all the problems known to him, but this was not enough for him. Therefore, Philip decided to come up with his own task.To do this, he took the string $t$ and a set of $n$ strings $s_1$, $s_2$, $s_3$, ..., $s_n$. Philip has $m$ queries, in the $i$th of the...
Let's use the Aho-Korasik structure to store strings from $S$. Let's build compressed suffix links on it. This way it is a little more optimal to find all the lines from $S$ ending in this position $t$. Denote by $pref[i]$ the number of substrings of $S$ in the prefix $t$ of length $i$. Denote by $suf[i]$ the number of...
[ "data structures", "string suffix structures", "strings" ]
3,400
#include <bits/stdc++.h> #define x first #define y second using namespace std; struct node { int nx[26]; int p; int pp; int len; int id; int cnt; bool term; node() : p(-1), pp(-1), len(0), id(-1), term(false), cnt(0) { for (int i = 0; i < 26; i++) { nx[i] = -1; } } }; vector<node> g; vector<string...
1802
A
Likes
Nikita recently held a very controversial round, after which his contribution changed very quickly. The announcement hung on the main page for $n$ seconds. In the $i$th second $|a_i|$th person either liked or removed the like (Nikita was lucky in this task and there are no dislikes). If $a_i > 0$, then the $a_i$th per...
Let's show a construction that maximizes the number of likes. We need to first leave all the likes that we can put, and only then delete them. To minimize the number of likes, we need to delete the like (if we can) immediately after we post it. The code below implements these constructs.
[ "greedy", "implementation" ]
800
#include "bits/stdc++.h" using namespace std; void solve() { int n; cin >> n; int likes = 0, dislikes = 0; for (int i = 0; i < n; i++) { int x; cin >> x; if (x > 0) likes++; else dislikes++; } for (int i = 1; i <= n; ++i) { if (i <= likes) cout << i << '...
1804
A
Lame King
You are given a checkerboard of size $201 \times 201$, i. e. it has $201$ rows and $201$ columns. The rows of this checkerboard are numbered from $-100$ to $100$ from bottom to top. The columns of this checkerboard are numbered from $-100$ to $100$ from left to right. The notation $(r, c)$ denotes the cell located in t...
Observation 1. Let $|a| = |b|$. The king can reach $(a, b)$ in $2 \cdot |a|$ moves by alternating moves along rows and moves along columns. Observation 2. Let $|a| \ne |b|$, in particular $a > b \geq 0$ (without loss of generality due to the board symmetry). The king can reach $(a, b)$ in $2a - 1$ moves. He moves towar...
[ "greedy", "math" ]
800
null
1804
B
Vaccination
Ethan runs a vaccination station to help people combat the seasonal flu. He analyses the historical data in order to develop an optimal strategy for vaccine usage. Consider there are $n$ patients coming to the station on a particular day. The $i$-th patient comes at the moment $t_i$. We know that each of these patient...
Observation 1. There exists an optimal answer where each pack of vaccine is used for a consecutive segment of patients. Indeed, if there are three patients $a < b < c$ such that $a$ and $c$ are vaccinated using the dose from one pack and $b$ is vaccinated using the dose from the other pack we can swap the packs used fo...
[ "greedy", "implementation" ]
1,000
null
1804
C
Pull Your Luck
While James is gone on business, Vesper takes her time and explores what the legendary Casino Royale has to offer to people who are fond of competitive programming. Her attention was grabbed by the very new "Pull Your Luck" roulette which functions in a pretty peculiar way. The roulette's wheel consists of $n$ sectors...
Assuming the constraint on the the sum of $n$ over all test cases we might want to simulate the process for each test case. However, we need an $O(n)$ (or other quasilinear complexity) solution. The key observation is that the sum of all integers from $1$ to $2n$ inclusive is divisible by $n$. Indeed, $\sum_{i = 1}^{2n...
[ "brute force", "greedy", "math", "number theory" ]
1,500
null
1804
D
Accommodation
Annie is an amateur photographer. She likes to take pictures of giant residential buildings at night. She just took a picture of a huge rectangular building that can be seen as a table of $n \times m$ windows. That means that the building has $n$ floors and each floor has exactly $m$ windows. Each window is either dark...
The number of one-bedroom and two-bedroom apartments is the same for each floor and each floor can have its own independent apartments layout. Thus, we can independently solve the problem for each floor and then just sum the results. Below is given the solution for one floor in $O(m)$ time. First, lets introduce some v...
[ "brute force", "dp", "greedy", "implementation" ]
2,000
null
1804
E
Routing
Ada operates a network that consists of $n$ servers and $m$ direct connections between them. Each direct connection between a pair of distinct servers allows bidirectional transmission of information between these two servers. Ada knows that these $m$ direct connections allow to directly or indirectly transmit informat...
A directed graph where each node has an out-degree equal to $1$ (exactly one arc starts at this node) is called functional. By setting auxiliary servers $a(v)$ for each server $v$ we define a functional graph. The following condition is necessary and sufficient. The answer exists if and only if there exists a functiona...
[ "bitmasks", "brute force", "dfs and similar", "dp", "graphs" ]
2,400
null
1804
F
Approximate Diameter
Jack has a graph of $n$ vertices and $m$ edges. All edges are bidirectional and of unit length. The graph is connected, i. e. there exists a path between any two of its vertices. There can be more than one edge connecting the same pair of vertices. The graph can contain self-loops, i. e. edges connecting a node to itse...
Let's recall some definitions to start with. $\rho_G(u, v)$ is the length of the shortest path between vertices $u$ and $v$ in graph $G$. Define as $c_G(u)$ the maximum distance from vertex $u$ to some other vertex of graph $G$. $c_G(u) = \max_{v \in V(G)} \rho(u, v)$. $d(G) = \max_{u, v \in V(G)} \rho(u, v) = \max_{u ...
[ "binary search", "divide and conquer", "graphs", "shortest paths" ]
2,700
null
1804
G
Flow Control
Raj has a single physical network line that connects his office to the Internet. This line bandwidth is $b$ bytes per millisecond. There are $n$ users who would like to use this network line to transmit some data. The $i$-th of them will use the line from millisecond $s_i$ to millisecond $f_i$ inclusive. His initial d...
The problem is inspired by AIMD algorithm for TCP flow and congestion control. The key solution idea comes from a real-world networking, every time the congestion happens the difference between the maximum active $t_i$ and the minimum active $t_i$ halves. Thus, if all users were to start and to stop at the same time th...
[ "data structures", "dsu", "implementation" ]
3,500
null
1804
H
Code Lock
Lara has a safe that is locked with a circle-shaped code lock that consists of a rotating arrow, a static circumference around the arrow, an input screen, and an input button. The circumference of the lock is split into $k$ equal sections numbered from $1$ to $k$ in clockwise order. Arrow always points to one of the s...
First, let's solve the task for the case of linear arrangement of letters instead of a circle. Then we will upgrade the solution. Let $c(x, y)$ be the number of positions $i$ of the password string $s$ such that $s_i = x$ and $s_{i + 1} = y$. In other words, $c(x, y)$ is the number of times Lara has to enter letter $y$...
[ "bitmasks", "dp" ]
3,300
null
1805
A
We Need the Zero
There is an array $a$ consisting of non-negative integers. You can choose an integer $x$ and denote $b_i=a_i \oplus x$ for all $1 \le i \le n$, where $\oplus$ denotes the bitwise XOR operation. Is it possible to choose such a number $x$ that the value of the expression $b_1 \oplus b_2 \oplus \ldots \oplus b_n$ equals $...
Note that $(a_1 \oplus x) \oplus (a_2 \oplus x) \oplus ...$ equals $a_1 \oplus a_2 \oplus \ldots \oplus a_n$ if $n$ is even, or $a_1 \oplus a_2 \oplus \ldots \oplus a_n \oplus x$ if $n$ is odd. Then, if the length of the array is odd, you must print $\oplus$ of the whole array. And if the length is even, we can't chang...
[ "bitmasks", "brute force" ]
800
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) xor = 0 for x in a: xor ^= x if xor == 0: print(0) else: if n % 2 == 1: print(xor) else: print(-1)
1805
B
The String Has a Target
You are given a string $s$. You can apply this operation to the string exactly once: choose index $i$ and move character $s_i$ to the beginning of the string (removing it at the old position). For example, if you apply the operation with index $i=4$ to the string "abaacd" with numbering from $1$, you get the string "aa...
At first, note that the operation should be applied only to the position of the minimal element of the string (since the 1st position in the final string should always contain the minimal letter). Next, let the positions of the minimum letter are $a_1, a_2, \ldots, a_k$. Then we must apply the operation to the last pos...
[ "greedy", "strings" ]
800
for _ in range(int(input())): n = int(input()) s = input() ind = s.rfind(min(s)) # Find the last ind such that s[ind] = min(s) print(s[ind] + s[:ind] + s[ind + 1:])
1805
C
Place for a Selfie
The universe is a coordinate plane. There are $n$ space highways, each of which is a straight line $y=kx$ passing through the origin $(0, 0)$. Also, there are $m$ asteroid belts on the plane, which we represent as open upwards parabolas, i. e. graphs of functions $y=ax^2+bx+c$, where $a > 0$. You want to photograph ea...
Let's find the answers for the parabolas one at a time. Suppose we are given a parabola $ax^2+bx+c$ and a line $kx$. Then their difference is the parabola $ax^2+(b-k)x+c$. In order for the line and the parabola not to intersect, the difference must never equal $0$, that is, the parabola $ax^2+(b-k)x+c$ must have no roo...
[ "binary search", "data structures", "geometry", "math" ]
1,400
#include <bits/stdc++.h> #define int long long using namespace std; void solve() { int n, m; cin >> n >> m; vector <int> lines(n); for (int i = 0; i < n; i++) { cin >> lines[i]; } sort(lines.begin(), lines.end()); for (int i = 0; i < m; i++) { int a, b, c; cin >> ...
1805
D
A Wide, Wide Graph
You are given a tree (a connected graph without cycles) with $n$ vertices. Consider a fixed integer $k$. Then, the graph $G_k$ is an undirected graph with $n$ vertices, where an edge between vertices $u$ and $v$ exists if and only if the distance between vertices $u$ and $v$ in the given tree is \textbf{at least} $k$....
Find the diameter (the longest path) in the original tree. Now if the number $k$ is greater than the length of the diameter, then there will be no edges in the graph. Otherwise, the ends of this diameter are connected to each other, and possibly to other vertices as well. Then we can pre-calculate the answer for each $...
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
1,800
#include <bits/stdc++.h> #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() using namespace std; const int N = 1e5 + 228; vector<int> G[N]; void dfs(int v, int par, int h, vector<int> &d) { d[v] = h; for (int i : G[v]) { if (i != par) { dfs(i, v, h + 1, d); }...
1805
E
There Should Be a Lot of Maximums
You are given a tree (a connected graph without cycles). Each vertex of the tree contains an integer. Let's define the $\mathrm{MAD}$ (maximum double) parameter of the tree as the maximum integer that occurs in the vertices of the tree \textbf{at least} $2$ times. If no number occurs in the tree more than once, then we...
First, find $MAD$ of the initial tree. If each number in the tree occurs no more than once, then for each query the answer is $0$. Then, if $MAD$ occurs at least $3$ times in the tree, then for each query the answer will be $MAD$, because by pigeonhole principle there will be at least $2$ $MAD$ in one of the two trees....
[ "brute force", "data structures", "dfs and similar", "dp", "trees", "two pointers" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 100; vector <pair <int, int>> g[N]; int val[N]; vector <int> ans; map <int, int> cnt1, cnt2; set <int> mad1, mad2; vector <int> path, path_ind; bool used[N]; bool dfs(int v, int tar) { used[v] = true; path.push_back(v); if (v == tar) {...
1805
F2
Survival of the Weakest (hard version)
\textbf{This is the hard version of the problem. It differs from the easy one only in constraints on $n$. You can make hacks only if you lock both versions.} Let $a_1, a_2, \ldots, a_n$ be an array of non-negative integers. Let $F(a_1, a_2, \ldots, a_n)$ be the sorted in the non-decreasing order array of $n - 1$ small...
Firstly, we will sort the array $a_1, a_2, \ldots, a_n$, and in the future we will always assume that all arrays in this problem are sorted. Let's solve the problem for $n \leq 200$. It may seem that with such constraints, the problem is solved quite trivially: we implement the function $F$ for $\mathcal{O}(n^2 \log n)...
[ "greedy", "math", "sortings", "two pointers" ]
3,100
#include <bits/stdc++.h> #define all(x) x.begin(), (x).end() using namespace std; const int M = 1000000007; long long ans = 0; int real_len = 0; long long binpow(long long a, int x) { long long ans0 = 1; while (x) { if (x % 2) { ans0 *= a; ans0 %= M; } a *= a;...
1806
A
Walking Master
YunQian is standing on an infinite plane with the Cartesian coordinate system on it. In one move, she can move to the diagonally adjacent point on the top right or the adjacent point on the left. That is, if she is standing on point $(x,y)$, she can either move to point $(x+1,y+1)$ or point $(x-1,y)$. YunQian initial...
Hint 1: The value of $b$ is always non-decreasing, and the value of $a-b$ is always non-increasing. It is possible to move from $(a,b)$ to $(c,d)$ if and only if $d\ge b$ and $a-b\ge c-d$, since the value of $b$ is always non-decreasing and the value of $a-b$ is always non-increasing. If it is possible, the answer is $...
[ "geometry", "greedy", "math" ]
800
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=500005; const int inf=0x3f3f3f3f; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int a,b,c,d; cin>>a>>b>>c>>d; if...
1806
B
Mex Master
You are given an array $a$ of length $n$. The score of $a$ is the MEX$^{\dagger}$ of $[a_1+a_2,a_2+a_3,\ldots,a_{n-1}+a_n]$. Find the minimum score of $a$ if you are allowed to rearrange elements of $a$ in any order. Note that you are \textbf{not required} to construct the array $a$ that achieves the minimum score. $^...
Hint 1: $ans\le 2$. First, let's determine if $ans$ can be $0$. That means we can't place two $0$s next to each other. This is achievable when the number of $0$s is not greater than $\lceil\frac{n}{2}\rceil$. Then determine if $ans$ can be $1$. That means we can't place $0$ and $1$ next to each other. Therefore, if the...
[ "constructive algorithms", "greedy" ]
900
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=200005; const int inf=0x3f3f3f3f; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int n; cin>>n; int sum0=0; boo...
1806
C
Sequence Master
For some positive integer $m$, YunQian considers an array $q$ of $2m$ (possibly negative) integers good, if and only if for every possible subsequence of $q$ that has length $m$, the product of the $m$ elements in the subsequence is equal to the sum of the $m$ elements that are \textbf{not} in the subsequence. Formally...
Hint 1: The number of good sequences is small. Hint 2: Consider two cases: all elements in $q$ are (not) equal. In case that all elements in $q$ are equal, we have $q_1^n=nq_1$. The integer solutions to this equation is $q_1=0$, $n=1$ or $(q_1,n)=(2,2)$. In the other case, we can see that the constraints are strong, so...
[ "brute force", "constructive algorithms", "math" ]
1,600
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=400005; const ll inf=0x3f3f3f3f3f3f3f3f; ll a[maxn]; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T; while(T--) { int n; cin>>n;...
1806
D
DSU Master
You are given an integer $n$ and an array $a$ of length $n-1$ whose elements are either $0$ or $1$. Let us define the value of a permutation$^\dagger$ $p$ of length $m-1$ ($m \leq n$) by the following process. Let $G$ be a graph of $m$ vertices labeled from $1$ to $m$ that does not contain any edges. For each $i$ fro...
We record an operation of adding edge as $(i,i+1,a_i)$. Hint 1: Only operation $(i,i+1,0)$ can contribute. Hint 2: Using dynamic programming, let $f_i$ denote the number of ways to let vertices $1\sim i$ form a tree with root $1$, considering only the first $i-1$ operations. We can observe: Only operation $(i,i+1,0)$ c...
[ "combinatorics", "dp", "dsu", "math" ]
2,500
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=500005; const int inf=0x3f3f3f3f; const int mod=998244353; int a[maxn]; int f[maxn]; signed main() { ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int T; cin>>T;...
1806
E
Tree Master
You are given a tree with $n$ weighted vertices labeled from $1$ to $n$ rooted at vertex $1$. The parent of vertex $i$ is $p_i$ and the weight of vertex $i$ is $a_i$. For convenience, define $p_1=0$. For two vertices $x$ and $y$ \textbf{of the same depth$^\dagger$}, define $f(x,y)$ as follows: - Initialize $\mathrm{a...
Hint 1: The time complexity of the solution is $O(n\sqrt{n})$. Hint 2: Brute force with something to store the answer. The solution turns out quite easy: just store the answer to each pair of $(x,y)$ when computing the answer by climbing up on the tree. If we see the time complexity of hash table as $O(1)$, then the ti...
[ "brute force", "data structures", "dfs and similar", "trees" ]
2,200
#include<bits/stdc++.h> #define ll long long #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=100005; const int sqrtn=325; const int B=320; const int inf=0x3f3f3f3f; int n,q; int a[maxn]; int h[maxn]; int fa[maxn]; int cnt[maxn]; int depth[maxn]; ll f[maxn][sqrtn]; ve...
1806
F2
GCD Master (hard version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $m$. You can make hacks only if both versions of the problem are solved.} You are given an array $a$ of length $n$ and two integers $m$ and $k$. Each element in $a$ satisfies $1\le a_i \le m$. In one ope...
Hint 1: There is a easy strategy for dealing with repeated elements. Suppose that all elements in $a$ are pairwise distinct in the following hints. Hint 2: We will always perform an operation on the minimum element. Hint 3: The best way is to choose $k+1$ elements, delete them, and add the gcd of them to the sequence. ...
[ "greedy", "math", "sortings" ]
2,900
#include<bits/stdc++.h> #define ll long long #define int128 __int128 #define fir first #define sec second #define pii pair<int,int> using namespace std; const int maxn=1000005; const ll inf=9e18; const int128 inf128=(int128)(inf)*(int128)(inf); ll a[maxn]; ll b[maxn]; ll g[maxn]; ll ra[maxn]; int128 suma[maxn]; int12...
1807
A
Plus or Minus
You are given three integers $a$, $b$, and $c$ such that \textbf{exactly one} of these two equations is true: - $a+b=c$ - $a-b=c$ Output + if the first equation is true, and - otherwise.
You need to implement what is given in the statement; for example, you can use an if-statement to output + if $a+b=c$, and - otherwise.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int a, b, c; cin >> a >> b >> c; if (a + b == c) {cout << "+\n";} else {cout << "-\n";} } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= t...
1807
B
Grab the Candies
Mihai and Bianca are playing with bags of candies. They have a row $a$ of $n$ bags of candies. The $i$-th bag has $a_i$ candies. The bags are given to the players in the order from the first bag to the $n$-th bag. If a bag has an even number of candies, Mihai grabs the bag. Otherwise, Bianca grabs the bag. Once a bag ...
Let $s_e$ be the total number of candies with all bags with an even number of candies, and $s_o$ - the total of all bags with an odd number of candies. If $s_e \leq s_o$, then the answer is NO, because at the end Mihai (who takes only even numbers of candies) will have less candies than Bianca. Otherwise if $s_e > s_o$...
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; int x, odd = 0, even = 0; for(int i = 0; i < n; i++) { cin >> x; if(x%2 == 0) { even+=x; } else { odd+=x; } } if(even > odd) { ...
1807
C
Find and Replace
You are given a string $s$ consisting of lowercase Latin characters. In an operation, you can take a character and replace \textbf{all} occurrences of this character with $0$ or replace \textbf{all} occurrences of this character with $1$. Is it possible to perform some number of moves so that the resulting string is a...
Let's solve a harder problem: given a string $s$ and a binary string $t$, can we make $s$ into $t$ using the find and replace operations? We can simply iterate through each character of $s$ and see the bit it has turned to in $t$ (that is, $s_i \to t_i$ for each $i$). Keep track of each change, and see if there is some...
[ "greedy", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s; cin >> s; int mp[26]; for (int i = 0; i < 26; i++) { mp[i] = -1; } for (int i = 0; i < n; i++) { int curr = (s[i] - 'a'); if (mp[curr] == -1) { mp[curr] = (i...
1807
D
Odd Queries
You have an array $a_1, a_2, \dots, a_n$. Answer $q$ queries of the following form: - If we change all elements in the range $a_l, a_{l+1}, \dots, a_r$ of the array to $k$, will the sum of the entire array be odd? Note that queries are \textbf{independent} and do not affect future queries.
Note that for each question, the resulting array is $[a_1, a_2, \dots, a_{l-1}, k, \dots, k, a_{r+1}, a_{r+2}, \dots, a_n].$ So, the sum of the elements of the new array after each question is $a_1 + \dots + a_{l-1} + (r-l+1) \cdot k + a_{r+1} + \dots + a_n.$ We can compute $a_1 + \dots + a_{l-1}$ and $a_{r+1} + \dots ...
[ "data structures", "implementation" ]
900
#include <iostream> using namespace std; long long n,a[200005],q,sum=0,pref[200005],t; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>t; while(t--) { sum = 0; cin >> n >> q; for(int i=1;i<=n;i++){ cin >> a[i]; sum+=a[i]; ...
1807
E
Interview
This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants. Before the last stage of the exam, the director conducted an interview. He gave Gon $n$ piles of stones, the $i$-th pile having $a_i$ stones. Each stone is identical and weighs $...
Consider this question: if we take some range $[a_l, \dots, a_r]$ of piles, how do we know if it contains the special pile? If it doesn't contain the special pile, then the total weight should be $a_l + a_{l+1} + \dots + a_r$ grams, since each stone weighs one gram. If it does contain the special pile, then the total w...
[ "binary search", "implementation", "interactive" ]
1,300
#include <bits/stdc++.h> using ll=long long; using ld=long double; int const INF=1000000005; ll const LINF=1000000000000000005; ll const mod=1000000007; ld const PI=3.14159265359; ll const MAX_N=3e5+5; ld const EPS=0.00000001; #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #define f first #define s second #de...
1807
F
Bouncy Ball
You are given a room that can be represented by a $n \times m$ grid. There is a ball at position $(i_1, j_1)$ (the intersection of row $i_1$ and column $j_1$), and it starts going diagonally in one of the four directions: - The ball is going down and right, denoted by $DR$; it means that after a step, the ball's locat...
We can see that there are at most $4\cdot n \cdot m$ states the ball can be in, because there are $n \cdot m$ cells and $4$ states of direction. We can simulate the bouncing process, keeping count of the bounces until we arrive at the finish cell when we can output the answer, or we arrive at a previously visited state...
[ "brute force", "dfs and similar", "implementation" ]
1,700
#include <bits/stdc++.h> using namespace std; void solve() { int n, m, x1, y1, x2, y2; string d_string; cin >> n >> m >> x1 >> y1 >> x2 >> y2; x1--;x2--;y1--;y2--; cin >> d_string; int d = (d_string[0] == 'U' ? 1+(d_string[1] == 'R' ? 2 : 0) : 0+(d_string[1] == 'R' ? 2 : 0)); bool vis[n][m...
1807
G1
Subsequence Addition (Easy Version)
The only difference between the two versions is that in this version, the constraints are lower. Initially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\dagger}$ of $a$ and add into $a$ an element equal to t...
Firstly, let's note that it doesn't matter in what order we add the elements to the array, since if we can add an element in any position, if it's possible to get the said elements of the array, then we can obtain them in any order. Now, let's note that it's always optimal to obtain the needed elements in sorted order ...
[ "brute force", "data structures", "dp", "greedy", "implementation", "sortings" ]
1,100
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() void solve() { int n; cin >> n...
1807
G2
Subsequence Addition (Hard Version)
The only difference between the two versions is that in this version, the constraints are higher. Initially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\dagger}$ of $a$ and add into $a$ an element equal to ...
Let's prove that for an array $a$ that was created by using a number of operations, with a sum of elements $s$ we can add into $a$ any number $x$ ($1 \leq x \leq s$). Suppose that it is true that in the array $a$ with some length $l$ we introduce a number $x$ ($1 \leq x \leq sum_a$). Then after introducing we can creat...
[ "bitmasks", "dp", "greedy", "implementation", "sortings" ]
1,100
#include "bits/stdc++.h" using namespace std; #define ll long long #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(),v.rend() #define pb push_back #define sz(a) (int)a.size() void solve() { int n; cin >> n...
1808
A
Lucky Numbers
Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively. Each starship has a number —some positive integer $x$. Let's define the luckiness of a number $x$ as the difference between the largest and smallest digits of that number. For e...
Let $r - l \geq 100$. Then it is easy to see that there exists a number $k$ such that $l \le k \le r$, and $k \equiv 90 \mod 100$. Then the number $k$ is the answer. If $r - l < 100$, you can find the answer by trying all the numbers. Despite the impressive constant, from the theoretical point of view we obtain a solut...
[ "brute force", "implementation" ]
900
null
1808
B
Playing in a Casino
Galaxy Luck, a well-known casino in the entire solar system, introduces a new card game. In this game, there is a deck that consists of $n$ cards. Each card has $m$ numbers written on it. Each of the $n$ players receives exactly one card from the deck. Then all players play with each other in pairs, and each pair of ...
You may notice that the problem can be solved independently for each column of the input matrix. The answer is then the sum $\sum\limits_{i = 1}^n \sum\limits_{j = i + 1}^n |a_i - a_j|$, where $a$ - array representing a column. Let's try to calculate this sum for each column. Let's sort all elements of the current colu...
[ "math", "sortings" ]
1,200
null
1808
C
Unlucky Numbers
{In this problem, unlike problem A, you need to look for \textbf{unluckiest number}, not the luckiest one.} \textbf{Note that the constraints of this problem differ from such in problem A.} Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets i...
Check all pairs ($l$, $r$) - the minimum and maximum digits of the number from the answer. Discard the common prefix of $l$ and $r$. Now we are left with some digits $a$ and $b$ as the leftmost digits of the number, with $a$ < $b$. If $b - a \geq 2$, then we can put $a + 1$ at the beginning of the number, and then put ...
[ "brute force", "dp", "greedy", "implementation" ]
1,900
null
1808
D
Petya, Petya, Petr, and Palindromes
Petya and his friend, the robot Petya++, have a common friend — the cyborg Petr#. Sometimes Petr# comes to the friends for a cup of tea and tells them interesting problems. Today, Petr# told them the following problem. A palindrome is a sequence that reads the same from left to right as from right to left. For exampl...
Let us see when $1$ is added to the palindrome. Let there be some string $s$ of odd length $k$, consider the index $i$ to the left of the central one. If this character and the corresponding one on the right side of the string are different, we can replace one of the characters with the other and get $+1$ to the answer...
[ "binary search", "brute force", "data structures", "two pointers" ]
2,100
null
1808
E1
Minibuses on Venus (easy version)
\textbf{This is the easy version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} Maxim is a minibus driver on Venus. To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting ...
First, let's rephrase the problem condition a bit. A ticket number is lucky if ($a_i$ - the digit that stands at position $i$ in the number) is satisfied: $a_i \equiv (a_1 + a_2 + \ldots + a_{i-1} + a_{i+1} + \ldots + a_{n-1} + a_n) \pmod{k}$ Let $S$ be the sum of all digits of the number. Then we can rewrite the surpr...
[ "combinatorics", "divide and conquer", "dp" ]
2,200
null
1808
E2
Minibuses on Venus (medium version)
\textbf{This is the medium version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} Maxim is a minibus driver on Venus. To ride on Maxim's minibus, you need a ticket. Each ticket has a number consistin...
First, read the editorial of problem E1. This section is a continuation and improvement of ideas from the previous section. Let us improve the solution for $O(nk^3)$. To do this, note that the transitions from $i$ to $i + 1$ can be given by a matrix $g$ of size $k \times k$. Then by multiplying $f[i]$ (i.e., multiplyin...
[ "combinatorics", "divide and conquer", "dp", "matrices" ]
2,500
null
1808
E3
Minibuses on Venus (hard version)
\textbf{This is the hard version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.} Maxim is a minibus driver on Venus. To ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting ...
First read the editorial for problems E1 and E2. This section is a continuation and improvement of ideas from previous sections. Let's calculate how many such digits $x$ can exist in total for a fixed $S$ modulo $k$ that: $2 \cdot x \equiv S \pmod{k}$ $k$ is odd. Then there can exist exactly one such digit $x$ from $0$...
[ "brute force", "combinatorics", "dp", "math" ]
2,800
null
1809
A
Garland
You have a garland consisting of $4$ colored light bulbs, the color of the $i$-th light bulb is $s_i$. Initially, all the light bulbs are turned off. Your task is to turn all the light bulbs on. You can perform the following operation any number of times: select a light bulb and switch its state (turn it on if it was ...
Note that there are only a few configuration classes: 1111, 1112, 1122, 1123 and 1234. Let's discuss each of them. If all $4$ bulbs are of the same color, then it is impossible to turn all the bulbs on, because after you switch one light bulb, it is impossible to turn the others on. If there is a color with $3$ bulbs, ...
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while (tc--) { string s; cin >> s; vector<int> cnt(10); for (auto c : s) ++cnt[c - '0']; int mx = *max_element(cnt.begin(), cnt.end()); if (mx == 4) cout << -1; el...
1809
B
Points on Plane
You are given a two-dimensional plane, and you need to place $n$ chips on it. You can place a chip only at a point with integer coordinates. The cost of placing a chip at the point $(x, y)$ is equal to $|x| + |y|$ (where $|a|$ is the absolute value of $a$). The cost of placing $n$ chips is equal to the \textbf{maximu...
Suppose, the answer is $k$. What's the maximum number of chips we can place? Firstly, the allowed points $(x, y)$ to place chips are such that $|x| + |y| \le k$. We can group them by $x$-coordinate: for $x = k$ there is only one $y = 0$, for $x = k - 1$ possible $y$ are $-1, 0, 1$; for $x = k - 2$ possible $y$ are in s...
[ "binary search", "greedy", "math" ]
1,000
import kotlin.math.sqrt fun main() { repeat(readln().toInt()) { val n = readln().toLong() var ans = sqrt(n.toDouble()).toLong() while (ans * ans > n) ans-- while (ans * ans < n) ans++ println(ans - 1) } }
1809
C
Sum on Subarrays
For an array $a = [a_1, a_2, \dots, a_n]$, let's denote its subarray $a[l, r]$ as the array $[a_l, a_{l+1}, \dots, a_r]$. For example, the array $a = [1, -3, 1]$ has $6$ non-empty subarrays: - $a[1,1] = [1]$; - $a[1,2] = [1,-3]$; - $a[1,3] = [1,-3,1]$; - $a[2,2] = [-3]$; - $a[2,3] = [-3,1]$; - $a[3,3] = [1]$. You ar...
There are many ways to solve this problem. I will describe the following recursive solution: if $k < n$, let's compose an array where every segment ending with the $k$-th element is positive, and every other segment is negative. This array can be $[-1, -1, -1, \dots, 200, -400, -1, -1, -1]$, where $200$ is the $k$-th e...
[ "constructive algorithms", "greedy", "math" ]
1,500
def solve(n, k): if n == 0: return [] if k < n: a = [-1 for i in range(n)] if k > 0: a[k - 1] = 200 a[k] = -400 else: a = solve(n - 1, k - n) a.append(1000) return a t = int(input()) for i in range(t): n, k = map(int, input().split()) ...
1809
D
Binary String Sorting
You are given a binary string $s$ consisting of only characters 0 and/or 1. You can perform several operations on this string (possibly zero). There are two types of operations: - choose two consecutive elements and swap them. In order to perform this operation, you pay $10^{12}$ coins; - choose any element from the ...
Note that the price of operations is much greater than the difference between them. Therefore, first of all, we have to minimize the number of operations, and then maximize the number of operations of the first type. Swapping two elements if at least one of them will be deleted later is not optimal. Therefore, first le...
[ "constructive algorithms", "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; const long long pw10 = 1e12; int main() { ios::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while (tc--) { string s; cin >> s; int n = s.size(); int cnt0 = 0, cnt1 = count(s.begin(), s.end(), '1'); long long ans = 1e18; if (n == ...
1809
E
Two Tanks
There are two water tanks, the first one fits $a$ liters of water, the second one fits $b$ liters of water. The first tank has $c$ ($0 \le c \le a$) liters of water initially, the second tank has $d$ ($0 \le d \le b$) liters of water initially. You want to perform $n$ operations on them. The $i$-th operation is specif...
Consider a naive solution. Iterate over all pairs $(c, d)$ and apply all operations. The complexity is $O(a \cdot b \cdot n)$. The constraints obviously imply that it's too much. What can we cut from it? Well, surely $O(n)$ will still remain there. Both of $a$ and $b$ also should. So we can probably only hope to turn t...
[ "binary search", "dp", "implementation", "math" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { int n, a, b; scanf("%d%d%d", &n, &a, &b); vector<int> v(n); forn(i, n) scanf("%d", &v[i]); vector<vector<int>> ans(a + 1, vector<int>(b + 1)); forn(cd, a + b + 1){ int l = max(0, cd - b), r = min(a,...
1809
F
Traveling in Berland
There are $n$ cities in Berland, arranged in a circle and numbered from $1$ to $n$ in clockwise order. You want to travel all over Berland, starting in some city, visiting all the other cities and returning to the starting city. Unfortunately, you can only drive along the Berland Ring Highway, which connects all $n$ c...
The problem has a rather obvious naive solution in $O(n)$ for each starting city, but it's too slow. So we have to speed up this solution somehow. Binary lifting is one of the options, but here we have a problem that it is difficult to connect two consecutive groups of steps, because after the first group there is a ce...
[ "binary search", "data structures", "graphs", "greedy", "implementation" ]
2,500
#include<bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) void solve(){ int n, k; scanf("%d%d", &n, &k); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); vector<int> b(n); forn(i, n) scanf("%d", &b[i]); vector<long long> pr(2 * n + 1); forn(i, 2 * n) pr[i + 1] = pr[i]...
1809
G
Prediction
Consider a tournament with $n$ participants. The rating of the $i$-th participant is $a_i$. The tournament will be organized as follows. First of all, organizers will assign each participant an index from $1$ to $n$. All indices will be unique. Let $p_i$ be the participant who gets the index $i$. Then, $n-1$ games wi...
We need some sort of better criterion other than "all matches can be predicted" first. Suppose the ratings of the participants are $r_1, r_2, \dots, r_n$ in the order of their indices. Then, if all games are predictable, the $i$-th game should be won by the participant with the rating equal to $\max \limits_{j=1}^{i+1}...
[ "combinatorics", "dp", "math" ]
2,800
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { return ((x + y) % MOD + MOD) % MOD; } int mul(int x, int y) { return x * 1ll * y % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y % 2 == 1) z = mul(z, x); x = mul(x...
1810
A
Beautiful Sequence
A sequence of $m$ integers $a_{1}, a_{2}, \ldots, a_{m}$ is good, if and only if there exists at least one $i$ ($1 \le i \le m$) such that $a_{i} = i$. For example, $[3,2,3]$ is a good sequence, since $a_{2} = 2$, $a_{3} = 3$, while $[3,1,1]$ is not a good sequence, since there is no $i$ such that $a_{i} = i$. A seque...
What is the necessary and sufficient condition? The necessary and sufficient condition for a beautiful sequence is that there exist one $i$, such that $a_{i} \le i$. Just check the sequence for the condition.
[ "brute force", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; int a[100005]; void solve() { int n; scanf("%d",&n); for(int i =1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= n;i++) { if(a[i] <= i) { puts("YES"); return; } } puts("NO"); } int main() { int t;scanf("...
1810
B
Candies
This problem is about candy. Initially, you only have $1$ candy, and you want to have exactly $n$ candies. You can use the two following spells in any order at most $40$ times in total. - Assume you have $x$ candies now. If you use the first spell, then $x$ candies become $2x-1$ candies. - Assume you have $x$ candies...
How the binary representation changes after an operation? First, we notice that after each operation, the number of candies is always a odd number. So even numbers can not be achieved. Then consider how the binary representation changes for a odd number $x$, after turn it into $2x+1$ or $2x-1$. For the $2x + 1$ operati...
[ "constructive algorithms", "math", "number theory" ]
800
#include<bits/stdc++.h> using namespace std; void solve() { int n;scanf("%d",&n); if(n % 2 == 0) { puts("-1");return; } vector<int> v; int f = 0; for(int i = 29;i >= 1;i--) { if((n >> i) & 1) { f = 1; v.push_back(2); } else if(f) { ...
1810
C
Make It Permutation
You have an integer array $a$ of length $n$. There are two kinds of operations you can make. - Remove an integer from $a$. This operation costs $c$. - Insert an arbitrary positive integer $x$ to any position of $a$ (to the front, to the back, or between any two consecutive elements). This operation costs $d$. You wan...
Try the enumerate the length $n$ of permutation. There're too many lengths to be checked. How to decrease the amount of $n$? Firstly, we need to remove numbers such that each number appears at most once, this part of cost is unavoidable. Then, let's sort the array $a_{1},a_{2} \dots a_{m}$ ($1\le a_{i} < a_{2} < \dots ...
[ "brute force", "greedy", "sortings" ]
1,300
#include<bits/stdc++.h> using namespace std; int p[100005]; typedef long long ll; void solve() { int n,a,b;scanf("%d%d%d",&n,&a,&b); set<int> st; ll sol = 0 , ans = 2e18; for(int i = 1;i <= n;i++) { int x;scanf("%d",&x); if(st.find(x) == st.end()) st.insert(x); else sol += a; ...
1810
D
Climbing the Tree
The snails are climbing a tree. The tree height is $h$ meters, and snails start at position $0$. Each snail has two attributes $a$ and $b$ ($a > b$). Starting from the $1$-st day, one snail climbs the tree like this: during the daylight hours of the day, he climbs up $a$ meters; during the night, the snail rests, and ...
The possible $L$ is always an interval. How to maintain it? The main idea is to that for each $a,b,n$, the possible $L$ is a interval $[l,r]$. We will show how to calculate that. In the first $n-1$ days, the snail will climb $(n-1)\cdot (a-b)$ meters. And in the daytime of the $n$-th day, the snail will climb $a$ meter...
[ "binary search", "math" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int q;scanf("%d",&q); ll L = 1 , R = 1e18; while(q--) { int op;scanf("%d",&op) ; if(op == 1) { int a,b,n;scanf("%d%d%d",&a,&b,&n); ll ql = 1LL*(n - 2)*(a - b) + a + 1, qr = 1LL*(n - 1)*(...
1810
E
Monsters
There is an undirected graph with $n$ vertices and $m$ edges. Initially, for each vertex $i$, there is a monster with danger $a_{i}$ on that vertex. For a monster with danger $a_{i}$, you can defeat it if and only if you have defeated at least $a_{i}$ other monsters before. Now you want to defeat all the monsters. Fir...
How to check whether it is possible to defeat all the monsters, starting from a fixed vertex $u$? Let $S(u)$ be the vertices set that can be reached, starting from vertex $u$. What's the relationship between $S(u)$ and $S(v)$, where $v\in S(u)$? For some vertex set $T$, let's define $E(T)$ as the ''neighbours'' of vert...
[ "brute force", "data structures", "dfs and similar", "dsu", "graphs", "greedy" ]
2,100
#include<bits/stdc++.h> using namespace std; int vis[200005]; int n , m; vector<int> E[200005]; int a[200005]; int T = 1; bool span(int u) { set<pair<int,int> > st; st.insert(pair<int,int>{a[u] , u}); int amt = 0 , df = 0; while(st.size()) { auto pa = (*st.begin()) ; vis[pa.second] = u; ...
1810
F
M-tree
A rooted tree is called good if every vertex of the tree either is a leaf (a vertex with no children) or has exactly $m$ children. For a good tree, each leaf $u$ has a positive integer $c_{u}$ written on it, and we define the value of the leaf as $c_{u} + \mathrm{dep}_{u}$, where $\mathrm{dep}_{u}$ represents the numb...
Can you solve a single query using binary search? How to check the answer? Try to find a closed formula for this problem. Let $num_{i}$ be the number of occurances of integer $i$ in the array $a$. To check whether the answer can be $\le x$ or not, we can do the following greedy: Starting with a single vertex written $x...
[ "data structures", "math", "sortings", "trees" ]
2,800
using namespace std; int n , m , q; const int N = 2e5 + 40; int num[N]; int a[N]; int cov[N*4 + 5] , mx[N*4 + 5] , mn[N*4 + 5]; void rec(int u) { mx[u] = max(mx[u<<1|1] , mx[u<<1]) ; mn[u] = min(mn[u<<1|1] , mn[u<<1]); } void pd(int u) { if(cov[u] != -1) { cov[u<<1] = mn[u<<1] = mx[u<<1] = cov[u]; ...
1810
G
The Maximum Prefix
You're going to generate an array $a$ with a length of at most $n$, where each $a_{i}$ equals either $1$ or $-1$. You generate this array in the following way. - First, you choose some integer $k$ ($1\le k \le n$), which decides the length of $a$. - Then, for each $i$ ($1\le i \le k$), you set $a_{i} = 1$ with probab...
How to calculate the maximal prefix sum? One possible way is let $f_{n+1} = 0$ and $f_{i}=max(f_{i+1},0)+a_{i}$. Consider this method to find maximal prefix sum: let $f_{n+1} = 0$ and $f_{i}=max(f_{i+1},0)+a_{i}$. We can discover that the only influence $[a_{i+1},a_{i+2} \dots a_{n}]$ has(to the whole array's maximal p...
[ "dp" ]
3,200
#include<bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int N = 5005; int p[N] , q[N]; int n; int f[N][N]; int h[N]; int fpow(int a,int b) { int ans = 1; while(b){ if(b & 1) ans = 1LL*ans*a%mod; a = 1LL*a*a%mod;b >>= 1; } return ans; } void solve() { scanf("%d",&n...
1810
H
Last Number
You are given a multiset $S$. Initially, $S = \{1,2,3, \ldots, n\}$. You will perform the following operation $n-1$ times. - Choose the largest number $S_{\text{max}}$ in $S$ and the smallest number $S_{\text{min}}$ in $S$. Remove the two numbers from $S$, and add $S_{\text{max}} - S_{\text{min}}$ into $S$. It's eas...
Actually I don't know how to hint. Try to find some rules related to $\frac{\sqrt{5}+1}{2}$, fibnacci or similar Assume that the moment before the $x$-th operation(but after $x-1$-th), the first time we have $S_{max} \le 2S_{min}$. Let's divide the operation into two part: before $x$ and equal or after $x$. Still, at t...
[ "combinatorics", "math" ]
2,900
#include<bits/stdc++.h> using namespace std; int l[500]; int fib[500]; int evenfib[500]; int getsum(int i,int n) ///1-index { if(n == 0) return 0; if(i <= 1) return fib[i]; if(n <= l[i - 2]) return getsum(i - 2, n); return fib[i - 2] + getsum(i - 1 , n - l[i - 2]); } int getsum2(int i,int n,int p) ///n...
1811
A
Insert Digit
You have a \textbf{positive} number of length $n$ and one additional digit. You can insert this digit anywhere in the number, including at the beginning or at the end. Your task is to make the result as large as possible. For example, you have the number $76543$, and the additional digit is $4$. Then the maximum num...
Note that numbers of the same length are compared lexicographically. That is, until some index the numbers will match, and then the digit in our number should be greater. Let's write out the numbers $s_1, s_2, \ldots s_i$ until $s_i \ge d$. As soon as this condition is false or the line ends, insert the digit $d$. We g...
[ "greedy", "math", "strings" ]
800
#include <iostream> using namespace std; void solve() { int n, d; cin >> n >> d; string s; cin >> s; for (int i = 0; i < n; ++i) { if (s[i] - '0' >= d) { cout << s[i]; } else { cout << d; for (int j = i; j < n; ++j) { cout << s[j]...
1811
B
Conveyor Belts
Conveyor matrix $m_n$ is matrix of size $n \times n$, where $n$ is an \textbf{even} number. The matrix consists of concentric ribbons moving clockwise. In other words, the conveyor matrix for $n = 2$ is simply a matrix $2 \times 2$, whose cells form a cycle of length $4$ clockwise. For any natural $k \ge 2$, the matri...
Note that the conveyor matrix $n \times n$ consists of $n$ cycles, through each of which we can move without wasting energy. Now you need to find the distance between the cycles where the start and end cells are located. In one step from any cycle, you can go either to the cycle that is closer to the edge of the matrix...
[ "implementation", "math" ]
1,000
def layer(n, x, y): return min([x, y, n + 1 - x, n + 1 - y]) def solve(): n, x1, y1, x2, y2 = map(int, input().split()) print(abs(layer(n, x1, y1) - layer(n, x2, y2))) t = int(input()) for _ in range(t): solve()
1811
C
Restore the Array
Kristina had an array $a$ of length $n$ consisting of non-negative integers. She built a new array $b$ of length $n-1$, such that $b_i = \max(a_i, a_{i+1})$ ($1 \le i \le n-1$). For example, suppose Kristina had an array $a$ = [$3, 0, 4, 0, 5$] of length $5$. Then she did the following: - Calculated $b_1 = \max(a_1,...
To solve the problem, you can build an array $a$ as follows $a_1 = b_1$ $a_i = \min(b_{i-1}, b_i)$ at $2 \le i \le n-1$ $a_n = b_{n-1}$ Let's show that from the constructed array $a$ we can get an array $B$ equal to the original array $b$: $B_1 = \max(a_1, a_2) = \max(b_1, \min(b_1, b_2))$ If $b_1 \gt b_2$, then $\max(...
[ "constructive algorithms", "greedy" ]
1,100
#include "bits/stdc++.h" using namespace std; void solve(){ int n; cin >> n; vector<int>b(n-1), a; for(int i = 0; i < n - 1; i++) cin >> b[i]; a.emplace_back(b[0]); for(int i = 0; i < n - 2; i++){ a.emplace_back(min(b[i], b[i + 1])); } a.emplace_back(b[n - 2]); for(auto &i :...
1811
D
Umka and a Long Flight
The girl Umka loves to travel and participate in math olympiads. One day she was flying by plane to the next olympiad and out of boredom explored a huge checkered sheet of paper. Denote the $n$-th Fibonacci number as $F_n = \begin{cases} 1, & n = 0; \\ 1, & n = 1; \\ F_{n-2} + F_{n-1}, & n \ge 2. \end{cases}$ A check...
$F_0^2 + F_1^2 +\ldots + F_n^2 = F_n\cdot F_{n+1}$, which can be proved by induction: $F_n\cdot F_{n+1} = F_n\cdot (F_{n-1}+F_n) = F_{n-1} \cdot F_n + F_n^2$. If the partition exists, it has the form $[F_0, F_1, \ldots, F_n]$, since the area of the rectangle with another partition will be greater than $F_n \cdot F_{n+1...
[ "constructive algorithms", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; const int MAXN = 50; int fib[MAXN]; void build() { fib[0] = fib[1] = 1; for (int i = 2; i < MAXN; ++i) fib[i] = fib[i - 2] + fib[i - 1]; } bool solve(int n, int x, int y) { if (n == 1) return true; if (fib[n - 1] <= y && y < fib[n]) return false; if (fib[n] <=...
1811
E
Living Sequence
In Japan, the number $4$ reads like death, so Bob decided to build a live sequence. Living sequence $a$ contains all natural numbers that do not contain the digit $4$. $a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, \ldots]$. For example, the number $1235$ is part of the sequence $a$, but the numbers $4321$, $44...
Note that any number in the sequence can be made up of $9$ possible digits (all digits except $4$). Then let's find the first digit of the answer, notice that it is just $x$ or $x+1$, where $x \cdot 9^{l-1} \le k$ (where $l$ - the length of the number we're looking for) and $x$ - the maximum. Note that $x$ simply corre...
[ "binary search", "dp", "math", "number theory" ]
1,500
#include <iostream> #include <cmath> #include <cctype> #include <vector> #include <algorithm> #include <set> #include <map> #include <deque> #include <stack> #include <unordered_set> #include <sstream> #include <cstring> #include <iomanip> #include <queue> #include <unordered_map> #include <random> #include <cfloat> #i...
1811
F
Is It Flower?
Vlad found a flowerbed with graphs in his yard and decided to take one for himself. Later he found out that in addition to the usual graphs, $k$-flowers also grew on that flowerbed. A graph is called a $k$-flower if it consists of a simple cycle of length $k$, through each vertex of which passes its own simple cycle of...
Note a few things: There are exactly $k^2$ vertices in the $k$-flower, since from each of the $k$ vertices of the main cycle comes another cycle of size $k$; in the $k$-flower, all vertices have degree $2$, except for the vertices of the main cycle, whose degrees are $4$; it follows that in $k$-flower $k^2 +k$ edges; T...
[ "dfs and similar", "graphs", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; int sz(int v, vector<vector<int>> &g, vector<bool> &used){ used[v] = true; int s = 1; for(int u: g[v]){ if(!used[u]) s += sz(u, g, used); } return s; } void remove(vector<int> &from, int x){ for(int &e: from){ if(e == x){ ...
1811
G1
Vlad and the Nice Paths (easy version)
\textbf{This is an easy version of the problem, it differs from the hard one only by constraints on $n$ and $k$}. Vlad found a row of $n$ tiles and the integer $k$. The tiles are indexed from left to right and the $i$-th tile has the color $c_i$. After a little thought, he decided what to do with it. You can start fr...
Let's use the dynamic programming. Let $dp[i][j]$ be the number of paths on the prefix $i$ of $j$ blocks of the same color. To make transitions in such dynamics, for the position $i$, we will iterate over the position $p$ in which the block started. Denote as $s$ the number of the same elements as $c_i$ and $c_p$ betwe...
[ "combinatorics", "dp", "math" ]
2,100
M = 10 ** 9 + 7 def pw(a, n): if n == 0: return 1 b = pw(a, n // 2) return b * b % M * (a if n % 2 == 1 else 1) % M def obr(x): return pw(x, M - 2) def cnk(n, k): return fact[n] * obr(fact[k]) % M * obr(fact[n - k]) % M def solve(): n, k = map(int, input().split()) c = [-1] +...
1811
G2
Vlad and the Nice Paths (hard version)
\textbf{This is hard version of the problem, it differs from the easy one only by constraints on $n$ and $k$}. Vlad found a row of $n$ tiles and the integer $k$. The tiles are indexed from left to right and the $i$-th tile has the color $c_i$. After a little thought, he decided what to do with it. You can start from ...
To solve the hard version, let's modify the simple version solution. Note that the $j$ parameter can be discarded, since we only need paths of maximum length on each prefix. Now, as $dp[i]$, we denote a pair of the number of maximum paths and the number of blocks in them. For the position $i$, we will find the position...
[ "binary search", "combinatorics", "data structures", "dp", "math", "two pointers" ]
2,200
from sys import stdin input = lambda: stdin.readline().strip() M = 10 ** 9 + 7 cnk = [[0] * (5000 + 1) for i in range(5000 + 1)] def solve(): n, k = map(int, input().split()) c = [-1] + [int(x) for x in input().split()] if k == 1: print(1) return dp = [[0, 0] for i in range(n + 1)] ...
1814
A
Coins
In Berland, there are two types of coins, having denominations of $2$ and $k$ burles. Your task is to determine whether it is possible to represent $n$ burles in coins, i. e. whether there exist non-negative integers $x$ and $y$ such that $2 \cdot x + k \cdot y = n$.
Note that $2$ coins with denomination $k$ can be replaced with $k$ coins with denomination $2$. So, if the answer exists, then there is also such a set of coins, where there is no more than one coin with denomination $k$. Therefore, it is enough to iterate through the number of coins with denomination $k$ (from $0$ to ...
[ "implementation", "math" ]
800
for _ in range(int(input())): n, k = map(int, input().split()) for x in range(2): if n - x * k >= 0 and (n - x * k) % 2 == 0: print("YES") break else: print("NO")
1814
B
Long Legs
A robot is placed in a cell $(0, 0)$ of an infinite grid. This robot has adjustable length legs. Initially, its legs have length $1$. Let the robot currently be in the cell $(x, y)$ and have legs of length $m$. In one move, it can perform one of the following three actions: - jump into the cell $(x + m, y)$; - jump i...
Let's fix the number of leg length increases we do. Let the final length be $k$. Notice that for all $i$ from $1$ to $k$ there is some time when the length is exactly $i$. Thus, we can perform jumps of form $(x, y) \rightarrow (x + i, y)$ or $(x, y) \rightarrow (x, y + i)$. What's the jumping strategy, then? Obviously,...
[ "brute force", "math" ]
1,700
for _ in range(int(input())): a, b = map(int, input().split()) ans = a + b for m in range(1, 100000): ans = min(ans, (a + m - 1) // m + (b + m - 1) // m + (m - 1)) print(ans)
1814
C
Search in Parallel
Suppose you have $n$ boxes. The $i$-th box contains infinitely many balls of color $i$. Sometimes you need to get a ball with some specific color; but you're too lazy to do it yourself. You have bought two robots to retrieve the balls for you. Now you have to program them. In order to program the robots, you have to c...
If the ball of color $x$ is present in the first list on position $i$, then it takes $i \cdot t_1$ seconds to find it. The same for the second list: if color $x$ is on position $j$, it takes $j \cdot t_2$ seconds to find it. So, for each position, we have a coefficient which will be multiplied by the number of times it...
[ "constructive algorithms", "greedy", "sortings" ]
1,500
#include<bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { int n; scanf("%d", &n); vector<int> s(2); for(int j = 0; j < 2; j++) scanf("%d", &s[j]); vector<pair<int, int>> a(n); for(int j = 0; j < n; j++) { scanf("%d", &a[j].first); a[j].se...
1814
D
Balancing Weapons
You've got a job in a game studio that developed an online shooter, and your first big task is to help to balance weapons. The game has $n$ weapons: the $i$-th gun has an integer fire rate $f_i$ and an integer damage per bullet $d_i$. The $i$-th gun's total firepower is equal to $p_i = f_i \cdot d_i$. You have to modi...
Note that the answer $n$ is always possible: for example, we can set $d_i = \frac{\prod{f_j}}{f_i}$, then $p_1 = \dots = p_n = \prod{f_j}$ and $\max{p_i} - \min{p_i} = 0$. If the answer is less than $n$ then there is at least one gun $id$ we won't change. It means that all other guns' firepower should be "around" $p_{i...
[ "binary search", "brute force", "data structures", "math", "two pointers" ]
2,500
fun main() { repeat(readln().toInt()) { val (n, k) = readln().split(' ').map { it.toInt() } val f = readln().split(' ').map { it.toLong() } val d = readln().split(' ').map { it.toLong() } fun checkAround(pos : Long) : Int { val qs = Array(2 * k + 1) { MutableList(0) { 0 ...
1814
E
Chain Chips
You are given an undirected graph consisting of $n$ vertices and $n-1$ edges. The $i$-th edge has weight $a_i$; it connects the vertices $i$ and $i+1$. Initially, each vertex contains a chip. Each chip has an integer written on it; the integer written on the chip in the $i$-th vertex is $i$. In one operation, you can...
Let's try to analyze how many times we traverse each edge, in the style of "Contribution to the Sum" technique. For each edge, the number of times it is traversed must be even, since for every chip that goes from the part of the graph $[1..i]$ to the part $[i+1..n]$, there should be a chip that goes in the opposite dir...
[ "data structures", "dp", "matrices" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long li; const li INF = (li)(1e18); const int N = 200043; struct data { array<array<long long, 2>, 2> d; data() { for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) d[i][j] = INF; }; data(li x) { for(int i = 0; i < 2; i++) for(int j ...
1814
F
Communication Towers
There are $n$ communication towers, numbered from $1$ to $n$, and $m$ bidirectional wires between them. Each tower has a certain set of frequencies that it accepts, the $i$-th of them accepts frequencies from $l_i$ to $r_i$. Let's say that a tower $b$ is accessible from a tower $a$, if there exists a frequency $x$ and...
Let's consider the sweep line approach by the value of the variable $x$; the vertex $i$ is active from the moment $l_i$ to the moment $r_i$. And we have to find vertices that are reachable in the graph of active vertices from the vertex $1$. So, we rephrased the problem as follows: there are vertices that are active at...
[ "brute force", "divide and conquer", "dsu" ]
2,700
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) const int N = 200002; const int V = 50 * N; using pt = pair<int, int>; int n, m; pt a[N]; vector<pt> t[4 * N]; int p[N], rk[N], vs[N]; int cntV; pt g[V]; bool ans[V]; void upd(int v, int l, int r, int L, int R, pt e) { if (L >= R) retur...
1815
A
Ian and Array Sorting
To thank Ian, Mary gifted an array $a$ of length $n$ to Ian. To make himself look smart, he wants to make the array in non-decreasing order by doing the following finitely many times: he chooses two adjacent elements $a_i$ and $a_{i+1}$ ($1\le i\le n-1$), and increases both of them by $1$ or decreases both of them by $...
Consider difference array $[a_2-a_1,a_3-a_2,...,a_n-a_{n-1}]$. If the original array is non-decreasing, what properties does the difference array have? Operations to the original array correspond to what operations in the difference array? We consider the difference array $b_i=a_{i+1}-a_i$ ($1\le i\le n-1$). Then the o...
[ "greedy", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; int arr[n]; long long int altsum=0; for(int i=0;i<n;i++){ cin >> arr[i]; if(i%2==0){ altsum-=arr[i]; } else{ altsum+=arr[i]; } } if(n%2==1||altsum>=0){...
1815
B
Sum Graph
This is an interactive problem. There is a hidden permutation $p_1, p_2, \dots, p_n$. Consider an undirected graph with $n$ nodes only with no edges. You can make two types of queries: - Specify an integer $x$ satisfying $2 \le x \le 2n$. For all integers $i$ ($1 \le i \le n$) such that $1 \le x-i \le n$, an edge be...
Consider using a type 1 operation on $x=n+1$ and $x=n+2$. What do you notice? The resulting graph, after performing type 1 operations according to hint 1, will be a chain (e.g. when $n=6$, it should look like $1 - 6 - 2 - 5 - 3 - 4$). Now, try to figure out a position $k$ such that node $p_k$ is one of the endpoints of...
[ "brute force", "constructive algorithms", "graphs", "implementation", "interactive", "shortest paths", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; void solve(int tc) { int n; cin >> n; cout << "+ " << n+1 << endl; cout << "+ " << n+2 << endl; int l = 1, r = n; int ord[n+1]; for(int i=1; i<=n; i++) { if(i & 1) ord[i] = l++; else ord[i] = r--; } int dist1[n+1]; dist1[1] = 0; int ma = 0, id; ...
1815
C
Between
You are given an integer $n$, as well as $m$ pairs of integers $(a_i,b_i)$, where $1\leq a_i , b_i \leq n$, $a_i \ne b_i$. You want to construct a sequence satisfying the following requirements: - All elements in the sequence are integers between $1$ and $n$. - There is exactly one element with value $1$ in the seque...
Construct a graph with $n$ vertices and add a directed edge $a \rightarrow b$ if between every two $a$ there must be a $b$. Let $v_a$ be the number of occurrences of $a$. The key observation is that if $a \rightarrow b$, then $v_{a} \leq v_{b} + 1$. Suppose $a_k \rightarrow a_{k-1} \rightarrow \cdots a_1$ is a directed...
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
2,200
#include<bits/stdc++.h> using namespace std; void solve(){ int n,m; cin >> n >> m; vector <int> adj[n+1]; int occ[n+1]; occ[1]=1; for(int i=0;i<m;i++){ int x,y; cin >> x >> y; adj[y].push_back(x); } for(int i=2;i<=n;i++){ occ[i]=0; } queue <int> b...
1815
D
XOR Counting
Given two positive integers $n$ and $m$. Find the sum of all possible values of $a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m$, where $a_1,a_2,\ldots,a_m$ are non-negative integers such that $a_1+a_2+\ldots+a_m=n$. Note that all possible values $a_1\bigoplus a_2\bigoplus\ldots\bigoplus a_m$ should be counted in the su...
The cases when $m=1$ and $m\ge3$ are relatively much easier than when $m=2$. When $m=2$, perform an $O(\log n)$ DP on answer. Notice we have to DP another thing as well. What is it? If $m=1$, it is clear that we only can have $a_1=n$ so the answer is $n$. If $m\ge3$, $\left[x,\frac{n-x}2,\frac{n-x}2,0,0,...\right]$ giv...
[ "bitmasks", "combinatorics", "dp", "math" ]
2,600
#include<bits/stdc++.h> using namespace std; unordered_map <long long int,long long int> npos,spos; const int MOD=998244353; long long int solve(long long int n){ if(npos[n]!=0){ return spos[n]; } if(n%2==1){ solve(n/2); npos[n]=npos[n/2]; spos[n]=spos[n/2]*2+npos[n/2]; ...
1815
E
Bosco and Particle
Bosco is studying the behaviour of particles. He decided to investigate on the peculiar behaviour of the so-called "four-one-two" particle. He does the following: There is a line of length $n+1$, where the topmost point is position $0$ and bottommost is position $n+1$. The particle is initially (at time $t=0$) at posi...
If the oscillator string is periodic, what should we do? Use the case when $n=1$ to help you calculate the answer. Observe that whole process is periodic. Note that the process is reversible. If you are in some state $s$, consisting of position of the particle and the current state position of each oscillator, you can ...
[ "dp", "math", "number theory", "strings" ]
3,100
#include<bits/stdc++.h> using namespace std; vector <int> prime; bool p[1000001]; const long long int mod=998244353; void init(){ p[1]=0; for(int i=2;i<=1000000;i++){ p[i]=1; } for(int i=2;i<=1000000;i++){ if(p[i]){ prime.push_back(i); } for(int j=i;j<=1...
1815
F
OH NO1 (-2-3-4)
You are given an undirected graph with $n$ vertices and $3m$ edges. The graph may contain multi-edges, but does not contain self-loops. The graph satisfies the following property: the given edges can be divided into $m$ groups of $3$, such that each group is a triangle. A triangle is defined as three edges $(a,b)$, $...
Go through from vertex $1$ through $n$ and decided their final weights in this order. When deciding the weights for $v$ , make sure it is different from $w$ if $w < v$ and $v$ is adjacent to $w$. Ignore vertices $x$ where $x$ is adjacent to $v$ but have $x > v$. If there are at least $d+1$ options to take from, and $d$...
[ "constructive algorithms", "graphs", "math" ]
3,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second const ll mod=998244353; const int N=2e6+1; ll n,m; vector<pair<int,int> >adj[N]; array<int,3>e[N]; array<int,3>f[N]; ll a[N],b[N]; pair<int,int>vis[10000005]; void solve(){ cin >> n >> m; for(int i=1; i<=n ;i++...
1816
A
Ian Visits Mary
Ian and Mary are frogs living on lattice points of the Cartesian coordinate plane, with Ian living on $(0,0)$ and Mary living on $(a,b)$. Ian would like to visit Mary by jumping around the Cartesian coordinate plane. Every second, he jumps from his current position $(x_p, y_p)$ to another lattice point $(x_q, y_q)$, s...
Let us show that Ian can get to Mary within two moves. Indeed, consider $(x_1,y_1)$ and $(x_2,y_2)$ where $x_2-x_1=1$, since the value of the $x$-coordinates of a point lying on the segment joining $(x_1,y_1)$ and $(x_2,y_2)$, and is not at the endpoints, is strictly between $x_1$ and $x_2$, but there are no integers s...
[ "constructive algorithms", "geometry", "number theory" ]
800
#include<bits/stdc++.h> using namespace std; void solve(){ int a,b; cin >> a >> b; cout << 2 << "\n" << a-1 << ' ' << 1 << "\n" << a << ' ' << b << "\n"; } int main(){ int t; cin >> t; while(t--){ solve(); } }
1816
B
Grid Reconstruction
Consider a $2 \times n$ grid, where $n$ is an \textbf{even} integer. You may place the integers $1, 2, \ldots, 2n$ on the grid, using each integer \textbf{exactly once}. A path is a sequence of cells achieved by starting at $(1, 1)$, then repeatedly walking either downwards or to the right, and stopping when $(2, n)$ ...
Consider the parity (odd/even) of $i+j$. What do you observe? Observe that $a_{i,j}$ will be added if $(i+j)$ is even, and will be subtracted otherwise. This forms a checkered pattern. Obviously, it is optimal for all values that will be added to be strictly larger than all values that will be subtracted. Also, the dif...
[ "constructive algorithms", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans[3][n + 1]; ans[1][1] = 2 * n - 1; ans[2][n] = 2 * n; for (int i = 2; i <= n; i++) { if (i % 2 == 0) { ...
1817
A
Almost Increasing Subsequence
A sequence is almost-increasing if it does not contain three \textbf{consecutive} elements $x, y, z$ such that $x\ge y\ge z$. You are given an array $a_1, a_2, \dots, a_n$ and $q$ queries. Each query consists of two integers $1\le l\le r\le n$. For each query, find the length of the longest almost-increasing subseque...
It is not obvious how the condition in the statement for an almost-increasing subsequence can be turned into a fast data structure that can support queries. So instead of tackling the problem head on, let's try to make an upperbound for how many elements can be in the maximum length almost-increasing subsequence. Assum...
[ "binary search", "data structures", "greedy" ]
1,500
#include "bits/stdc++.h" using namespace std; typedef vector<int> vi; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,q; cin >> n >> q; vi a(n); for(int& i : a) cin >> i; vi p(n-1); for(int i=1;i<n-1;++i) { int downhill = a[i-1]>=a[i] and a[i]>=a[i+1]; p[...
1817
B
Fish Graph
You are given a simple undirected graph with $n$ nodes and $m$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $1$ to $n$. We define a graph to be a Fish Graph if it contains a simple cycle with a special node $u$ belonging to the cycle. Apart from the edges in the cycle, the graph ...
Problem idea: jeroenodb Preparation: jeroenodb Can you find a necessary condition for whether a Fish Subgraph exists? For the Fish Subgraph to exist, the graph must have a cycle with one node in the cycle having degree at least 4. When the necessary condition is satisfied, actually, you can always find a Fish Subgraph....
[ "brute force", "constructive algorithms", "dfs and similar", "graphs" ]
1,900
null
1817
B
Fish Graph
You are given a simple undirected graph with $n$ nodes and $m$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $1$ to $n$. We define a graph to be a Fish Graph if it contains a simple cycle with a special node $u$ belonging to the cycle. Apart from the edges in the cycle, the graph ...
Try to prove this, and see if your proof can be turned into an algorithm. Firstly, let's try to find some necessary conditions for a Fish Subgraph to exist. Because the Fish Graph has a cycle with two extra edges attached, the original must contain a cycle with a node in the cycle having degree at least 4. It turns out...
[ "brute force", "constructive algorithms", "dfs and similar", "graphs" ]
1,900
#include "bits/stdc++.h" using namespace std; #define all(x) begin(x),end(x) typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> pi; void solve() { int n,m; cin >> n >> m; vvi adj(n); while(m--) { int u,v; cin >> u >> v; --u,--v; adj[u].push_back(v); adj[v]...
1817
C
Similar Polynomials
A polynomial $A(x)$ of degree $d$ is an expression of the form $A(x) = a_0 + a_1 x + a_2 x^2 + \dots + a_d x^d$, where $a_i$ are integers, and $a_d \neq 0$. Two polynomials $A(x)$ and $B(x)$ are called similar if there is an integer $s$ such that for any integer $x$ it holds that $$ B(x) \equiv A(x+s) \pmod{10^9+7}. $...
Not that if polynomials are equivalent, they must have the same leading coefficient $k$. Let $A(x) = \dots + a x^{d-1} + k x^d$ and $B(x) = \dots + b x^{d-1} + k x^d$. Then $B(x-s) = \dots + (b-k s d)x^{d-1} + x^d.$ So, if $A(x)$ and $B(x)$ are equivalent, then $A(x) \equiv B(x-s)$, where $a = b-k s d$, or $s = \frac{b...
[ "combinatorics", "math" ]
2,400
const int mod = 1e9 + 7; namespace algebra { const int maxn = 3e6 + 42; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); template<typename T> T bpow(T x, size_t n) { if(n == 0) { return T(1); } else { auto t = bpow(x, n / 2); t ...
1817
D
Toy Machine
There is a toy machine with toys arranged in two rows of $n$ cells each ($n$ is odd). \begin{center} Initial state for $n=9$. \end{center} Initially, $n-2$ toys are placed in the non-corner cells of the top row. The bottom row is initially empty, and its leftmost, rightmost, and central cells are blocked. There are $...
Problem idea: adamant Preparation: jeroenodb Instead of caring about the positions of all the toys, we only need to care about the position of the special toy with index $k$. The other toys can be treated as undistinguishable. The intended way of solving this problem is playing the game in the webpage, trying to come u...
[ "constructive algorithms", "games", "implementation" ]
2,700
#include "bits/stdc++.h" using namespace std; int main() { int n,k; cin >> n >> k; --k; int half = (n-3)/2; string res = ""; if(k==half) { res = "DL"; } else { while(true) { if(k<half) { res+="R"; int need = half-1-k; w...
1817
E
Half-sum
You're given a multiset of non-negative integers $\{a_1, a_2, \dots, a_n\}$. In one step you take two elements $x$ and $y$ of the multiset, remove them and insert their mean value $\frac{x + y}{2}$ back into the multiset. You repeat the step described above until you are left with only two numbers $A$ and $B$. What i...
Similar to the Huffman encoding, the process described in the statement can be represented as constructing a tree, in which on every step we take two trees with weights $a$ and $b$, and connect them with a shared root into a single tree with weight $\frac{a+b}{2}$. In the end of the process, we have two trees with weig...
[ "brute force", "divide and conquer", "greedy" ]
3,400
// split into 1, ..., k and k+1, ..., n pair<int, istring> check_k(istring const& a, int k) { int n = size(a); istring A(n, 0), B(n, 0); for(int i = 0; i < n; i++) { if(i <= k) { A[min(k, i + 1)] += a[i]; } else { B[min(n - k - 2, n - i)] += a[i]; } } ...
1817
F
Entangled Substrings
\begin{quote} Quantum entanglement is when two particles link together in a certain way no matter how far apart they are in space. \end{quote} You are given a string $s$. A pair of its non-empty substrings $(a, b)$ is called entangled if there is a (possibly empty) link string $c$ such that: - Every occurrence of $a$...
Suffix automaton approach. For every substring $a$ of $s$ we can define the longest string $\hat{a}$ such that $a$ only occurs in $s$ as a specific substring of $\hat{a}$. To find $\hat{a}$, we find the longest strings $x$ and $y$ such that the occurrences of $a$ are always preceded by $x$ and always succeeded by $y$. ...
[ "string suffix structures", "strings" ]
3,500
map<char, int> to[maxn]; int len[maxn], link[maxn]; int last, sz = 1; void add_letter(char c) { int p = last; last = sz++; len[last] = len[p] + 1; for(; to[p][c] == 0; p = link[p]) { to[p][c] = last; } int q = to[p][c]; if(q != last) { if(len[q] == len[p] + 1) { ...
1818
A
Politics
In a debate club with $n$ members, including yourself (member $1$), there are $k$ opinions to be discussed in sequence. During each discussion, members express their agreement or disagreement with the opinion. Let's define $Y$ as the number of members who agree and $N$ as the number of members who disagree. After each ...
The members that stay in the end must have the same take about each of the discussed opinions (if takes about some opinion differ for two members, at least one of them should have left during the discussion of that opinion). It means that the people that are left must all have the same takes as the president. On the ot...
[ "greedy", "implementation" ]
800
void solve() { int n, k; cin >> n >> k; string t[n]; int ans = n; for(int i = 0; i < n; i++) { cin >> t[i]; if(t[i] != t[0]) { ans--; } } cout << ans << "\n"; }
1818
B
Indivisible
You're given a positive integer $n$. Find a permutation $a_1, a_2, \dots, a_n$ such that for any $1 \leq l < r \leq n$, the sum $a_l + a_{l+1} + \dots + a_r$ is not divisible by $r-l+1$. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,...
If $n > 1$ is odd, there is no solution, as the sum of the whole array $\frac{n(n+1)}{2}$ is always divisible by $n$. Otherwise, the solution is as follows: Start with the identity permutation $1, 2, \dots, n$. Swap the adjacent pairs to get $2, 1, 4, 3, 6, 5, ..., n, n-1$. Indeed, consider the sum of a sub-array $a_l,...
[ "constructive algorithms" ]
900
void solve() { int n; cin >> n; if(n == 1) { cout << 1 << "\n"; } else if(n % 2) { cout << -1 << "\n"; } else { int a[n]; iota(a, a + n, 1); for(int i = 0; i < n; i += 2) { swap(a[i], a[i + 1]); } for(auto it: a) { cout ...
1819
A
Constructive Problem
As you know, any problem that does not require the use of complex data structures is considered constructive. You are offered to solve one of such problems. You are given an array $a$ of $n$ non-negative integers. You are allowed to perform the following operation \textbf{exactly once}: choose some non-empty subsegmen...
Let the current value of mex equal to $m$ and the value of mex after performing operation equals to $m'$. It's easy to see that in the resulting array there should exist element equals to $m + 1$ (if it doesn't exist, the value of mex won't be equal to $m + 1$). Also notice that $k$ should be equal to $m$ because this ...
[ "brute force", "greedy" ]
1,300
// Nikita Golikov, 2023 #include <bits/stdc++.h> using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; #ifdef GOLIKOV #define debug(x) cerr << (#x) << ":\t" << (x) << endl #else #define debug(x) 238; #endif template <class A, class B> bool smin(A& x, B&& y) ...
1819
B
The Butcher
Anton plays his favorite game "Defense of The Ancients 2" for his favorite hero — The Butcher. Now he wants to make his own dinner. To do this he will take a rectangle of height $h$ and width $w$, then make a vertical or horizontal cut so that both resulting parts have integer sides. After that, he will put one of the ...
Note that we know the area of the original rectangle. This value can be calculated as the sum of the areas of the given rectangles. Now let's consider two similar cases: the first cut was horizontal or the first cut was vertical. We will present the solution for the first case, the second one is considered similarly. I...
[ "geometry", "greedy", "implementation", "sortings", "two pointers" ]
1,900
//#pragma GCC target("trapv") #include <iostream> #include <vector> #include <algorithm> #include <set> #include <string> #include <cmath> #include <map> #include <iostream> #include <list> #include <stack> #include <cassert> using namespace std; typedef long long ll; typedef long double ld; #define fastInp cin.tie(0...
1819
C
The Fox and the Complete Tree Traversal
The fox Yae climbed the tree of the Sacred Sakura. A tree is a connected undirected graph that does not contain cycles. The fox uses her magical powers to move around the tree. Yae can jump from vertex $v$ to another vertex $u$ if and only if the distance between these vertices does not exceed $2$. In other words, in ...
Note that if the tree contains the subgraph shown below, then there is no answer. To prove this it is enough to consider all possible cases for how a cyclic route can pass through the upper vertex and understand that it is impossible to construct such route. Let's assume that the tree does not contain the subgraph show...
[ "constructive algorithms", "dp", "implementation", "math", "trees" ]
2,400
// #pragma comment(linker, "/stack:200000000") // #pragma GCC optimize("Ofast,no-stack-protector") // #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") // #pragma GCC optimize("unroll-loops") #include <stdio.h> #include <bits/stdc++.h> #ifdef PERVEEVM_LOCAL #define debug(x) std::c...
1819
D
Misha and Apples
Schoolboy Misha got tired of doing sports programming, so he decided to quit everything and go to the magical forest to sell magic apples. His friend Danya came to the magical forest to visit Misha. What was his surprise when he found out that Misha found a lot of friends there, the same former sports programmers. And...
In this problem, we need to choose which types of apples will be sold in stores with $k_i = 0$. Let's fix some arrangement of apples and consider the last moment in it when the apples disappeared from the backpack. All the apples that we took after this moment will go into the final answer, and if there was also a stor...
[ "brute force", "data structures", "dp", "two pointers" ]
2,800
#include <bits/stdc++.h> #include <exception> using namespace std; using ll = long long; void solve() { int n, m; cin >> n >> m; vector<vector<int>> apples(n); for (int i = 0; i < n; ++i) { int k; cin >> k; for (int j = 0; j < k; ++j) { int x; cin >> x;...
1819
E
Roads in E City
This is an interactive problem. As is well known, the city "E" has never had its roads repaired in its a thousand and a half years old history. And only recently the city administration repaired some of them. It is known that in total in the city "E" there are $n$ intersections and $m$ roads, which can be used in bot...
Let's consider city as a graph. We will call an edge good if the road is repaired, and bad if the road is not repaired. Since we know that we can reach any vertex from any other vertex using good edges, we will find the minimum spanning tree of the graph built on good edges. To do this, we will iterate through the edge...
[ "interactive", "math", "probabilities", "trees" ]
3,200
#include <bits/stdc++.h> #define x first #define y second using namespace std; mt19937 rnd; struct solve { vector<pair<int, int>> r; vector<vector<pair<int, int>>> s; vector<int> ans; int n, m; static constexpr int rep = 45; int dfs(int a, int p, int b) { for (auto i : s[a]) { if (i.x == b) { return i.y...
1819
F
Willy-nilly, Crack, Into Release!
You have long dreamed of working in a large IT company and finally got a job there. You have studied all existing modern technologies for a long time and are ready to apply all your knowledge in practice. But then you sit down at your desk and see a sheet of paper with the company's motto printed in large letters: abcd...
There are two ways to approach this problem. Let's start with a solution that does not involve associations with known images. Consider a cyclic sequence of strings that satisfies the condition of the problem. Consider the longest common prefix of all the strings in this sequence. It is not very interesting to us, sinc...
[ "data structures", "dp" ]
3,500
#include <bits/stdc++.h> using namespace std; using pi = pair<int, int>; using ll = long long; const int Q = 1e5; const int N = 20; const int V = N*Q; const ll LINF = 1e18; struct MinMaxValue { ll min_value; ll max_value; MinMaxValue operator * (const MinMaxValue& x) const { if (x.max_value < 0...
1820
A
Yura's New Name
After holding one team contest, boy Yura got very tired and wanted to change his life and move to Japan. In honor of such a change, Yura changed his name to something nice. Fascinated by this idea he already thought up a name $s$ consisting only of characters "_" and "^". But there's a problem — Yura likes smiley face...
Let's see that if initial name contains "__" as a substring, we have to add character "^" between these two characters because both smiley faces start and end with character "^" and don't contain "__" as a substring. Also let's see that the resulting name have to start and end with character "^" and it's length have to...
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; if (s == "^") { cout << 1 << '\n'; continue; } int ans = 0; if (s[0] == '_') ++ans; if (s.back() == '_')...
1820
B
JoJo's Incredible Adventures
Did you think there was going to be a JoJo legend here? But no, that was me, Dio! Given a binary string $s$ of length $n$, consisting of characters 0 and 1. Let's build a \textbf{square} table of size $n \times n$, consisting of 0 and 1 characters as follows. In the first row of the table write the original string $s...
First of all, consider the cases if the given string consists only of ones and only of zeros. It's easy to see that answers for these cases are $n^2$ and $0$. In all other cases let's split all strings into segments that consist only of ones. Also if the first and the last characters of the string equals to "1", these ...
[ "math", "strings", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios::sync_with_stdio(0); cin.tie(0); int t = 1; cin >> t; while (t--) { string s; cin >> s; s += s; int k = 0, z = 0; for (char c : s) { z = c == '1' ? z+1 : 0; k = max(k, ...
1821
A
Matching
An integer template is a string consisting of digits and/or question marks. A positive (strictly greater than $0$) integer matches the integer template if it is possible to replace every question mark in the template with a digit in such a way that we get the decimal representation of that integer \textbf{without any ...
In a positive integer, the first digit is from $1$ to $9$, and every next digit can be any. This allows us to implement the following combinatorial approach: calculate the number of different values for the first digit, which is $0$ if the first character of $s$ is 0, $1$ if the first character of $s$ is any other digi...
[ "combinatorics", "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { string s; cin >> s; int ans = 1; if(s[0] == '0') ans = 0; if(s[0] == '?') ans = 9; for(int j = 1; j < s.size(); j++) if(s[j] == '?') ans *= 10; cout << ans << endl; } }
1821
B
Sort the Subarray
Monocarp had an array $a$ consisting of $n$ integers. He has decided to choose two integers $l$ and $r$ such that $1 \le l \le r \le n$, and then sort the subarray $a[l..r]$ (the subarray $a[l..r]$ is the part of the array $a$ containing the elements $a_l, a_{l+1}, a_{l+2}, \dots, a_{r-1}, a_r$) in \textbf{non-descendi...
Let's find the leftmost and the rightmost position in which the arrays $a$ and $a'$ differ. Since only the elements in the chosen subsegment might change, the subarray we sorted should contain these two positions. Let's start with the subarray from the leftmost "different" position to the rightmost one, and then expand...
[ "brute force", "greedy" ]
1,100
#include<bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { int n; scanf("%d", &n); vector<int> a(n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); vector<int> a1(n); for(int i = 0; i < n; i++) scanf("%d", &a1[i]); int diffl = -1, diffr = -1...
1821
C
Tear It Apart
You are given a string $s$, consisting of lowercase Latin letters. In one operation, you can select several (one or more) positions in it such that no two selected positions are adjacent to each other. Then you remove the letters on the selected positions from the string. The resulting parts are concatenated without c...
The resulting string looks like a single letter repeated a number of times. That sounds too vague. Let's fix the exact letter $c$ that will be left. Since the size of the alphabet is only $26$, we can afford that. The letters now separate into letters $c$ and other letters. And all other letters can be treated as indis...
[ "brute force", "implementation", "math", "strings" ]
1,300
for _ in range(int(input())): s = input() n = len(s) ans = n for x in range(26): c = chr(x + ord('a')) i = 0 cur = 0 while i < n: j = i while j < n and (s[j] == c) == (s[i] == c): j += 1 if s[i] != c: cur = max(cur, j - i) i = j if cur == 0: ans = 0 break pw = 0 while (1 << ...
1821
D
Black Cells
You are playing with a really long strip consisting of $10^{18}$ white cells, numbered from left to right as $0$, $1$, $2$ and so on. You are controlling a special pointer that is initially in cell $0$. Also, you have a "Shift" button you can press and hold. In one move, you can do one of three actions: - move the po...
Let's look at what's happening in the task: in the end the pointer will move into some position $p$ and some segments on the prefix $[0, p]$ will be colored. Note that it's optimal to stop only inside some segment (or $l_i \le p \le r_i$ for some $i$), and if we colored $x$ segments (including the last segment $[l_i, p...
[ "binary search", "brute force", "greedy", "math" ]
1,900
fun main() { repeat(readln().toInt()) { val (n, k) = readln().split(' ').map { it.toInt() } val l = readln().split(' ').map { it.toInt() } val r = readln().split(' ').map { it.toInt() } var ans = 2e9.toInt() var cntShort = 0 var lenLong = 0 for (i in 0 until...
1821
E
Rearrange Brackets
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: - bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); -...
First, let's define the cost of an RBS a bit clearer. The absolute smallest cost of removing each pair of brackets is the number of bracket pairs it's inside of. That can actually be achieved - just remove the pairs right to left (according to the positions of the opening brackets in pairs). So you can instead say that...
[ "brute force", "dp", "greedy", "sortings", "strings" ]
2,100
for _ in range(int(input())): k = int(input()) s = input() n = len(s) st = [] cnt = [0 for i in range(n + 1)] ans = 0 for i in range(n): if s[i] == '(': ans += len(st) st.append(i) else: cnt[(i - st.pop()) // 2] += 1 for i in range(n, -1, -1): t = min(k, cnt[i]) ans -= t * i k -= t print(an...
1821
F
Timber
There is a beautiful alley with trees in front of a shopping mall. Unfortunately, it has to go to make space for the parking lot. The trees on the alley all grow in a single line. There are $n$ spots for trees, index $0$ is the shopping mall, index $n+1$ is the road and indices from $1$ to $n$ are the spots for trees....
People say that this problem can be bashed with generating functions. Sadly, I know nothing about them, so I'll explain the more adhoc solution I managed to come up. Let's investigate the general form of some placement of trees. Imagine we fixed some position $x_1, x_2, \dots, x_m$ for them. How to check if it's possib...
[ "combinatorics", "dp", "fft", "math" ]
2,600
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int MOD = 998244353; int add(int a, int b){ a += b; if (a >= MOD) a -= MOD; if (a < 0) a += MOD; return a; } int mul(int a, int b){ return a * 1ll * b % MOD; } int binpow(int a, int b){ int res = 1;...
1822
A
TubeTube Feed
Mushroom Filippov cooked himself a meal and while having his lunch, he decided to watch a video on TubeTube. He can not spend more than $t$ seconds for lunch, so he asks you for help with the selection of video. The TubeTube feed is a list of $n$ videos, indexed from $1$ to $n$. The $i$-th video lasts $a_i$ seconds an...
This problem can be solved by going through all the options of the video that the Mushroom will choose to watch. Let the Mushroom choose the $i$-th video. He can view it if $a[i] + i - 1$ does not exceed $t$. Since he will have to spend $i - 1$ a second scrolling the TubeTube feed and $a[i]$ watching the video. As an a...
[ "brute force", "implementation" ]
800
def solve(): n, t = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] bst = -2 for i in range(n): if i + a[i] <= t and (bst == -2 or b[bst] < b[i]): bst = i print(bst + 1) t = int(input()) for _ in range(t): solve()
1822
B
Karina and Array
Karina has an array of $n$ integers $a_1, a_2, a_3, \dots, a_n$. She loves multiplying numbers, so she decided that the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of a pair of \textbf{adjacent} elements in the array. For example, for $n = 4$, $a=[3, 5, 7, 4]$, the be...
In the problem, we are not required to minimize the number of deletions, so we will search for the answer greedily. First, let's find two numbers in the array whose product is maximal. Note that the product of this pair of numbers will be the answer, since we can remove all elements from the array except this pair, the...
[ "greedy", "math", "sortings" ]
800
t = int(input()) for testCase in range(t): n = int(input()) a = list(map(int, input().split(' '))) a.sort() print(max(a[0] * a[1], a[-1] * a[-2]))
1822
C
Bun Lover
Tema loves cinnabon rolls — buns with cinnabon and chocolate in the shape of a "snail". Cinnabon rolls come in different sizes and are square when viewed from above. The most delicious part of a roll is the chocolate, which is poured in a thin layer over the cinnabon roll in the form of a spiral and around the bun, as...
Let's separate the complex chocolate layer into three simple parts. Now it is not difficult to calculate the total length of the three parts. The length of the light-yellow segment $1$. Length of the cyan polyline $1 + 2 + \dots + n = \dfrac{n \cdot (n + 1)}{2}$. Length of the lilac polyline $1 + 2 + \dots + (n + 1) = ...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int q; cin >> q; while (q--) { int n; cin >> n; cout << ((n + 1) * n) + n + 2 << "\n"; } return 0; }