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
1856
E1
PermuTree (easy version)
\textbf{This is the easy version of the problem. The differences between the two versions are the constraint on $n$ and the time limit. You can make hacks only if both versions of the problem are solved.} You are given a tree with $n$ vertices rooted at vertex $1$. For some permutation$^\dagger$ $a$ of length $n$, le...
Let's consider the subproblem of maximizing the number of suitable pairs for some fixed $\operatorname{lca}(u, v) = x$. Then, we want to maximize the number of pairs $(u, v)$ such that $a_u < a_x < a_v$ and $u$ and $v$ are in different subtrees of $x$. So for each subtree of $x$, we only care about the number of vertic...
[ "dfs and similar", "dp", "trees" ]
1,800
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const int maxn = 1000000; vector<int> g[maxn]; int s[maxn]; ll ans = 0; void dfs(int v...
1856
E2
PermuTree (hard version)
\textbf{This is the hard version of the problem. The differences between the two versions are the constraint on $n$ and the time limit. You can make hacks only if both versions of the problem are solved.} You are given a tree with $n$ vertices rooted at vertex $1$. For some permutation$^\dagger$ $a$ of length $n$, le...
First of all, the most important takeaways from the editorial for the easy version: For each $x$ from $1$ to $n$, you can solve $n$ independent subproblems of maximizing the number of suitable pairs for a fixed value of $\operatorname{lca}(u, v) = x$, and then add up the results to get the final answer. For each subpro...
[ "bitmasks", "dfs and similar", "dp", "fft", "greedy", "implementation", "math", "trees" ]
2,700
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const int maxn = 1000000; vector<int> g[maxn]; int s[maxn]; ll ans = 0; vector<ll> b; l...
1857
A
Array Coloring
You are given an array consisting of $n$ integers. Your task is to determine whether it is possible to color all its elements in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored. For example, if the array is [$1,2,4,3,2,3,5,4$], ...
Let's analyze the impact of adding odd or even numbers to a set with sum $S$: If you add an even element to the set, the parity of $S$ remains unchanged. If you add an odd element to the set, the parity of $S$ changes. Based on this observation, let's focus on the coloring of odd elements in the array. The number of od...
[ "greedy", "math" ]
800
for i in range(int(input())): n=int(input()) a=[*map(int,input().split())] cnt=0 for i in range(n): if a[i]%2!=0:cnt+=1 if cnt%2==0:print('YES') else:print('NO')
1857
B
Maximum Rounding
Given a natural number $x$. You can perform the following operation: - choose a positive integer $k$ and round $x$ to the $k$-th digit Note that the positions are numbered from right to left, starting from zero. If the number has $k$ digits, it is considered that the digit at the $k$-th position is equal to $0$. The...
First, sorry for the unclear statement. We have rewritten it for several times and have chosen the best one. Let's define $n$ as the length of the $x$. Notice, that after applying the rounding to $k$, all the digits to the right of $k$ become $0$. If the $k$-th digit is less than $5$, after the rounding it'll only wors...
[ "greedy", "implementation", "math" ]
1,100
for i in range(int(input())): s=[0]+[*map(int,list(input()))] k=len(s) for i in range(len(s)-1,0,-1): if s[i]>4:s[i-1]+=1;k=i if s[0]!=0:print(s[0],end='') s=[*map(str,s)] print(''.join(s[1:k]+['0']*(len(s)-k)))
1857
C
Assembly via Minimums
Sasha has an array $a$ of $n$ integers. He got bored and for all $i$, $j$ ($i < j$), he wrote down the minimum value of $a_i$ and $a_j$. He obtained a new array $b$ of size $\frac{n\cdot (n-1)}{2}$. For example, if $a=$ [$2,3,5,1$], he would write [$\min(2, 3), \min(2, 5), \min(2, 1), \min(3, 5), \min(3, 1), min(5, 1)...
Suppose we have an array $a$ that we want to construct, with elements $a_1, a_2, \dots, a_n$. To simplify the process, let's assume that the elements of $a$ are sorted in non-decreasing order, meaning $a_1 \le a_2 \le \dots \le a_n$. Let's start with $a_1$. Since the elements of $a$ are sorted, the pairs $(a_1, a_2), (...
[ "greedy", "sortings" ]
1,200
for _ in range(int(input())): n=int(input()) l=sorted(map(int,input().split())) j=0 for i in range(n-1,0,-1): print(l[j],end=' ') j+=i print(l[-1])
1857
D
Strong Vertices
Given two arrays $a$ and $b$, both of length $n$. Elements of both arrays indexed from $1$ to $n$. You are constructing a directed graph, where edge from $u$ to $v$ ($u\neq v$) exists if $a_u-a_v \ge b_u-b_v$. A vertex $V$ is called strong if there exists a path from $V$ to all other vertices. A path in a directed gr...
The first step is to modify the inequality. $a_u-a_v \geq b_u-b_v \Leftrightarrow a_u-b_u \geq a_v-b_v$. We can create a new array $c$, where $c_i=a_i-b_i$ and our inequality is transformed to $c_u\geq c_v$. Suppose the set $p_1,\dots p_m$ is the set of such vertices $v$ that $c_v$ is maximum possible. From each $p_i$ ...
[ "math", "sortings", "trees" ]
1,300
for _ in range(int(input())): n=int(input()) a=[*map(int,input().split())] b=[*map(int,input().split())] c=[a[i]-b[i] for i in range(n)] mx=max(c) ans=[] for i in range(n): if c[i]==mx:ans.append(i+1) print(len(ans)) print(*ans)
1857
E
Power of Points
You are given $n$ points with integer coordinates $x_1,\dots x_n$, which lie on a number line. For some integer $s$, we construct segments [$s,x_1$], [$s,x_2$], $\dots$, [$s,x_n$]. Note that if $x_i<s$, then the segment will look like [$x_i,s$]. The segment [$a, b$] covers all integer points $a, a+1, a+2, \dots, b$. ...
If we have the segments $[l_1,r_1],\dots,[l_n,r_n]$, the sum of $f_p$ is the sum of the segments' lengths. That's because a segment $[a,b]$ intersect exactly $b-a+1$ points. Now we can find the answer for fixed $s$ in $O(N)$. How to do it more efficiently? Let's sort the given points so that $x_1\le x_2\le \dots \le x_...
[ "math", "sortings" ]
1,500
for i in range(int(input())): n=int(input()) a=sorted([(b,i)for i,b in enumerate(map(int,input().split()))]) ans=[0]*n s1=0 s2=sum(a[i][0] for i in range(n)) for i in range(n): ans[a[i][1]]=s2-a[i][0]*(n-i)+n-i+a[i][0]*i-s1+i s1+=a[i][0] s2-=a[i][0] print(*ans)
1857
F
Sum and Product
You have an array $a$ of length $n$. Your task is to answer $q$ queries: given $x,y$, find the number of pairs $i$ and $j$ ($1 \le i < j \le n$) that both $a_i + a_j = x$ and $a_i \cdot a_j = y$. That is, for the array $[1,3,2]$ and asking for $x=3,y=2$ the answer is $1$: - $i=1$ and $j=2$ fail because $1 + 3 = 4$ a...
The system of equations in the statement resembles Vieta's formula for quadratic equations. If we have $\begin{cases} a_i + a_j = b \\ a_i \cdot a_j = c \end{cases}$ To find the roots of the quadratic equation, we can use the discriminant formula, $D = b^2 - 4ac$. The roots will then be $x_1 = \frac{b - \sqrt{D}}{2}$ a...
[ "binary search", "data structures", "math" ]
1,600
from collections import Counter from math import sqrt for _ in range(int(input())): n=int(input()) a=[*map(int,input().split())] d=Counter(map(str,a)) for i in range(int(input())): x,y=map(int,input().split()) if x*x-4*y<0:print(0);continue D=int(sqrt(x*x-4*y)) x1=(x+D)...
1857
G
Counting Graphs
Given a tree consisting of $n$ vertices. A tree is a connected undirected graph without cycles. Each edge of the tree has its weight, $w_i$. Your task is to count the number of different graphs that satisfy all four conditions: - The graph does not have self-loops and multiple edges. - The weights on the edges of the...
The first observation is that the graphs will consist of $n$ vertices because the MST is fixed. Hence, the graphs will look like the given tree with some new vertices connected. The next step is to determine the possible weights of a new edge between vertices $u$ and $v$. Let $P(u,v)$ be the maximum weight on the simpl...
[ "combinatorics", "divide and conquer", "dsu", "graphs", "greedy", "sortings", "trees" ]
2,000
mod=998244353 def find_(v): stack=[v] while dsu[v]!=v: stack.append(dsu[v]) v=stack[-1] while stack: dsu[stack[-1]]=dsu[v] v=stack.pop() return dsu[v] for i in range(int(input())): n,S=map(int,input().split()) l=[tuple(map(int,input().split()))for i in range(n-1...
1858
A
Buttons
Anna and Katie ended up in a secret laboratory. There are $a+b+c$ buttons in the laboratory. It turned out that $a$ buttons can only be pressed by Anna, $b$ buttons can only be pressed by Katie, and $c$ buttons can be pressed by either of them. Anna and Katie decided to play a game, taking turns pressing these buttons...
On each turn, the current player gets rid of one of the buttons available to them. At the same time, if you press the "common" button, the enemy will not be able to press it as well. Since each player wants to leave their opponent without buttons to press before they run out of those themselves, they will click on the ...
[ "games", "greedy", "math" ]
800
t = int(input()) for i in range(t): a, b, c = map(int, input().split()) if c % 2 == 0: if a > b: print("First") else: print("Second") else: if b > a: print("Second") else: print("First")
1858
B
The Walkway
There are $n$ benches near the Main Walkway in Summer Infomatics School. These benches are numbered by integers from $1$ to $n$ in order they follow. Also there are $m$ cookie sellers near the Walkway. The $i$-th ($1 \le i \le m$) cookie sellers is located near the $s_i$-th bench. Petya is standing in the beginning of...
First, let's calculate how many cookies Petya will eat if we don't remove the cookie sellers at all (we will later refer to this value as $res$). Note that since the cookie sellers reset the time elapsed since the last eaten cookie, the number of cookies eaten on all segments between adjacent cookie sellers are counted...
[ "brute force", "dp", "greedy", "math", "number theory" ]
1,500
#include <bits/stdc++.h> using namespace std; int solve(int d, vector<int> x) { int ans = 0; for (int i = 1; i < x.size(); i++) { ans += (x[i] - x[i - 1] - 1) / d; } ans += int(x.size()) - 2; return ans; } void solve() { #define tests int n, m, d; cin >> n >> m >> d; ...
1858
C
Yet Another Permutation Problem
Alex got a new game called "GCD permutations" as a birthday present. Each round of this game proceeds as follows: - First, Alex chooses a permutation$^{\dagger}$ $a_1, a_2, \ldots, a_n$ of integers from $1$ to $n$. - Then, for each $i$ from $1$ to $n$, an integer $d_i = \gcd(a_i, a_{(i \bmod n) + 1})$ is calculated. -...
It is impossible to get $d_i = \gcd(a_i, a_{(i\mod n) + 1}) > \left\lfloor \frac{n}{2}\right\rfloor$: otherwise, at least one of the numbers in $a$ would be divisible by $d_i$ and would be greater than $d_i$ at the same time, so it would be at least $2 \cdot d_i$, which is greater than $n$. Therefore, the maximum possi...
[ "constructive algorithms", "greedy", "math", "number theory" ]
1,000
#include<iostream> #include<vector> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); int cur = 0; for (int i = 1; i <= n; i += 2) { for (int j = i; j <= n; j *= 2) { a[cur++] = j; ...
1858
D
Trees and Segments
The teachers of the Summer Informatics School decided to plant $n$ trees in a row, and it was decided to plant only oaks and firs. To do this, they made a plan, which can be represented as a binary string $s$ of length $n$. If $s_i = 0$, then the $i$-th tree in the row should be an oak, and if $s_i = 1$, then the $i$-t...
There are many various dynamic programming solutions of this problem. We will describe one of them. Let's calculate the dynamics $pref_{i, \ j}$ = the length of the longest subsegment of zeros that can be obtained on the prefix up to $i$, which ends at index $i$ and costs exactly $j$ operations. Similarly, $suf_{i, \ j...
[ "brute force", "data structures", "dp", "greedy", "two pointers" ]
2,200
#include <bits/stdc++.h> #define int long long using namespace std; using ll = long long; void solve(); template<typename ...Args> void println(Args... args) { apply([](auto &&... args) { ((cout << args << ' '), ...); }, tuple(args...)); cout << '\n'; } int32_t main() { cin.tie(nullptr); ios_base::...
1858
E2
Rollbacks (Hard Version)
This is a hard version of this problem. The only difference between the versions is that you have to solve the hard version in online mode. You can make hacks only if both versions of the problem are solved. You have an array $a$, which is initially empty. You need to process queries of the following types: - + $x$ —...
First, let's learn how to solve the problem without rollbacks. Let $b$ be an array of the same length as $a$, where $b_i=1$ if $i$ is the minimum position at which the number $a_i$ is in the array $a$, and $b_i=0$ otherwise. Then the number of different numbers in the array $a$ is equal to the sum of all the elements o...
[ "data structures", "interactive", "trees" ]
2,600
#include <bits/stdc++.h> using i64 = long long; constexpr int N = 1 << 20; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int q; std::cin >> q; std::vector<int> pos(N, q); int n = 0; std::vector<std::array<int, 5>> a; std::vector<int> b(q), c(q...
1859
A
United We Stand
Given an array $a$ of length $n$, containing integers. And there are two initially empty arrays $b$ and $c$. You need to add each element of array $a$ to \textbf{exactly one} of the arrays $b$ or $c$, in order to satisfy the following conditions: - Both arrays $b$ and $c$ are non-empty. More formally, let $l_b$ be the...
What does it mean that $A$ divides $B$? First, if all numbers are equal, then there is no answer (since $a$ is divisible by $a$, if both arrays are non-empty, then $c_1$ is a divisor of $b_1$). Second, if $a$ is divisible by $b$ and they are both natural numbers, then the following equality holds: $b \le a$ (by definit...
[ "constructive algorithms", "math", "number theory" ]
800
#include <iostream> #include <algorithm> #include <vector> using namespace std; void solve() { int n = 0; cin >> n; vector<int> inp; inp.assign(n, 0); for (auto& x : inp) cin >> x; sort(inp.begin(), inp.end()); if (inp.back() == inp[0]) { cout << "-1\n"; return; } else { int it = 0; while (inp[it] == ...
1859
B
Olya and Game with Arrays
Artem suggested a game to the girl Olya. There is a list of $n$ arrays, where the $i$-th array contains $m_i \ge 2$ positive integers $a_{i,1}, a_{i,2}, \ldots, a_{i,m_i}$. Olya can move \textbf{at most one} (possibly $0$) integer from \textbf{each} array to another array. Note that integers can be moved from one arra...
Do all numbers in a single array really matter? If only the first minimum and the second minimum matter, what is the only way to increase a single array's beauty? What can we say about the array which will have the smallest number in the end? To increase the answer for each array separately, it is necessary to move the...
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,000
#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; #define all(v) v.begin(), v.end() typedef long long ll; const int INF = 1e9 + 7; void solve() { int n; cin >> n; int minn = INF; vector<int> min2; for (int i = 0 ; i < n ; i++) { in...
1859
C
Another Permutation Problem
Andrey is just starting to come up with problems, and it's difficult for him. That's why he came up with a strange problem about permutations$^{\dagger}$ and asks you to solve it. Can you do it? Let's call the cost of a permutation $p$ of length $n$ the value of the expression: \begin{center} $(\sum_{i = 1}^{n} p_i \...
What if we fix the maximum element in the resulting array? Try using greedy. Optimize the log factor away by noticing a certain fact. Let's fix the maximum element in an array - let it be $M$. Now, let's iterate from $n$ to $1$. Let the current chosen number be $i$. I claim that if we maintain the remaining available n...
[ "brute force", "dp", "greedy", "math" ]
1,200
#include <iostream> #include <algorithm> #include <set> #include <stack> #include <vector> using namespace std; void solve() { int N = 0; cin >> N; int ans = 0; vector<int> pr; pr.assign(N * N, -1); for (int i = 1; i <= N; ++i) { for (int j = 1; j <= N; ++j) { pr[i * j - 1] = 1; } } for (int mx = N * N; m...
1859
D
Andrey and Escape from Capygrad
An incident occurred in Capygrad, the capital of Tyagoland, where all the capybaras in the city went crazy and started throwing mandarins. Andrey was forced to escape from the city as far as possible, using portals. Tyagoland is represented by a number line, and the city of Capygrad is located at point $0$. There are ...
What if we use greedy a bit? Where it is always beneficial to teleport? Use scanline Statement: It is always beneficial to teleport to point $b_i$. Proof: Let's assume that we were able to teleport from point $X$ to the right of $b_i$, but not from $b_i$. Then we used some segment $A$ that covers point $X$, but does no...
[ "binary search", "data structures", "dp", "dsu", "greedy", "sortings" ]
1,800
#include <iostream> #include <vector> #include <set> #include <iomanip> #include <cmath> #include <algorithm> #include <map> #include <stack> #include <cassert> #include <unordered_map> #include <bitset> #include <random> #include <unordered_set> #include <chrono> using namespace std; #define all(a) a.begin(), a.en...
1859
E
Maximum Monogonosity
You are given an array $a$ of length $n$ and an array $b$ of length $n$. The cost of a segment $[l, r]$, $1 \le l \le r \le n$, is defined as $|b_l - a_r| + |b_r - a_l|$. Recall that two segments $[l_1, r_1]$, $1 \le l_1 \le r_1 \le n$, and $[l_2, r_2]$, $1 \le l_2 \le r_2 \le n$, are non-intersecting if one of the fo...
Maybe we can relax some conditions? Do we really need to always correctly calculate all sums? Optimize the obvious dp. Let's call the value of a segment $[l; r]$ $f(l, r) = abs(a_l - b_r) + abs(a_r - b_l)$. Let's write $dp[n1][k1]$ - maximum value of segments of total length $k1$ that end before $n1$. The obvious way t...
[ "brute force", "dp", "math" ]
2,500
#include <iostream> #include <vector> using namespace std; const long long INF = 1e18; #define int long long void solve() { int N = 0, K = 0; cin >> N >> K; vector<int> a; vector<int> b; a.assign(N, 0); b.assign(N, 0); for (int i = 0; i < N; ++i) { cin >> a[i]; } for (int i = 0; i < N; ++i) { cin >> b[i];...
1859
F
Teleportation in Byteland
There are $n$ cities in Byteland, some of which are connected by roads, which can be traversed in any direction. The $i$-th road has its own hardness parameter $w_i$. Time spent on traversing a road with its hardness equal to $w_i$ is $\lceil\frac{w_i}{c}\rceil$, where $c$ is the current driving skill. The travel netw...
How many times do we really need to take driving courses? Can you think how would an optimal answer path look like? Can you recalculate the distances required to get to a city from every vertex? Root the tree arbitrarily. First, we can notice that there is no need to take driving courses more than $log{maxW}$ times. No...
[ "data structures", "dfs and similar", "divide and conquer", "graphs", "shortest paths", "trees" ]
3,200
#include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <numeric> #include <algorithm> #include <set> #include <map> #include <cmath> #include <stack> #include <deque> #include <string> #include <ctime> #include <bitset> #include <queue> #include <cassert> #include<unordered_set> #include<u...
1860
A
Not a Substring
A bracket sequence is a string consisting of characters '(' and/or ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example: - bracket sequences "()()" and "(())" a...
Let's consider the following two cases: the string $s$ contains two consecutive equal characters, for example, ")(((" or "())". In this case, we can choose a string $t$ of the form "()()()", since it does not contain a substring of two equal characters, therefore $s$ is not a substring of $t$; in the string $s$, all ad...
[ "constructive algorithms", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { string s; cin >> s; int n = s.size(); string a, b; for (int i = 0; i < 2 * n; ++i) { a += "()"[i & 1]; b += ")("[i < n]; } if (a.find(s) == string::npos) { cout ...
1860
B
Fancy Coins
Monocarp is going to make a purchase with cost of exactly $m$ burles. He has two types of coins, in the following quantities: - coins worth $1$ burle: $a_1$ regular coins and infinitely many fancy coins; - coins worth $k$ burles: $a_k$ regular coins and infinitely many fancy coins. Monocarp wants to make his purchas...
There are two ways to approach this problem: a mathematical way and an algorithmic way. Approach 1 Let's start by looking at the possible ways to represent $m$ burles with our coins. For example, we could try to use as many coins of value $k$ as possible: then, the number of coins of value $k$ will be $\lfloor\frac{m}{...
[ "binary search", "brute force", "greedy", "math" ]
1,200
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int m, k, a1, ak; cin >> m >> k >> a1 >> ak; // function which calculates the number of fancy coins taken // if we take exactly x coins of value k auto f = [m, k, a1, ak](int x) { int taken_1 =...
1860
C
Game on Permutation
Alice and Bob are playing a game. They have a permutation $p$ of size $n$ (a permutation of size $n$ is an array of size $n$ where each element from $1$ to $n$ occurs exactly once). They also have a chip, which can be placed on any element of the permutation. Alice and Bob make alternating moves: Alice makes the first...
For each position $i$, let's determine its status: whether this position is winning or losing for the player who moved the chip into that position. Since a player can only move a chip into a position with smaller index, we can determine the statuses of positions in the order from $1$ to $n$. You can treat it as dynamic...
[ "data structures", "dp", "games", "greedy" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; int ans = 0; int mn = n + 1, mnWin = n + 1; while (n--) { int x; cin >> x; if (mn < x && x < mnWin) { ans += 1; ...
1860
D
Balanced String
You are given a binary string $s$ (a binary string is a string consisting of characters 0 and/or 1). Let's call a binary string \textbf{balanced} if the number of subsequences 01 (the number of indices $i$ and $j$ such that $1 \le i < j \le n$, $s_i=0$ and $s_j=1$) equals to the number of subsequences 10 (the number o...
Let's calculate the following dynamic programming: $dp_{i, cnt0, cnt01}$ - the minimum number of changes in string $s$ if we consider only $i$ first characters of it, the number of characters 0 on that prefix is $cnt0$, and the number of subsequences 01 on that prefix is equal to $cnt01$. The transitions are pretty sim...
[ "dp" ]
2,200
#include <bits/stdc++.h> using namespace std; using li = long long; const int N = 111; int n; string s; int dp[2][N][N * N]; int main() { cin >> s; n = s.size(); dp[0][0][0] = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j <= i + 1; ++j) { for (int cnt = 0; cnt <= j * (i + 1 - j); ++cnt)...
1860
E
Fast Travel Text Editor
You are given a string $s$, consisting of lowercase Latin letters. There's a cursor, initially placed between two adjacent letters of the string. The cursor can't be placed before the first or after the last letter. In one move, you can perform one of three actions: - move a cursor one position to the left (if that ...
Let's start with the easiest slow solution. We can basically treat the problem as a graph one. There are $n-1$ vertices and the operations represent edges: from $i$ to $i+1$, from $i+1$ to $i$ and from $i$ to $j$ if $s_i = s_j$ and $s_{i+1} = s_{j+1}$. Then, for a query, we can run any algorithm that finds the shortest...
[ "data structures", "dfs and similar", "graphs", "shortest paths" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; const int AL = 26; struct query{ int f, t, ans; }; struct edge{ int u, w; }; int main() { cin.tie(0); iostream::sync_with_stdio(false); string s; cin >> s; int n = s.size(); int m...
1860
F
Evaluate RBS
You are given $2n$ tuples of values $(a, b, c)$, where $a$ and $b$ are positive integers and $c$ is a bracket '(' or ')'. Exactly $n$ tuples have $c = $'(' and the other $n$ tuples have $c =$ ')'. You are asked to choose two positive values $x$ and $y$ ($x > 0$ and $y > 0$; \textbf{not necessarily integers}) and sort ...
Think of this as a geometry problem. If that's a revelation for you, don't worry, you'll start seeing it with more experience. We have some points $(a, b)$, are asked to choose a vector $(x, y)$ and sort the points by a dot product of $(a, b)$ and $(x, y)$. What exactly is a dot product? Well, $A \cdot B = |A| \cdot |B...
[ "data structures", "geometry", "implementation", "math", "sortings" ]
2,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; struct bracket{ int a, b, c; }; struct point{ int x, y; }; long long cross(const point &a, const point &b){ return a.x * 1ll * b.y - a.y * 1ll * b.x; } long long dot(const point &a, co...
1861
A
Prime Deletion
A prime number is a positive integer that has exactly two different positive divisors: $1$ and the integer itself. For example, $2$, $3$, $13$ and $101$ are prime numbers; $1$, $4$, $6$ and $42$ are not. You are given a sequence of digits from $1$ to $9$, in which \textbf{every digit from $1$ to $9$ appears exactly on...
There are many possible approaches to this problem. For example, you could use brute force to solve it: iterate on every integer from $1$, check that it is a prime number by iterating on its divisors, and check that it appears as a subsequence in the given digit sequence. If you find the answer, break the loop and prin...
[ "constructive algorithms", "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { string s; cin >> s; if(s.find("1") < s.find("3")) cout << 13; else cout << 31; cout << endl; } }
1861
B
Two Binary Strings
You are given two strings $a$ and $b$ of equal length, consisting of only characters 0 and/or 1; both strings start with character 0 and end with character 1. You can perform the following operation any number of times (possibly zero): - choose one of the strings and two \textbf{equal} characters in it; then turn all...
If the answer is YES, we can always bring both strings to the form $00 \dots 01 \dots 11$ (some prefix consists of zeros, some suffix consists of ones, and all zeroes are before all ones). It's true because after we make both strings equal, we can apply another operation with $l = i, r = |a|$, where $i$ is the minimum ...
[ "constructive algorithms", "dp", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int tc = 0; tc < t; ++tc) { string a, b; cin >> a >> b; bool ok = false; for (int i = 0; i + 1 < a.size(); ++i) { if (a[i] == b[i] && a[i] == '0' && a[i + 1] == b[i + 1] && a[i + ...
1861
C
Queries for the Array
Monocarp had an array $a$ consisting of integers. Initially, \textbf{this array was empty}. Monocarp performed three types of queries to this array: - choose an integer and append it \textbf{to the end of the array}. Each time Monocarp performed a query of this type, he wrote out a character +; - remove \textbf{the l...
First of all, let's analyze which situations cause the answer to be NO. There are two types: if the number of elements in the array is currently less than $2$, the array is definitely sorted. So, if we get a 0 and the number of elements is $0$ or $1$, the answer is NO; if the array is sorted, but some prefix of it (may...
[ "data structures", "dfs and similar", "implementation", "strings", "trees" ]
1,600
#include<bits/stdc++.h> using namespace std; vector<int> has0, has1; vector<vector<int>> g; bool ans; bool dfs(int x, int d) { if(has0[x] && (has1[x] || d <= 1)) ans = false; bool res = false; for(auto y : g[x]) res |= dfs(y, d + 1); if(has0[x] && res) ans = false; return res || has1[x]; } void sol...
1861
D
Sorting By Multiplication
You are given an array $a$ of length $n$, consisting of \textbf{positive integers}. You can perform the following operation on this array any number of times (possibly zero): - choose three integers $l$, $r$ and $x$ such that $1 \le l \le r \le n$, and multiply every $a_i$ such that $l \le i \le r$ by $x$. Note that...
At first, let's figure out which multiplications by negative values we perform. After a few multiplications, some subarrays of the array $a$ might become negative. If there is more than one such negative subarray (and there are non-negative elements between them), then the array cannot be sorted by multiplication by no...
[ "dp", "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 5; int t; int n; int a[N]; int main() { cin >> t; for (int tc = 0; tc < t; ++tc){ cin >> n; for (int i = 0; i < n; ++i) cin >> a[i]; int cnt = 0; for (int i = 1; i < n; ++i) cnt += (a[i -...
1861
E
Non-Intersecting Subpermutations
You are given two integers $n$ and $k$. For an array of length $n$, let's define its cost as the maximum number of contiguous subarrays of this array that can be chosen so that: - each element belongs to at most one subarray; - the length of each subarray is exactly $k$; - each subarray contains each integer from $1$...
Let's try to solve another problem first: we are given an array and a value of $k$, we need to compute its cost. How can we do it? We can solve it greedily: find the leftmost subarray of length $k$ that contains all values from $1$ to $k$ and doesn't intersect with previously added subarrays, add it to the answer, rins...
[ "combinatorics", "dp", "implementation", "math" ]
2,300
#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 sub(int x, int y) { return add(x, -y); } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1;...
1861
F
Four Suits
The game of Berland poker is played as follows. There are $n+1$ people: $n$ players, numbered from $1$ to $n$, and the dealer. The dealer has a deck which contains cards of four different suits (the number of cards of each suit \textbf{is not necessarily the same}); the number of cards in the deck is divisible by $n$. ...
As far as I am concerned, fully greedy solutions don't work in this problem. However, we can try employing some greedy ideas. First of all, let's calculate how many cards each player should receive. I will call it $remain_i$ for the $i$-th player. Suppose we want to maximize the answer for the $i$-th player. Let's iter...
[ "binary search", "bitmasks", "flows", "greedy" ]
3,200
#include<bits/stdc++.h> using namespace std; const int K = 4; const int N = 2 * int(1e6) + 43; pair<long long, long long> operator+(const pair<long long, long long>& a, const pair<long long, long long>& b) { return make_pair(a.first + b.first, a.second + b.second); } pair<long long, long long> operator-(const ...
1862
A
Gift Carpet
Recently, Tema and Vika celebrated Family Day. Their friend Arina gave them a carpet, which can be represented as an $n \cdot m$ table of lowercase Latin letters. Vika hasn't seen the gift yet, but Tema knows what kind of carpets she likes. Vika will like the carpet if she can read her name on. She reads column by col...
Note that if the answer is <<YES>>, then there exists a reading of the word <<vika>> in which the leftmost letter <<v>> is included. Among such readings, we can also consider the one in which the leftmost letter <<i>> is included, which is located to the right of the first occurrence of <<v>>. Similarly, we can do the ...
[ "dp", "greedy", "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int q; cin >> q; while (q--) { int n, m; cin >> n >> m; vector<string> carpet(n); for (int i = 0; i < n; ++i) { cin >> carpet[i]; } string vika = "vika"; ...
1862
B
Sequence Game
Tema and Vika are playing the following game. First, Vika comes up with a sequence of positive integers $a$ of length $m$ and writes it down on a piece of paper. Then she takes a new piece of paper and writes down the sequence $b$ according to the following rule: - First, she writes down $a_1$. - Then, she writes dow...
Let's compare each pair of adjacent numbers. If the left number is smaller than the right number, then the right number is at least $2$. We will insert $1$ between them. Now, for each pair of numbers, it is true that either these two numbers were originally in the sequence, or one of them is $1$. In this case, if two n...
[ "constructive algorithms" ]
800
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int q; cin >> q; while (q--) { int n; cin >> n; vector<int> a; for (int i = 0; i < n; ++i) { int x; cin >> x; if (i && a.back() > x) { ...
1862
C
Flower City Fence
Anya lives in the Flower City. By order of the city mayor, she has to build a fence for herself. The fence consists of $n$ planks, each with a height of $a_i$ meters. According to the order, the heights of the planks must \textbf{not increase}. In other words, it is true that $a_i \ge a_j$ for all $i < j$. Anya becam...
Obviously, if $a_1 \neq n$, then this fence is not symmetric, because the fence $a$ has a length of $n$, while the horizontally laid fence has a length of $a_1 \neq n$. Now let's build a fence $b$ using horizontal boards that would match the original fence $a$. And let's check if the arrays $a$ and $b$ are equal. If th...
[ "binary search", "data structures", "implementation", "sortings" ]
1,100
#include <iostream> #include <vector> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; i++) { cin >> a[i]; } if (a[1] != n) { cout << "NO" << '\n'; ...
1862
D
Ice Cream Balls
Tema decided to improve his ice cream making skills. He has already learned how to make ice cream in a cone \textbf{using exactly two} balls. Before his ice cream obsession, Tema was interested in mathematics. Therefore, he is curious about the \textbf{minimum} number of balls he needs to have in order to make \textbf...
First, let's note that having more than two balls of the same type is meaningless. Let's denote $x$ as the number of flavours of balls represented by two instances of each ball. Let $y$ denote the number of flavours represented by a single instance. Let's calculate the number of different ways to make an ice cream from...
[ "binary search", "combinatorics", "constructive algorithms", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int q; cin >> q; while (q--) { int n; cin >> n; int l = 0, r = min<int>(2e9, 2 * n); while (r - l > 1) { int m = (l + r) >> 1; // m = x + y, answer = x + 2 * y ...
1862
E
Kolya and Movie Theatre
Recently, Kolya found out that a new movie theatre is going to be opened in his city soon, which will show a new movie every day for $n$ days. So, on the day with the number $1 \le i \le n$, the movie theatre will show the premiere of the $i$-th movie. Also, Kolya found out the schedule of the movies and assigned the e...
Let's notice that if we visit the cinema on days with numbers $i_1, i_2, \ldots, i_k$, the total entertainment value of the visited movies will be equal to $(a_{i_1} - d \cdot i_1) + (a_{i_2} - d \cdot (i_2 - i_1)) + \ldots + (a_{i_k} - d \cdot (i_k - i_{k-1})) = (a_{i_1} + a_{i_2} + \ldots + a_{i_k}) - d \cdot i_k$. T...
[ "constructive algorithms", "data structures", "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int t; cin >> t; for (int _ = 0; _ < t; ++_) { int n, m, d; cin >> n >> m >> d; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int ans = 0; ...
1862
F
Magic Will Save the World
A portal of dark forces has opened at the border of worlds, and now the whole world is under a terrible threat. To close the portal and save the world, you need to defeat $n$ monsters that emerge from the portal one after another. Only the sorceress Vika can handle this. She possesses two magical powers — water magic ...
First, let's note that Vika can defeat all the monsters at once, in the last second. There is no point in spending mana gradually. Now, let's say we know how many seconds Vika will accumulate mana before spending it. Then we also know how much mana she will have accumulated by that time. How should she spend it? Note t...
[ "binary search", "bitmasks", "brute force", "dp" ]
1,800
#include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int q; cin >> q; while (q--) { int w, f, n; cin >> w >> f >> n; vector<int> s(n); int sum_s = 0; for (int i = 0; i < n; ++i) { cin >> s[i]; sum_s += s[i]...
1862
G
The Great Equalizer
Tema bought an old device with a small screen and a worn-out inscription "The Great Equalizer" on the side. The seller said that the device needs to be given an array $a$ of integers as input, after which "The Great Equalizer" will work as follows: - Sort the current array in non-decreasing order and remove duplicate...
Let's take a look at the maximum difference between adjacent numbers in a sorted sequence. Each cycle it decreases by $1$. This helps us understand the main observation: the answer for the sequence is the maximum number in it + the maximum difference between adjacent numbers in sorted order. To answer queries, it is su...
[ "binary search", "data structures", "math", "sortings" ]
2,000
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; scanf("%d", &n); vector<int> a(n); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); } if (n == 1) { int q; scanf("%d", &q)...
1863
A
Channel
Petya is an administrator of a channel in one of the messengers. A total of $n$ people are subscribed to his channel, and Petya is not considered a subscriber. Petya has published a new post on the channel. At the moment of the publication, there were $a$ subscribers online. We assume that every subscriber always read...
Let $p$ be the total number of + signs in the notification string. If $a + p < n$, then the answer is clearly "NO". Now let's look at the current number of users online. Initially there are $a$ of them. Each notification either increases this number by $1$, or decreases it by $1$. If at some moment of time the number o...
[ "greedy", "implementation" ]
800
null
1863
B
Split Sort
You are given a permutation$^{\dagger}$ $p_1, p_2, \ldots, p_n$ of integers $1$ to $n$. You can change the current permutation by applying the following operation several (possibly, zero) times: - choose some $x$ ($2 \le x \le n$); - create a new permutation by: - first, writing down all elements of $p$ that are les...
For every $k$ such that $a_i = k$, $a_j = k + 1$ and $i > j$ we have to choose $x = k + 1$ at least once for these elements to be in the correct order. It is easy to see that if we choose all such $x = k + 1$ for all such $k$ exactly once in any order, we will get the identity permutation.
[ "greedy", "math", "sortings" ]
1,100
null
1863
C
MEX Repetition
You are given an array $a_1,a_2,\ldots, a_n$ of \textbf{pairwise distinct} integers from $0$ to $n$. Consider the following operation: - consecutively for each $i$ from $1$ to $n$ in this order, replace $a_i$ with $\operatorname{MEX}(a_1, a_2, \ldots, a_n)$. Here $\operatorname{MEX}$ of a collection of integers $c_1,...
Append the initial array $a_1, \ldots, a_n$ with $a_{n+1} = \operatorname{MEX}(a_1, \ldots, a_n)$. It is easy to see that $a_1, \ldots, a_{n+1}$ is a permutation of $0, 1, \ldots, n$. In this case setting $a_i = \operatorname{MEX}(a_1, \ldots, a_n)$ is basically equivalent $a_i = a_{n+1}$, but after this the new $\oper...
[ "implementation", "math" ]
1,100
null
1863
D
Two-Colored Dominoes
There is an $n\times m$ board divided into cells. There are also some dominoes on this board. Each domino covers two adjacent cells (that is, two cells that share a side), and no two dominoes overlap. Piet thinks that this board is too boring and it needs to be painted. He will paint the cells of the dominoes black an...
Let's consider the requirement on the rows. Clearly, all horizontal dominoes (since each of them has $1$ black and $1$ white cell) do not influence the black-white balance for the rows. Thus, we are only interested in vertical dominoes. Consider the first row and the vertical dominoes that intersect this row. Their num...
[ "constructive algorithms", "greedy" ]
1,400
null
1863
E
Speedrun
You are playing a video game. The game has $n$ quests that need to be completed. However, the $j$-th quest can only be completed at the beginning of hour $h_j$ of a game day. The game day is $k$ hours long. The hours of each game day are numbered $0, 1, \ldots, k - 1$. After the first day ends, a new one starts, and so...
First of all, assume that the first quest we complete is at the hour $x$. We can assume that $0\leq x < k$, as increasing it by $k$ just shifts all the times by $k$. In this case one can greedily find the completion times for all the quests: essentially, for every quest $v$, if we know that the quests it depends on are...
[ "brute force", "dfs and similar", "dp", "graphs", "greedy", "math", "sortings", "two pointers" ]
2,100
null
1863
F
Divide, XOR, and Conquer
You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$. In one operation you split the array into two parts: a non-empty prefix and a non-empty suffix. The value of each part is the bitwise XOR of all elements in it. Next, discard the part with the smaller value. If both parts have equal values, you can choose...
Let $s = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_r$, $x = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_k$, $y = a_{k + 1} \oplus a_{k + 2} \oplus \ldots \oplus a_{r}$. If $s$ is zero, than we can choose any $k$ and any side because $s = x \oplus y = 0 \implies x = y$. If $s$ is not zero we can choose such $k$ for th...
[ "bitmasks", "dp", "math" ]
2,600
null
1863
G
Swaps
You are given an array of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). You can perform the following operation several (possibly, zero) times: - pick an arbitrary $i$ and perform swap$(a_i, a_{a_i})$. How many distinct arrays is it possible to attain? Output the answer modulo $(10^9 + 7)$.
Consider a directed graph with $n$ vertices, where for each vertex $i$ there is an edge $i\to a_i$. This is a functional graph, that is, every vertex has exactly one edge outgoing from it. Let's see how our operations affect the graph. We will write $u\to v$ to illustrate the fact that $a_u = v$. Call the operation $\m...
[ "combinatorics", "dp", "graphs", "math" ]
2,800
null
1863
H
Goldberg Machine 3
There is a complete rooted binary tree, that is, a rooted tree in which each vertex has either $0$ or $2$ children. The root of the tree is vertex $1$. A node without children is called a leaf. Each leaf has a hunger value, we denote the hunger value of leaf $v$ by $h_v$. Each inner vertex of the tree has a selector p...
Let's consider a dynamic programming approach: for leaves, set $dp_v = a_v$, and for an internal vertex $v$ with children $u$ and $w$, set $dp_v = 2 \max(dp_u, dp_w)-[dp_u \neq dp_w]$ we use an indicator notation $[\ldots]$. Let $d_v = dp_v - 1$, then the update becomes $d_v = 2 \max(d_u, d_w) + [d_u = d_w]$. Let $h_v$...
[ "dp", "trees" ]
3,500
null
1863
I
Redundant Routes
You are given a tree with $n$ vertices labeled $1, 2, \ldots, n$. The length of a simple path in the tree is the number of vertices in it. You are to select a set of simple paths of length at least $2$ each, but you cannot simultaneously select two distinct paths contained one in another. Find the largest possible siz...
Let's call two paths adjacent if one can be obtained from the other by adding an edge to one end and removing an edge from the other end. Proposition. There exists an optimal solution in which each pair of adjacent paths is either simultaneously chosen or simultaneously not chosen. Proof. Consider an optimal solution t...
[ "constructive algorithms", "dp", "trees" ]
3,500
null
1864
A
Increasing and Decreasing
You are given three integers $x$, $y$, and $n$. Your task is to construct an array $a$ consisting of $n$ integers which satisfies the following conditions: - $a_1=x$, $a_n=y$; - $a$ is \textbf{strictly} increasing (i.e. $a_1 < a_2 < \ldots < a_n$); - if we denote $b_i=a_{i+1}-a_{i}$ for $1 \leq i \leq n-1$, then $b$ ...
We use the following greedy construction: For all $i$ ($1<i<n$), set $a_i=a_{i+1}-(n-i)$. If $a_2-a_1 \geq n-1$, we've found a solution, otherwise there is no solution. Proof. Assume there's a solution which includes an index $i$ ($1<i<n$) such that $a_{i+1}-a_i>n-i$. We can make $a_j:=a_j+\Delta$ for all $j$ ($2 \le j...
[ "constructive algorithms", "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ...
1864
B
Swap and Reverse
You are given a string $s$ of length $n$ consisting of lowercase English letters, and an integer $k$. In one step you can perform \textbf{any one} of the two operations below: - Pick an index $i$ ($1 \le i \le n - 2$) and swap $s_{i}$ and $s_{i+2}$. - Pick an index $i$ ($1 \le i \le n-k+1$) and reverse the order of le...
By the first kind of operation, we already know that every odd index (same for the even ones) can be swapped with each other freely. Therefore, let us write down the values of the indices modulo $2$. For example, if $n$ is $10$, the indices modulo $2$ are $[1,0,1,0,1,0,1,0,1,0]$. Now, we consider the two cases. When $k...
[ "constructive algorithms", "greedy", "sortings", "strings" ]
1,100
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ...
1864
C
Divisor Chain
You are given an integer $x$. Your task is to reduce $x$ to $1$. To do that, you can do the following operation: - select a divisor $d$ of $x$, then change $x$ to $x-d$, i.e. reduce $x$ by $d$. (We say that $d$ is a divisor of $x$ if $d$ is an positive integer and there exists an integer $q$ such that $x = d \cdot q$...
Let us divide the task into two steps, on each step we will use each divisor at most once. For convenience, let us denote $L$ as the largest value, such that $2^L \le x$ holds. The two steps are as follows. Reduce $x$ to $2^L$. Given any integer $x$, we can see that its lowest significant bit is a divisor of $x$. If $x...
[ "bitmasks", "constructive algorithms", "math", "number theory" ]
1,300
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; bool bit(int mask, int pos) { return (mask >> pos) & 1; } int main() { ios_...
1864
D
Matrix Cascade
There is a matrix of size $n \times n$ which consists of 0s and 1s. The rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$. AquaMoon wants to turn all elements of ...
Firstly, the first row has some elements that are $\text{1}$ s and some elements that are $\text{0}$ s. The elements that are $\text{1}$ can only be turned into $\text{0}$ by operating on the corresponding cell an odd number of times, and the elements that are $\text{0}$ can only be turned into $\text{0}$ by operating ...
[ "brute force", "constructive algorithms", "data structures", "dp", "greedy", "math" ]
1,700
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ...
1864
E
Guess Game
Carol has a sequence $s$ of $n$ non-negative integers. She wants to play the "Guess Game" with Alice and Bob. To play the game, Carol will \textbf{randomly} select two integer indices $i_a$ and $i_b$ within the range $[1, n]$, and set $a=s_{i_a}$, $b=s_{i_b}$. Please note that $i_a$ and $i_b$ may coincide. Carol will...
First, let's analize a single game for fixed $a$, $b$, and how many turns it takes. Consider the binary representation of $a \mid b$. We consider bits from highest to lowest. For bits with a value of $0$, we can ignore it because it firmly tells us that both bits of $a$ and $b$ are $0$. For convenience, we assume that ...
[ "bitmasks", "data structures", "games", "math", "probabilities", "sortings", "strings", "trees" ]
2,100
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; struct node { int to[2]; int cnt; node() { to[0] = to[1] = -1; ...
1864
F
Exotic Queries
AquaMoon gives RiverHamster a sequence of integers $a_1,a_2,\dots,a_n$, and RiverHamster gives you $q$ queries. Each query is expressed by two integers $l$ and $r$. For each query independently, you can take any continuous segment of the sequence and subtract an identical non-negative value from all the numbers of thi...
The final solution is irrelevant to Cartesian trees. First, we consider only the sequence of elements to be manipulated. We claim that it is optimal to operate on the whole sequence so that the minimum elements are all decreased to $0$, and then solve the problem on the segments separated by the $0$s recursively. A str...
[ "data structures", "implementation", "sortings" ]
2,300
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; vector<int> sum; int N; void updSumTree(int pos) { for (pos += N; pos; pos >>= 1...
1864
G
Magic Square
Aquamoon has a Rubik's Square which can be seen as an $n \times n$ matrix, the elements of the matrix constitute a permutation of numbers $1, \ldots, n^2$. Aquamoon can perform two operations on the matrix: - Row shift, i.e. shift an entire row of the matrix several positions (at least $1$ and at most $n-1$) to the r...
Theorem 1: After a row shift, all numbers moved are in the correct column. Proof 1: Suppose a number moved after a row shift is not in the correct column, if it is not in the correct row, it needs at least two more moves to its target position, otherwise it needs at least three more moves because the row cannot be shif...
[ "combinatorics", "constructive algorithms", "implementation" ]
3,100
#include <bits/stdc++.h> #define all(a) (a).begin(), (a).end() #define sz(a) (int)(a).size() #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; const int mod = 998244353; const int nmax = 600; int fact[nmax]; int main() { i...
1864
H
Asterism Stream
Bogocubic is playing a game with amenotiomoi. First, Bogocubic fixed an integer $n$, and then he gave amenotiomoi an integer $x$ which is initially equal to $1$. In one move amenotiomoi performs \textbf{one} of the following operations with the same probability: - increase $x$ by $1$; - multiply $x$ by $2$. Bogocubi...
Here is a basic $\Theta(n)$ dp solution. Before that let $k = \frac{1}{2}$. At the same time, because a special geometric sequence $f(x)=ak^{bx}$ will be frequently used next, it is defined as $\{a,b\}$. Let $f(x)$ be the expected number of moves needed if we start with $x$. Obviously, there is the following formula: $...
[ "dp", "math", "matrices" ]
3,200
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast", "inline", "-ffast-math") #pragma GCC target("avx,sse2,sse3,sse4,mmx") #define int long long const int MOD = 998244353; int n, k; long long power(int x, int p) { if (p < 0) return power(power(x, MOD - 2), -p); int answer = 1; ...
1864
I
Future Dominators
Dhruvil and amenotiomoi are sitting in different countries and chatting online. Initially, amenotiomoi has an empty board of size $n \times n$, and Dhruvil has a sequence of integers $1, 2, \ldots, n^2$, each number occurring exactly once. The numbers may be placed in the cells of the board, each cell is either empty o...
This problem is based on a method of online edge deletion and querying connectivity of a planar graph. Firstly, if this vertex is not an articulation point, it will not cause any change in connectivity. Therefore, the algorithm needs to determine whether a certain vertex is an articulation point. Thinking about using a...
[ "graphs", "greedy" ]
3,500
#include<bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast","inline","-ffast-math") #pragma GCC target("avx,sse2,sse3,sse4,mmx") struct node { int mx,sz;bool bg; pair<int,int> mn; vector<node*> cp; void cln(){for(node* i:cp)i->cp.erase(find(i->cp.begin(),i->cp.end(),this));cp.clear();} void...
1866
A
Ambitious Kid
Chaneka, Pak Chanek's child, is an ambitious kid, so Pak Chanek gives her the following problem to test her ambition. Given an array of integers $[A_1, A_2, A_3, \ldots, A_N]$. In one operation, Chaneka can choose one element, then increase or decrease the element's value by $1$. Chaneka can do that operation multiple...
In order to have the product of all elements be $0$, at least one element must be $0$. For each element $A_i$, the minimum number of operations to turn it into $0$ is $|A_i|$. Therefore, the minimum number of operations to turn at least one element into $0$ is the minimum value of $|A_i|$ out of all elements. Time comp...
[ "math" ]
800
null
1866
B
Battling with Numbers
On the trip to campus during the mid semester exam period, Chaneka thinks of two positive integers $X$ and $Y$. Since the two integers can be very big, both are represented using their prime factorisations, such that: - $X=A_1^{B_1}\times A_2^{B_2}\times\ldots\times A_N^{B_N}$ (each $A_i$ is prime, each $B_i$ is posit...
For a prime $k$, let $f_k(w)$ be the exponent of $k$ in the factorisation of $w$. In particular, if the factorisation of $w$ does not contain $k$, then $f_k(w)=0$. We can obtain that for any prime $k$, it holds that: $f_k(X)=f_k(\text{LCM}(p,q))=\max(f_k(p),f_k(q))$ $f_k(Y)=f_k(\text{GCD}(p,q))=\min(f_k(p),f_k(q))$ For...
[ "combinatorics", "math", "number theory" ]
1,400
null
1866
C
Completely Searching for Inversions
Pak Chanek has a directed acyclic graph (a directed graph that does not have any cycles) containing $N$ vertices. Vertex $i$ has $S_i$ edges directed away from that vertex. The $j$-th edge of vertex $i$ that is directed away from it, is directed towards vertex $L_{i,j}$ and has an integer $W_{i,j}$ ($0\leq W_{i,j}\leq1...
Note that during the entire process, each time we do dfs(x) for the same value of $x$, the sequence of values appended to the end of $Z$ is always the same. So, for each vertex $x$, we want to obtain some properties about the sequence of values that will be appended if we do dfs(x). Since we want to calculate the numbe...
[ "dfs and similar", "dp", "graphs" ]
1,900
null
1866
D
Digital Wallet
There are $N$ arrays, each array has $M$ positive integer elements The $j$-th element of the $i$-th array is $A_{i,j}$. Initially, Chaneka's digital wallet contains $0$ money. Given an integer $K$. Chaneka will do $M-K+1$ operations. In the $p$-th operation, Chaneka does the following procedure: - Choose any array. L...
First, notice that since the initial value of all elements are positive, it is always optimal to always choose an element that has not been chosen before in each operation. Let's look at the $N$ arrays as a grid of $N$ rows and $M$ columns. We can solve this problem by iterating each column from left to right and using...
[ "dp", "greedy" ]
2,300
null
1866
E
Elevators of Tamem
There is a building named Taman Membeku (shortened as Tamem). The building has $N$ floors numbered from $1$ to $N$ from bottom to top. The only way to move between floors in the building is to use elevators. There are $3$ elevators available in Tamem, namely elevators $1$, $2$, and $3$. Pak Chanek works as an elevator...
First, let's solve the problem if there are no events of type $2$. We can solve this problem using dynamic programming. First, define: $\text{enter}[e]$: the initial floor of the person in the $e$-th event. $\text{exit}[e]$: the desired floor of the person in the $e$-th event. Then, define $\text{dp}[i][j][k]$ as the m...
[ "dp" ]
2,700
null
1866
F
Freak Joker Process
After the success of the basketball teams formed and trained by Pak Chanek last year (Basketball Together), Pak Chanek wants to measure the performance of each player that is considered as a superstar. There are $N$ superstar players that have been trained by Pak Chanek. At the end of the season, some calculations wil...
We can solve this problem using square root decomposition. First we group the events into $\sqrt Q$ blocks of sizes $\sqrt Q$ and solve for each block independently. For the start of each block, we can calculate all values of $A$ and $B$ easily. Additionally, we can calculate: $\text{biggerA}[x]$: the number of values ...
[ "binary search", "data structures", "sortings" ]
3,100
null
1866
G
Grouped Carriages
Pak Chanek observes that the carriages of a train is always full on morning departure hours and afternoon departure hours. Therefore, the balance between carriages is needed so that it is not too crowded in only a few carriages. A train contains $N$ carriages that are numbered from $1$ to $N$ from left to right. Carri...
Suppose we set the maximum number of passengers in the same carriage to be at most $Z$. If there is a valid strategy to fit the constraint, doing the same strategy for every maximum number of passengers in the same carriage that is greater than $Z$ is also possible. Hence, we can try to find the answer by doing binary ...
[ "binary search", "data structures", "dp", "flows", "greedy" ]
2,100
null
1866
H
Happy Sets
Define a set $A$ as a child of set $B$ if and only if for each element of value $x$ that is in $A$, there exists an element of value $x+1$ that is in $B$. Given integers $N$ and $K$. In order to make Chaneka happy, you must find the number of different arrays containing $N$ sets $[S_1, S_2, S_3, \ldots, S_N]$ such tha...
First, consider all possible arrays $S'$ (the array of sets after rearranging). For each valid $S'$, we want to find the number of ways to shuffle it. The answer to the original problem is equal to the sum of ways to shuffle each possible $S'$, since for each shuffled $S'$ it can be shown that there is only one way to ...
[ "combinatorics" ]
2,100
null
1866
I
Imagination Castle
Given a chessboard of size $N \times M$ ($N$ rows and $M$ columns). Each row is numbered from $1$ to $N$ from top to bottom and each column is numbered from $1$ to $M$ from left to right. The tile in row $r$ and column $c$ is denoted as $(r,c)$. There exists $K$ distinct special tiles on the chessboard with the $i$-th ...
Define a winning tile as a tile where if a player starts a turn with the castle in that tile, she will have a strategy to win. Define a losing tile as a tile where if a player starts a turn with the castle in that tile, no matter what she does, the other player will always have a strategy to win. We can see each specia...
[ "dp", "games", "two pointers" ]
2,300
null
1866
J
Jackets and Packets
Pak Chanek has $N$ jackets that are stored in a wardrobe. Pak Chanek's wardrobe has enough room for two stacks of jackets, namely the left stack and the right stack. Initially, all $N$ jackets are in the left stack, while the right stack is empty. Initially, the $i$-th jacket from the top of the left stack has colour $...
Instead of looking at the two stacks as two separate arrays, consider them as a single array $A$ whose elements are the colours of the jackets in the right stack from bottom to top, then the colours of the jackets in the left stack from top to bottom. Also maintain a pointer that indicates the separation point between ...
[ "dp" ]
2,800
null
1866
K
Keen Tree Calculation
There is a tree of $N$ vertices and $N-1$ edges. The $i$-th edge connects vertices $U_i$ and $V_i$ and has a length of $W_i$. Chaneka, the owner of the tree, asks you $Q$ times. For the $j$-th question, the following is the question format: - $X_j$ $K_j$ – If each edge that contains vertex $X_j$ has its length multip...
First, calculate the diameter of the initial tree. For a question involving some vertex $p$. There are only two cases to consider: The diameter is the same as the diameter of the initial tree. The diameter goes through vertex $p$. If the diameter goes through vertex $p$, then the diameter consists of two paths, each of...
[ "binary search", "data structures", "dp", "geometry", "graphs", "implementation", "trees" ]
2,500
null
1866
L
Lihmuf Balling
After working at a factory (Lihmuf Sorting), Lihmuf wants to play a game with his good friend, Pak Chanek. There are $N$ boxes numbered from $1$ to $N$. The $i$-th box contains $i$ balls. Pak Chanek and Lihmuf will play a game using those boxes. There will be $N$ turns numbered from $1$ to $N$. On each turn, Pak Chane...
To solve this, we just need to find the total number of balls Lihmuf will earn for each possible value of $K$ from $1$ to $M$. If $K=1$, then Lihmuf gets $0$ balls. If $K>1$ and $K$ is a factor of $N$, then Lihmuf will get all balls in the boxes with indices that are multiples of $K$. If $K$ is not coprime to $N$, then...
[ "binary search", "brute force", "math" ]
2,400
null
1866
M
Mighty Rock Tower
Pak Chanek comes up with an idea in the midst of boredom to play a game. The game is a rock tower game. There is a big rock that is used as a base. There are also $N$ small identical rocks that Pak Chanek will use to build a rock tower with a height of $N$ above the base rock. Initially, there are no small rocks that ...
Let $f(x)$ be the the expected number of moves to turn a tower of height $x-1$ into $x$. In order to calculate that, let's say the tower's current height is $x-1$ and we want to make it into $x$. If we place one small rock, then the following cases can happen: With a probability of $(P_x\%)^k(1-P_x\%)$, exactly $k$ roc...
[ "brute force", "combinatorics", "dp", "math", "probabilities" ]
2,400
null
1867
A
green_gold_dog, array and permutation
green_gold_dog has an array $a$ of length $n$, and he wants to find a permutation $b$ of length $n$ such that the number of distinct numbers in the element-wise difference between array $a$ and permutation $b$ is maximized. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in ...
Let's subtract $n$ from the minimum number, subtract $n - 1$ from the second minimum, $n - 2$ from the third $\ldots$, and subtract $1$ from the maximum. Then the number of distinct elements will be $n$. Obviously, it is impossible to achieve a better result. Let's prove that the number of distinct elements will be equ...
[ "constructive algorithms", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { ll n; cin >> n; vector<pair<ll, ll>> arr(n); for (ll i = 0; i < n; i++) { ll x; cin >> x; arr[i].first = x; arr[i].second = i; } vector<ll> ans(n); sort(arr.begin(), arr.end()); reverse(arr.begin(),arr.end()); for (ll...
1867
B
XOR Palindromes
You are given a binary string $s$ of length $n$ (a string that consists only of $0$ and $1$). A number $x$ is good if there exists a binary string $l$ of length $n$, containing $x$ ones, such that if each symbol $s_i$ is replaced by $s_i \oplus l_i$ (where $\oplus$ denotes the bitwise XOR operation), then the string $s...
Firstly, a string is a palindrome if and only if for any $i$ ($1 \leq i \leq n$) $s_i = s_{n-i+1}$ (because when reversed, $s_i$ becomes $s_{n-i+1}$). We can divide the characters into pairs, where each pair consists of $s_i$ and $s_{n-i+1}$. If $s_i = s_{n-i+1}$, then we need to have $l_i = l_{n-i+1}$ in order to obta...
[ "bitmasks", "constructive algorithms", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int n; cin >> n; string s; cin >> s; string t(n+1,'0'); int ans = 0; int max_1 = 0; int max_2 =...
1867
C
Salyg1n and the MEX Game
\textbf{This is an interactive problem!} salyg1n gave Alice a set $S$ of $n$ distinct integers $s_1, s_2, \ldots, s_n$ ($0 \leq s_i \leq 10^9$). Alice decided to play a game with this set against Bob. The rules of the game are as follows: - Players take turns, with Alice going first. - In one move, Alice adds one num...
The correct strategy for Alice is to add the number $\operatorname{MEX}(S)$ to the set $S$ on the first move, and add the last removed number on the remaining moves. Let m = $\operatorname{MEX}(S \cup {\operatorname{MEX}(S)})$, at the start of the game. In other words, m is equal to the second $\operatorname{MEX}$ of t...
[ "constructive algorithms", "data structures", "games", "greedy", "interactive" ]
1,300
#include <iostream> #include <vector> using namespace std; void solve() { int n; cin >> n; vector<int> s(n); for (int i = 0; i < n; ++i) cin >> s[i]; int mex = -1; for (int i = 0; i < n; ++i) { if (i == 0 && s[i] != 0) { mex = 0; break; } if (i > 0 && s[i] != s[i - 1] + 1) { mex = s[i - 1] + 1;...
1867
D
Cyclic Operations
Egor has an array $a$ of length $n$, initially consisting of zeros. However, he wanted to turn it into another array $b$ of length $n$. Since Egor doesn't take easy paths, only the following operation can be used (possibly zero or several times): - choose an array $l$ of length $k$ ($1 \leq l_i \leq n$, all $l_i$ are...
If $k = 1$, then we can change $b_i$ to $i$, so the answer is YES only if $b_i = i$, otherwise the answer is NO. Otherwise, let's build an undirected graph with $n$ vertices and edges ($i, b_i$). Any component of this graph will look like a cycle (possibly of size $1$) to each vertex of which a tree is attached (possib...
[ "brute force", "constructive algorithms", "dfs and similar", "graphs", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--) { int n,k; cin >> n >> k; int b[n]; int vis[n]; for(int j = 0;j < n;++j) { cin >> b[j]; v...
1867
E1
Salyg1n and Array (simple version)
\textbf{This is the simple version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 100 queries. You can make hacks only if both versions of the problem are solved.} \textbf{This is an interactive problem!} salyg1n has given you...
Let's make queries to subarrays starting at positions $1$, $k + 1$, $2k + 1$, $\ldots$ $m \cdot k + 1$, as long as these queries are valid, meaning their right boundary does not exceed $n$. Let's save the $\operatorname{XOR}$ of all the answers to these queries. We will call these queries primary. Now, we will shift th...
[ "constructive algorithms", "interactive", "math" ]
2,000
#include <iostream> using namespace std; int ask(int i) { cout << "? " << i << endl; int x; cin >> x; return x; } void solve() { int n, k; cin >> n >> k; int res = 0; int i; for (i = 1; i + k - 1 <= n; i += k) res ^= ask(i); for (; i <= n; ++i) res ^= ask(i - k + 1); cout << "! " << res << endl;...
1867
E2
Salyg1n and Array (hard version)
\textbf{This is the hard version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 57 queries. You can make hacks only if both versions of the problem are solved.} \textbf{This is an interactive problem!} salyg1n has given you a ...
Let's make queries to subarrays starting at positions $1$, $k + 1$, $2k + 1$, $\ldots$ $m \cdot k + 1$, such that the size of the uncovered part is greater than $2 \cdot k$ and not greater than $3 \cdot k$. In other words, $2 \cdot k < n - (m + 1) \cdot k \le 3 \cdot k$. Let's keep the $\operatorname{XOR}$ of all the a...
[ "constructive algorithms", "interactive" ]
2,200
#include <iostream> using namespace std; int ask(int i) { cout << "? " << i << endl; int x; cin >> x; return x; } void solve() { int n, k; cin >> n >> k; int res = 0; int i; for (i = 1; n - i + 1 >= 2 * k; i += k) res ^= ask(i); if (n - i + 1 == k) { res ^= ask(i); cout << "! " << res << endl; retu...
1867
F
Most Different Tree
Given a tree with $n$ vertices rooted at vertex $1$, denote it as $G$. Also denote $P(G)$ as the multiset of subtrees of all vertices in tree $G$. You need to find a tree $G'$ of size $n$ rooted at vertex $1$ such that the number of subtrees in $P(G')$ that are isomorphic to any subtree in $P(G)$ is minimized. A subtr...
Here we say that the answer for tree $G'$ is the number of subtrees in $P(G')$ that have an isomorphic subtree in $P(G)$. Let's find a tree $T$ of minimum size that has no isomorphic tree in $P(G)$. Let the size of tree $T$ be $x$. Then take a chain of size $n - x$, and let the root of $T$ be the kid of the last vertex...
[ "brute force", "constructive algorithms", "dfs and similar", "greedy", "hashing" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MAXSZ = 15; void rec(int ns, int last, vector<int>& now, vector<vector<int>>& aint, vector<int>& col, vector<int>& sz, int& ss, int sns) { if (ss < 0) { return; } if (ns == 0) { col.back()++; aint.push_back(now); ss -= sns; return; } ...
1868
A
Fill in the Matrix
There is an empty matrix $M$ of size $n\times m$. Zhongkao examination is over, and Daniel would like to do some puzzle games. He is going to fill in the matrix $M$ using permutations of length $m$. That is, each row of $M$ must be a permutation of length $m^\dagger$. Define the value of the $i$-th column in $M$ as $...
On one hand, the matrix $M$ has $n$ rows, so the maxmium $v_i$ does not exceed $\operatorname{MEX}(0,1,\cdots,n-1)=n$, and $s$ does not exceed $n+1$. On the other hand, the matrix $M$ has $m$ columns, and there are only $m$ numbers in the array $v$, so $s$ must not exceed $m$. Therefore, the upper bound of $s$ is $\min...
[ "constructive algorithms", "implementation" ]
1,300
#include <bits/stdc++.h> #define all(s) s.begin(), s.end() using namespace std; using ll = long long; using ull = unsigned long long; const int _N = 1e5 + 5; int T; void solve() { int n, m; cin >> n >> m; if (m == 1) cout << 0 << '\n'; else if (n > m - 1) cout << m << '\n'; else cout << n + 1 << '\n'; for (int...
1868
B1
Candy Party (Easy Version)
{This is the easy version of the problem. The only difference is that in this version everyone must give candies to \textbf{exactly one} person and receive candies from \textbf{exactly one} person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions...
Denote $s$ as $\frac{1}{n}\sum_{i=1}^n a_i$. If $s$ is not an integer, then it will be impossible to make all people have the same number of candies, so the answer is "No". Since a person gives candies to and receives candies from exactly one person, suppose he gives away $2^x$ candies and receives $2^y$ candies, then ...
[ "bitmasks", "constructive algorithms", "graphs", "greedy", "implementation", "math" ]
1,700
#include <bits/stdc++.h> #define all(s) s.begin(), s.end() using namespace std; using ll = long long; using ull = unsigned long long; const int _N = 1e5 + 5; int T; void solve() { int n; cin >> n; vector<ll> a(n); ll sum = 0; for (int i = 0; i < n; i++) cin >> a[i], sum += a[i]; if (sum % n) return cout << "No" ...
1868
B2
Candy Party (Hard Version)
{This is the hard version of the problem. The only difference is that in this version everyone must give candies to \textbf{no more than one} person and receive candies from \textbf{no more than one} person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if bot...
Read the tutorial for D1 first. Consider the graph we built in this version. It should only consist of chains and cycles. For the start nodes of chains and the end nodes of chains, $|a_i-s|=2^d$ must hold. Thus, for $|a_i-s|\ne 2^d$, we sill have only one way to decide the number of candies given away and received (the...
[ "bitmasks", "constructive algorithms", "dp", "greedy", "implementation", "math" ]
2,100
#include <bits/stdc++.h> #define all(s) s.begin(), s.end() using namespace std; using ll = long long; using ull = unsigned long long; const int _N = 1e5 + 5; int T; void solve() { int n; cin >> n; vector<ll> a(n); ll sum = 0; for (int i = 0; i < n; i++) cin >> a[i], sum += a[i]; if (sum % n) return cout << "No" ...
1868
C
Travel Plan
During the summer vacation after Zhongkao examination, Tom and Daniel are planning to go traveling. There are $n$ cities in their country, numbered from $1$ to $n$. And the traffic system in the country is very special. For each city $i$ ($1 \le i \le n$), there is - a road between city $i$ and $2i$, if $2i\le n$; - ...
For any path of length $t$, the number of assignments in which the maximum value of cities is no bigger than $k$ is $k^t$. As a result, the number of assignments in which the maximum value of cities is exactly $k$ is $k^t-(k-1)^t$, while the sum of the maximum value of cities in all assignments is $\sum_{k=1}^m(k^t-(k-...
[ "combinatorics", "dp", "implementation", "math", "trees" ]
2,400
#include <bits/stdc++.h> #define rep(i,n) for(int i=0,_##i##__end=(n);i<_##i##__end;++i) #define rep1(i,n) for(int i=1,_##i##__end=(n);i<=_##i##__end;++i) #define mp make_pair #define fi first #define se second typedef long long ll; using namespace std; const ll mod1=998244353; int t; ll n; int m; ll qkpw(ll a,ll b) { ...
1868
D
Flower-like Pseudotree
A pseudotree is a connected graph which has \textbf{exactly one} cycle and \textbf{no} self-loops. Note that a pseudotree \textbf{may contain multiple-edges}. It can be shown that a pseudotree with $n$ vertices always contains $n$ edges. After deleting all edges on the cycle in the pseudotree, a forest$^{\dagger}$ wil...
If $\sum_{i=1}^n d_i\neq 2n$, it's obviously impossible to construct a flower-like psuedotree. So let's just consider the situation when $\sum_{i=1}^n d_i=2n$. Sort $d_i$ from largest to smallest. If $d_1=d_2=\dots=d_n=2$, we can simply construct a cycle. Otherwise $d_1>2$, in which case there must be at least two $d_i...
[ "constructive algorithms", "graphs", "greedy", "implementation", "trees" ]
3,000
#include <bits/stdc++.h> #define int long long #define double long double using namespace std; struct node{ int d,pos; }a[1000005]; bool cmp(node x,node y){ return x.d>y.d; } void pe(int x,int y){ cout<<a[x].pos<<" "<<a[y].pos<<"\n"; } signed main(){ ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int t; cin...
1868
E
Min-Sum-Max
Tom is waiting for his results of Zhongkao examination. To ease the tense atmosphere, his friend, Daniel, decided to play a game with him. This game is called "Divide the Array". The game is about the array $a$ consisting of $n$ integers. Denote $[l,r]$ as the subsegment consisting of integers $a_l,a_{l+1},\ldots,a_r$...
Let $s$ be the suffix sum array of array $a$. That is, $s_i=\sum_{j=1}^ia_i$ and $s_0=0$. Let the partition point of the array be $r_0,r_1,\dots,r_m$, where $r_0=0$ and $r_m=n$. Pick one of the maximums of $s_{r_0},s_{r_1},\dots,s_{r_m}$ and let it be $s_{r_x}$. Similarly, let the minimum be $s_{r_y}$. If $|x-y|\geq 2$...
[ "constructive algorithms", "dp", "greedy" ]
3,500
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <set> #include <map> #include <math.h> #include <iomanip> #include <bitset> #include <random> #include <ctime> #include <string_view> #include <queue> #include <cassert> using namespace std; #define fi first #define se second #defin...
1868
F
LIS?
Entering senior high school life, Tom is attracted by LIS problems, not only the Longest Increasing Subsequence problem, but also the Largest Interval Sum problem. Now he gets a really interesting problem from his friend Daniel. However, it seems too hard for him to solve it, so he asks you for help. Given an array $a...
Call an interval candidate good if and only if it has no prefixes or suffixes with sum $<0$. For a candidate good interval $[l,r]$, if there is no $l'<l$ or $r'>r$ such that $[l',r]$, $[l,r']$ or $[l',r']$ is also a candidate good interval, we call it good interval. It's easy to show that all intervals which satisfy th...
[ "data structures", "greedy", "implementation" ]
3,500
/* hmz is cute! -------------------------------------------- You've got to have faith Don't let them cut you down cut you down once more */ //#pragma GCC optimize("Ofast,no-stack-protector") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include<bits/stdc++.h> using namespace s...
1869
A
Make It Zero
During Zhongkao examination, Reycloer met an interesting problem, but he cannot come up with a solution immediately. Time is running out! Please help him. Initially, you are given an array $a$ consisting of $n \ge 2$ integers, and you want to change all elements in it to $0$. In one operation, you select two indices ...
Note that $\underbrace{x\oplus x\oplus \cdots\oplus x}_{\text{even times}}=0,$ So if $r-l+1$ is even, after performing the operation on $[l,r]$ twice, the subarray $a[l;r]$ will all become $0$. When $n$ is even, we can perform the operation on $[1,n]$ twice. When $n$ is odd, we can perform the operation on $[1,n-1]$ tw...
[ "constructive algorithms" ]
900
#include <bits/stdc++.h> #define all(s) s.begin(), s.end() using namespace std; using ll = long long; using ull = unsigned long long; const int _N = 1e5 + 5; int T; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; if (n & 1) { cout << "4" << '\n'; cout << "1 " << n -...
1869
B
2D Traveling
Piggy lives on an infinite plane with the Cartesian coordinate system on it. There are $n$ cities on the plane, numbered from $1$ to $n$, and the first $k$ cities are defined as major cities. The coordinates of the $i$-th city are $(x_i,y_i)$. Piggy, as a well-experienced traveller, wants to have a relaxing trip afte...
First of all, it's easy to see that if there are no major cities, the minimum value of the total cost should be $|x_a-x_b|+|y_a-y_b|$ - the optimal choice is to fly directly from city $a$ to city $b$. Claim. Piggy will pass through a maximum of $2$ major cities. Proof. If he passes through $3$ or more major cities in a...
[ "geometry", "math", "shortest paths", "sortings" ]
1,100
#include <bits/stdc++.h> #define all(s) s.begin(), s.end() using namespace std; using ll = long long; using ull = unsigned long long; const int _N = 1e5 + 5; int T; void solve() { int n, k, s, t; cin >> n >> k >> s >> t; vector<int> x(n + 1), y(n + 1); for (int i = 1; i <= n; i++) cin >> x[i] >> y[i]; ll ans = l...
1870
A
MEXanized Array
You are given three non-negative integers $n$, $k$, and $x$. Find the maximum possible sum of elements in an array consisting of non-negative integers, which has $n$ elements, its MEX is equal to $k$, and all its elements do not exceed $x$. If such an array does not exist, output $-1$. The MEX (minimum excluded) of an...
Note that if $min(n, x+1) < k$, then the answer is $-1$. Otherwise, there are two cases: If $k=x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, \dots, k-1]$. If $k=x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, \dots, k-1]$. If $k \ne x$, then the suitable array looks like $[0, 1, 2, \dots, ...
[ "constructive algorithms", "greedy", "math" ]
800
null
1870
B
Friendly Arrays
You are given two arrays of integers — $a_1, \ldots, a_n$ of length $n$, and $b_1, \ldots, b_m$ of length $m$. You can choose any element $b_j$ from array $b$ ($1 \leq j \leq m$), and for \textbf{all} $1 \leq i \leq n$ perform $a_i = a_i | b_j$. You can perform any number of such operations. After all the operations, ...
Note that after performing the operation on $b_j$, which has some bit set to 1, this bit will become 1 for all numbers in $a$ (and will remain so, as a bit cannot change from 1 to 0 in the result of an OR operation). If $n$ is even, then in the final XOR, this bit will become 0, as it will be equal to the XOR of an eve...
[ "bitmasks", "greedy", "math" ]
1,200
null
1870
C
Colorful Table
You are given two integers $n$ and $k$. You are also given an array of integers $a_1, a_2, \ldots, a_n$ of size $n$. It is known that for all $1 \leq i \leq n$, $1 \leq a_i \leq k$. Define a two-dimensional array $b$ of size $n \times n$ as follows: $b_{i, j} = \min(a_i, a_j)$. Represent array $b$ as a square, where t...
Let's fix the color $x$ for which we will calculate the answer. If there is no $a_i = x$, then there will be no cells of color $x$, and the answer is $0$. Otherwise, there is at least one cell of color $x$. To find the minimum rectangle containing all cells of this color, we need to find the topmost, bottommost, leftmo...
[ "binary search", "data structures", "dp", "implementation", "math", "two pointers" ]
1,300
null
1870
D
Prefix Purchase
You have an array $a$ of size $n$, initially filled with zeros ($a_1 = a_2 = \ldots = a_n = 0$). You also have an array of integers $c$ of size $n$. Initially, you have $k$ coins. By paying $c_i$ coins, you can add $1$ to all elements of the array $a$ from the first to the $i$-th element ($a_j \mathrel{+}= 1$ for all ...
Note that if there is a prefix for which there is a longer prefix that costs less, then it is useless to buy the shorter prefix. All its purchases can be replaced with purchases of the longer prefix, and the answer will only improve. Therefore, we can replace each $c_i$ with the minimum $c_j$ among $i \leq j \leq n$ (t...
[ "greedy", "implementation", "sortings" ]
1,800
null
1870
E
Another MEX Problem
You are given an array of integers $a$ of size $n$. You can choose a set of non-overlapping subarrays of the given array (note that some elements may be not included in any subarray, this is allowed). For each selected subarray, calculate the MEX of its elements, and then calculate the bitwise XOR of all the obtained M...
Let's solve the problem using dynamic programming, let's store $dp[i][j]$ such that $dp[i][j]=1$ if it is possible to obtain an $XOR$ of $MEX$ values from the prefix up to $i$ (excluding $i$) equal to $j$, and $0$ otherwise. Notice that the answer cannot be greater than $n$. Therefore, the size of this two-dimensional ...
[ "bitmasks", "brute force", "dp", "shortest paths" ]
2,300
null
1870
F
Lazy Numbers
You are given positive integers $n$ and $k$. For each number from $1$ to $n$, we write its representation in the number system with base $k$ (without leading zeros) and then sort the resulting array in lexicographic order as strings. In the sorted array, we number the elements from $1$ to $n$ (i.e., indexing starts fro...
Let's store all the number entries in a trie. Consider two traversals of this trie - depth-first search (DFS) and breadth-first search (BFS). In both traversals, we go to the children of a node in ascending order of the number on the edge (in the trie). Let the index of the node representing the number $x$ in the DFS t...
[ "binary search", "math" ]
2,900
null
1870
G
MEXanization
Let's define $f(S)$. Let $S$ be a multiset (i.e., it can contain repeated elements) of non-negative integers. In one operation, you can choose any non-empty subset of $S$ (which can also contain repeated elements), remove this subset (all elements in it) from $S$, and add the MEX of the removed subset to $S$. You can p...
Let's start by introducing a more convenient way to store numbers - an array $cnt$, where $cnt[x]$ represents the number of occurrences of $x$ in the prefix for which we are finding the answer. All $x$ such that $x > n$ will be added to $cnt[0]$ because applying the operation to ${x}$ in such cases is optimal. Let's in...
[ "data structures" ]
3,300
null
1870
H
Standard Graph Problem
You are given a weighted directed graph with $n$ vertices and $m$ edges. Each vertex in the graph can be either highlighted or normal. Initially, all vertices are normal. The cost of the graph is defined as the minimum sum of edge weights that need to be selected so that from each normal vertex one can reach at least o...
Let's unfold all the edges, now we need to ensure that all regular vertices are reachable from the selected vertices. First, you should familiarize yourself with the algorithm for finding the ordered minimum spanning tree, also known as the Edmonds' algorithm (I will refer to his work here and without knowledge of it, ...
[ "data structures", "graphs", "greedy", "trees" ]
3,500
null
1872
A
Two Vessels
You have two vessels with water. The first vessel contains $a$ grams of water, and the second vessel contains $b$ grams of water. Both vessels are very large and can hold any amount of water. You also have an empty cup that can hold \textbf{up to} $c$ grams of water. In one move, you can scoop \textbf{up to} $c$ gram...
Let $d = a - b$, the difference in masses of water in the vessels. Our goal is to make $d$ equal to $0$. Note that with one pouring, we can add any number from the range $[-2 \cdot c; 2 \cdot c]$ to $d$. Therefore, the answer to the problem will be $\lceil \frac{|d|}{2 \cdot c} \rceil$.
[ "brute force", "greedy", "math" ]
800
for _ in range(int(input())): a, b, c = map(int, input().split()) print((abs(a - b) + 2 * c - 1) // (2 * c))
1872
B
The Corridor or There and Back Again
You are in a corridor that extends infinitely to the right, divided into square rooms. You start in room $1$, proceed to room $k$, and then return to room $1$. You can choose the value of $k$. Moving to an adjacent room takes $1$ second. Additionally, there are $n$ traps in the corridor: the $i$-th trap is located in ...
Let's see when we can reach room $k$ and return back. In this case, the time difference between entering and exiting room $1 \le x \le k$ is equal to $2 \cdot (k - x)$. Therefore, it is necessary for all traps to satisfy: $s_i > 2 \cdot (k - d_i)$. Now we need to find the maximum $k$ that satisfies these conditions. To...
[ "greedy", "implementation" ]
900
for _ in range(int(input())): n = int(input()) ans = 2 * 10 ** 9 for i in range(n): d, s = map(int, input().split()) ans = min(ans, d + (s - 1) // 2) print(ans)
1872
C
Non-coprime Split
You are given two integers $l \le r$. You need to find \textbf{positive} integers $a$ and $b$ such that the following conditions are simultaneously satisfied: - $l \le a + b \le r$ - $\gcd(a, b) \neq 1$ or report that they do not exist. $\gcd(a, b)$ denotes the greatest common divisor of numbers $a$ and $b$. For exa...
To begin with, let's learn how to solve the problem when $l = r$. In other words, we need to find a value $1 \le a < l$ such that $\gcd(a, l - a) \neq 1$. Notice that $\gcd(a, l - a) = \gcd(a, l)$. Then it is easy to see that if $l$ is prime, then $\gcd(a, l) = 1$ for any $1 \le a < l$, otherwise any divisor of $l$ (ex...
[ "math", "number theory" ]
1,100
def min_divisor(n): for d in range(2, round(n ** 0.5) + 1): if n % d == 0: return d return n for _ in range(int(input())): l, r = map(int, input().split()) for x in range(l, r + 1): md = min_divisor(x) if md != x: print(md, x - md) break ...
1872
D
Plus Minus Permutation
You are given $3$ integers — $n$, $x$, $y$. Let's call the score of a permutation$^\dagger$ $p_1, \ldots, p_n$ the following value: $$(p_{1 \cdot x} + p_{2 \cdot x} + \ldots + p_{\lfloor \frac{n}{x} \rfloor \cdot x}) - (p_{1 \cdot y} + p_{2 \cdot y} + \ldots + p_{\lfloor \frac{n}{y} \rfloor \cdot y})$$ In other words...
Let's call a number red if it is divisible by $x$. Let's call a number blue if it is divisible by $y$. Let's call a number purple if it is both red and blue at the same time. The score of a permutation, by definition, is the sum of $p_i$ for all red numbers $i$ from $1$ to $n$, minus the sum of $p_i$ for all blue numbe...
[ "math" ]
1,200
from math import gcd def lcm(a, b): return a * b // gcd(a, b) def range_sum(l, r): if l > r: return 0 return (l + r) * (r - l + 1) // 2 for _ in range(int(input())): n, x, y = map(int, input().split()) l = lcm(x, y) plus = n // x - n // l minus = n // y - n // l print...
1872
E
Data Structures Fan
You are given an array of integers $a_1, a_2, \ldots, a_n$, as well as a binary string$^{\dagger}$ $s$ consisting of $n$ characters. Augustin is a big fan of data structures. Therefore, he asked you to implement a data structure that can answer $q$ queries. There are two types of queries: - "1 $l$ $r$" ($1\le l \le r...
Of course this problem has solutions that use data structures. For example, you can use a segment tree with range updates to solve it in $O((n + q) \log n)$ time, or you can use a square root decomposition to solve it in $O((n + q) \sqrt{n})$ time. However, of course, we do not expect participants in Div3 to have knowl...
[ "binary search", "bitmasks", "data structures", "dp" ]
1,500
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) s = input() q = int(input()) ans = [0, 0] a = [0] + a s = '0' + s pref = [0] * (n + 1) for i in range(1, n + 1): ans[int(s[i])] ^= a[i] pref[i] = pref[i - 1] ^ a[i] massxor = 0 ...
1872
F
Selling a Menagerie
You are the owner of a menagerie consisting of $n$ animals numbered from $1$ to $n$. However, maintaining the menagerie is quite expensive, so you have decided to sell it! It is known that each animal is afraid of exactly one other animal. More precisely, animal $i$ is afraid of animal $a_i$ ($a_i \neq i$). Also, the ...
Simple greedy observation: if at some point in time there exists an animal $i$ such that no one fears it (there is no index $a_j = i$), then it is optimal to sell that animal first. Let's iteratively sell such animals as long as they exist. After selling animal $i$, we must additionally check if animal $a_i$ has become...
[ "dfs and similar", "dsu", "graphs", "implementation", "math" ]
1,800
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) c = list(map(int, input().split())) sons = [0] * n for i in range(n): a[i] -= 1 sons[a[i]] += 1 q = [] for i in range(n): if sons[i] == 0: q.append(i) ans = [] added...