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
1787
C
Remove the Bracket
RSJ has a sequence $a$ of $n$ integers $a_1,a_2, \ldots, a_n$ and an integer $s$. For each of $a_2,a_3, \ldots, a_{n-1}$, he chose a pair of \textbf{non-negative integers} $x_i$ and $y_i$ such that $x_i+y_i=a_i$ and $(x_i-s) \cdot (y_i-s) \geq 0$. Now he is interested in the value $$F = a_1 \cdot x_2+y_2 \cdot x_3+y_3...
$(x_i-s)(y_i-s)\geq 0$ tells us either $\min(x_i,y_i)\geq s$ or $\max(x_i,y_i) \leq s$, so pickable $x_i$ is a consecutive range. Just consider $(x_i+y_i)$, remove the bracket then it turns to $\ldots+ y_{i-1}\cdot x_i+y_i\cdot x_{i+1}+\ldots$. When $y_{i-1} = x_{i+1}$, the result is constant, so we assume that $y_{i-1...
[ "dp", "greedy", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 200005; long long f[N][2],x[N],y[N]; void get() { int i,n,s,j; cin>>n>>s; for(i=1; i<=n; i++) { cin>>j; if(i==1||i==n) x[i]=y[i]=j; else if(j<=s) x[i]=0,y[i]=j; else x[i]=s,y[i]=j-s; } f[1][0]=f[1][1]=0; for(i=2; i<=n; i++) { f[i][0]=min(f[i-1]...
1787
D
Game on Axis
There are $n$ points $1,2,\ldots,n$, each point $i$ has a number $a_i$ on it. You're playing a game on them. Initially, you are at point $1$. When you are at point $i$, take following steps: - If $1\le i\le n$, go to $i+a_i$, - Otherwise, the game ends. Before the game begins, you can choose two integers $x$ and $y$ ...
First, add directed edges from $i$ to $i+a_i$. If there's a path from $1$ to $x$ satisfying $x<1$ or $x>n$, the game end. We consider all nodes $x$ satisfying $x<1$ or $x>n$ to be the end node, and we call the path which starts at node $1$ until it loops or ends the key path. If we can end the game at first: Let's coun...
[ "combinatorics", "dfs and similar", "dsu", "graphs", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 200005; int a[N]; int v[N]; //= 1 -> in the tree with the end node int s[N]; //subtree size struct E { int to; E *nex; } *h[N]; void add(int u, int v) { E *cur = new E; cur->to = v, cur->nex = h[u], h[u] = cur; } void dfs(int u) { s[u] = v[u] = 1; for (E...
1787
E
The Harmonization of XOR
You are given an array of exactly $n$ numbers $[1,2,3,\ldots,n]$ along with integers $k$ and $x$. Partition the array in exactly $k$ non-empty disjoint subsequences such that the bitwise XOR of all numbers in each subsequence is $x$, and each number is in exactly one subsequence. Notice that there are no constraints o...
First, we observe that three subsequences can combine into one, so we only need to care about the maximum number of subsequences. Make subsequences in the form of $[a,a \oplus x]$ as much as possible, leave $[x]$ alone if possible, and the rest becomes a subsequence. This would be optimal. Proof: Let $B$ be the highest...
[ "bitmasks", "constructive algorithms", "greedy", "math" ]
2,100
null
1787
F
Inverse Transformation
A permutation scientist is studying a self-transforming permutation $a$ consisting of $n$ elements $a_1,a_2,\ldots,a_n$. A permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$ are permutations, while $[1, 1]$, $[4, 3, 1]$ are not...
Consider another question: Given the initial permutation $a$ and find the permutation $a'$ on the $k$-th day? After a day, element $x$ will become $\sigma(x) = a_x$, so we can consider the numbers as nodes, and we add directed edges from $x$ to $a_x$. Note that $a$ is a permutation, so the graph consists of several cyc...
[ "constructive algorithms", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 200005; int dest[N], visit[N], ans[N], mp[N], ansinv[N], sp; int pow2(int y, int M) { long long x = 2, ans = 1; while (y) { if (y & 1) ans = ans * x % M; x = x * x % M, y >>= 1; } return ans % M; } vector<int> cyc[N]; void get() { sp = 0; int n, i, j...
1787
G
Colorful Tree Again
An edge-weighted tree of $n$ nodes is given with each edge colored in some color. Each node of this tree can be blocked or unblocked, all nodes are unblocked initially. A simple path is a path in a graph that does not have repeating nodes. The length of a path is defined as the sum of weights of all edges on the path....
On the original tree, all good paths are constant and one edge can only be on at most one good path. For each color $c$, find all edges of color $c$, and judge if they form a simple path by counting the degree of each node on the path. If so, mark these edges and calculate the length. When a query changes a node $u$, s...
[ "brute force", "data structures", "trees" ]
3,000
null
1787
H
Codeforces Scoreboard
You are participating in a Codeforces Round with $n$ problems. You spend exactly one minute to solve each problem, the time it takes to submit a problem can be ignored. You can only solve at most one problem at any time. The contest starts at time $0$, so you can make your first submission at any time $t \ge 1$ minute...
Since $\max\{b_i-k_i\cdot t,a_i\} = b_i - \min\{k_i\cdot t, b_i - a_i\}$, we can pre-calculate the sum of $b_i$. Let $c_i = b_i - a_i$. Now our mission is to minimize the sum of $\min\{k_i\cdot t, b_i - a_i\}$. If we assume $\min\{k_i\cdot t, b_i - a_i\} = k_i\cdot t$ for some $i$, sort these problems in descending ord...
[ "binary search", "data structures", "dp", "geometry" ]
3,300
null
1787
I
Treasure Hunt
Define the beauty value of a sequence $b_1,b_2,\ldots,b_c$ as the maximum value of $\sum\limits_{i=1}^{q}b_i + \sum\limits_{i=s}^{t}b_i$, where $q$, $s$, $t$ are all integers and $s > q$ or $t\leq q$. Note that $b_i = 0$ when $i<1$ or $i>c$, $\sum\limits_{i=s}^{t}b_i = 0$ when $s>t$. For example, when $b = [-1,-2,-3]$...
First, we observe that: $\max\limits_{l>p\,\texttt{or}\,r\leq p}{(\sum\limits_{i=1}^{p}{a_i}+\sum\limits_{i=l}^{r}{a_i})}=\max\limits_{p=1}^{n}{\sum\limits_{i=1}^{p}{a_i}}+\max\limits_{l,r}{\sum\limits_{i=l}^{r}{a_i}}$. Proof: We can proof it by contradiction. Define $g(l,r,p)$ as $\sum\limits_{i=1}^{p}{a_i}+\sum\limit...
[ "data structures", "divide and conquer", "two pointers" ]
3,400
null
1788
A
One and Two
You are given a sequence $a_1, a_2, \ldots, a_n$. Each element of $a$ is $1$ or $2$. Find out if an integer $k$ exists so that the following conditions are met. - $1 \leq k \leq n-1$, and - $a_1 \cdot a_2 \cdot \ldots \cdot a_k = a_{k+1} \cdot a_{k+2} \cdot \ldots \cdot a_n$. If there exist multiple $k$ that satisfy...
There should be same number of $2$ at $a_1, a_2, \cdots a_k$ and $a_{k+1}, \cdots, a_n$. By checking every $k$, we can solve the problem at $O(N^2)$. By sweeping $k$ from $1$ to $n-1$, we can solve the problem in $O(N)$. Not counting the number of $2$ but naively multiplying using sweeping in python was accepted since ...
[ "brute force", "implementation", "math" ]
800
null
1788
B
Sum of Two Numbers
The sum of digits of a non-negative integer $a$ is the result of summing up its digits together when written in the decimal system. For example, the sum of digits of $123$ is $6$ and the sum of digits of $10$ is $1$. In a formal way, the sum of digits of $\displaystyle a=\sum_{i=0}^{\infty} a_i \cdot 10^i$, where $0 \l...
Let's assume that there is no carry while adding $x$ and $y$. Denote $n=a_9 \cdots a_1a_0$, $x=b_9 \cdots b_1b_0$, $y=c_9 \cdots c_1c_0$ in decimal system. The condition can be changed as the following condition. - $a_i=b_i+c_i$ for all $0 \leq i \leq 9$. - Sum of $b_i$ and sum of $c_i$ should differ by at most $1$. If...
[ "constructive algorithms", "greedy", "implementation", "math", "probabilities" ]
1,100
null
1788
C
Matching Numbers
You are given an integer $n$. Pair the integers $1$ to $2n$ (i.e. each integer should be in exactly one pair) so that each sum of matched pairs is consecutive and distinct. Formally, let $(a_i, b_i)$ be the pairs that you matched. $\{a_1, b_1, a_2, b_2, \ldots, a_n, b_n\}$ should be a permutation of $\{1, 2, \ldots, 2...
Let's assume that $1$ to $2n$ is paired and each sum of pair is $k, k+1, \cdots, k+n-1$. Sum from $1$ to $2n$ should equal to the sum of $k$ to $k+n-1$. So we obtain $n(2n+1)=\frac{(2k+n-1)n}{2}$, which leads to $4n+2=2k+n-1$. Since $4n+2$ is even, $2k+n-1$ should be even. So if $n$ is even, we cannot find such pairing...
[ "constructive algorithms", "greedy", "math" ]
1,300
null
1788
D
Moving Dots
We play a game with $n$ dots on a number line. The initial coordinate of the $i$-th dot is $x_i$. These coordinates are distinct. Every dot starts moving simultaneously with the same constant speed. Each dot moves in the direction of the closest dot (different from itself) until it meets another dot. In the case of a...
Let's think about the original problem where we do not think about subsets. We can easily observe that each dot does not change direction during moving. Assume that dots gather at coordinate $x$. Rightmost dot of dots that have smaller coordinate than $x$ should move right, and leftmost dot which has bigger coordinate ...
[ "binary search", "brute force", "combinatorics", "math", "two pointers" ]
2,000
null
1788
E
Sum Over Zero
You are given an array $a_1, a_2, \ldots, a_n$ of $n$ integers. Consider $S$ as a set of segments satisfying the following conditions. - Each element of $S$ should be in form $[x, y]$, where $x$ and $y$ are integers between $1$ and $n$, inclusive, and $x \leq y$. - No two segments in $S$ intersect with each other. Two...
Denote $p$ as the prefix sum of $a$. For a segment $[x+1, y]$ to be an element of $S$, $p_x \leq p_y$ should be satisfied. Let's denote $dp_i$ as the maximum value of the sum of length of segment smaller than $i$ in $S$. Segment $[x, y]$ is smaller than $i$ if $y \leq i$. If there is no segment ending at $i$, $dp_i=dp_...
[ "data structures", "dfs and similar", "dp" ]
2,200
null
1788
F
XOR, Tree, and Queries
You are given a tree of $n$ vertices. The vertices are numbered from $1$ to $n$. You will need to assign a weight to each edge. Let the weight of the $i$-th edge be $a_i$ ($1 \leq i \leq n-1$). The weight of each edge should be an integer between $0$ and $2^{30}-1$, inclusive. You are given $q$ conditions. Each condi...
Let's denote $p_i$ as xor of edges in path from node $1$ to node $i$. Edges in path from $i$ to $j$ is (edges in path from $1$ to $i$) + (edges in path from $1$ to $j$) - $2 \times$(edges in path from $1$ to $lca(i, j)$) where $lca(i, j)$ denotes the least common ancestor of $i$ and $j$. Since xor of two same number is...
[ "bitmasks", "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "implementation", "trees" ]
2,500
null
1789
A
Serval and Mocha's Array
Mocha likes arrays, and Serval gave her an array consisting of positive integers as a gift. Mocha thinks that for an array of positive integers $a$, it is good iff the greatest common divisor of all the elements in $a$ is no more than its length. And for an array of at least $2$ positive integers, it is beautiful iff ...
Considering an array $a$ of $n$ ($n\geq 2$) positive integers, the following inequality holds for $2\leq i\leq n$: $\gcd(a_1,a_2,\cdots,a_i) \leq \gcd(a_1,a_2) \leq 2$ Therefore, when the prefix $[a_1,a_2]$ of $a$ is good, we can show that all the prefixes of $a$ whose length is no less than $2$ are good, then $a$ is b...
[ "brute force", "math", "number theory" ]
800
null
1789
B
Serval and Inversion Magic
Serval has a string $s$ that only consists of 0 and 1 of length $n$. The $i$-th character of $s$ is denoted as $s_i$, where $1\leq i\leq n$. Serval can perform the following operation called Inversion Magic on the string $s$: - Choose an segment $[l, r]$ ($1\leq l\leq r\leq n$). For $l\leq i\leq r$, change $s_i$ into...
If $s$ is palindromic initially, we can operate on the interval $[1,n]$, the answer is Yes. Let's consider the other case. In a palindrome $s$, for each $i$ in $[1,\lfloor n/2\rfloor]$, $s_{i}=s_{n-i+1}$ must hold. For those $i$, we may check whether $s_{i}=s_{n-i+1}$ is true in the initial string. For all the illegal ...
[ "brute force", "implementation", "strings", "two pointers" ]
800
null
1789
C
Serval and Toxel's Arrays
Toxel likes arrays. Before traveling to the Paldea region, Serval gave him an array $a$ as a gift. This array has $n$ \textbf{pairwise distinct} elements. In order to get more arrays, Toxel performed $m$ operations with the initial array. In the $i$-th operation, he modified the $p_{i}$-th element of the $(i-1)$-th ar...
Consider the contribution of each value. We only need to count the number of concatenated arrays each value appears in, and sum all those counts up. The answer to this problem only depends on the number of appearances of this value. Notice that the appearance of each value forms some intervals. Each interval starts whe...
[ "combinatorics", "dp", "implementation", "math" ]
1,500
null
1789
D
Serval and Shift-Shift-Shift
Serval has two $n$-bit binary integer numbers $a$ and $b$. He wants to share those numbers with Toxel. Since Toxel likes the number $b$ more, Serval decides to change $a$ into $b$ by some (possibly zero) operations. In an operation, Serval can choose any \textbf{positive} integer $k$ between $1$ and $n$, and change $a...
First of all, it could be proven that the answer exists if and only if $a$ and $b$ are both zero or $a$ and $b$ are both non-zero. If $a$ is zero, it remains zero after any operations. Therefore it cannot become $b$ if $b$ is non-zero. If $a$ is non-zero, logical left shift it will definitely increase its lowest bit or...
[ "bitmasks", "brute force", "constructive algorithms", "implementation" ]
2,200
null
1789
E
Serval and Music Game
Serval loves playing music games. He meets a problem when playing music games, and he leaves it for you to solve. You are given $n$ positive integers $s_1 < s_2 < \ldots < s_n$. $f(x)$ is defined as the number of $i$ ($1\leq i\leq n$) that exist non-negative integers $p_i, q_i$ such that: $$s_i=p_i\left\lfloor{s_n\ov...
Consider the following two cases: Case 1: $x$ is not a factor of $s_n$. In this case we have $\left\lfloor{s_n\over x}\right\rfloor + 1 = \left\lceil{s_n\over x}\right\rceil$. Let $k = \left\lfloor{s_n\over x}\right\rfloor$. It can be shown that there are at most $2\sqrt{s_n}$ different values of $k$. The constraint of...
[ "brute force", "dp", "implementation", "math", "number theory" ]
2,500
null
1789
F
Serval and Brain Power
Serval loves Brain Power and his brain power problem. Serval defines that a string $T$ is powerful iff $T$ can be obtained by concatenating some string $T'$ multiple times. Formally speaking, $T$ is powerful iff there exist a string $T'$ and an integer $k\geq 2$ such that $$T=\underbrace{T'+T'+\dots+T'}_{k\text{ times...
Assume that the longest powerful subsequence of the given string $S$ is $T$, which can be obtained by concatenating $k$ copies of string $T'$. Noticing that $|S|\leq 80$, we have the observation that $k\cdot |T'| \leq |S| \leq 80$, so it is impossible that both $k$ and $|T'|$ is large. When $k < 5$, we only need to con...
[ "bitmasks", "brute force", "dp", "greedy", "implementation", "strings" ]
2,700
null
1790
A
Polycarp and the Day of Pi
On March 14, the day of the number $\pi$ is celebrated all over the world. This is a very important mathematical constant equal to the ratio of the circumference of a circle to its diameter. Polycarp was told at school that the number $\pi$ is irrational, therefore it has an infinite number of digits in decimal notati...
In the problem, you had to find the largest common prefix(LCP) of the first $30$ characters of the number $\pi$ and the string $n$. To do this, we will go from the beginning and compare the characters until we find a non-matching one, or until the string $n$ ends.
[ "implementation", "math", "strings" ]
800
t = int(input()) pi = '31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679' for _ in range(t): n = input() + '#' for i in range(len(n)): if pi[i] != n[i]: print(i) break
1790
B
Taisia and Dice
Taisia has $n$ six-sided dice. Each face of the die is marked with a number from $1$ to $6$, each number from $1$ to $6$ is used once. Taisia rolls all $n$ dice at the same time and gets a sequence of values $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 6$), where $a_i$ is the value on the upper face of the $i$-th dice. The...
It is easy to find the value on the cube that the cat stole, it is equal $mx = s - r$. All other values must be no more than $mx$. Let's try to get $r$ by taking $mx$ $\lfloor\frac{r}{mx}\rfloor$ times and adding the remainder there if it is non-zero. We could not get more than $n - 1$ cubes this way, because otherwise...
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; const int MAXN = 55; int n, s1, s2; vector<int> res; void solve() { res.clear(); int d = s1 - s2; for (; s2 >= d; s2 -= d) res.push_back(d); if (s2) res.push_back(s2); for (int i = 0; i < res.size() && res.size() + 1 < n;) { if (res[i] == 1) { ++i; ...
1790
C
Premutation
A sequence of $n$ numbers is called permutation if it contains all integers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not. Kristina had a permutation $p$ of $n$ elements. She wrote it on the whiteboard $n$ tim...
When Kristina writes sequences on the whiteboard, she removes an element with each index exactly once. Thus, the first element of the permutation will be deleted only once - on the first step. All sequences except one will start with it To solve the problem, find a sequence $p_i$ such that: it starts with some element ...
[ "brute force", "implementation", "math" ]
1,000
#include "bits/stdc++.h" using namespace std; int n; void solve(){ cin >> n; vector<vector<int>>perm(n, vector<int>(n - 1)); vector<int>p(n, 0); vector<int>cnt(n + 1, 0); for(int i = 0; i < n; i++){ p[i] = i + 1; for(int j = 0; j < n - 1; j++){ cin >> perm[i][j]; ...
1790
D
Matryoshkas
Matryoshka is a wooden toy in the form of a painted doll, inside which you can put a similar doll of a smaller size. A set of nesting dolls contains one or more nesting dolls, their sizes are consecutive positive integers. Thus, a set of nesting dolls is described by two numbers: $s$ — the size of a smallest nesting d...
First, for each size, let's count $cnt_s$ - the number of dolls of this size. Then, let's create a set, in which for each doll of size $s$ we add the numbers $s$ and $s + 1$. This will allow you to process all the segments, as well as the dimensions adjacent to them. We will iterate over the set in ascending order of s...
[ "data structures", "greedy", "sortings" ]
1,200
#include <iostream> #include <vector> #include <queue> #include <map> #include <set> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); map<int, int> cnt; set<int> b; for (int i = 0; i < n; ++i) { cin >> a[i]; cnt[a[i]]++; b.insert(a[i]); b.i...
1790
E
Vlad and a Pair of Numbers
Vlad found two positive numbers $a$ and $b$ ($a,b>0$). He discovered that $a \oplus b = \frac{a + b}{2}$, where $\oplus$ means the bitwise exclusive OR , and division is performed without rounding.. Since it is easier to remember one number than two, Vlad remembered only $a\oplus b$, let's denote this number as $x$. H...
Consider the answer by bits. We know that if the $i$th bit of the number $x$ is zero, then these bits are the same for $a$ and $b$, otherwise they differ. Then let's first make $a = x$, $b = 0$. Note that $a\oplus b$ is already equal to $x$, but $\frac{a+b}{2}$ is not yet. So we need to dial another $x$ with matching b...
[ "bitmasks", "constructive algorithms" ]
1,400
t = int(input()) for _ in range(t): x = int(input()) a = x b = 0 for i in range(32, -1, -1): if x & (1 << i) > 0: continue if 2 * x - a - b >= (2 << i): a += 1 << i b += 1 << i if a + b == 2 * x and a ^ b == x: print(a, b) else: ...
1790
F
Timofey and Black-White Tree
Timofey came to a famous summer school and found a tree on $n$ vertices. A tree is a connected undirected graph without cycles. Every vertex of this tree, except $c_0$, is colored \textbf{white}. The vertex $c_0$ is colored \textbf{black}. Timofey wants to color all the vertices of this tree in \textbf{black}. To do ...
Let's store for each vertex the minimum distance from it to the nearest black one, let's call it $d[v]$. We will also store the global answer, which for obvious reasons does not increase, we will call it $ans$. Let's now color the vertex $c_i$, let's set $d[c_i] = 0$ and run a depth first search from it. This DFS will ...
[ "brute force", "dfs and similar", "divide and conquer", "graphs", "greedy", "math", "shortest paths", "trees" ]
2,100
#include <bits/stdc++.h> using namespace std; const int MAXN = 200200; const int INF = 1e9; int n, ANS = INF; int crr[MAXN], dist[MAXN], res[MAXN]; bool clr[MAXN]; vector<int> gr[MAXN]; void init() { ANS = INF; for (int v = 0; v < n; ++v) gr[v].clear(); fill(dist, dist + n, INF); memset(clr, 0, n); } void dfs...
1790
G
Tokens on Graph
You are given an undirected connected graph, some vertices of which contain tokens and/or bonuses. Consider a game involving one player  — you. You can move tokens according to the following rules: - At the beginning of the game, you can make exactly one turn: move any token to any adjacent vertex. - If the movement ...
Let's calculate the shortest paths to the finish along the vertices containing bonuses. We will try to reach the finish line with the chip that is closest to it, and mark it. If there is none, we lose. Other chips will give her extra moves. Find all connected components from vertices containing bonuses. Then, for each ...
[ "constructive algorithms", "dfs and similar", "graphs", "shortest paths" ]
2,300
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> token(n), boni(n); vector<vector<int>> g(n); vector<int> good(n); int m; cin >> m; int p, b; cin >> p >> b; for(int i = 0; i < p; i++) { int x; cin >> x; --x; ...
1791
A
Codeforces Checking
Given a lowercase Latin character (letter), check if it appears in the string $codeforces$.
You need to implement what is written in the statement. You can either use an if-statement for each of the characters $\{\texttt{c}, \texttt{o}, \texttt{d}, \texttt{e}, \texttt{f}, \texttt{r}, \texttt{s}\}$, or you can iterate through the string $\texttt{codeforces}$ check if the current character equals $c$.
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const string s = "codeforces"; void solve() { char c; cin >> c; for (char i : s) { if (i == c) {cout << "YES\n"; return;} } cout << "NO\n"; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();...
1791
B
Following Directions
Alperen is standing at the point $(0,0)$. He is given a string $s$ of length $n$ and performs $n$ moves. The $i$-th move is as follows: - if $s_i = L$, then move one unit left; - if $s_i = R$, then move one unit right; - if $s_i = U$, then move one unit up; - if $s_i = D$, then move one unit down. \begin{center} {\sm...
We can keep track of our current point $(x,y)$ as we iterate over the string: if $s_i = \texttt{L}$, then decrement $x$ (set $x \leftarrow x-1$); if $s_i = \texttt{R}$, then increment $x$ (set $x \leftarrow x+1$); if $s_i = \texttt{U}$, then increment $y$ (set $y \leftarrow y+1$); if $s_i = \texttt{D}$, then decrement ...
[ "geometry", "implementation" ]
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 x = 0, y = 0; for (int i = 0; i < n; i++) { if (s[i] == 'L') {x--;} if (s[i] == 'R') {x++;} if (s[i] == 'D') {y--;} if (s[i] == 'U') {y++;} if (x =...
1791
C
Prepend and Append
Timur initially had a binary string$^{\dagger}$ $s$ (possibly of length $0$). He performed the following operation several (possibly zero) times: - Add $0$ to one end of the string and $1$ to the other end of the string. For example, starting from the string $1011$, you can obtain either $\textcolor{red}{0}1011\textco...
Let's perform the process in reverse: we will remove the first and last character of the string, if these two characters are different. We should do this as long as possible, since we need to find the shortest initial string. So the algorithm is straightfoward: keep track of the left and right characters, and if they a...
[ "implementation", "two pointers" ]
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 l = 0, r = n - 1, ans = n; while (s[l] != s[r] && ans > 0) {l++; r--; ans -= 2;} cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie...
1791
D
Distinct Split
Let's denote the $f(x)$ function for a string $x$ as the number of distinct characters that the string contains. For example $f(abc) = 3$, $f(bbbbb) = 1$, and $f(babacaba) = 3$. Given a string $s$, split it into two non-empty strings $a$ and $b$ such that $f(a) + f(b)$ is the maximum possible. In other words, find the...
Let's check all splitting points $i$ for all ($1 \leq i \leq n - 1$). We denote a splitting point as the last index of the first string we take (and all the remaining characters will go to the second string). We need to keep a dynamic count of the number of distinct characters in both strings $a$ (the first string) and...
[ "brute force", "greedy", "strings" ]
1,000
#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; string s; ...
1791
E
Negatives and Positives
Given an array $a$ consisting of $n$ elements, find the maximum possible sum the array can have after performing the following operation \textbf{any number of times}: - Choose $2$ \textbf{adjacent} elements and flip both of their signs. In other words choose an index $i$ such that $1 \leq i \leq n - 1$ and assign $a_i...
We can notice that by performing any number of operations, the parity of the count of negative numbers won't ever change. Thus, if the number of negative numbers is initially even, we can make it equal to $0$ by performing some operations. So, for an even count of negative numbers, the answer is the sum of the absolute...
[ "dp", "greedy", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a(n); long long sum = 0; int negs = 0; for(int i = 0; i < n; ++i) { cin >> a[i]; if(a[i] < 0) { ++negs; ...
1791
F
Range Update Point Query
Given an array $a_1, a_2, \dots, a_n$, you need to handle a total of $q$ updates and queries of two types: - $1$ $l$ $r$ — for each index $i$ with $l \leq i \leq r$, update the value of $a_i$ to the sum of the digits of $a_i$. - $2$ $x$ — output $a_x$.
Let $S(n)$ denote the sum of the digits of $n$. The key observation is the following: after the operation is applied to index $i$ thrice, it won't change after any further operations. The proof$^{\dagger}$ is provided at the bottom of the editorial. So we only need to update $a_i$ if it's been updated at most $2$ times...
[ "binary search", "brute force", "data structures" ]
1,500
#include <bits/stdc++.h> using namespace std; int digit_sum(int n) { int ret = 0; while(n) { ret += n % 10; n /= 10; } return ret; } void solve() { int n, q; cin >> n >> q; vector<int> a(n); set<int> s; for(int i = 0; i < n; ++i) { cin >> a[i]; if(a[i] > ...
1791
G1
Teleporters (Easy Version)
\textbf{The only difference between the easy and hard versions are the locations you can teleport to.} Consider the points $0, 1, \dots, n$ on the number line. There is a teleporter located on each of the points $1, 2, \dots, n$. At point $i$, you can do the following: - Move left one unit: it costs $1$ coin. - Move ...
It's easy to see that it's optimal to only move right or to use a portal once we are at it. We can notice that when we teleport back, the problem is independent of the previous choices. We still are at point $0$ and have some portals left. Thus, we can just find out the individual cost of each portal, sort portals by i...
[ "greedy", "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, c, ans = 0...
1791
G2
Teleporters (Hard Version)
\textbf{The only difference between the easy and hard versions are the locations you can teleport to.} Consider the points $0,1,\dots,n+1$ on the number line. There is a teleporter located on each of the points $1,2,\dots,n$. At point $i$, you can do the following: - Move left one unit: it costs $1$ coin. - Move righ...
Please also refer to the tutorial for the easy version. If we are not at the first taken portal, the problem is still independent for each portal, but this time the cost of a portal is $min(a_i + i, a_i + n + 1 - i)$ (since we can come to a portal either from point $0$ or point $n+1$). So, we again sort the portals by ...
[ "binary search", "greedy", "sortings" ]
1,900
#include <bits/stdc++.h> #define startt ios_base::sync_with_stdio(false);cin.tie(0); typedef long long ll; using namespace std; #define vint vector<int> #define all(v) v.begin(), v.end() #define MOD 1000000007 #define MOD2 998244353 #define MX 1000000000 #define MXL 1000000000000000000 #define PI (ld)2*acos(0.0) #defi...
1792
A
GamingForces
Monocarp is playing a computer game. He's going to kill $n$ monsters, the $i$-th of them has $h_i$ health. Monocarp's character has two spells, either of which he can cast an arbitrary number of times (possibly, zero) and in an arbitrary order: - choose exactly two alive monsters and decrease their health by $1$; - c...
The first spell looks pretty weak compared to the second spell. Feels like you almost always replace one with another. Let's show that you can totally avoid casting the spell of the first type twice or more on one monster. Let the two first spell casts be $(i, j)$ and $(i, k)$ for some monsters $i, j$ and $k$. You can ...
[ "greedy", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int cnt1 = 0; for (int i = 0; i < n; ++i) { int x; cin >> x; cnt1 += (x == 1); } cout << n - cnt1 / 2 << '\n'; } }
1792
B
Stand-up Comedian
Eve is a beginner stand-up comedian. Her first show gathered a grand total of two spectators: Alice and Bob. Eve prepared $a_1 + a_2 + a_3 + a_4$ jokes to tell, grouped by their type: - type 1: both Alice and Bob like them; - type 2: Alice likes them, but Bob doesn't; - type 3: Bob likes them, but Alice doesn't; - ty...
First, let Eve tell the jokes of the first type - they will never do any harm. At the same time, let her tell the jokes of the fourth time at the very end - they will not do any good. Types two and three are kind of opposites of each other. If you tell jokes of each of them one after another, then the moods of both spe...
[ "greedy", "math" ]
1,200
for _ in range(int(input())): a1, a2, a3, a4 = map(int, input().split()) if a1 == 0: print(1) else: print(a1 + min(a2, a3) * 2 + min(a1 + 1, abs(a2 - a3) + a4))
1792
C
Min Max Sort
You are given a permutation $p$ of length $n$ (a permutation of length $n$ is an array of length $n$ in which each integer from $1$ to $n$ occurs exactly once). You can perform the following operation any number of times (possibly zero): - choose two different elements $x$ and $y$ and erase them from the permutation;...
If the array is already sorted, then the answer is $0$. Otherwise, there is a last operation, after which the permutation takes the form $1, 2, \dots, n$. Which means that the elements $1$ and $n$ are selected as the last operation (because they are at the first and last positions after the operation). Now we know that...
[ "binary search", "brute force", "greedy", "math", "two pointers" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> pos(n + 1); for (int i = 0; i < n; ++i) { int x; cin >> x; pos[x] = i; } int l = (n + 1) / 2, r = (n + 2) / 2; while (l > 0 && (l == r || (pos[l] <...
1792
D
Fixed Prefix Permutations
You are given $n$ permutations $a_1, a_2, \dots, a_n$, each of length $m$. Recall that a permutation of length $m$ is a sequence of $m$ distinct integers from $1$ to $m$. Let the beauty of a permutation $p_1, p_2, \dots, p_m$ be the largest $k$ such that $p_1 = 1, p_2 = 2, \dots, p_k = k$. If $p_1 \neq 1$, then the be...
Let's try to solve for one of the given permutations. Let it be some $p$. How to make the answer for it at least $1$? Well, we have to find another permutation $q$ such that $p \cdot q = (1, r_2, r_3, \dots, r_m)$. How about at least $k$? Well, the same: $p \cdot q = (1 2 \dots, k, r_{k+1}, \dots, r_m)$. Push $q$ to th...
[ "binary search", "bitmasks", "data structures", "hashing", "math", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) int get(const vector<int> &a, const vector<int> &b){ int res = 0; while (res < int(a.size()) && a[res] == b[res]) ++res; return res; } int main(){ int t; scanf("%d", &t); while (t--){ int n, m; scanf("%d%...
1792
E
Divisors and Table
You are given an $n \times n$ multiplication table and a positive integer $m = m_1 \cdot m_2$. A $n \times n$ multiplication table is a table with $n$ rows and $n$ columns numbered from $1$ to $n$, where $a_{i, j} = i \cdot j$. For each divisor $d$ of $m$, check: does $d$ occur in the table at least once, and if it do...
Firstly, let's factorize $m$. Since $m = m_1 \cdot m_2$ we can factorize $m_1$ and $m_2$ separately and then "unite" divisors. For example, use can get canonical representations of $m_1 = p_1^{f_1} p_2^{f_2} \dots p_k^{f_k}$ and $m_2 = p_1^{g_1} p_2^{g_2} \dots p_k^{g_k}$ to get canonical representation of $m = p_1^{f_...
[ "brute force", "dfs and similar", "dp", "number theory" ]
2,400
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A,...
1792
F1
Graph Coloring (easy version)
\textbf{The only difference between the easy and the hard version is the constraint on $n$.} You are given an undirected complete graph on $n$ vertices. A complete graph is a graph where each pair of vertices is connected by an edge. You have to paint the edges of the graph into two colors, red and blue (each edge wil...
Lemma: if an undirected graph is disconnected, then its complement is connected. Similarly, if its complement is disconnected, then the graph itself is connected. Proof: suppose a graph is disconnected. Pick two vertices $x$ and $y$ from different components. Every vertex outside of $x$'s component is connected to $x$ ...
[ "combinatorics", "dp", "graphs" ]
2,700
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int varMul(int x) { return x; } template<typename... Args> int varMul(i...
1792
F2
Graph Coloring (hard version)
\textbf{The only difference between the easy and the hard version is the constraint on $n$.} You are given an undirected complete graph on $n$ vertices. A complete graph is a graph where each pair of vertices is connected by an edge. You have to paint the edges of the graph into two colors, red and blue (each edge wil...
Please read the tutorial for the easy version first, since this tutorial uses some definitions from it. Okay, we need more definitions. Here they come: $C_0 = 0, C_i = \frac{A_i}{i!} \textrm{ if } i > 0$ $D_0 = 0, D_i = \frac{B_i}{(i-1)!} \textrm{ if } i > 0$ This way, we can transform the formula for $B_n$ to the foll...
[ "brute force", "combinatorics", "divide and conquer", "dp", "fft", "graphs" ]
2,900
#include<bits/stdc++.h> using namespace std; const int LOGN = 18; const int N = (1 << LOGN); const int MOD = 998244353; const int g = 3; #define forn(i, n) for(int i = 0; i < int(n); i++) inline int mul(int a, int b) { return (a * 1ll * b) % MOD; } inline int norm(int a) { while(a >= MOD) a -= MOD...
1793
A
Yet Another Promotion
The famous store "Second Food" sells groceries only two days a month. And the prices in each of days differ. You wanted to buy $n$ kilos of potatoes for a month. You know that on the first day of the month $1$ kilo of potatoes costs $a$ coins, and on the second day $b$ coins. In "Second Food" you can buy any \textbf{in...
Let $n = (m + 1) \cdot q + r$. Note that you need to use a promotion if $a \cdot m \leq b \cdot (m + 1)$. In this case, we will buy potatoes $q$ times for the promotion. The remaining potatoes (or all if the promotion is unprofitable) can be bought at $\min(a, b)$ per kilogram. Then the answer is: $q \cdot \min(a \cdot...
[ "greedy", "math" ]
800
t = int(input()) for i in range(t): a, b = map(int, input().split(" ")) n, m = map(int, input().split(" ")) q = n // (m + 1) r = n - q * (m + 1) print(q * min(a * m, b * (m + 1))+ r*min(a,b))
1793
B
Fedya and Array
For his birthday recently Fedya was given an array $a$ of $n$ integers arranged in a circle, For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, $\ldots$, $a_{n - 1}$ and $a_n$, $a_n$ and $a_1$) the absolute difference between them is equal to $1$. Let's call a local maximum an element, which is gr...
Note that the local minimums and maximums will alternate, and there will be the same number of them $k$. Let's call the $i$-th local maximum by $a_i$, the $i$-th local minimum by $b_i$. Without loss of generality, consider that $a_i$ goes before $b_i$. To get $b_i$ from $a_i$ we need to write out $a_i - b_i$ numbers, t...
[ "constructive algorithms", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { ll a, b; cin >> a >> b; ll n = 2 * (a - b); cout << n << '\n'; vector<ll> arr(n); int ptr = 0; for (ll c = b; c <= a; ++c) { arr[ptr++] = c; } for (ll c = a - 1; c > b; --c) { arr[pt...
1793
C
Dora and Search
As you know, the girl Dora is always looking for something. This time she was given a permutation, and she wants to find such a subsegment of it that none of the elements at its ends is either the minimum or the maximum of the entire subsegment. More formally, you are asked to find the numbers $l$ and $r$ $(1 \leq l \l...
Suppose we want to check whether the entire array satisfies the claim. If this is the case, then we can output the entire array as an answer. Otherwise, one of the two extreme elements does not meet our requirements. From this we can conclude that all segments containing an element that does not meet our requirements w...
[ "constructive algorithms", "data structures", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; void solve() { int n; cin >> n; vi a(n); for (int &i: a) cin >> i; int l = 0, r = n - 1; int mn = 1, mx = n; while (l <= r) { if (a[l] == mn) { l++; mn++; } else if (a[l] ...
1793
D
Moscow Gorillas
In winter, the inhabitants of the Moscow Zoo are very bored, in particular, it concerns gorillas. You decided to entertain them and brought a permutation $p$ of length $n$ to the zoo. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is...
Denote by $pos_x$ the index of the number $x$ in the permutation. Subsegments with $\operatorname{MEX}>1$ are as follows $1 \le l \le pos_1 \le r \le n$. Denote by: $l_x = \min{[pos_1, pos_2, \ldots, pos_x]}$, $r_x=\max{[pos_1, pos_2, \ldots, os_x]}$. Subsegments with $\operatorname{MEX}>x$ are as follows $1 \le l \le ...
[ "binary search", "dp", "greedy", "implementation", "math", "two pointers" ]
1,800
#include <bits/stdc++.h> #define int long long using namespace std; void solve() { int n; cin >> n; vector<int> pos_a(n + 1); vector<int> pos_b(n + 1); for (int i = 0; i < n; i++) { int a; cin >> a; pos_a[a] = i + 1; } for (int i = 0; i < n; i++) { int b; ...
1793
E
Velepin and Marketing
The famous writer Velepin is very productive. Recently, he signed a contract with a well-known publication and now he needs to write $k_i$ books for $i$-th year. This is not a problem for him at all, he can write as much as he wants about samurai, space, emptiness, insects and werewolves. He has $n$ regular readers, e...
Let's sort people by their group size requirement. Suppose we have such a person $i$ that he is not satisfied, and we have a person $j > i$ who is satisfied. Then we can replace person $j$ in his group with $i$ and the answer for us will not be worse. It follows that for a particular $k$ the answer is some prefix of th...
[ "binary search", "data structures", "dp", "greedy", "sortings", "two pointers" ]
2,600
#include<bits/stdc++.h> using namespace std; #define ll long long #define pii pair<int, int> #define ld long double #define all(a) (a).begin(), (a).end() const int inf = 1e9 + 7; signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int> c(n); for...
1793
F
Rebrending
Kostya and Zhenya — the creators of the band "Paper" — after the release of the legendary album decided to create a new band "Day movers", for this they need to find two new people. They invited $n$ people to the casting. The casting will last $q$ days. On the $i$th of the days, Kostya and Zhenya want to find two peop...
Let's go through all the elements from left to right. The main task will be to support the current version of $dp[i]$ -- the minimum difference of $a_i$ with the elements to the right of it that we managed to consider. Let us correctly calculate $dp$ for the first $r$ elements. Let's move on to $r + 1$. Let's show how ...
[ "brute force", "data structures", "divide and conquer", "implementation" ]
2,600
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 228; template<class T, class Fun = function<T(const T &, const T &)>> struct SegTree { Fun f; vector<T> t; int n; SegTree(int sz, const Fun &g, T default_value = T()) : f(g) { n = 1; while (n < sz) n <<= 1; t...
1794
A
Prefix and Suffix Array
Marcos loves strings a lot, so he has a favorite string $s$ consisting of lowercase English letters. For this string, he wrote down all its non-empty prefixes and suffixes (except for $s$) on a piece of paper in arbitrary order. You see all these strings and wonder if Marcos' favorite string is a palindrome or not. So,...
Observe that there are exactly two strings of length $n-1$ (one prefix and one suffix). We will call them $x$ and $y$. Then, $s$ is a palindrome if and only if $\text{rev}(x)=y$, where $\text{rev}(x)$ is the reversal of string $x$. So, to solve the problem it is enough to find the two strings of length $n-1$ and check ...
[ "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int test_number = 0; test_number < t; test_number++){ int n; cin >> n; vector <string> long_subs; for(int i = 0; i < 2 * n - 2; i++){ string s; cin >> s; if((int)s.size()...
1794
B
Not Dividing
You are given an array of $n$ positive integers $a_1, a_2, \ldots, a_n$. In one operation, you can choose any number of the array and add $1$ to it. Make at most $2n$ operations so that the array satisfies the following property: $a_{i+1}$ is \textbf{not} divisible by $a_i$, for each $i = 1, 2, \ldots, n-1$. You do \...
First, we add one to all the numbers in the array equal to $1$. This uses at most $n$ operations. Then, we iterate through the elements of the array from left to right, starting from the second element. At each step, let $a_x$ be the element we are iterating. If $a_x$ is divisible by $a_{x-1}$, we add one to $a_x$. Now...
[ "constructive algorithms", "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int test_number = 0; test_number < t; test_number++){ int n; cin >> n; vector <int> a(n); for(int i = 0; i < n; i++){ cin >> a[i]; } for(int i = 0; i < n; i++){ if(a[i] =...
1794
C
Scoring Subsequences
The score of a sequence $[s_1, s_2, \ldots, s_d]$ is defined as $\displaystyle \frac{s_1\cdot s_2\cdot \ldots \cdot s_d}{d!}$, where $d!=1\cdot 2\cdot \ldots \cdot d$. In particular, the score of an empty sequence is $1$. For a sequence $[s_1, s_2, \ldots, s_d]$, let $m$ be the maximum score among all its subsequences...
We will first see how to find the cost of a single non-decreasing sequence $s_1, s_2, \ldots, s_\ell$. If we choose a subsequence with $k$ elements, to achieve the maximum score it is optimal to choose the $k$ largest elements. As the sequence is in non-decreasing order, the $k$ largest elements will be the last $k$ el...
[ "binary search", "greedy", "math", "two pointers" ]
1,300
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int test_number = 0; test_number < t; test_number++){ int n; cin >> n; vector <int> a(n); for(int i = 0; i < n; i++){ cin >> a[i]; } vector<int> res; for(int i = 0; i < n;...
1794
D
Counting Factorizations
The prime factorization of a positive integer $m$ is the unique way to write it as $\displaystyle m=p_1^{e_1}\cdot p_2^{e_2}\cdot \ldots \cdot p_k^{e_k}$, where $p_1, p_2, \ldots, p_k$ are prime numbers, $p_1 < p_2 < \ldots < p_k$ and $e_1, e_2, \ldots, e_k$ are positive integers. For each positive integer $m$, $f(m)$...
First, we will count how many times each different element in $a$ occurs and check which of these elements are prime numbers. This can be done by checking for each element if it has a divisor up to its square root or using the Sieve of Eratosthenes. To construct a number $m$ such that $f(m)=\{a_1, a_2, \ldots, a_{2n}\}...
[ "combinatorics", "divide and conquer", "dp", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll MOD = 998244353; //checks if n is prime bool is_prime(ll n){ if(n == 1){ return false; } for(ll i = 2; i * i <= n; i++){ if(n %i == 0){ return false; } } return true; } //computes b ** e % MOD ll fast_pow(ll b, ll e){ ll r...
1794
E
Labeling the Tree with Distances
You are given an unweighted tree of $n$ vertices numbered from $1$ to $n$ and a list of $n-1$ integers $a_1, a_2, \ldots, a_{n-1}$. A tree is a connected undirected graph without cycles. You will use each element of the list to label one vertex. No vertex should be labeled twice. You can label the only remaining unlabe...
First, count the number of occurrences of each element in the list $a$. Let these numbers be $c_0, c_1, \ldots, c_{n-1}$. Then, compute the polynomial hash of the array $c$, that is $\displaystyle H=\sum_{i=0}^{n-1}c_i\:b^i$ where $b$ is the base of the hash. Because the tree is unweighted, there are only $n$ possible ...
[ "data structures", "dp", "greedy", "hashing", "implementation", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 200005; mt19937_64 rng(chrono::system_clock::now().time_since_epoch().count()); //Hashing stuff const ll MOD[3] = {999727999, 1070777777, 1000000007}; ll B[3]; vector<ll> shift(vector<ll> h, ll val = 0){ for(int k = 0; k < 3; k+...
1795
A
Two Towers
There are two towers consisting of blocks of two colors: red and blue. Both towers are represented by strings of characters B and/or R denoting the order of blocks in them \textbf{from the bottom to the top}, where B corresponds to a blue block, and R corresponds to a red block. \begin{center} {\small These two towers...
Note that it does not make sense to move several blocks first from the left tower to the right, and then from the right to the left, since this is similar to canceling the last actions. Using the fact described above and small restrictions on the input data, one of the possible solutions is the following: choose which ...
[ "brute force", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m; string s, t; cin >> n >> m >> s >> t; reverse(t.begin(), t.end()); s += t; int cnt = 0; for (int i = 1; i < n + m; ++i) cnt += s[i - 1] == s[i]; cout << (cnt <= 1 ? "YES\n" : "NO\n...
1795
B
Ideal Point
You are given $n$ one-dimensional segments (each segment is denoted by two integers — its endpoints). Let's define the function $f(x)$ as the number of segments covering point $x$ (a segment covers the point $x$ if $l \le x \le r$, where $l$ is the left endpoint and $r$ is the right endpoint of the segment). An integ...
First of all, let's delete all segments that do not cover the point $k$ (because they increase the value of the function $f$ at points other than $k$). If there are no segments left, then the answer is NO. Otherwise, all segments cover the point $k$. And it remains to check whether the point $k$ is the only point which...
[ "brute force", "geometry", "greedy" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; int L = 0, R = 55; while (n--) { int l, r; cin >> l >> r; if (l <= k && k <= r) L = max(L, l), R = min(R, r); } cout << (L == R ? "YES\n" : "NO\n")...
1795
C
Tea Tasting
A tea manufacturer decided to conduct a massive tea tasting. $n$ sorts of tea will be tasted by $n$ tasters. Both the sorts of tea and the tasters are numbered from $1$ to $n$. The manufacturer prepared $a_i$ milliliters of the $i$-th sort of tea. The $j$-th taster can drink $b_j$ milliliters of tea at once. The tasti...
Consider how each sort of tea affects the tasters. The $i$-th sort makes testers $i, i + 1, \dots, j - 1$, for some $j$, drink to their limit $b_i, b_{i + 1}, \dots, b_{j - 1}$, and the $j$-th taster drink the remaining tea. Sometimes there is no such $j$-th taster, but we'll explore the general case. Let's add the rem...
[ "binary search", "data structures", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<li> a(n), b(n); for (auto& x : a) cin >> x; for (auto& x : b) cin >> x; vector<li> sum(n + 1); for (int ...
1795
D
Triangle Coloring
You are given an undirected graph consisting of $n$ vertices and $n$ edges, where $n$ is divisible by $6$. Each edge has a weight, which is a positive (greater than zero) integer. The graph has the following structure: it is split into $\frac{n}{3}$ triples of vertices, the first triple consisting of vertices $1, 2, 3...
Let's ignore the constraint on the number of red/blue vertices for a moment. What is the maximum possible weight of a coloring? From any triple, we can have any two edges connect vertices of different colors. So, the maximum possible weight of a coloring (not necessarily a valid one) is the sum of all edge weights exce...
[ "combinatorics", "math" ]
1,600
#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...
1795
E
Explosions?
You are playing yet another game where you kill monsters using magic spells. There are $n$ cells in the row, numbered from $1$ to $n$. Initially, the $i$-th cell contains the $i$-th monster with $h_i$ health. You have a basic spell that costs $1$ MP and deals $1$ damage to the monster you choose. You can cast it any n...
Note that each unit of damage dealt by explosions save us from using one more basic spell. In other words, the more the damage from explosions, the better. So, the answer will be equal to $\sum{h_i} - (\text{maximum total damage from explosions})$. Note that in order to kill all remaining monsters with the last spell, ...
[ "binary search", "data structures", "dp", "greedy", "math" ]
2,200
import java.util.* fun main() { repeat(readln().toInt()) { val n = readln().toInt() var h = readln().split(' ').map { it.toInt() } val d = Array(2) { LongArray(n) { 0 } } for (tp in 0..1) { val s = Stack<Pair<Int, Int>>() for (i in h.indices) { ...
1795
F
Blocking Chips
You are given a tree, consisting of $n$ vertices. There are $k$ chips, placed in vertices $a_1, a_2, \dots, a_k$. All $a_i$ are distinct. Vertices $a_1, a_2, \dots, a_k$ are colored black initially. The remaining vertices are white. You are going to play a game where you perform some moves (possibly, zero). On the $i$...
The constraints tell us that the solution should be linear or pretty close to it. Well, in particular, that implies that the solution almost certainly isn't dynamic programming, since we have both $n$ and $k$ to care about. Thus, we'll think about something greedy. When we know the number of move the game will last, we...
[ "binary search", "constructive algorithms", "dfs and similar", "greedy", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) vector<vector<int>> g; vector<int> req; vector<char> used; vector<int> d; bool dfs(int v, int p = -1){ d[v] = 0; for (int u : g[v]) if (u != p){ if (!dfs(u, v)) return false; if (!used[u]) d[...
1795
G
Removal Sequences
You are given a simple undirected graph, consisting of $n$ vertices and $m$ edges. The vertices are numbered from $1$ to $n$. The $i$-th vertex has a value $a_i$ written on it. You will be removing vertices from that graph. You are allowed to remove vertex $i$ only if its degree is equal to $a_i$. When a vertex is rem...
Let's consider what the sequence of removals looks like in general. We will base some intuition on a fact that at least one valid sequence is guaranteed to exist. Remove all vertices that have their degree correct from the start at once. There surely be such vertices, since a valid sequence would have to start with som...
[ "bitmasks", "dfs and similar", "graphs" ]
2,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) typedef unsigned long long uli; int main(){ int t; scanf("%d", &t); while (t--){ int n, m; scanf("%d%d", &n, &m); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); v...
1796
A
Typical Interview Problem
The FB-string is formed as follows. Initially, it is empty. We go through all positive integers, starting from $1$, in ascending order, and do the following for each integer: - if the current integer is divisible by $3$, append F to the end of the FB-string; - if the current integer is divisible by $5$, append B to th...
It's easy to see that the FB-string repeats every $8$ characters: after processing every $15$ numbers, we will get the same remainders modulo $3$ and $5$ as $15$ numbers ago, and when we process $15$ consecutive numbers, we get $8$ characters. So, $f_{i+8} = f_i$. This means that if we want to find a substring no longe...
[ "brute force", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { string fb; int cur = 1; while(fb.size() < 100) { if(cur % 3 == 0) fb += "F"; if(cur % 5 == 0) fb += "B"; cur++; } int t; cin >> t; for(int i = 0; i < t; i++) { int k; cin >> k; ...
1796
B
Asterisk-Minor Template
You are given two strings $a$ and $b$, consisting of lowercase Latin letters. A template $t$ is string, consisting of lowercase Latin letters and asterisks (character '*'). A template is called asterisk-minor if the number of asterisks in it is less than or equal to the number of letters in it. A string $s$ is said t...
What's the reason behind authors specifically asking for templates that have less or equal asterisks than letters? Well, without that the problem would be kind of trivial. A template "*" is matched by every string, so it would always work. Hmm, let's try to make something similar to that template then. We basically hav...
[ "implementation", "strings" ]
1,000
for _ in range(int(input())): a = input() b = input() if a[0] == b[0]: print("YES") print(a[0] + "*") continue if a[-1] == b[-1]: print("YES") print("*" + a[-1]) continue for i in range(len(b) - 1): if (b[i] + b[i + 1]) in a: print(...
1796
C
Maximum Set
A set of positive integers $S$ is called beautiful if, for every two integers $x$ and $y$ from this set, either $x$ divides $y$ or $y$ divides $x$ (or both). You are given two integers $l$ and $r$. Consider all beautiful sets consisting of integers not less than $l$ and not greater than $r$. You have to print two numb...
Every beautiful set can be represented as a sequence of its elements in sorted order. Let these elements for some set be $a_1, a_2, \dots, a_m$; also, let $d_i = \frac{a_{i+1}}{a_i}$. When the set is beautiful, every $d_i$ is an integer greater than $1$. It's easy to see that if $a_1$ and $a_m$ belong to $[l, r]$, the ...
[ "binary search", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int l, r; cin >> l >> r; int max_size = 1; while((l << max_size) <= r) max_size++; int ans2 = (r / (1 << (max_size - 1)) - l + 1); if(ma...
1796
D
Maximum Subarray
You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ integers. You are also given two integers $k$ and $x$. You have to perform the following operation exactly once: add $x$ to the elements on \textbf{exactly} $k$ \textbf{distinct} positions, and subtract $x$ from all the others. For example, if $a = [2, ...
There are greedy and dynamic programming solutions. We will describe dynamic programming solution. The main task is to choose some segment that is the answer to the problem, while choosing $k$ positions to increase by $x$. To do this, we can use dynamic programming $dp_{i, j, t}$, where $i$ is the number of positions t...
[ "data structures", "dp", "greedy", "two pointers" ]
2,000
#include <bits/stdc++.h> using namespace std; using li = long long; const int N = 222222; const int K = 22; const li INF = 1e18; int n, k, x; int a[N]; li dp[N][K][3]; int main() { ios::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while (tc--) { cin >> n >> k >> x; for (int i = 0; i < n; ...
1796
E
Colored Subgraphs
Monocarp has a tree, consisting of $n$ vertices. He is going to select some vertex $r$ and perform the following operations on each vertex $v$ from $1$ to $n$: - set $d_v$ equal to the distance from $v$ to $r$ (the number of edges on the shortest path); - color $v$ some color. A nice coloring satisfies two condition...
Let's start by choosing a vertex $r$ naively. Iterate over all vertices and try each of them. Root the tree by $r$ and observe what the conditions become. $d_v$ for each $v$ is just the depth of each vertex. Well, then the only case, when the connected subgraph of vertices of the same color has all values of $d$ distin...
[ "dfs and similar", "dp", "games", "greedy", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) vector<vector<int>> g; vector<multiset<int>> len; multiset<int> all; int getlen(int v){ return len[v].empty() ? 1 : *len[v].begin() + 1; } void init(int v, int p = -1){ for (int u : g[v]) if (u != p){ ...
1796
F
Strange Triples
Let's call a triple of positive integers ($a, b, n$) strange if the equality $\frac{an}{nb} = \frac{a}{b}$ holds, where $an$ is the concatenation of $a$ and $n$ and $nb$ is the concatenation of $n$ and $b$. For the purpose of concatenation, the integers are considered without leading zeroes. For example, if $a = 1$, $...
Let $|n|$ be the length of number $n$. Then $\frac{an}{nb} = \frac{a}{b} \Leftrightarrow (a \cdot 10^{|n|} + n) b = a (n \cdot 10^{|b|} + b)$ $(a \cdot 10^{|n|} + n) b = a (n \cdot 10^{|b|} + b) \Leftrightarrow g^2 a' b' \cdot 10^{|n|} + g n b' = g a' n \cdot 10^{|b|} + g^2 a' b' \Leftrightarrow$ $\Leftrightarrow g a' ...
[ "brute force", "math", "number theory" ]
2,900
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) using li = long long; const int MAXLEN = 5; vector<int> divs(int x) { vector<int> res; for (int i = 1; i * i <= x; ++i) { if (x % i == 0) { res.push_back(i); if (i * i != x) res.push_back(x / i); } } re...
1797
A
Li Hua and Maze
There is a rectangular maze of size $n\times m$. Denote $(r,c)$ as the cell on the $r$-th row from the top and the $c$-th column from the left. Two cells are adjacent if they share an edge. A path is a sequence of adjacent empty cells. Each cell is initially empty. Li Hua can choose some cells (except $(x_1, y_1)$ and...
We can put obstacles around $(x_1,y_1)$ or $(x_2,y_2)$ and the better one is the answer. More formally, let's define a function $f$: $f(x,y)= \begin{cases} 2,&(x,y)\textrm{ is on the corner}\\ 3,&(x,y)\textrm{ is on the border}\\ 4,&(x,y)\textrm{ is in the middle}\\ \end{cases}$ Then the answer is $\min\{f(x_1,y_1),f(x...
[ "constructive algorithms", "flows", "graphs", "greedy", "implementation" ]
800
//By: OIer rui_er #include <bits/stdc++.h> #define rep(x,y,z) for(int x=(y);x<=(z);x++) #define per(x,y,z) for(int x=(y);x>=(z);x--) #define debug(format...) fprintf(stderr, format) #define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false) using namespace std; typedef long long ll; #def...
1797
B
Li Hua and Pattern
Li Hua has a pattern of size $n\times n$, each cell is either blue or red. He can perform \textbf{exactly $k$} operations. In each operation, he chooses a cell and changes its color from red to blue or from blue to red. Each cell can be chosen as many times as he wants. Is it possible to make the pattern, that matches ...
We can calculate the minimum needed operations $k_{\min}$ easily by enumerating through the cells and performing an operation if the color of the cell is different from the targeted cell. Obviously, if $k < k_{\min}$, the problem has no solution. Otherwise, there are two cases: If $2\mid n$, the solution exists if and ...
[ "constructive algorithms", "greedy" ]
1,100
//By: OIer rui_er #include <bits/stdc++.h> #define rep(x,y,z) for(int x=(y);x<=(z);x++) #define per(x,y,z) for(int x=(y);x>=(z);x--) #define debug(format...) fprintf(stderr, format) #define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false) using namespace std; typedef long long ll; const ...
1797
C
Li Hua and Chess
\textbf{This is an interactive problem.} Li Ming and Li Hua are playing a game. Li Hua has a chessboard of size $n\times m$. Denote $(r, c)$ ($1\le r\le n, 1\le c\le m$) as the cell on the $r$-th row from the top and on the $c$-th column from the left. Li Ming put a king on the chessboard and Li Hua needs to guess its...
We can first ask $(1,1)$ and get the result $k$. Obviously, the king must be on the following two segments: from $(1,k+1)$ to $(k+1,k+1)$. from $(k+1,1)$ to $(k+1,k+1)$. Then, we can ask $(1,k+1)$ and $(k+1,1)$ and get the results $p,q$. There are three cases: If $p=q=k$, the king is at $(k+1,k+1)$. If $p < k$, the kin...
[ "constructive algorithms", "greedy", "interactive" ]
1,600
#include <bits/stdc++.h> using namespace std; int T, n, m; int ask(int x, int y) { printf("? %d %d\n", x, y); fflush(stdout); scanf("%d", &x); return x; } void give(int x, int y) { printf("! %d %d\n", x, y); fflush(stdout); } int main() { for(scanf("%d", &T);T;T--) { scanf("%d%d", &n, &m); int T1 = a...
1797
D
Li Hua and Tree
Li Hua has a tree of $n$ vertices and $n-1$ edges. The root of the tree is vertex $1$. Each vertex $i$ has importance $a_i$. Denote the size of a subtree as the number of vertices in it, and the importance as the sum of the importance of vertices in it. Denote the heavy son of a non-leaf vertex as the son with the \tex...
Denote $T_x$ as the subtree of $x$. The "rotate" operation doesn't change the tree much. More specifically, only the importance of $T_{fa_x},T_x,T_{son_x}$ changes. We can use the brute force method to maintain useful information about each vertex when the operations are performed. What we need to do next is to find th...
[ "brute force", "data structures", "dfs and similar", "dp", "implementation", "trees" ]
1,900
//By: Luogu@rui_er(122461) #include <bits/stdc++.h> #define rep(x,y,z) for(ll x=y;x<=z;x++) #define per(x,y,z) for(ll x=y;x>=z;x--) #define debug printf("Running %s on line %d...\n",__FUNCTION__,__LINE__) #define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false) using namespace std; typed...
1797
E
Li Hua and Array
Li Hua wants to solve a problem about $\varphi$ — Euler's totient function. Please recall that $\varphi(x)=\sum\limits_{i=1}^x[\gcd(i,x)=1]$.$^{\dagger,\ddagger}$ He has a sequence $a_1,a_2,\cdots,a_n$ and he wants to perform $m$ operations: - "1 $l$ $r$" ($1\le l\le r\le n$) — for \textbf{each} $x\in[l,r]$, change $...
Denote $w=\max\limits_{i=1}^n\{a_i\}$. Also denote $\varphi^k(x)=\begin{cases}x,&k=0\\\varphi(\varphi^{k-1}(x)),&k\in\mathbb{N}^*\end{cases}$. It can be proven that after $O(\log w)$ operations, any $a_i$ will become $1$ and more operations are useless. In other words, $\varphi^{\log_2 w+1}(a_i)=1$. Let's construct a t...
[ "brute force", "data structures", "dsu", "math", "number theory", "two pointers" ]
2,300
//By: Luogu@rui_er(122461) #include <bits/stdc++.h> #define rep(x,y,z) for(int x=y;x<=z;x++) #define per(x,y,z) for(int x=y;x>=z;x--) #define debug printf("Running %s on line %d...\n",__FUNCTION__,__LINE__) #define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false) using namespace std; typ...
1797
F
Li Hua and Path
Li Hua has a tree of $n$ vertices and $n-1$ edges. The vertices are numbered from $1$ to $n$. A pair of vertices $(u,v)$ ($u < v$) is considered cute if \textbf{exactly one} of the following two statements is true: - $u$ is the vertex with the minimum index among all vertices on the path $(u,v)$. - $v$ is the vertex ...
There exists an acceptable $O(n\log^2n+m)$ solution using centroid decomposition, but there is a better $O(n\log n+m)$ solution using reconstruction trees. The initial tree is shown in the following picture: Consider the following reconstruction trees. We will define two reconstruction trees called min-RT and max-RT wh...
[ "data structures", "dfs and similar", "divide and conquer", "dsu", "trees" ]
3,000
//By: OIer rui_er #include <bits/stdc++.h> #define rep(x,y,z) for(ll x=(y);x<=(z);x++) #define per(x,y,z) for(ll x=(y);x>=(z);x--) #define debug(format...) fprintf(stderr, format) #define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false) using namespace std; typedef long long ll; const ll...
1798
A
Showstopper
You are given two arrays $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$. In one operation, you can choose any integer $i$ from $1$ to $n$ and swap the numbers $a_i$ and $b_i$. Determine whether, after using any (possibly zero) number of operations, the following two conditions can be satisfied simultaneously: -...
The first solution: Fix the position of the numbers $a_n, b_n$. And for each other index $i$, let's check whether the conditions $a_i \leq a_n$ and $b_i \leq b_n$ are met. If not, swap $a_i$ and $b_i$ and check again. If the conditions are not met for some index in both variants - the answer is "No", otherwise "Yes". T...
[ "greedy", "implementation", "sortings" ]
800
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(n): if a[i] > b[i]: a[i], b[i] = b[i], a[i] if a[-1] == max(a) and b[-1] == max(b): print("YES") else: print("NO")
1798
B
Three Sevens
Lottery "Three Sevens" was held for $m$ days. On day $i$, $n_i$ people with the numbers $a_{i, 1}, \ldots, a_{i, n_i}$ participated in the lottery. It is known that in each of the $m$ days, only one winner was selected from the lottery participants. The lottery winner on day $i$ was not allowed to participate in the l...
Let's calculate the array $last$, where $last_X$ is the last day of the lottery in which the person $X$ participated. Then the only day when $X$ could be a winner is the day $last_X$. Then on the day of $i$, only the person with $last_X = i$ can be the winner. It is also clear that if there are several such participant...
[ "brute force", "data structures", "greedy", "implementation" ]
1,000
MAX = 50000 last = [0] * (MAX + 777) for _ in range(int(input())): m = int(input()) a_ = [] for day in range(m): n = int(input()) a = list(map(int, input().split())) for x in a: last[x] = day a_.append(a) ans = [-1] * m for day in range(m): for x i...
1798
C
Candy Store
The store sells $n$ types of candies with numbers from $1$ to $n$. One candy of type $i$ costs $b_i$ coins. In total, there are $a_i$ candies of type $i$ in the store. You need to pack all available candies in packs, each pack should contain only one type of candies. Formally, for each type of candy $i$ you need to ch...
To begin with, let's understand when 1 price tag will be enough. Let the total cost of all packs of candies be $cost$. Two conditions are imposed on $cost$: The first condition: $cost$ must be divided by each of the numbers $b_i$, because $cost = b_i \cdot d_i$. This is equivalent to the fact that $cost$ is divided by ...
[ "greedy", "math", "number theory" ]
1,700
from math import gcd def lcm(a, b): return a * b // gcd(a, b) for _ in range(int(input())): n = int(input()) a = [] b = [] for i in range(n): ai, bi = map(int, input().split()) a.append(ai) b.append(bi) g = 0 l = 1 ans = 1 for i in range(n): g = gcd(g, ...
1798
D
Shocking Arrangement
You are given an array $a_1, a_2, \ldots, a_n$ consisting of integers such that $a_1 + a_2 + \ldots + a_n = 0$. You have to rearrange the elements of the array $a$ so that the following condition is satisfied: $$\max\limits_{1 \le l \le r \le n} \lvert a_l + a_{l+1} + \ldots + a_r \rvert < \max(a_1, a_2, \ldots, a_n)...
If the array consists entirely of zeros, then this is impossible, since $\max(a) - \min(a) = 0$. Otherwise, we will put all zeros at the beginning. Now our array is without zeros. We will add the elements into the array in order. If now the sum of the added elements is $\leq 0$, we will take any of the remaining positi...
[ "constructive algorithms", "greedy", "math" ]
1,600
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) if max(a) == 0: print("No") else: print("Yes") prefix_sum = 0 pos = [] neg = [] for x in a: if x >= 0: pos.append(x) else: ...
1798
E
Multitest Generator
Let's call an array $b_1, b_2, \ldots, b_m$ a test if $b_1 = m - 1$. Let's call an array $b_1, b_2, \ldots, b_m$ a multitest if the array $b_2, b_3, \ldots, b_m$ can be split into $b_1$ non-empty subarrays so that each of these subarrays is a test. Note that each element of the array must be included in exactly one su...
The first idea: you can make a multitest from any array using $2$ operations. To do this, replace the first element with $1$, and the second with $n - 2$, where $n$ is the length of the array. It remains to learn how to determine whether it is possible to make a multitest from an array for $0$ and for $1$ change. First...
[ "brute force", "dp" ]
2,300
N = 300777 a = [0] * N go = [0] * N good_chain = [0] * N chain_depth = [0] * N suf_max_chain_depth = [0] * N ans = "" for _ in range(int(input())): n = int(input()) a = [0] + list(map(int, input().split())) chain_depth[n + 1] = 0 suf_max_chain_depth[n + 1] = 0 curr_max_chain_depth = 0 for i in ...
1798
F
Gifts from Grandfather Ahmed
Grandfather Ahmed's School has $n+1$ students. The students are divided into $k$ classes, and $s_i$ students study in the $i$-th class. So, $s_1 + s_2 + \ldots + s_k = n+1$. Due to the upcoming April Fools' Day, all students will receive gifts! Grandfather Ahmed planned to order $n+1$ boxes of gifts. Each box can con...
Incredible mathematical fact: from any $2n - 1$ integers, you can choose $n$ with a sum divisible by $n$ (Erdős-Ginzburg-Ziv theorem) The proof can be found in the world wide Web. Brief idea: first prove for primes, and then prove that if true for $n = a$ and $n = b$, then true for $n = ab$. Sort the class sizes: $s_1 ...
[ "dp", "math", "number theory" ]
2,500
#include <bits/stdc++.h> #define pb push_back // #define int long long #define all(x) x.begin(), x.end() #define ld long double using namespace std; const int N = 210; bool dp[N][N][N]; bool take[N][N][N]; signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n, k; ...
1799
A
Recent Actions
On Codeforces the "Recent Actions" field shows the last $n$ posts with recent actions. Initially, there are posts $1, 2, \ldots, n$ in the field (this is in order from top to down). Also there are infinitely many posts not in the field, numbered with integers $n + 1, n + 2, \ldots$. When recent action happens in the ...
Note, that posts will be removed in the order $n, n - 1, \ldots, 1$. The post $n - k + 1$ will be removed at the first time, when there are at least $k$ different numbers among $p_1, p_2, \ldots, p_i$. So let's calculate the number of different numbers among $p_1, p_2, \ldots, p_i$ for each $i$ using boolean array of l...
[ "data structures", "greedy", "implementation", "math" ]
800
null
1799
B
Equalize by Divide
You are given an array $a_1, a_2, \ldots, a_n$ of positive integers. You can make this operation multiple (possibly zero) times: - Choose two indices $i$, $j$ ($1 \leq i, j \leq n$, $i \neq j$). - Assign $a_i := \lceil \frac{a_i}{a_j} \rceil$. Here $\lceil x \rceil$ denotes $x$ rounded up to the smallest integer $\ge...
If all numbers are equal initially - we can do nothing. Otherwise if some $a_i = 1$, answer do not exist: this $a_i$ can't became bigger during operations and all other elements can't be equal to $1$ simultaniously, because after the last operation $a_j > 1$ (otherwise we can remove this operation). If all $a_i \geq 2$...
[ "brute force", "constructive algorithms", "greedy", "math" ]
1,200
null
1799
C
Double Lexicographically Minimum
You are given a string $s$. You can reorder the characters to form a string $t$. Define $t_{\mathrm{max}}$ to be the lexicographical maximum of $t$ and $t$ in reverse order. Given $s$ determine the lexicographically minimum value of $t_{\mathrm{max}}$ over all reorderings $t$ of $s$. A string $a$ is lexicographically...
Let's iterate all symbols of $s$ in order from smallest to largest and construct an answer $t_{max}$. Let the current symbol be $x$. If there are at least $2$ remaining symbols equal to $x$, we should add them to the current prefix and suffix of $t_{max}$ and continue. If there are at most one other symbol $y$ is left ...
[ "greedy", "strings" ]
1,700
null
1799
D2
Hot Start Up (hard version)
This is a hard version of the problem. The constraints of $t$, $n$, $k$ are the only difference between versions. You have a device with two CPUs. You also have $k$ programs, numbered $1$ through $k$, that you can run on the CPUs. The $i$-th program ($1 \le i \le k$) takes $cold_i$ seconds to run on some CPU. However...
Consider maintaining the following 2-dimensional DP: $dp_{i,j}$ will be the minimum time needed to run all previous programs such that the last program run on CPU 1 was program $i$, and the last program run on CPU 2 was program $j$. Initially we have $dp_{0,0} = 0$ (here, $0$ is a placeholder program) and $dp_{i,j} = I...
[ "data structures", "dp" ]
2,100
null
1799
E
City Union
You are given $n \times m$ grid. Some cells are filled and some are empty. A city is a maximal (by inclusion) set of filled cells such that it is possible to get from any cell in the set to any other cell in the set by moving to adjacent (by side) cells, without moving into any cells not in the set. In other words, a ...
Let's note, that the resulting grid is correct if and only if filled cells form continious segment in each row and column (condition *) and there is one city. So we can define a filling operation: given a grid, fill all cells between the most left and most right cells in each row and the most up and most down cells in ...
[ "constructive algorithms", "dfs and similar", "dsu", "geometry", "greedy", "implementation", "math" ]
2,300
null
1799
F
Halve or Subtract
You have an array of positive integers $a_1, a_2, \ldots, a_n$, of length $n$. You are also given a positive integer $b$. You are allowed to perform the following operations (possibly several) times in any order: - Choose some $1 \le i \le n$, and replace $a_i$ with $\lceil \frac{a_i}{2} \rceil$. Here, $\lceil x \rce...
For convenience, let $half(x)$ denote $\lceil \frac{x}{2} \rceil$, and $sub(x)$ denote $\max(x - b, 0)$. First, notice that if we apply both operations to some element, it will be optimal to apply halving first, then subtraction. We can prove this with 2 cases: $a_i \le 2b$. In this case, $half(a_i) \le b$, and so $sub...
[ "binary search", "brute force", "dp", "greedy", "sortings" ]
2,700
null
1799
G
Count Voting
There are $n$ people that will participate in voting. Each person has exactly one vote. $i$-th person has a team $t_i$ ($1 \leq t_i \leq n$) where $t_i = t_j$ means $i$, $j$ are in the same team. By the rules each person should vote for the person from the different team. Note that it automatically means that each per...
Let's solve the problem using inclusion-conclusion principle. If we do not consider teams, there are $\frac{n!}{\prod\limits_{i=1}^{n} c_i!}$ ways to make votings. But now consider such sets of bad votings: person $i$ made a vote for the person from the same team $t_i$. We want to calculate the size of the union of suc...
[ "combinatorics", "dp", "math" ]
2,600
null
1799
H
Tree Cutting
You are given a tree with $n$ vertices. A hero $k$ times do the following operation: - Choose some edge. - Remove it. - Take one of the two remaining parts and delete it. - Write the number of vertices in the remaining part. You are given an initial tree and the a sequence of written numbers. Find the number of ways...
We should calculate the number of ways to choose some $k$ edges of our tree (and directions of them) corresponding to operations, such that the operations that will be done with them will result in the given sequence of written numbers. To calculate these ways let's consider a subtree $dp_{v,mask}$ for our main tree. H...
[ "bitmasks", "dfs and similar", "dp" ]
3,200
null
1800
A
Is It a Cat?
You were walking down the street and heard a sound. The sound was described by the string $s$ consisting of lowercase and uppercase Latin characters. Now you want to find out if the sound was a cat meowing. For the sound to be a meowing, the string can only contain the letters 'm', 'e', 'o' and 'w', in either uppercas...
To solve the problem, you may convert the string to lower case, strip all duplicated characters from it and compare the result to "meow" string. To exclude duplicate characters, you can, for example, use the unique function in C++.
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; string s; cin >> s; transform(s.begin(), s.end(), s.begin(), [] (char c) { return tolower(c); }); s.erase(unique(s.begin(), s.end()), s.end()); cout << (s == "meow" ? "YES" : "NO") << "\n"; } int main(...
1800
B
Count the Number of Pairs
Kristina has a string $s$ of length $n$, consisting only of lowercase and uppercase Latin letters. For each pair of lowercase letter and its matching uppercase letter, Kristina can get $1$ burl. However, pairs of characters cannot overlap, so each character can only be in one pair. For example, if she has the string $...
Count two arrays $big$ and $small$, such that $big[i]$ contains the number of occurrences of $i$th letter of the alphabet in the string in upper case, while $small[i]$ - in lower case. Let's add all existing pairs to the answer, so let's add $min(small[i], big[i])$ to it for each letter. Subtract this minimum from $sma...
[ "greedy", "strings" ]
1,000
#include <bits/stdc++.h> using namespace std; const int N = 26; void solve(){ int n, k; cin >> n >> k; string s; cin >> s; vector<int>big(N, 0), small(N, 0); for(auto &i : s){ if('A' <= i && 'Z' >= i) big[i - 'A']++; else small[i - 'a']++; } int answer = 0; for(int i...
1800
C1
Powering the Hero (easy version)
\textbf{This is an easy version of the problem. It differs from the hard one only by constraints on $n$ and $t$}. There is a deck of $n$ cards, each of which is characterized by its power. There are two types of cards: - a hero card, the power of such a card is always equal to $0$; - a bonus card, the power of such a...
To solve it, it should be noted that despite the way the deck with bonuses works, the order in which they will be applied is not important. Then, when we meet the hero card, we just need to add to the answer the maximum of the available bonuses. Constraints allow you to sort the current array with bonus values each tim...
[ "data structures", "greedy" ]
1,000
def solve(): n = int(input()) s = [int(x) for x in input().split()] ans = 0 buffs = [0] * n for e in s: if e > 0: buffs += [e] j = len(buffs) - 1 while buffs[j] < buffs[j - 1]: buffs[j], buffs[j - 1] = buffs[j - 1], buffs[j] ...
1800
C2
Powering the Hero (hard version)
\textbf{This is a hard version of the problem. It differs from the easy one only by constraints on $n$ and $t$}. There is a deck of $n$ cards, each of which is characterized by its power. There are two types of cards: - a hero card, the power of such a card is always equal to $0$; - a bonus card, the power of such a ...
To solve it, it should be noted that despite the way the deck with bonuses works, the order in which they will be applied is not important. Then, when we meet the hero card, we just need to add to the answer the maximum of the available bonuses. Constraints make you use structures such as a priority queue to quickly fi...
[ "data structures", "greedy" ]
1,100
from queue import PriorityQueue def solve(): n = int(input()) s = [int(x) for x in input().split()] ans = 0 buffs = PriorityQueue() for e in s: if e > 0: buffs.put(-e) elif not buffs.empty(): ans -= buffs.get() print(ans) t = int(input()) for _ in rang...
1800
D
Remove Two Letters
Dmitry has a string $s$, consisting of lowercase Latin letters. Dmitry decided to remove two \textbf{consecutive} characters from the string $s$ and you are wondering how many different strings can be obtained after such an operation. For example, Dmitry has a string "aaabcc". You can get the following different stri...
Consider deleting characters with numbers $i$ and $i + 1$, as well as characters with numbers $i + 1$ and $i + 2$. In the first case, the symbol with the number $i + 2$ remains, in the second - $i$. Symbols with numbers less than $i$ or more than $i + 2$ remain in both cases. Therefore, the same strings will be obtaine...
[ "data structures", "greedy", "hashing", "strings" ]
1,200
#include <iostream> #include <vector> #include <queue> #include <map> #include <set> using namespace std; void solve() { int n; cin >> n; string s; cin >> s; int res = n - 1; for (int i = 1; i + 1 < n; ++i) { if (s[i - 1] == s[i + 1]) { res--; } } cout << re...
1800
E1
Unforgivable Curse (easy version)
\textbf{This is an easy version of the problem. In this version, $k$ is always $3$.} The chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned and wants revenge on the chief wizard. So he stole spell $s$ from his student Harry. The spell — is a $n$-length string of lower...
In these constraints , the problem could be solved as follows: Note that for strings of length $6$ and more, it is enough to check that the strings $s$ and $t$ match character by character, that is, up to permutation, since each character can be moved to the desired half, and then moved to the desired side by length $1...
[ "brute force", "constructive algorithms", "dsu", "graphs", "greedy", "strings" ]
1,400
#include <bits/stdc++.h> using namespace std; #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void slow_solve(int n, int k, string s, string t) { set<string> was; queue<string> q; q.push(s); was.insert(s); auto add = [&](string& s, int i, int j) { i...
1800
E2
Unforgivable Curse (hard version)
\textbf{This is a complex version of the problem. This version has no additional restrictions on the number $k$.} The chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned and wants revenge on the chief wizard. So he stole spell $s$ from his student Harry. The spell — is...
The solution of the problem $E1$ hints to us that with the help of such operations, it is possible to move the symbol in the right direction by $1$ using two operations. Then we can show that among the symbols that we can swap with at least one other symbol, we can get any permutation. For example, you can apply such a...
[ "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "strings" ]
1,500
#include <bits/stdc++.h> using namespace std; #define sz(v) (int)v.size() #define all(v) v.begin(),v.end() #define eb emplace_back void solve() { int n, k; cin >> n >> k; string s; cin >> s; string t; cin >> t; vector<int> cnt(26, 0); bool ok = true; for (int i = 0; i < n; ++i) { if ...
1800
F
Dasha and Nightmares
Dasha, an excellent student, is studying at the best mathematical lyceum in the country. Recently, a mysterious stranger brought $n$ words consisting of small latin letters $s_1, s_2, \ldots, s_n$ to the lyceum. Since that day, Dasha has been tormented by nightmares. Consider some pair of integers $\langle i, j \rangl...
Observation $1$: the product of odd numbers is odd, so the condition for the length of nightmare is automatically completed. Denote by $f(x)$ the number of ones in binary representation of $x$. Let's enumerate the letters of the Latin alphabet from $0$ to $25$. Observation $2$: for each word, it is enough to know the s...
[ "bitmasks", "hashing", "meet-in-the-middle", "strings" ]
1,900
#pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx2,avx,fma,bmi2") #include <bits/stdc++.h> #include <immintrin.h> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; #define endl '\n' //#define int long long #define all(arr) arr.begin(), arr....
1800
G
Symmetree
Kid was gifted a tree of $n$ vertices with the root in the vertex $1$. Since he really like symmetrical objects, Kid wants to find out if this tree is symmetrical. \begin{center} {\small For example, the trees in the picture above are symmetrical.} \end{center} \begin{center} {\small And the trees in this picture are...
Note that if one subtree is a mirror image of another, then they are isomorphic (that is, equal without taking into account the vertex numbers). To check the subtrees for isomorphism, we use hashing of root trees. Now we just have to learn how to check trees for symmetry. To do this, let's calculate how many children o...
[ "dfs and similar", "hashing", "implementation", "trees" ]
2,200
#include <bits/stdc++.h> #define int long long #define pb emplace_back #define mp make_pair #define x first #define y second #define all(a) a.begin(), a.end() #define rall(a) a.rbegin(), a.rend() typedef long double ld; typedef long long ll; using namespace std; mt19937 rnd(time(nullptr)); const int inf = 2e18; co...
1801
A
The Very Beautiful Blanket
Kirill wants to weave the very beautiful blanket consisting of $n \times m$ of the same size square patches of some colors. He matched some non-negative integer to each color. Thus, in our problem, the blanket can be considered a $B$ matrix of size $n \times m$ consisting of non-negative integers. Kirill considers tha...
The maximum number of different numbers we can type is always $n\cdot m$. Let's show how you can build an example for any $n$ and $m$. Note that if we were able to construct a correct matrix, then any of its submatrix is also a correct matrix of a smaller size. Therefore, let's build a correct matrix for some $N$ and $...
[ "bitmasks", "constructive algorithms" ]
1,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int SZ = 256; int v[SZ][SZ]; void Solve(){ int n, m; cin >> n >> m; cout << n * m << '\n'; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cout << v[i][j] << " \n"[j + 1 == m]; } signed main(){ ...
1801
B
Buying gifts
Little Sasha has two friends, whom he wants to please with gifts on the Eighth of March. To do this, he went to the largest shopping center in the city.There are $n$ departments in the mall, each of which has exactly two stores. For convenience, we number the departments with integers from $1$ to $n$. It is known that ...
To begin with, let's sort all departments in descending order $b_i$ (and if ~--- is equal, in ascending order $a_i$). Now let's go through the $i$ department, in which the most expensive gift for the second girlfriend will be bought. Note that in all departments with numbers $j < i$, Sasha must buy a gift for the first...
[ "data structures", "greedy", "sortings" ]
1,800
#include <bits/stdc++.h> using namespace std; template<typename T> bool smin(T& a, const T& b) { if (b < a) { a = b; return true; } return false; } template<typename T> bool smax(T& a, const T& b) { if (a < b) { a = b; return true; } return false; } const int ...
1801
C
Music Festival
The boy Vitya loves to listen to music very much. He knows that $n$ albums are due to be released this Friday, $i$-th of which contains $k_i$ tracks. Of course, Vitya has already listened to all the tracks, and knows that in the $i$-th album, the coolness of the $j$-th track is equal to $a_{i,j}$.Vitya has a friend Mas...
Let's introduce the concept of a compressed album for an album, which is obtained from the original one by removing all elements except those that are the first maxima on their corresponding prefixes. For example: For the album $[\textbf{1}, \textbf{4}, 4, 3, \textbf{6}, 5, 6]$ the album will be compressed $[1, 4, 6]$....
[ "binary search", "data structures", "dp", "greedy", "sortings" ]
1,900
#include "bits/stdc++.h" #include <algorithm> #include <locale> #include <random> #include <unordered_map> #include <vector> using namespace std; #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() typedef long long ll; typedef long double db; typedef unsigned long long ull; vector<int> shrink(vec...
1801
D
The way home
The famous magician Borya Budini traveled through the country $X$, which consists of $n$ cities. However, an accident happened, and he was robbed in the city number $1$. Now Budini will have a hard way home to the city number $n$.He's going to get there by plane. In total, there are $m$ flights in the country, $i$-th f...
Note that the show can be done "postponed". As soon as we don't have enough money to walk along the edge, we can do several shows in advance among the peaks that we have already passed, so as to earn the maximum amount of money. For the general case, you can write $dp[v][best] = (\textit{min show}, \textit{max money})$...
[ "binary search", "data structures", "dp", "graphs", "greedy", "shortest paths", "sortings" ]
2,100
#include "bits/stdc++.h" #define rep(i, n) for (int i = 0; i < (n); ++i) #define pb push_back #define all(a) (a).begin(), (a).end() #define ar array #define vec vector using namespace std; using ll = long long; using pi = pair<int, int>; using vi = vector<int>; using vpi = vector<pair<int, int>>; const ll INF = 2e...
1801
E
Gasoline prices
Berland — is a huge country consisting of $n$ cities. The road network of Berland can be represented as a root tree, that is, there is only $n - 1$ road in the country, and you can get from any city to any other exactly one way, if you do not visit any city twice. For the convenience of representing the country, for ea...
To begin with, let's understand what is required of us. A tree is given, in each vertex of which the price range for this vertex is recorded. A query is a pair of paths of equal length, the prices at the $i$-th vertices along these paths should be equal for all $i$. We need to find the number of ways to place prices at...
[ "data structures", "divide and conquer", "dsu", "hashing", "trees" ]
3,000
#include "bits/stdc++.h" using namespace std; const int mod = (int) 1e9 + 7; int inv(int x) { int res = 1, n = mod - 2; while (n) { if (n & 1) { res = res * 1ll * x % mod; } x = x * 1ll * x % mod; n /= 2; } return res; } const int N = (int) 2e5 + 22, K = 1...
1801
F
Another n-dimensional chocolate bar
Mom bought the boy Vasya a $n$-dimensional chocolate bar, which is a $n$-dimensional cube with the length of each side equal to $1$. The chocolate is planned to be divided into slices. According to the $i$th dimension, it can be divided by hyperplanes into $a_i$ equal parts. Thus, the chocolate is divided in total into...
For $A$ we denote the maximum value of $a_i$ To begin with, let's solve the problem for $O(n\cdot k\cdot f(k, A))$ using dynamic programming. Let's put $dp[i][j]$- the maximum possible volume of the smallest piece, if by the first $i$ measurements we divided the chocolate into $j$ parts. If we have divided into more th...
[ "dp", "math", "meet-in-the-middle", "number theory" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MAXN = 200; int a[MAXN]; const int MAXK = 1e7 + 100, MAXH = 1e4; int hsh[MAXK]; int rev[MAXH]; double dp[MAXN][MAXH]; vector<array<int, 2>> go[MAXH]; main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; ...