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
2070
B
Robot Program
There is a robot on the coordinate line. Initially, the robot is located at the point $x$ ($x \ne 0$). The robot has a sequence of commands of length $n$ consisting of characters, where L represents a move to the left by one unit (from point $p$ to point $(p-1)$) and R represents a move to the right by one unit (from p...
Let's simulate the process until either the command sequence terminates or the robot reaches the point $0$. If the sequence ends and the robot is not at $0$, then the answer to the problem is $0$. Otherwise, we need to check whether the robot can return to the point $0$ if we begin executing commands again. We can simp...
[ "brute force", "implementation", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { int t; cin >> t; while (t--) { li n, x, k; cin >> n >> x >> k; string s; cin >> s; for (int i = 0; i < n; ++i) { x += (s[i] == 'L' ? -1 : +1); --k; if (!x) break; } li ans = 0; ...
2070
C
Limited Repainting
You are given a strip, consisting of $n$ cells, all cells are initially colored red. In one operation, you can choose a segment of consecutive cells and paint them \textbf{blue}. Before painting, the chosen cells can be either red or blue. Note that it is not possible to paint them red. You are allowed to perform at m...
The problem asks to minimize the maximum. An experienced participant should immediately consider binary search as a possible solution. The condition for binary search can be formulated as follows: is there a coloring such that its penalty does not exceed $x$? If the penalty does not exceed $x$, then it does not exceed ...
[ "binary search", "greedy" ]
1,500
for _ in range(int(input())): n, k = map(int, input().split()) s = input() a = list(map(int, input().split())) l, r = 0, 10**9 res = -1 def check(d): last = 'R' cnt = 0 for i in range(n): if a[i] > d: if s[i] == 'B' and last != 'B': ...
2070
D
Tree Jumps
You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. Let $d_x$ be the distance (the number of edges on the shortest path) from the root to the vertex $x$. There is a chip that is initially placed at the root. You can perform the...
We can solve this problem by using dynamic programming. Let $dp_v$ represent the number of valid sequences ending at vertex $v$. To calculate $dp_v$, we can iterate over all previous vertices $u$ in the sequence, such that $d_v = d_u + 1$ and $u \ne p_v$ (or $u$ is the root). Then, $dp_v$ is the sum of $dp_u$ for all s...
[ "dfs and similar", "dp", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; if (x < 0) x += MOD; return x; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> p(n), d(n); vector<vector<int>> vs(n); for ...
2070
E
Game with Binary String
Consider the following game. Two players have a binary string (a string consisting of characters 0 and/or 1). The players take turns, the first player makes the first turn. During a player's turn, he or she has to choose exactly two adjacent elements of the string and remove them (\textbf{the first element and the last...
First, we need to modify the game a bit. Suppose that, instead of removing two adjacent characters, a player can remove any pair of characters of the required type. So, the first player can remove any two characters equal to 0; the second player can remove any two characters, at least one of which is 1. Now the order o...
[ "constructive algorithms", "data structures", "divide and conquer", "games", "greedy", "math" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = 300003; const int M = 3 * N; const int S = 4 * N; struct segtree { vector<int> T; void add(int v, int l, int r, int pos, int val) { T[v] += val; if(l != r - 1) { int m = (l + r) / 2; if(pos < m...
2070
F
Friends and Pizza
Monocarp has $n$ pizzas, the $i$-th pizza consists of $a_i$ slices. Pizzas are denoted by uppercase Latin letters from A to the $n$-th letter of the Latin alphabet. Monocarp also has $m$ friends, and he wants to invite \textbf{exactly two} of them to eat pizza. For each friend, Monocarp knows which pizzas that friend ...
Before solving this problem, I highly recommend that you learn Sum over Subsets Dynamic Programming (aka SOS DP), if you don't know it yet. For example, you can use this CF blog, it has a great explanation of SOS DP: https://codeforces.com/blog/entry/45223 First, we will somewhat change the problem. The original proble...
[ "bitmasks", "divide and conquer", "dp", "fft" ]
3,000
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; vector<long long> cnt(1 << n); for(int i = 0; i < m; i++) { string s; cin >> s; int mask = 0; for(auto c : s) mask += ...
2071
A
The Play Never Ends
Let's introduce a two-player game, table tennis, where a winner is always decided and draws are impossible. Three players, Sosai, Fofo, and Hohai, want to spend the rest of their lives playing table tennis. They decided to play forever in the following way: - In each match, two players compete while the third spectat...
When Fofo is the spectator of the first match, what is the earliest subsequent game in which he will spectate again? Suppose Sosai wins the first game. What becomes clear? Once the winner of the first match is decided, the rest of the game is completely predictable. For example, if Hohai wins the first match which Fofo...
[ "math", "number theory" ]
800
#include<bits/stdc++.h> using namespace std; void solve() { int k; cin >> k; if (k % 3 == 1) { cout << "Yes\n"; } else { cout << "No\n"; } } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
B
Perfecto
A permutation $p$ of length $n$$^{\text{∗}}$ is perfect if, for each index $i$ ($1 \le i \le n$), it satisfies the following: - The sum of the first $i$ elements $p_1 + p_2 + \ldots + p_i$ is \textbf{not} a perfect square$^{\text{†}}$. You would like things to be perfect. Given a positive integer $n$, find a perfect ...
Consider the identity permutation, defined by $p_i = i$. When and why does this permutation not work? The smallest index $i$ where the issue occurs must satisfy the condition that $1 + \ldots + i$ is a perfect square. What is the simplest and most efficient way to resolve this issue? The first observation is that if th...
[ "brute force", "constructive algorithms", "greedy", "math" ]
1,100
#include<bits/stdc++.h> using namespace std; void solve() { auto check = [&](int k) { int j = sqrtl((int64_t)k * (k + 1) / 2); return ((int64_t)j * j != (int64_t)k * (k + 1) / 2); }; int n; cin >> n; if (!check(n)) { cout << "-1\n"; return; } vector<int> ans(n...
2071
C
Trapmigiano Reggiano
In an Italian village, a hungry mouse starts at vertex $\textrm{st}$ on a given tree$^{\text{∗}}$ with $n$ vertices. Given a permutation $p$ of length $n$$^{\text{†}}$, there are $n$ steps. For the $i$-th step: - A tempting piece of Parmesan cheese appears at vertex $p_i$. If the mouse is currently at vertex $p_i$, i...
Root the tree at vertex $\textrm{en}$. What observations can you make? Can the cheese be placed at the vertices in a specific sequence that prevents the mouse from moving farther away from vertex $\textrm{en}$? First, root the tree at vertex $\textrm{en}$ and approach it step by step. Observe that after processing all ...
[ "constructive algorithms", "data structures", "dfs and similar", "dp", "greedy", "sortings", "trees" ]
1,700
#include<bits/stdc++.h> using namespace std; void solve() { int n, s, e; cin >> n >> s >> e; vector adj(n + 1, vector<int> ()); for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; adj[u].push_back(v), adj[v].push_back(u); } vector dis(n + 1, vector<int> ()); vector...
2071
D1
Infinite Sequence (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $l=r$. You can hack only if you solved all versions of this problem.} You are given a positive integer $n$ and the first $n$ terms of an infinite binary sequence $a$, which is defined as follows: - For $m>n$,...
Try to determine the connection between $a_{2m}$ and $a_{2m+1}$ for indices where $2m > n$. Try to express $a_{2m}$ as the XOR of a short prefix of terms plus at most one extra term. For convenience, assume $n$ is odd (if not, increment $n$ and handle the edge case separately). Start by precomputing the first $2n$ term...
[ "bitmasks", "brute force", "dp", "implementation", "math" ]
1,800
#include<bits/stdc++.h> using namespace std; void solve() { int n; int64_t l, r; cin >> n >> l >> r; vector<int> a(n + 1); for (int i = 1; i <= n; i++) { cin >> a[i]; } vector<int> pref(n + 1); for (int i = 1; i <= n; i++) { pref[i] = pref[i - 1] + a[i]; } if (n %...
2071
D2
Infinite Sequence (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $l\le r$. You can hack only if you solved all versions of this problem.} You are given a positive integer $n$ and the first $n$ terms of an infinite binary sequence $a$, which is defined as follows: - For $m>...
Generalize the recursive method for evaluating an index to handle the computation of the prefix sum. First, check the editorial of D1. To upgrade the solution, we define a recursive function: $\text{sum}(m) = \left( \displaystyle\sum_{\substack{i \leq m \\ i \text{ even}}} a_i,\; \displaystyle\sum_{\substack{i \leq m \...
[ "bitmasks", "brute force", "constructive algorithms", "data structures", "dp", "implementation", "math" ]
2,500
#include<bits/stdc++.h> using namespace std; void solve() { int n; int64_t l, r; cin >> n >> l >> r; vector<int> a(n + 1); for (int i = 1; i <= n; i++) { cin >> a[i]; } vector<int> pref(n + 1); for (int i = 1; i <= n; i++) { pref[i] = pref[i - 1] + a[i]; } if (n %...
2071
E
LeaFall
You are given a tree$^{\text{∗}}$ with $n$ vertices. Over time, each vertex $i$ ($1 \le i \le n$) has a probability of $\frac{p_i}{q_i}$ of falling. Determine the expected value of the number of unordered pairs$^{\text{†}}$ of \textbf{distinct} vertices that become leaves$^{\text{‡}}$ in the resulting forest$^{\text{§}...
Think about an unordered pair $(u, v)$ where both u and v are leaves in the final forest. Consider dividing all such pairs into separate categories based on their relationship in the original tree. Let the first category be the pairs that are directly connected (neighbors), and analyze under what conditions both vertic...
[ "combinatorics", "dp", "probabilities", "trees" ]
2,600
#include<bits/stdc++.h> using namespace std; const int mod = 998244353; int add(int x, int y) { return x + y - (x + y >= mod) * mod; } void add2(int &x, int y) { x += y; if (x >= mod) x -= mod; } int mul(int x, int y) { return int((int64_t)x * y % mod); } int sub(int x, int y) { return x - y + (x < ...
2071
F
Towering Arrays
An array $b = [b_1, b_2, \ldots, b_m]$ of length $m$ is called $p$-towering if there exists an index $i$ ($1\le i\le m$) such that for every index $j$ ($1 \le j \le m$), the following condition holds: $$b_j \ge p - |i - j|.$$ Given an array $a = [a_1, a_2, \ldots, a_n]$ of length $n$, you can remove at most $k$ elemen...
Binary search on $p$. After fixing $p$, find the maximum $p$-towering subsequence. if we denote the set of indexes that correspond to the maximum "increasing" $p$-towering subsequence on prefix $i$ as $S_i$, then for any $i < n$: $S_i \subseteq S_{i + 1}$. Let's do binary search on $p$. After fixing some $p$ our goal i...
[ "binary search", "data structures" ]
2,700
#include <bits/stdc++.h> #define len(a) (int)a.size() #define all(a) a.begin(), a.end() using namespace std; const int MAXI = 1e9 + 1e7; const int MAXN = 2e5 + 100; struct Node { int min_on_subtree = 0, push_addition = 0; }; Node t[MAXN * 4]; int a[MAXN], pref[MAXN], suf[MAXN]; class Segtree { private: int ...
2072
A
New World, New Me, New Array
Natsume Akito has just woken up in a new world and immediately received his first quest! The system provided him with an array $a$ of $n$ zeros, an integer $k$, and an integer $p$. In one operation, Akito chooses two integers $i$ and $x$ such that $1 \le i \le n$ and $-p \le x \le p$, and performs the assignment $a_i ...
In an array $a$ of length $n$ containing numbers from $-p$ to $p$ inclusive, any sum $k$ in the range $[-p \cdot n; p \cdot n]$ is achievable. We will present an algorithm that constructs an array with a given sum $k$ within this range. We will construct the array for $k \ge 0$, as the problem for $k$ and $-k$ is equiv...
[ "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n, k, p; cin >> n >> k >> p; if (-n * p <= k && k <= n * p) { cout << (abs(k) + p - 1) / p << '\n'; } else { cout << "-1\n"; } } int main() { int tt; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2072
B
Having Been a Treasurer in the Past, I Help Goblins Deceive
After completing the first quest, Akito left the starting cave. After a while, he stumbled upon a goblin village. Since Akito had nowhere to live, he wanted to find out the price of housing. It is well known that goblins write numbers as a string of characters '-' and '_', and the value represented by the string $s$ i...
For $n \le 2$ or when the number of $i$ such that $s_i =$ '-' is less than two or there are no indices $i$ where $s_i =$ '_', the answer will be $0$. Otherwise, let's solve the problem if there is only one symbol '_' in the string. It is easy to see that the string will look like a prefix of length $\ell_p$ made of '-'...
[ "combinatorics", "constructive algorithms", "strings" ]
900
#include <bits/stdc++.h> using namespace std; void solve() { int n; string s; cin >> n >> s; int64_t dash = count(s.begin(), s.end(), '-'); int64_t under = n - dash; int64_t ans = (dash / 2) * (dash - dash / 2) * under; cout << ans << '\n'; } int main() { int tt; cin >> tt; while (tt --> 0) { ...
2072
C
Creating Keys for StORages Has Become My Main Skill
Akito still has nowhere to live, and the price for a small room is everywhere. For this reason, Akito decided to get a job at a bank as a key creator for storages. In this magical world, everything is different. For example, the key for a storage with the code $(n, x)$ is an array $a$ of length $n$ such that: - $a_1 ...
In problems involving $\text{MEX}$, a common idea is its greedy maximization. This problem is no exception. Note that $a\ |\ b \ge \max(a, b)$. We will iterate through the number $m$ from $0$ to $\min(n - 1, x)$. We will also keep a number $v$ initially set to $0$. When processing the current $m$, we check that $v\ |\ ...
[ "bitmasks", "constructive algorithms", "greedy" ]
1,200
#include <iostream> #include <vector> using namespace std; void Solve() { int len, val; cin >> len >> val; vector<int> ans(len, val); int or_val = 0; bool flag = true; for (int i = 0; i < len - 1; ++i) { if (((or_val | i) & val) == (or_val | i)) { or_val |= i; ans[i] = i; } else { ...
2072
D
For Wizards, the Exam Is Easy, but I Couldn't Handle It
Akito got tired of being a simple locksmith at a bank, so he decided to enroll in the Magical Academy and become the best wizard in the world! However, to enroll, he needed to solve a single problem on the exam, which the ambitious hero could not manage. In the problem, he was given an array $a$ of length $n$. He need...
In fact, a cyclic shift of the subarray $[l, r]$ to the left by $1$ is the same as removing the element $a_l$ from the array and then inserting it after the $r$-th element. This means that we can move the number $a_i$ to any position $j \ge i$. Let's see how the number of inversions in the array changes with the operat...
[ "brute force", "greedy", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int best_diff = 0, L = 0, R = 0; for (int i = 0; i < n; ++i) { int cnt_greater = 0, cnt_less = 0; for (int j = i + 1; j < n; ++j) { cnt_greater ...
2072
E
Do You Love Your Hero and His Two-Hit Multi-Target Attacks?
Akito decided to study a new powerful spell. Since it possesses immeasurable strength, it certainly requires a lot of space and careful preparation. For this, Akito went out into the field. Let's represent the field as a Cartesian coordinate system. For the spell, Akito needs to place $0 \le n \le 500$ staffs at \text...
After playing a bit with the formulas $\rho(a, b)$ and $d(a, b)$, we can derive that $\rho(a, b) = d(a, b)$ if $x_a = x_b$ or $y_a = y_b$. Let us define a recursive function $f(k, x_0, y_0)$ that returns a set of sticks $P$ such that there are exactly $k$ unordered pairs that satisfy the condition, given that for all s...
[ "binary search", "brute force", "constructive algorithms", "dp", "geometry", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; vector<pair<int64_t, int64_t>> rec(int64_t k, int64_t x0 = 0, int64_t y0 = 0) { if (!k) { return {}; } int64_t delta = 0; while (delta * (delta - 1) / 2 <= k) { delta++; } delta--; auto remaining = rec(k - delta * (delta - 1) / 2, x0 + delta + 1, y0 ...
2072
F
Goodbye, Banker Life
Monsters are approaching the city, and to protect it, Akito must create a protective field around the city. As everyone knows, protective fields come in various levels. Akito has chosen the field of level $n$. To construct the field, a special phrase is required, which is the $n$-th row of the Great Magical Triangle, r...
Since the value of the $i$-th bit in $a \oplus b$ depends only on the $i$-th bits of the numbers $a$ and $b$, we can solve the problem separately for each bit. Let $a_i$ be the $i$-th bit of the number $a$. If $k_i = 0$, then the triangle for the $i$-th bit will consist only of $0$s. If $k_i = 1$, then since $\oplus$ i...
[ "2-sat", "bitmasks", "combinatorics", "constructive algorithms", "fft", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; constexpr int64_t kMaxN = 1e6 + 69; vector<int64_t> c(kMaxN); void precalc() { c[0] = c[1] = 0; for (int i = 2; i < kMaxN; ++i) { c[i] = c[i - 1]; int x = i; while (x % 2 == 0) { x /= 2, c[i]++; } } } void solve() { int n, k; cin >> n >> ...
2072
G
I've Been Flipping Numbers for 300 Years and Calculated the Sum
After three hundred years of slime farming, Akito finally obtained the magical number $n$. Upon reaching the merchant, he wanted to exchange the number for gold, but the merchant gave the hero a quest. The merchant said that for the quest, the skill $\text{rev}(n, p)$ would be required, which Akito, by happy coinciden...
Let's consider three cases: $2 \le p \le \sqrt{n}$. We calculate for each of the $\mathcal{O}(\sqrt{n})$ values of $p$ in $\mathcal{O}(\log n)$. One could think that it takes $\mathcal{O}(\sqrt{n} \log{n})$ time, but it actually takes $\mathcal{O}(\sqrt{n})$ time! Read this comment for explanation. $n < p \le k$. For e...
[ "binary search", "brute force", "combinatorics", "divide and conquer", "math", "number theory" ]
2,200
#include <bits/stdc++.h> using namespace std; constexpr int64_t mod = 1e9 + 7; constexpr int64_t twoInv = 500'000'004; constexpr int64_t sixInv = 166'666'668; int64_t add(int64_t a, int64_t b) { return (a % mod + b % mod) % mod; } int64_t mns(int64_t a, int64_t b) { return (a % mod - b % mod + mod) % mod; } in...
2074
A
Draw a Square
The pink soldiers have given you $4$ \textbf{distinct points} on the plane. The $4$ points' coordinates are $(-l,0)$, $(r,0)$, $(0,-d)$, $(0,u)$ correspondingly, where $l$, $r$, $d$, $u$ are positive integers. \begin{center} {\small In the diagram, a square is drawn by connecting the four points $L$, $R$, $D$, $U$.} \...
For the given four points to make a square, we can see that the following must hold: $l$, $r$, $d$, $u$ must all be equal. The proof is left as a practice for the reader, but generally, it can be proved easily by seeing that the square is both a rhombus and a rectangle. The problem is solved in $\mathcal{O}(1)$ per tes...
[ "geometry", "implementation" ]
800
for i in range(int(input())): l,r,d,u=map(int,input().split()) if l==r==d==u: print("Yes") else: print("No")
2074
B
The Third Side
The pink soldiers have given you a sequence $a$ consisting of $n$ positive integers. You must repeatedly perform the following operation \textbf{until there is only $1$ element left}. - Choose two \textbf{distinct} indices $i$ and $j$. - Then, choose a positive integer value $x$ such that there exists a \textbf{non-d...
We can solve this problem by observing a property on the sum of elements. After each operation, it must hold that $a_i+a_j>x$, and the new element is at most $a_i+a_j-1$. Therefore, the sum decreases by at least $1$. However, we notice that a triangle of side lengths $p$, $q$, $p+q-1$ is always non-degenerate due to th...
[ "geometry", "greedy", "math" ]
800
t = int(input()) for _ in range(t): n = int(input()) sm = sum(map(int, input().split())) print(sm - n + 1)
2074
C
XOR and Triangle
This time, the pink soldiers have given you an integer $x$ ($x \ge 2$). Please determine if there exists a \textbf{positive} integer $y$ that satisfies the following conditions. - $y$ is \textbf{strictly} less than $x$. - There exists a \textbf{non-degenerate triangle}$^{\text{∗}}$ with side lengths $x$, $y$, $x \opl...
Let us interpret the triangle inequality in terms of bitmasking. Then, we get the following. (One is omitted as it is implied in the constraints.) $x+y>x \oplus y$, $(x \oplus y)+2(x \,\&\, y)> x \oplus y$, $x\,\&\,y>0$; $y+(x \oplus y)>x$, $y+(x + y) - 2(x\,\&\,y)> x$, $y > x\,\&\,y$. In other words, $y$ satisfies the...
[ "bitmasks", "brute force", "geometry", "greedy", "probabilities" ]
1,100
t = int(input()) for _ in range(t): x = int(input()) ans = -1 for i in range(30): for j in range(30): y = (1 << i) | (1 << j) if y < x and x + y > (x ^ y) and y + (x ^ y) > x: ans = y print(ans)
2074
D
Counting Points
The pink soldiers drew $n$ circles with their center \textbf{on the $x$-axis} of the plane. Also, they have told that \textbf{the sum of radii is exactly $m$}$^{\text{∗}}$. Please find the number of integer points \textbf{inside or on the border of} at least one circle. Formally, the problem is defined as follows. Yo...
For some value of $x$ and a circle centered on $(x_i,0)$ with radius $r_i$, we can find the range of $y$ where the points lie on using simple algebra. $y^2 \le r_i^2-(x-x_i)^2 \Longrightarrow -\sqrt{r_i^2-(x-x_i)^2} \le y \le \sqrt{r_i^2-(x-x_i)^2}$ Here, we can see that when $a=\left \lfloor {\sqrt{r_i^2-(x-x_i)^2}} \...
[ "brute force", "data structures", "geometry", "implementation", "two pointers" ]
1,400
#include<bits/stdc++.h> using namespace std; using ll=long long; int main() { int t;cin>>t; for(int i=0;i<t;i++) { int n,m;cin>>n>>m; map<ll,ll>cnt; auto isqrt=[&](ll x) { ll val=sqrtl(x)+5; while(val*val>x)val--; return val; }; ...
2074
E
Empty Triangle
This is an interactive problem. The pink soldiers hid from you $n$ ($3 \le n \le 1500$) \textbf{fixed} points $(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$, \textbf{whose coordinates are not given to you}. Also, it is known that no two points have the same coordinates, and no three points are collinear. You can ask the F...
After querying the triple $(i,j,k)$ and receiving the index $p$, we seem to gain almost no info other than the following. The three triples $(p,j,k)$, $(i,p,k)$, $(i,j,p)$ all yield strictly fewer points inside the triangle than $(i,j,k)$. One may think that repeatedly substituting one index arbitrarily with $p$ gets a...
[ "geometry", "interactive", "probabilities" ]
1,600
#include<bits/stdc++.h> using namespace std; int main() { mt19937 mt(727); uniform_int_distribution uni(1,3); int tc;cin>>tc; while(tc--) { int n;cin>>n; if(n<0)return 0; vector<int>vec(n); for(int i=0;i<n;i++)vec[i]=i+1; shuffle(begin(vec),end(vec),mt); ...
2074
F
Counting Necessary Nodes
A \textbf{quadtree} is a tree data structure in which each node has at most four children and accounts for a square-shaped region. Formally, \textbf{for all tuples} of nonnegative integers $k,a,b \ge 0$, there exists \textbf{exactly one node} accounting for the following region$^{\text{∗}}$. $$[a \cdot 2^k,(a+1) \cdo...
Notice how the interval on each axis corresponds to those found in nodes of segment trees. Let us find the segment tree intervals on each axis and call those sets of intervals $I_x$ and $I_y$. Then, for each rectangle formed by some $a \times b$ such that $a \in I_x$, $b \in I_y$, the following holds. No node with side...
[ "bitmasks", "divide and conquer", "greedy", "implementation", "math" ]
2,000
#include<bits/stdc++.h> using namespace std; using ll=long long; int main() { int t;cin>>t; for(int i=0;i<t;i++) { int l1,r1,l2,r2;cin>>l1>>r1>>l2>>r2; vector<pair<ll,ll>>it1,it2; auto rec=[&](auto rec,int L,int R,int l,int r,vector<pair<ll,ll>>&v)->void { if(r<...
2074
G
Game With Triangles: Season 2
\begin{center} \begin{tabular}{c} The Frontman greets you to this final round of the survival game. \ \end{tabular} \end{center} There is a regular polygon with $n$ sides ($n \ge 3$). The vertices are indexed as $1,2,\ldots,n$ in clockwise order. On each vertex $i$, the pink soldiers have written a positive integer $a...
If we cut a single edge and consider the regular polygon as a polyline of $n$ points, then we can think of using some form of Range DP to solve this problem. This is correct when you simply take the maximum value over all possible edges you can cut. It is not hard to see that doing this should not change the overall ti...
[ "dp", "geometry" ]
2,100
#include<bits/stdc++.h> using namespace std; using ll=long long; ll dp[505][505]; int main() { cin.tie(0)->sync_with_stdio(0); int t;cin>>t; for(int tc=0;tc<t;tc++) { ll n;cin>>n; vector<ll>vec(n); for(ll&i:vec)cin>>i; for(int i=0;i<n;i++) { for(in...
2075
A
To Zero
You are given two integers $n$ and $k$; $k$ is an odd number not less than $3$. Your task is to turn $n$ into $0$. To do this, you can perform the following operation any number of times: choose a number $x$ from $1$ to $k$ and subtract it from $n$. However, if the \textbf{current} value of $n$ is even (divisible by $...
If you subtract an odd number from an odd number, you will get an even number. And if you subtract an even number from an even number, you will also get an even number. Therefore, after each operation, we obtain an even number. Additionally, we can always subtract the maximum number that we can. If the result of the su...
[ "greedy", "math" ]
800
t = int(input()) for i in range(t): n, k = map(int, input().split()) ans = 0 if n % 2 == 1: n -= k ans = 1 k -= 1 ans += (n + k - 1) // k print(ans)
2075
B
Array Recoloring
You are given an integer array $a$ of size $n$. Initially, all elements of the array are colored red. You have to choose exactly $k$ elements of the array and paint them blue. Then, while there is at least one red element, you have to select any red element with a blue neighbor and make it blue. The cost of painting ...
Since the cost depends on the first $k$ painted elements and the last one, it cannot exceed the sum of $(k+1)$ maximum elements of the array. In fact, in most cases, you can get exactly that cost. Let $k \ge 2$ and the positions of the $(k+1)$ maxima are $p_1, p_2, \dots, p_k, p_{k+1}$. In this case, you can initially ...
[ "constructive algorithms", "greedy" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (auto &x : a) cin >> x; long long ans = 0; if (k > 1) { sort(a.begin(), a.end(), greater<int>()); ans = accumulate(a.begin(), a.begin() +...
2075
C
Two Colors
Monocarp has installed a new fence at his summer house. The fence consists of $n$ planks of the same size arranged in a row. Monocarp decided that he would paint his fence according to the following rules: - each plank of the fence will be painted in exactly one color; - the number of different colors that the planks...
Consider a general form of a fence: the planks from $1$ to $k$ are painted in one color, and the planks from $k + 1$ to $n$ are painted in another color. Let's iterate over the value of $k$. It is then easy to determine which colors are suitable for the first half and which are suitable for the second half. Any color w...
[ "binary search", "combinatorics", "math" ]
1,500
from bisect import bisect_left for _ in range(int(input())): n, m = map(int, input().split()) a = sorted(list(map(int, input().split()))) ans = 0 for k in range(1, n): x = m - bisect_left(a, k) y = m - bisect_left(a, n - k) ans += x * y - min(x, y) print(ans)
2075
D
Equalization
You are given two non-negative integers $x$ and $y$. You can perform the following operation any number of times (possibly zero): choose a positive integer $k$ and divide either $x$ or $y$ by $2^k$ rounding down. The cost of this operation is $2^k$. However, there is an additional constraint: you cannot select the sam...
Note that for any positive integer $x$, the following equality holds: $\left\lfloor\frac{\left\lfloor\frac{x}{2^a}\right\rfloor}{2^b}\right\rfloor = \left\lfloor\frac{x}{2^{a+b}}\right\rfloor$. This means that for each number, only the total power of two by which it will be divided is significant. Due to the restrictio...
[ "bitmasks", "brute force", "dp", "graphs", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; using li = long long; const int B = 60; const li INF = 1e18; int main() { ios::sync_with_stdio(false); cin.tie(0); array<array<li, B>, B> dp; for (int i = 0; i < B; ++i) { for (int j = 0; j < B; ++j) { dp[i][j] = INF; } } dp[0][0] = 0; for (in...
2075
E
XOR Matrix
For two arrays $a = [a_1, a_2, \dots, a_n]$ and $b = [b_1, b_2, \dots, b_m]$, we define the XOR matrix $X$ of size $n \times m$, where for each pair $(i,j)$ ($1 \le i \le n$; $1 \le j \le m$) it holds that $X_{i,j} = a_i \oplus b_j$. The symbol $\oplus$ denotes the bitwise XOR operation. You are given four integers $n...
If there are at least three pairwise distinct elements in one of the two arrays ($a$ and $b$), then there will also be at least three distinct elements in the matrix. Therefore, we can assume that the number of distinct elements in each of the arrays does not exceed $2$. This allows us to construct the answer from the ...
[ "bitmasks", "combinatorics", "dp", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; const int K = 31; 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; } i...
2075
F
Beautiful Sequence Returns
Let's call an integer sequence \textbf{beautiful} if the following conditions hold: - for every element except the first one, there is an element to the left less than it; - for every element except the last one, there is an element to the right larger than it; For example, $[1, 2]$, $[42]$, $[1, 4, 2, 4, 7]$, and $[...
For the start, let's note that the definition of the beauty of a sequence is equivalent to the following: a sequence is beautiful if and only if the first element is a unique minimum and the last element is a unique maximum. Next, consider each element of the array as a point in $2D$: let's transform $a_i$ into the poi...
[ "binary search", "brute force", "data structures", "implementation" ]
3,000
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); vector<int> Tadd, Tmax; int getmax(int v) { return Tmax[v] + Tadd[v]; }...
2077
A
Breach of Faith
\begin{quote} Breach of Faith - Supire feat.eili \end{quote} You and your team have worked tirelessly until you have a sequence $a_1, a_2, \ldots, a_{2n+1}$ of positive integers satisfying these properties. - $1 \le a_i \le 10^{18}$ for all $1 \le i \le 2n + 1$. - $a_1, a_2, \ldots, a_{2n+1}$ are pairwise \textbf{dis...
Rearrange the equation around. Try to maximize the missing number. The equation can be rearranged to $a_{2n} = a_1 + (a_3 - a_2) + (a_5 - a_4) + \ldots + (a_{2n-1} - a_{2n-2}) + a_{2n+1}$ Choose $a_1$ as the largest number, $a_3, a_5, \ldots, a_{2n+1}$ as the next $n$ largest numbers, and the rest as $a_2, a_4, \ldots,...
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,500
for test_case in range(int(input())): n = int(input()) b = sorted([int(_) for _ in input().split()]) a = [0 for _ in range(2*n+1)] # Implementation note: 0-based index used here # assign a[0], a[2], ... large numbers for i in range(0, n+1): a[2*i] = b[n+i-1] # assi...
2077
B
Finding OR Sum
\begin{quote} ALTER EGO - Yuta Imai vs Qlarabelle \end{quote} This is an interactive problem. There are two hidden non-negative integers $x$ and $y$ ($0 \leq x, y < 2^{30}$). You can ask no more than $2$ queries of the following form. - Pick a non-negative integer $n$ ($0 \leq n < 2^{30}$). The judge will respond wi...
Try to get information on half of the bits. Alternate the bits. The queries are $\ldots 0101_2$ and $\ldots 1010_2$. It's easier to look at the case with only two binary digits first. Let the result of query $01_2$ be $q_1$ and $10_2$ be $q_2$. Observe that if $q_2 = 100_2$ then the first (from the right) digit of both...
[ "bitmasks", "constructive algorithms", "implementation", "interactive", "math" ]
1,900
def query(n): print(n) return int(input()) def end_query(): print("!") return int(input()) def test_case(): n0, n1 = 0, 0 for i in range(1, 30, 2): n0 |= (1 << i) for i in range(0, 30, 2): n1 |= (1 << i) q0 = query(n0) q1 = query(n1) m = end_query() ...
2077
C
Binary Subsequence Value Sum
\begin{quote} Last | Moment - onoken \end{quote} For a binary string$^{\text{∗}}$ $v$, the score of $v$ is defined as the maximum value of $$F\big(v, 1, i\big) \cdot F\big(v, i+1, |v|\big)$$ over all $i$ ($0 \leq i \leq |v|$). Here, $F\big(v, l, r\big) = r - l + 1 - 2 \cdot \operatorname{zero}(v, l, r)$, where $\op...
Find a closed-form expression for the score of a binary string. The closed-form expression for the score of a binary string is $\lfloor \frac{cnt_0-cnt_1}{2} \rfloor \lceil \frac{cnt_0-cnt_1}{2} \rceil$ Where $cnt_0$ and $cnt_1$ are the number of $\tt{0}$ and $\tt{1}$ in the binary string, respectively. $\lfloor \frac{...
[ "combinatorics", "data structures", "dp", "fft", "math", "matrices" ]
2,300
mod = 998244353 import sys input = sys.stdin.readline for test_case in range(int(input())): n, q = map(int, input().split()) s = list(map(int, list(input()[:-1]))) cnt0 = n - sum(s) pw2 = pow(2, n-4+mod-1, mod) for _ in range(q): a = int(input()) - 1 cnt0 += 2 * s[a] - 1 s[...
2077
D
Maximum Polygon
Given an array $a$ of length $n$, determine the lexicographically largest$^{\text{∗}}$ subsequence$^{\text{†}}$ $s$ of $a$ such that $s$ can be the side lengths of a polygon. Recall that $s$ can be the side lengths of a polygon if and only if $|s| \geq 3$ and $$ 2 \cdot \max(s_1, s_2, \ldots, s_{|s|}) < s_1 + s_2 + \...
Find a way to get the answer if you fixed the largest value or the first value of the subsequence. Sufficiently long (which is not that long) arrays will definitely be polygon side lengths. Suppose we consider some integer $x$, and we try to find the lexicographically largest subsequence (say $s$) such that the maximum...
[ "brute force", "data structures", "greedy", "implementation", "math" ]
3,100
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ld long double #define nline "\n" #define f first #define s second const ll INF_MUL=1e13; const ll IN...
2077
E
Another Folding Strip
For an array $b$ of length $m$, define $f(b)$ as follows. Consider a $1 \times m$ strip, where all cells initially have darkness $0$. You want to transform it into a strip where the color at the $i$-th position has darkness $b_i$. You can perform the following operation, which consists of two steps: - Fold the paper ...
Folding is basically alternating the parity of the indices. Maximum subarray sum. As mentioned in Hint 1, we can see that if the darkness of the cells $i_1, i_2, \ldots, i_k$ increases in some operation, the parity of $i_j$ should be different from that of $i_{j+1}$ for $1 \le j \le k - 1$ Let us try to find $f(a[1, n]...
[ "combinatorics", "constructive algorithms", "data structures", "divide and conquer", "dp", "greedy", "math" ]
2,700
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ld long double #define nline "\n" #define f first #define s second const ll INF_MUL=1e13; const ll IN...
2077
F
AND x OR
Suppose you have two arrays $c$ and $d$, each of length $k$. The pair $(c, d)$ is called \textbf{good} if $c$ can be changed to $d$ by performing the following operation any number of times. - Select two distinct indices $i$ and $j$ ($1 \leq i, j \leq k$, $i \neq j$) and a nonnegative integer $x$ ($0 \leq x < 2^{30}$)...
Characterize the property of a good pair of arrays. Think about the last operation that turns a good pair of arrays into the same array. $(a, b)$ is a good pair only if at least one of these two conditions hold $a = b$ $a = b$ There exist two distinct indices $i$, $j$ such that $b_i$ is a submask of $b_j$. There exist ...
[ "bitmasks", "constructive algorithms", "dp" ]
3,300
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ld long double #define nline "\n" #define f first #define s second const ll INF_MUL=1e13; const ll IN...
2077
G
RGB Walking
\begin{quote} Red and Blue and Green - fn and Silentroom \hfill ⠀ \end{quote} You are given a connected graph with $n$ vertices and $m$ bidirectional edges with weight not exceeding $x$. The $i$-th edge connects vertices $u_i$ and $v_i$, has weight $w_i$, and is assigned a color $c_i$ ($1 \leq i \leq m$, $1 \leq u_i, ...
It might help to solve this task with two colors first. As in, minimize the difference between red and blue. Walking back and forth can do wonders. Let the difference between the red edges and the blue edges passed be $d$. Let the edge weights of the red edges be $r_1, r_2, \ldots$ and the blue edges be $b_1, b_2, \ldo...
[ "bitmasks", "chinese remainder theorem", "dfs and similar", "graphs", "number theory" ]
3,500
#include <bits/stdc++.h> #define int long long using namespace std; typedef pair<int, int> pii; void test_case() { // read input int n, m, x; cin >> n >> m >> x; vector<tuple<int, int, int>> edge_list[3]; map<char, int> color_map = {{'r', 0}, {'g', 1}, {'b', 2}}; for (int i = 1; i ...
2078
A
Final Verdict
\begin{quote} Testify - void (Mournfinale) feat. 星熊南巫 \end{quote} You are given an array $a$ of length $n$, and must perform the following operation until the length of $a$ becomes $1$. Choose a positive integer $k < |a|$ such that $\frac{|a|}{k}$ is an integer. Split $a$ into $k$ subsequences$^{\text{∗}}$ $s_1, s_2,...
Something doesn't change after each operation. The average of the entire array doesn't change after each operation. Simply check whether the average value of $a$ is $x$ or not. Time complexity: $\mathcal{O}(n)$ per test case.
[ "math" ]
800
for test_case in range(int(input())): n, x = [int(_) for _ in input().split()] a = [int(_) for _ in input().split()] if sum(a) == n*x: print("YES") else: print("NO") # model solution
2078
B
Vicious Labyrinth
\begin{quote} Axium Crisis - ak+q \end{quote} There are $n$ cells in a labyrinth, and cell $i$ ($1 \leq i \leq n$) is $n - i$ kilometers away from the exit. In particular, cell $n$ is the exit. Note also that each cell is connected to the exit but is not accessible from any other cell in any way. In each cell, there ...
Try to put as many people in cell $n$ as possible. The minimum sum of distances will always be $1$. The following configuration gives $1$ as the sum of distances. For odd $k$: $n, n, \ldots, n, n, n-1$ For even $k$: $n-1, n-1, \ldots, n-1, n, n-1$ And the sum of distances cannot be $0$. Look at this as a directed (or m...
[ "constructive algorithms", "graphs", "greedy", "implementation", "math" ]
1,100
for test_case in range(int(input())): n, k = [int(_) for _ in input().split()] if k % 2 == 0: for i in range(n-2): print(n-1, end = ' ') print(n, end = ' ') print(n-1) else: for i in range(n-2): print(n, end = ' ') print(n, end = ' ') p...
2078
D
Scammy Game Ad
Consider the following game. In this game, a level consists of $n$ pairs of gates. Each pair contains one left gate and one right gate. Each gate performs one of two operations: - \textbf{Addition Operation} (+ a): Increases the number of people in a lane by a constant amount $a$. - \textbf{Multiplication Operation} ...
It is optimal to place everyone on the same lane. Think about the multiplier. It is best to think of each $\tt{+}$ as "how much can we multiply this by". This is the greedy solution. When we get more people, place all to where the $\tt{x}$ will occur first. If both lanes have the next multiply at the same gate pair, th...
[ "dp", "greedy", "implementation" ]
1,800
def test_case(): n = int(input()) op = [[] for _ in range(n+1)] val = [[] for _ in range(n+1)] for i in range(1, n + 1): tmp = input().split() op[i] = [tmp[0], tmp[2]] val[i] = [int(tmp[1]), int(tmp[3])] op[0] = ['+', '+'] val[0] = [1, 1] dp = [[0, 0] for _ in ran...
2081
A
Math Division
Ecrade has an integer $x$. He will show you this number in the form of a binary number of length $n$. There are two kinds of operations. - Replace $x$ with $\left\lfloor \dfrac{x}{2}\right\rfloor$, where $\left\lfloor \dfrac{x}{2}\right\rfloor$ is the greatest integer $\le \dfrac{x}{2}$. - Replace $x$ with $\left\lce...
Consider $x$ in binary form. What are all possible numbers of operations to make $x$ equal to $1$? Consider using dynamic programming to calculate the answer. Similar to the previous problem, the possible number of operations can only be $n-1$ or $n$, depending on whether a carry-over occurs in $x$ during the $(n-1)$ -...
[ "bitmasks", "dp", "math", "probabilities" ]
1,800
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll inv2 = 5e8 + 4,mod = 1e9 + 7; ll t,n; char s[1000009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch...
2081
B
Balancing
Ecrade has an integer array $a_1, a_2, \ldots, a_n$. It's guaranteed that for each $1 \le i < n$, $a_i \neq a_{i+1}$. Ecrade can perform several operations on the array to make it strictly increasing. In each operation, he can choose two integers $l$ and $r$ ($1 \le l \le r \le n$) and replace $a_l, a_{l+1}, \ldots, ...
Let's only consider the comparison between adjacent pairs first. Call a pair $(a_i,a_{i+1})$ an inversion pair if $a_i>a_{i+1}$. In each operation, how can the number of inversion pairs change? Under what circumstances can we decrease the maximum number of inversion pairs in every operation? Let's only consider the com...
[ "greedy" ]
2,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,a[200009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int ma...
2081
C
Quaternary Matrix
A matrix is called quaternary if all its elements are $0$, $1$, $2$, or $3$. Ecrade calls a quaternary matrix $A$ good if the following two properties hold. - The bitwise XOR of all numbers in each row of matrix $A$ is equal to $0$. - The bitwise XOR of all numbers in each column of matrix $A$ is equal to $0$. Ecrad...
Do we really have to consider the problem on the whole matrix? Use greedy algorithm and guess some possible conclusions. Can you prove them (or construct some counterexamples) ? The problem can be rephrased as follows: Let the XOR sum of each row be $r_1, r_2, \ldots, r_n$, and the XOR sum of each column be $c_1, c_2, ...
[ "bitmasks", "constructive algorithms", "greedy", "implementation", "matrices" ]
2,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,m,a[1009][1009]; char s[1009]; vector <ll> row[4],col[4]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (c...
2081
D
MST in Modulo Graph
You are given a complete graph with $n$ vertices, where the $i$-th vertex has a weight $p_i$. The weight of the edge connecting vertex $x$ and vertex $y$ is equal to $\operatorname{max}(p_x, p_y) \bmod \operatorname{min}(p_x, p_y)$. Find the smallest total weight of a set of $n - 1$ edges that connect all $n$ vertices...
There are only $O(n\log n)$ edges that are truly useful in the whole graph. First, for vertices with the same weight, they can naturally be treated as a single vertex. We observe that in the interval of weights $(kx,(k+1)x)\ (k\ge 1)$, only the smallest $y$ is useful. It is because, if $x<y<z<2x$, connecting edges $(x,...
[ "constructive algorithms", "dsu", "graphs", "greedy", "math", "number theory", "sortings", "trees" ]
2,600
#include<iostream> #include<cstdio> #include<algorithm> #include<string.h> #include<vector> #include<queue> #include<map> #include<ctime> #include<bitset> #include<set> #include<math.h> //#include<unordered_map> #define fi first #define se second #define mp make_pair #define pii pair<int,int> #define pb push_back #defi...
2081
E
Quantifier
Given a rooted tree with $n+1$ nodes labeled from $0$ to $n$, where the root is node $0$, and \textbf{its only child is node $1$}. There are $m$ \textbf{distinct} chips labeled from $1$ to $m$, each colored either black or white. Initially, they are arranged on edge $(0,1)$ from top to bottom in ascending order of labe...
Move each chip as deep as possible in descending order of labels. Can we simplify the operations after that? Now we only need to move the chips upward and swap adjacent chips with the same color. What can we do after that? We can perform dynamic programming (DP) to calculate the numbers. What information do we need to ...
[ "combinatorics", "dp", "implementation" ]
3,300
#include <bits/stdc++.h> #define eb emplace_back using namespace std; typedef long long ll; const int p=998244353; int T,n,m,fa[5005],col[5005],d[5005],stk[5005],top,ct[5005][2]; int C[5005][5005],fac[5005],siz[5005],f[5005][2][5005],g[2][5005],ans; vector<int> to[5005],vec[5005]; inline void diff(int u,int v){ int S=...
2081
F
Hot Matrix
Piggy Zhou loves matrices, especially those that make him get excited, called hot matrix. A hot matrix of size $n \times n$ can be defined as follows. Let $a_{i, j}$ denote the element in the $i$-th row, $j$-th column ($1 \le i, j \le n$). - Each column and row of the matrix is a permutation of all numbers from $0$ t...
First, it is not difficult to observe that when $n$ is odd, a solution exists if and only if $n = 1$. When $n$ is even, a solution always exists. Consider the following construction: Let $n = 2m$. Use $(x, y)$ to denote the cell in the $x$-th row and $y$-th column of the matrix, and assume the top-left corner of the ma...
[ "constructive algorithms", "math" ]
3,300
#include<bits/stdc++.h> using namespace std; int Test_num,n; int a[3002][3002]; void solve() { scanf("%d",&n); if(n>=3 && (n&1))return (void)(puts("NO")); puts("YES"); if(n==1)return (void)(puts("0")); for(int i=0;i<n;i+=2) { for(int j=1;j<=i+1;++j)a[j][i+2-j]=i+((j&1)^1); for(int j=i+2;j<=n;++j)a[j][j-i-1]=i...
2081
G1
Hard Formula
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, the limits on $n$ and the time limit are smaller. You can hack only if you solved all versions of this problem.} You are given an integer $n$, and you need to compute $(\sum_{k=1}^n k\bmod\varphi(k))\bmod 2^{3...
If $g'(np)\neq g'(n)$ , then $p\le n$ unless $n=2,p=3$ or $n=1,p=2$ . Think about the method of $\min 25$ sieve. We define $\displaystyle g(n)=\frac n{\varphi(n)}=\prod_{p|n}\frac p{p-1},g'(n)=\lfloor g(n)\rfloor$. It's easy to see that $res=\frac{N(N+1)}2-\sum_{i=1}^Ng'(i)\varphi(i)$. Let's consider how to calculate $...
[ "math", "number theory" ]
3,100
#include<cstdio> #include<cmath> typedef unsigned long long ull; typedef unsigned uint; const uint M=1e6+5; ull N;const uint ANS[11]={0,0,0,1,1,2,2,3,3,6,8}; uint B,n4,top,pri[M],F0[M],F1[M],G0[M],G1[M],SF[M],SG[M]; inline ull Div(const ull&n,const ull&m){ return double(n)/m; } inline ull min(const ull&a,const ull&b){...
2081
G2
Hard Formula (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the limit on $n$ and the time limit are higher. You can hack only if you solved all versions of this problem.} You are given an integer $n$, and you need to compute $(\sum_{k=1}^n k\bmod\varphi(k))\bmod 2^{32}...
Consider the DFS structure of $\min 25$ sieve. What kind of nodes are important? How many of nodes are important? Consider using Du Sieve to get some important functions. For further optimization, let's consider the DFS tree of $\min25$ sieve: $N$ vertices, rooted on $1$, the father of a node $d$ is $\frac{d}{\text{max...
[ "math" ]
3,400
#include<bitset> #include<cstdio> #include<vector> #include<cmath> #include<ctime> using std::min; using std::max; typedef unsigned uint; typedef unsigned long long ull; namespace Sol{ const uint M=4162277+5,Pi=1001258+5,M2=500000000+5; uint sum;ull N; uint F[M],G[M]; uint top,Sp[Pi],pri[Pi],pi[M],phi[M...
2082
A
Binary Matrix
A matrix is called binary if all its elements are either $0$ or $1$. Ecrade calls a binary matrix $A$ good if the following two properties hold: - The bitwise XOR of all numbers in each row of matrix $A$ is equal to $0$. - The bitwise XOR of all numbers in each column of matrix $A$ is equal to $0$. Ecrade has a bina...
Do we really have to consider the problem on the whole matrix? Let $r$ be the number of rows where the bitwise XOR of all the numbers in it is $1$, and $c$ be the number of columns where the bitwise XOR of all the numbers in it is $1$. Our goal is to make both $r$ and $c$ zero. When we change an element in the matrix, ...
[ "constructive algorithms", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,m,r,c; char s[1009]; bool a[1009][1009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getc...
2082
B
Floor or Ceil
Ecrade has an integer $x$. There are two kinds of operations. - Replace $x$ with $\left\lfloor \dfrac{x}{2}\right\rfloor$, where $\left\lfloor \dfrac{x}{2}\right\rfloor$ is the greatest integer $\le \dfrac{x}{2}$. - Replace $x$ with $\left\lceil \dfrac{x}{2}\right\rceil$, where $\left\lceil \dfrac{x}{2}\right\rceil$ i...
Consider $x$ in binary form. What are all possible values of $x$ after $n+m$ operations? Let's consider how to find the maximum value first. Consider $x$ in binary form. Let the number formed by the last $n+m$ bits of $x$ be denoted as $r$, and the remaining higher bits form the number $l$ (for instance, if $x=12=(1100...
[ "brute force", "greedy" ]
1,600
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,x,n,m; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } ll F(ll x,ll...
2084
A
Max and Mod
You are given an integer $n$. Find any permutation $p$ of length $n$$^{\text{∗}}$ such that: - For all $2 \le i \le n$, $\max(p_{i - 1}, p_i) \bmod i$ $^{\text{†}}$ $= i - 1$ is satisfied. If it is impossible to find such a permutation $p$, output $-1$. \begin{footnotesize} $^{\text{∗}}$A permutation of length $n$ i...
When $n$ is odd, we can construct $p = [n, 1, 2, \ldots, n - 1]$. In this case: For $i = 2$, $\max(p_1, p_2) = n$ and $n \bmod 2 = 1$. For $i \geq 3$, $\max(p_{i - 1}, p_i) = i - 1$ and $(i - 1) \bmod i = i - 1$. It can be proven that there is no solution when $n$ is even. Clearly, $n$ cannot be placed at $p_1, p_2$, o...
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int T, n; cin >> T; while (T--) { cin >> n; if (n & 1) { cout << n << ' '; for (int i = 1; i < n; ++i) { cout << i << " \n"[i == n - 1]; } } else { cout << "-1\n"; } } return 0; }
2084
B
MIN = GCD
You are given a positive integer sequence $a$ of length $n$. Determine if it is possible to rearrange $a$ such that there exists an integer $i$ ($1 \le i<n$) satisfying $$ \min([a_1,a_2,\ldots,a_i])=\gcd([a_{i+1},a_{i+2},\ldots,a_n]). $$ Here $\gcd(c)$ denotes the greatest common divisor of $c$, which is the maximum p...
For any positive integer sequence $a$, we always have $\gcd(a) \leq \min(a)$. Let $x = \min(a)$, then $x$ must be placed on the $\min([a_1, a_2, \ldots, a_i])$ side. Thus, we can conclude that: $\min([a_1, a_2, \ldots, a_i]) = \gcd([a_{i + 1}, a_{i + 2}, \ldots, a_n]) = x$ Now, we need to select some numbers, excluding...
[ "greedy", "math", "number theory" ]
1,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); int T, n; cin >> T; while (T--) { cin >> n; vector<ll> a(n); for (ll &x : a) { cin >> x; } int p = min_element(a.begin(), a.end()) - a.begin(); ll g = 0; for (int i = 0; i < n; ++...
2084
C
You Soared Afar With Grace
You are given a permutation $a$ and $b$ of length $n$$^{\text{∗}}$. You can perform the following operation at most $n$ times: - Choose two indices $i$ and $j$ ($1 \le i, j \le n$, $i \ne j$), swap $a_i$ with $a_j$, swap $b_i$ with $b_j$. Determine whether $a$ and $b$ can be reverses of each other after operations. I...
By analyzing the structure of the operation, we can see that each pair $(a_i, b_i)$ is swapped together, meaning that the corresponding $b_i$ of a given $a_i$ remains unchanged. Since our goal is to make $b$ the reverse of $a$, in the final sequence, $(a_{n - i + 1}, b_{n - i + 1})$ must be equal to $(b_i, a_i)$. This ...
[ "constructive algorithms", "data structures", "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; const int maxn = 200100; int n, a[maxn], b[maxn], m, p[maxn], ans[maxn][2]; inline void work(int x, int y) { if (x == y) { return; } ans[++m][0] = x; ans[m][1] = y; swap(a[x], a[y]); swap(p[a[x]], p[a[y]]); swap(b[x], b[y]); } void solve() { cin >> n; for (in...
2084
D
Arcology On Permafrost
You are given three integers $n$, $m$, and $k$, where $m \cdot k < n$. For a sequence $b$ consisting of non-negative integers, define $f(b)$ as follows: - You may perform the following operation on $b$: - Let $l$ denote the current length of $b$. Choose a positive integer $1 \leq i \leq l - k + 1$, remove the subarr...
Since performing the operation will never increase $\operatorname{mex}$ of the sequence, we can treat "at most $m$ operations" as "exactly $m$ operations". Next, we consider computing the maximum value of $f(a)$. First, we have $f(a) \leq n - m \cdot k$ because after the operations, the length of $a$ becomes $n - m \cd...
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T--) { int n, m, k; cin >> n >> m >> k; for (int i = 0; i < n; ++i) { cout << i % (n < (m + 1) * k ? k : n / (m + 1)) << " \n"[i == n - 1]; } } return 0; }
2084
E
Blossom
You are given a permutation $a$ of length $n$$^{\text{∗}}$ where some elements are missing and represented by $-1$. Define the value of a permutation as the sum of the MEX$^{\text{†}}$ of all its non-empty subsegments$^{\text{‡}}$. Find the sum of the value of all possible valid permutations that can be formed by fil...
We transform $\operatorname{mex}([a_i, a_{i + 1}, \ldots, a_j])$ into $\sum\limits_{k = 0}^{n - 1} [\text{numbers from 0 to}\ k\ \text{all appear in}\ [i, j]]$. Let there be $t$ occurrences of $-1$ in $a$. Since $a$ needs to be a permutation, for each number from $0$ to $k$, if it has appeared in $a$, it must appear in...
[ "binary search", "combinatorics", "dp", "implementation", "math", "two pointers" ]
2,400
#include <bits/stdc++.h> using namespace std; const int maxn = 5050; const int mod = 1000000007; int n, a[maxn], fac[maxn], C[maxn][maxn], b[maxn], d[maxn][maxn]; bool vis[maxn]; void solve() { cin >> n; for (int i = 0; i <= n; ++i) { vis[i] = 0; for (int j = 0; j <= n; ++j) { d[i][j] = 0; } } fac[0] = ...
2084
F
Skyscape
You are given a permutation $a$ of length $n$$^{\text{∗}}$. We say that a permutation $b$ of length $n$ is good if the two permutations $a$ and $b$ can become the same after performing the following operation \textbf{at most $n$ times} (possibly zero): - Choose two integers $l, r$ such that $1 \le l < r \le n$ and $a...
A permutation $b$ is considered good if and only if the ordered pairs in $a$ remain ordered pairs in $b$. In other words, for any pair $i < j$, if the position of $i$ in $a$ is smaller than that of $j$, then the position of $i$ in $b$ must also be smaller than that of $j$. Proof of necessity: The operation will not tur...
[ "constructive algorithms", "data structures", "greedy" ]
2,900
#include <bits/stdc++.h> using namespace std; const int maxn = 500100; int n, a[maxn], b[maxn], c[maxn], p[maxn], q[maxn]; struct node { int r, x; node(int a = 0, int b = 0) : r(a), x(b) {} }; inline bool operator < (const node &a, const node &b) { return a.r > b.r || (a.r == b.r && a.x > b.x); } vector<node> v...
2084
G1
Wish Upon a Satellite (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $t \le 1000$, $n \le 5000$ and the sum of $n$ does not exceed $5000$. You can hack only if you solved all versions of this problem.} For a non-empty sequence $c$ of length $k$, define $f(c)$ as follows: - Tur...
First, we have $f(c) = \begin{cases} \min(c_1, c_k) & k \bmod 2 = 0 \\ \max(c_1, c_k) & k \bmod 2 = 1 \end{cases}$ Symmetrically, let $g(c)$ be the result when the order of the first and second players is swapped. Then, $g(c) = \begin{cases} \max(c_1, c_k) & k \bmod 2 = 0 \\ \min(c_1, c_k) & k \bmod 2 = 1 \end{cases}$ ...
[ "dp", "games" ]
2,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int n; cin >> n; vector<int> a(n + 1, -1); vector< vector<ll> > f(n + 1, vector<ll>(n + 1, 1e18)); for (int i = 1, x; i <= n; ++i) { cin >> x; if (x) { a[x] = i & 1; } } if (a[1] != 1) { f[1][0] = 0; } if (a[1] != 0)...
2084
G2
Wish Upon a Satellite (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $t \le 10^4$, $n \le 5 \cdot 10^5$ and the sum of $n$ does not exceed $5 \cdot 10^5$. You can hack only if you solved all versions of this problem.} For a non-empty sequence $c$ of length $k$, define $f(c)$ as...
Please read the solution for G1 first. Now, consider the operations we need to perform on the DP array at each step: For all $j$, update $f_{i, j}$ by adding $j \times \left(\left\lfloor\frac{n}{2}\right\rfloor - (i - j)\right) + (i - j) \times \left(\left\lceil\frac{n}{2}\right\rceil - j\right) = 2j^2 + (-2i - (n \bmo...
[ "data structures", "dp" ]
3,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 500100; int n, a[maxn]; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); int p[maxn], nt, ls[maxn], rs[maxn], sz[maxn]; bool vis[maxn]; struct vec { ll a0, a1, a2; vec(ll a = 0, ll b = 0, ll c = 0) : a0(a), a1...
2084
H
Turtle and Nediam 2
\begin{quote} LGR-205-Div.1 C Turtle and Nediam \end{quote} You are given a binary sequence $s$ of length $n$ which only consists of $0$ and $1$. You can do the following operation \textbf{at most $n - 2$ times} (possibly zero): - Let $m$ denote the current length of $s$. Choose an integer $i$ such that $1 \le i \le...
First, extract the longest contiguous segments in $s$ where the values remain the same. Suppose there are $m$ such segments with lengths $a_1, a_2, \dots, a_m$. Then, the operations can be described as follows: Choose an index $1 \leq i \leq |a|$ such that $a_i \geq 2$ and decrease $a_i$ by 1. Choose an index $2 \leq i...
[ "dp", "greedy" ]
3,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 2000100; const ll mod = 1000000007; int n, a[maxn], m, nxt[maxn], stk[maxn], top; ll f[maxn], g[maxn], d[maxn]; char s[maxn]; inline ll calc() { top = 0; for (int i = m; i >= 1; i -= 2) { while (top && a[stk[top]] - stk[top] / 2...
2085
A
Serval and String Theory
A string $r$ consisting only of lowercase Latin letters is called universal if and only if $r$ is lexicographically smaller$^{\text{∗}}$ than the reversal$^{\text{†}}$ of $r$. You are given a string $s$ consisting of $n$ lowercase Latin letters. You are required to make $s$ universal. To achieve this, you can perform ...
When $s$ is lexicographically equal to or greater than the reversal of $s$, is it possible to make $s$ universal by performing the operations? If possible, what is the minimum number of the operations required to make $s$ universal? Case 1. If $s$ contains only one kind of letter, the answer will be NO. Case 2. If $s$ ...
[ "constructive algorithms", "implementation" ]
900
getint = lambda: int(input()) getints = lambda: map(int, input().split()) def solve(): n, k = getints() s = input().strip() if s < s[::-1] or (k >= 1 and min(s) != max(s)): print('YES') else: print('NO') t = getint() for _ in range(t): solve()
2085
B
Serval and Final MEX
You are given an array $a$ consisting of $n\ge 4$ non-negative integers. You need to perform the following operation on $a$ until its length becomes $1$: - Select two indices $l$ and $r$ ($1\le {\textcolor{red}{ l < r }} \le |a|$), and replace the subarray $[a_l,a_{l+1},\ldots,a_r]$ with a single integer $\operatorna...
Before the last operation, what should the array be to obtain $0$? How to make all the elements in the array non-zero? Note that before the last operation, all the integers in the array should be positive. Thus, we aim to turn the zeroes in $a$ into non-zeroes. To achieve this, we split the given array $a$ into two hal...
[ "constructive algorithms", "implementation" ]
1,200
getint = lambda: int(input()) getints = lambda: map(int, input().split()) def solve(): n = getint() a = list(getints()) op = [] mid, r = n // 2, n if 0 in a[mid:]: op.append([mid + 1, n]) r -= n - mid - 1 if 0 in a[:mid]: op.append([1, mid]) r -= mid - 1 op.append([1, r]) print(len(op)) for o in op: ...
2085
C
Serval and The Formula
You are given two positive integers $x$ and $y$ ($1\le x, y\le 10^9$). Find a \textbf{non-negative} integer $k\le 10^{18}$, such that $(x+k) + (y+k) = (x+k)\oplus (y+k)$ holds$^{\text{∗}}$, or determine that such an integer does not exist. \begin{footnotesize} $^{\text{∗}}$$\oplus$ denotes the bitwise XOR operation. ...
The formula $(x+k) + (y+k) = (x+k) \oplus (y+k)$ is equivalent to $(x+k) \mathbin{\&} (y+k) = 0$, where $\&$ denotes the bitwise AND operation. Note that a power of $2$ shares no common bits with any positive integer less than it. It can be shown that such an non-negative integer $k$ does not exist when $x=y$. When $x\...
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
1,600
getint = lambda: int(input()) getints = lambda: map(int, input().split()) def solve(): x, y = getints() if x == y: print(-1) else: print(2 ** 48 - max(x, y)) t = getint() for _ in range(t): solve()
2085
D
Serval and Kaitenzushi Buffet
Serval has just found a Kaitenzushi buffet restaurant. Kaitenzushi means that there is a conveyor belt in the restaurant, delivering plates of sushi in front of the customer, Serval. In this restaurant, each plate contains exactly $k$ pieces of sushi and the $i$-th plate has a deliciousness $d_i$. Serval will have a m...
Do not go for DP. How many plates of sushi can be taken? What are the constraints on the time of taking plates of sushi? Note that the last $i$-th time taking a plate of sushi should be no later than the $(n - i\cdot(k+1) + 1)$-th minute. This constraint limits the time that a taking action can be performed. Therefore,...
[ "data structures", "graph matchings", "greedy" ]
2,000
#include <cstdio> #include <queue> using namespace std; const int N = 2e5 + 5; int n, k; int d[N]; long long ans; void solve() { scanf("%d%d", &n, &k); ans = 0; priority_queue <int> q; for (int i = 1; i <= n; i++) { scanf("%d", &d[i]); q.push(d[i]); if ((n - i + 1) % (k + 1) == 0) { ans += q.top(); ...
2085
E
Serval and Modulo
There is an array $a$ consisting of $n$ non-negative integers and a magic number $k$ ($k\ge 1$, $k$ is an integer). Serval has constructed another array $b$ of length $n$, where $b_i = a_i \bmod k$ holds$^{\text{∗}}$ for all $1\leq i\leq n$. Then, he \textbf{shuffled} $b$. You are given the two arrays $a$ and $b$. Fin...
What happens when an integer $a_i$ mods $k$? Note that the difference between $a_i$ and $b_i$ is a multiple of $k$. The same holds for the difference between the sum of $a_i$ and the sum of $b_i$. Notice that $d(n) \leq 2304$ holds for all $n \leq 10^{10}$, where $d(n)$ denotes the number of divisors of $n$. Note that ...
[ "constructive algorithms", "math", "number theory" ]
2,200
#include <cstdio> using namespace std; const int N = 1e4 + 5; const int C = 1e6 + 5; int n; int a[N], b[N]; int cnt[C]; long long s; bool check(int k) { for (int i = 1; i <= n; i++) cnt[a[i] % k]++; for (int i = 1; i <= n; i++) if (--cnt[b[i]] < 0) { cnt[b[i]] = 0; for (int i = 1; i <= n; i++) cnt[a...
2085
F1
Serval and Colorful Array (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $n\le 3000$. You can hack only if you solved all versions of this problem.} Serval has a magic number $k$ ($k\ge 2$). We call an array $r$ colorful if and only if: - The length of $r$ is $k$, and - Each integ...
Consider the integers in the colorful subarray after swapping. How to gather these integers together, forming a colorful subarray, with the minimum number of swaps? Consider the middle one among all the the elements in the colorful subarray. Consider the elements in the colorful subarray after swapping. The first obser...
[ "data structures", "greedy" ]
2,600
#include <cstdio> #include <algorithm> using namespace std; const int N = 3005; const long long oo = 1e18; int n, k; int a[N], l[N], r[N], d[N]; long long ans; void solve() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); ans = oo; for (int i = 1; i <= n; i++) { for (int j = 1; j <=...
2085
F2
Serval and Colorful Array (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $n\le 4\cdot 10^5$. You can hack only if you solved all versions of this problem.} Serval has a magic number $k$ ($k\ge 2$). We call an array $r$ colorful if and only if: - The length of $r$ is $k$, and - Eac...
Is it possible to simplify the constraints? Is it possible to remove the constraint that exactly $k\over 2$ elements should be chosen from both sides of the enumerated position? Optimizing the solution of F1 using (possibly, heavy) data structures results in a $O(n\log n)$ solution. Here we introduce a linear approach ...
[ "data structures", "greedy" ]
2,900
#include <cstdio> #include <algorithm> using namespace std; const int N = 4e5 + 5; const long long oo = 1e18; int n, k; int a[N]; int last[N], dd[N]; long long s, d, ans; void solve() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) last[i] = dd[i] = 0; s = 0; for (int i = 1; i <= n; i++) { scanf("%d",...
2086
A
Cloudberry Jam
The most valuable berry of the Karelian forests is cloudberry. To make jam from cloudberries, you take equal amounts of berries and sugar and cook them. Thus, if you have $2$ kg of berries, you need $2$ kg of sugar. However, from $2$ kg of berries and $2$ kg of sugar, you will not get $4$ kg of jam, as one might expect...
As stated in the problem, to prepare one $3$kg jar of jam, $2$ kg of berries are required; therefore, to prepare $n$ jars, you need to take $2 \cdot n$ kg of cloudberries.
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--) { int n; cin >> n; cout << n * 2 << "\n"; } return 0; }
2086
B
Large Array and Segments
There is an array $a$ consisting of $n$ \textbf{positive} integers, and a positive integer $k$. An array $b$ is created from array $a$ according to the following rules: - $b$ contains $n \cdot k$ numbers; - the first $n$ numbers of array $b$ are the same as the numbers of array $a$, that is, $b_{i} = a_{i}$ for $i \le...
In this problem, the array $b$ is obtained by copying the array $a$ exactly $k$ times. Notice that all elements of the array $a$ are positive; therefore, the elements of the array $b$ are also positive. From this, we can conclude that the optimal $r$ for any $l$ that maximizes the sum over the segment [$l, r$] is alway...
[ "binary search", "brute force", "greedy" ]
1,100
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int n, k, x; cin >> n >> k >> x; vector<int> a(n); for (int i = 0; i < n; i++){ cin >> a[i]; } if (accumulate(a.begin(), a.end(), 0ll) * k < x){ cout << 0 << '\n'; return; } int l ...
2086
C
Disappearing Permutation
A permutation of integers from $1$ to $n$ is an array of size $n$ where each integer from $1$ to $n$ appears exactly once. You are given a permutation $p$ of integers from $1$ to $n$. You have to process $n$ queries. During the $i$-th query, you replace $p_{d_i}$ with $0$. Each element is replaced with $0$ exactly onc...
Let's take a closer look at how the fixing the array operation works: Suppose we have a missing number $p_{d_{i}}$, we know that the final permutation must contain this number, and the only place we can put the number $p_{d_{i}}$ is position $p_{d_{i}}$. However, if we place the number there, we might lose $p_{p_{d_{i}...
[ "dfs and similar", "dp", "dsu", "graphs", "greedy", "implementation" ]
1,300
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int n; cin >> n; vector<int> p(n); for (int i = 0; i < n; i++){ cin >> p[i]; p[i]--; } set<int> X; for (int i = 0; i < n; i++){ int d; cin >> d; d--; while(!X.co...
2086
D
Even String
You would like to construct a string $s$, consisting of lowercase Latin letters, such that the following condition holds: - For every pair of indices $i$ and $j$ such that $s_{i} = s_{j}$, the difference of these indices is even, that is, $|i - j| \bmod 2 = 0$. Constructing any string is too easy, so you will be give...
From the statement, it follows that all identical letters in $s$ must be positioned either at even indices or at odd indices simultaneously. Let's examine how the ways to construct the string $s$ are formed: A subset of letters that we take for the odd positions (the remaining letters will be at the even positions); Th...
[ "brute force", "combinatorics", "dp", "math", "strings" ]
1,700
#include<bits/stdc++.h> using namespace std; #define int long long const int MOD = 998'244'353; int bpow(int x, int p){ int res = 1; while(p){ if (p % 2){ res = (res * x) % MOD; } p >>= 1; x = (x * x) % MOD; } return res; } int fact(int x){ int res = 1; for (int i = 1; i <= x; i++){ res = (res ...
2086
E
Zebra-like Numbers
We call a positive integer zebra-like if its binary representation has alternating bits up to the most significant bit, and the least significant bit is equal to $1$. For example, the numbers $1$, $5$, and $21$ are zebra-like, as their binary representations $1$, $101$, and $10101$ meet the requirements, while the numb...
First, let's see how many zebra-Like numbers less than or equal to $10^{18}$ exist. It turns out there are only $30$ of them, and based on some zebra-like number $z_{i}$, the next one can be calculated using the formula $z_{i + 1} = 4 \cdot z_{i} + 1$. Then, we have to be able to quickly calculate the zebra value for a...
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dp", "greedy", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; vector<long long> z; void precalc() { z = {1ll}; while(z.back() < 1e18) z.push_back(4 * z.back() + 1); } map<pair<long long, long long>, long long> dp; long long get(long long r, long long x) { if(dp.count(make_pair(r, x))) return dp[make_pair(r,...
2086
F
Online Palindrome
This is an interactive problem. The jury has a string $s$ consisting of lowercase Latin letters. The following constraints apply to this string: - the string has an odd length that does not exceed $99$; - the string consists only of the characters "a" and "b". There is also a string $t$, which is initially empty. Th...
From the problem statement, it can be understood that at each step, when we have an odd number of characters, the string $t$ must be a palindrome, since the length of the string $s$ is not provided. Therefore, we need to come up with a strategy for swaps to ensure this condition is met. The first thought is to try a br...
[ "brute force", "constructive algorithms", "interactive" ]
3,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int N = 100; bool dp[N][N]; pair<int, int> nxt[N][N][2]; bitset<N> cur; bitset<N> form[N][N]; int main(){ forn(i, N) forn(j, N) dp[i][j] = (i + j) % 2; for (int len = 1; len < N; len += 2){ forn(x, len + 1){...
2089
A
Simple Permutation
Given an integer $n$. Construct a permutation $p_1, p_2, \ldots, p_n$ of length $n$ that satisfies the following property: For $1 \le i \le n$, define $c_i = \lceil \frac{p_1+p_2+\ldots +p_i}{i} \rceil$, then among $c_1,c_2,\ldots,c_n$ there must be at least $\lfloor \frac{n}{3} \rfloor - 1$ prime numbers.
Lemma (Bertrand's postulate): For each positive integer $x$, there is a prime $p$ inside the interval $[x,2x]$. Find a prime number $p$ between $\lfloor \frac{n}{3} \rfloor$ and $\lceil \frac{2n}{3} \rceil$, and construct the permutation in an alternating way: $p, p-1, p+1, p-2, p+2, \dots$. Place the remaining numbers...
[ "constructive algorithms", "number theory" ]
1,700
#include<bits/stdc++.h> using namespace std; bool isPrime(int x){ if(x <= 1) return 0; for(int i = 2 ; i * i <= x ; ++i) if(x % i == 0) return 0; return 1; } vector<int> generateSol(int n, int p){ vector<int> ans; ans.push_back(p); for(int i = 1 ; i <= n ; ++i){ if(p - i > 0) ans.push_back(p - i); ...
2089
B1
Canteen (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $k=0$. You can hack only if you solved all versions of this problem.} Ecrade has two sequences $a_0, a_1, \ldots, a_{n - 1}$ and $b_0, b_1, \ldots, b_{n - 1}$ consisting of integers. It is guaranteed that the ...
For each $a_i$, calculate the minimum number of cyclic right shifts required to reduce it to zero, denoted as $d_i$. The answer is the maximum $d_i$ across all $i$. For cyclic problems, we can consider breaking the cycle into a chain (i.e., let $a_{i+n} = a_i$, $b_{i+n} = b_i$). Consider constructing a parenthesis sequ...
[ "binary search", "data structures", "flows", "greedy", "two pointers" ]
1,900
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,k,a[400009],stk[400009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s...
2089
B2
Canteen (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, there are no additional limits on $k$. You can hack only if you solved all versions of this problem.} Ecrade has two sequences $a_0, a_1, \ldots, a_{n - 1}$ and $b_0, b_1, \ldots, b_{n - 1}$ consisting of inte...
We can use binary search on the answer $x$, and calculate the minimum number of changes needed to make $a$ zero within $x$ rounds. However, direct computation on the cyclic chain of $2n$ elements is troublesome (due to overlapping contributions). Instead, we can cyclically shift $a$ and $b$ such that $c_{n-1} = \min\li...
[ "binary search", "data structures", "dp", "flows", "greedy", "two pointers" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,k,pos,a[400009],stk[400009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); retu...
2089
C2
Key of Like (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $k$ can be non-zero. You can hack only if you solved all versions of this problem.} A toy box is a refrigerator filled with childhood delight. Like weakness, struggle, hope ... When such a sleeper is reawakene...
This problem is inspired by a minigame from a recently released party video game, but the story was modified to comply with the title. We tried to isolate the artistic part and the theoretical part, and I apologize if you still feel like working on reading comprehension exercises. Noticing that each member's strategy i...
[ "dp", "math", "probabilities" ]
3,100
#include <cstdio> #include <cstring> using namespace std; #define MOD 1000000007 #define MAXN 108 #define MAXL 5004 #define MAXK 27 int e[MAXN], p[2][MAXK][MAXN], inv[2 * MAXL + MAXK]; inline void _update(int * const a, const int lbd, const int rbd, const int base, const int diff) { (a[0] += base) %= MOD; (a[lbd] +...
2089
D
Conditional Operators
In C++, the conditional operator ?: is used as the value of x?y:z is $y$ if $x$ is true; otherwise, the value is $z$. $x$, $y$, and $z$ may also be expressions. It is right-associated; that is, a?b:c?d:e is equivalent to a?b:(c?d:e). $0$ means false and $1$ means true. Given a binary string with length $2n+1$, you nee...
Each operation transform three adjacent characters into one. If the string starts with 11, the answer should be yes since we can first transform the remaining part into a single 0 or 1 and then the value of 11? is always $1$. If the string ends with 1, only 101 has no solution, otherwise it starts with 11 or 0, or we c...
[ "constructive algorithms" ]
3,200
#include<bits/stdc++.h> char s[333333]; char val(char x,char y,char z){ return x=='1'?y:z; } std::pair<std::string, char> fold(int l,int r){ std::string str; char v=s[r]; for(int i=l;i<r;i+=2){ str+=s[i]; str+='?'; str+=s[i+1]; str+=':'; } str+=s[r]; for(int i=r-2;i>=l;i-=2){ v=val(s[i],s[i+1],v); } ...
2089
E
Black Cat Collapse
The world of the black cat is collapsing. In this world, which can be represented as a rooted tree with root at node $1$, Liki and Sasami need to uncover the truth about the world. Each day, they can explore a node $u$ that has not yet collapsed. After this exploration, the black cat causes $u$ and all nodes in its s...
Firstly, consider a classical dp to calculate $dp_{u,k}$ as the number of delete $k$ vertices in subtree $u$ without considering deleting vertex $n-i+1$ everyday. This is trivial. Then, due to the existence of an "automatic deletion" process, we cannot view the selected points within the subtree of $u$ as operations wi...
[]
3,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; int read() { int x=0,f=1; char c=getchar(); while(c<'0'||c>'9') { if(c=='-')f=-1; c=getchar(); } while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar(); return x*f; } namespace tokido_saya { const int maxn=81,mod=998244353; typedef vector<int>::itera...
2090
A
Treasure Hunt
Little B and his friend Little K found a treasure map, and now they just need to dig up the treasure, which is buried at a depth of $a.5$ meters. They take turns digging. On the first day, Little B digs; on the second day, Little K. After each day, they switch. Little B digs exactly $x$ meters of soil each day, while ...
Let's calculate how many operations we need. The number of pairs of operations is $\left\lfloor\frac{a}{x + y}\right\rfloor$. Additionally, we add $+1$ if $(a \bmod (x + y)) \ge x$, because in this case, the first player will be able to make one more move. Note that the first part is always even, which means the answer...
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int x, y, a; cin >> x >> y >> a; if (a % (x + y) < x) { cout << "NO\n"; } else { cout << "YES\n"; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) solve...
2090
B
Pushing Balls
Ecrade has an $n \times m$ grid, originally empty, and he has pushed several (possibly, zero) balls in it. Each time, he can push one ball into the grid either from the leftmost edge of a particular row or the topmost edge of a particular column of the grid. When a ball moves towards a position: - If there is no bal...
We can transform the problem into: select a row / column and replace the leftmost / topmost $0$ with $1$. Then the solution is clear: if, for each $1$ in the grid, there does not exist any $0$ on its top, or does not exist any $0$ on its left, then the answer is YES; otherwise NO. But how to prove that if the condition...
[ "brute force", "dp", "implementation" ]
1,000
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,m,a[59][59],vis[59][59]; char s[59]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(...
2090
C
Dining Hall
Inside the large kingdom, there is an infinite dining hall. It can be represented as a set of cells ($x, y$), where $x$ and $y$ are non-negative integers. There are an infinite number of tables in the hall. Each table occupies four cells ($3x + 1, 3y + 1$), ($3x + 1, 3y + 2$), ($3x + 2, 3y + 1$), ($3x + 2, 3y + 2$), wh...
Original idea from myee has $4$ cases, which is a medium difficulty problem using deletable heap. You may find the original statement in zh-cn on GitHub later. The Codeforces version by FairyWinx has only $2$ cases, in order to meet the difficulty as Div2C. The En/Ru statement changes for times after checking. Sorry fo...
[ "data structures", "greedy", "implementation", "sortings" ]
1,700
#include <bits/stdc++.h> using uint = unsigned; using bol = bool; const uint T=2000; const uint R=200000; uint Ord[R+5]; uint Nxt(uint p,uint o) { uint x=p/T,y=p%T; if(o&1)y=y/3*3+3-y%3; if(o&2)x=x/3*3+3-x%3; return x*T+y; } bol G[2][T*T];uint Ans[2]; int main() { #ifdef MYEE freopen("QAQ.in","...
2091
A
Olympiad Date
The final of the first Olympiad by IT Campus "NEIMARK" is scheduled for March 1, 2025. A nameless intern was tasked with forming the date of the Olympiad using digits — 01.03.2025. To accomplish this, the intern took a large bag of digits and began drawing them one by one. In total, he drew $n$ digits — the digit $a_i...
Let's start a digit counter $cnt[i]$ ($0 \leq i \leq 9$). At the moment when $3 \leq cnt[0]$, $1 \leq cnt[1]$, $2 \leq cnt[2]$, $1 \leq cnt[3]$, $1 \leq cnt[5]$ - the answer is found. If after counting all the digits one of the conditions is not fulfilled, then there is no solution and the answer is $0$. $O(n)$.
[ "greedy", "strings" ]
800
#include <iostream> using namespace std; void solve() { int n; cin >> n; int cnt[10] = {}; bool f = 0; for (int i = 0; i < n; i++) { int dig; cin >> dig; cnt[dig]++; if (cnt[0] >= 3 && cnt[1] >= 1 && cnt[2] >= 2 && cnt[3] >= 1 && cnt[5] >= 1 && !f...
2091
B
Team Training
At the IT Campus "NEIMARK", there are training sessions in competitive programming — both individual and team-based! For the next team training session, $n$ students will attend, and the skill of the $i$-th student is given by a positive integer $a_i$. The coach considers a team strong if its strength is at least $x$...
Let's assume that there are $k$ people in a team and $a[i_1]$ - the student with the lowest skill. Then all other participants will have skill greater than or equal to $a[i_1] \leq a[i_2], \ldots a[i_k]$. The greater the value of $a[i_1]$, the fewer people are needed to form a team. In essence, at each stage after sort...
[ "dp", "greedy", "sortings" ]
800
#include <iostream> #include <algorithm> using namespace std; void solve() { int n, x; cin >> n >> x; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); reverse(a, a + n); int ans = 0; for (int i = 0, cnt = 1; i < n; i++, cnt++) { if (a[i] * cnt...
2091
C
Combination Lock
At the IT Campus "NEIMARK", there are several top-secret rooms where problems for major programming competitions are developed. To enter one of these rooms, you must unlock a circular lock by selecting the correct code. This code is updated every day. Today's code is a permutation$^{\text{∗}}$ of the numbers from $1$ ...
Let after $k$ cyclic shifts the element $p_i$ be at position $(i + k) \mod n$. For this point to be fixed, it is necessary that $(i + k) \mod n = p_i$. Let assume that permutation $p$ is starting from $0$, $[0, 1, 2, \ldots, n - 1]$. From this we get that $k = p_i - i \ (mod \ n)$. For any cyclic shift to be a fixed po...
[ "constructive algorithms", "greedy" ]
1,000
#include <iostream> using namespace std; void solve() { int n; cin >> n; if (n % 2 == 0) { cout << -1 << endl; return; } for (int i = n; i > 0; i--) { cout << i << ' '; } cout << endl; } int main() { int t = 1; cin >> t; while (t--) solve(); ...
2091
D
Place of the Olympiad
For the final of the first Olympiad by IT Campus "NEIMARK", a rectangular venue was prepared. You may assume that the venue is divided into $n$ rows, each containing $m$ spots for participants' desks. A total of $k$ participants have registered for the final, and each participant will sit at an individual desk. Now, th...
Let the length of the maximal bench be $x$, then to maximize the number of desks in one row - we need to put as many benches of exactly $x$ length as possible. There should be an indent after each bench, let's say, that the length of the block is $x + 1$. The total number of such blocks in a row will be $\lfloor \frac{...
[ "binary search", "greedy", "math" ]
1,200
#include <iostream> using namespace std; void solve() { long long n, m, k, l, r, mid; cin >> n >> m >> k; l = 0, r = m; while (l + 1 < r) { mid = (l + r) / 2; if ((m / (mid + 1) * mid + m % (mid + 1)) * n >= k) { r = mid; } else { l = mid; ...
2091
E
Interesting Ratio
Recently, Misha at the IT Campus "NEIMARK" camp learned a new topic — the Euclidean algorithm. He was somewhat surprised when he realized that $a \cdot b = lcm(a, b) \cdot gcd(a, b)$, where $gcd(a, b)$ — is the greatest common divisor (GCD) of the numbers $a$ and $b$ and $lcm(a, b)$ — is the least common multiple (LCM...
Let $a = gcd(a, b) \cdot x$, $b = gcd(a, b) \cdot y$ for some $x$ and $y$. Now $F(a,b)=\frac{lcm(a, b)}{gcd(a, b)} = \frac{a \cdot b}{ gcd(a,b)^2} = x \cdot y$. Since $F(a,b)$ - is a prime number, then $x \cdot y$ - is a prime number. For $x \cdot y$ to be a prime number, then one of the numbers must be prime and the o...
[ "brute force", "math", "number theory", "two pointers" ]
1,300
#include <iostream> using namespace std; const int MAXN = 10000001; bool prime[MAXN]; void solve() { int n, ans = 0; cin >> n; for (int i = 2; i <= n; i++) { if (prime[i]) { ans += n / i; } } cout << ans << endl; } int main() { for (int i = 0; i < MAXN; ...
2091
F
Igor and Mountain
The visitors of the IT Campus "NEIMARK" are not only strong programmers but also physically robust individuals! Some practice swimming, some rowing, and some rock climbing! Master Igor is a prominent figure in the local rock climbing community. One day, he went on a mountain hike to ascend one of the peaks. As an expe...
Let's use the dynamic programming method $dp[i][j][f]$: $i$ - row number. $j$ - column number. $f = 0$ means that exactly one hold has already been selected in the current row, and a second one can still be added (since there are a maximum of two holds per level). $f = 1$ means that two holds have already been used in ...
[ "binary search", "brute force", "dp" ]
1,800
#include <iostream> using namespace std; const int MAXN = 2010; const int MOD = 998244353; string s[MAXN]; int dp[MAXN][MAXN][2]; long long sdp[MAXN][MAXN][2]; int n, m, d; long long getsum(int x, int y1, int y2, int f) { long long res = sdp[x][y2][f]; if (y1) res -= sdp[x][y1 - 1][f]; return res; } i...
2091
G
Gleb and Boating
Programmer Gleb frequently visits the IT Campus "NEIMARK" to participate in programming training sessions. Not only is Gleb a programmer, but he is also a renowned rower, so he covers part of his journey from home to the campus by kayaking along a river. Assume that Gleb starts at point $0$ and must reach point $s$ (i...
Let's consider a simple solution - we will iterate through Gleb's current strength $t$, from $k$ to $1$, and check which positions can be reached using that strength value. For each fixed $t$, the set of positions can be obtained by any search method, for example, breadth-first search. Next, let's assume that Gleb has ...
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "greedy", "math", "number theory", "shortest paths" ]
2,300
#include <iostream> #include <vector> using namespace std; int s, k, p; vector<bool> was1, was2; void bfs() { vector<int> v; for (int i = 0; i < s; i++) { if (was1[i]) v.push_back(i); } int q = 0; while (q < v.size()) { int x = v[q++]; int y = x + p * k; ...
2092
A
Kamilka and the Sheep
Kamilka has a flock of $n$ sheep, the $i$-th of which has a beauty level of $a_i$. All $a_i$ are distinct. Morning has come, which means they need to be fed. Kamilka can choose a non-negative integer $d$ and give each sheep $d$ bunches of grass. After that, the beauty level of each sheep increases by $d$. In the eveni...
It's always possible to make Kamilka's pleasure at least $|x - y|$ for any $x, y \in a$. First of all, it can be observed that for any two sheep with beauty levels $x < y$, the maximum possible pleasure cannot exceed $y - x$, since $\gcd(x, y) = \gcd(x, y - x)$. Secondly, we can choose $x = \min(a)$, $y = \max(a)$, and...
[ "greedy", "math", "number theory", "sortings" ]
800
t = int(input()) for test in range(t): n = int(input()) a = [int(i) for i in input().split()] print(max(a) - min(a))
2092
B
Lady Bug
As soon as Dasha Purova crossed the border of France, the villain Markaron kidnapped her and placed her in a prison under his large castle. Fortunately, the wonderful Lady Bug, upon hearing the news about Dasha, immediately ran to save her in Markaron's castle. However, to get there, she needs to crack a complex passwo...
Note that you can split strings $a$ and $b$ into two "zig-zags": $a_0, b_1, a_2, b_3, \dots$ and $b_0, a_1, b_2, a_3, \dots$ What are the necessary and sufficient conditions for each of these zig-zags? Note that you can split strings $a$ and $b$ into two "zig-zags": $a_0, b_1, a_2, b_3, \dots$ and $b_0, a_1, b_2, a_3, ...
[ "brute force", "constructive algorithms", "implementation", "math" ]
1,000
t = int(input()) for test in range(t): n = int(input()) a = input() b = input() cnt1, cnt2 = 0, 0 for i in range(n): if i % 2: cnt2 += (a[i] == '0') cnt1 += (b[i] == '0') else: cnt1 += (a[i] == '0') cnt2 += (b[i] == '0') if cnt1...
2092
C
Asuna and the Mosquitoes
For her birthday, each of Asuna's $n$ admirers gifted her a tower. The height of the tower from the $i$-th admirer is equal to $a_i$. Asuna evaluates the beauty of the received gifts as $\max(a_1, a_2, \ldots, a_n)$. She can perform the following operation an arbitrary number of times (possibly, zero). - Take such $1...
Consider two cases: first, when all numbers have the same parity; and second, when there is at least one even and one odd number. Let $S$ be the sum of all numbers, and $k$ be the number of odd numbers in the array. Then, in the second case, the answer is $S - k + 1$. Case 1. All numbers in $a$ have the same parity. In...
[ "constructive algorithms", "greedy", "math" ]
1,200
t = int(input()) for test in range(t): n = int(input()) a = [int(i) for i in input().split()] ans, cnt = 0, 0 for i in a: ans += i cnt += i % 2 if not cnt or cnt == n: print(max(a)) else: print(ans - cnt + 1)
2092
D
Mishkin Energizer
In anticipation of a duel with his old friend Fernan, Edmond is preparing an energy drink called "Mishkin Energizer". The drink consists of a string $s$ of length $n$, made up only of the characters L, I, and T, which correspond to the content of three different substances in the drink. We call the drink balanced if i...
It is impossible to balance the string if and only if all its letters are the same. It is clear that there is no solution if all the letters in $s$ are the same. Let us now prove that a solution always exists in all other cases. While the string remains unbalanced, let us assume that $\text{cnt}(a) \le \text{cnt}(b) \l...
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
1,800
#include <vector> #include <string> #include <iostream> #include <set> #include <map> using namespace std; vector<char> a = {'L', 'I', 'T'}; int main() { int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; set<char> se; for (auto u : s) se.insert(u); i...
2092
E
She knows...
D. Pippy is preparing for a "black-and-white" party at his home. He only needs to repaint the floor in his basement, which can be represented as a board of size $n \times m$. After the last party, the entire board is painted green, except for some $k$ cells $(x_1, y_1), (x_2, y_2), \ldots, (x_k, y_k)$, each of which i...
If a cell has an even number of neighbours, does its color matter? Let $S$ be the set of cells that have an odd number of neighbouring cells. It is easy to observe that $S$ consists of border cells, excluding the corner ones. More precisely, $S = \{(i, j) \ \vert \ \left( i \in \{1, n\} \right) \ \bigoplus \ \left( j \...
[ "combinatorics", "constructive algorithms", "graphs", "math" ]
2,100
#include <iostream> #include <vector> using namespace std; using ll = long long; const ll mod = 1000000007; ll binpow (ll a, ll n) { ll res = 1; while (n) { if (n & 1) { res *= a; res %= mod; } a *= a; a %= mod; n >>= 1; } return res; } void solve() { ll n...
2092
F
Andryusha and CCB
Let us define the beauty of a binary string $z$ as the number of indices $i$ such that $1 \le i < |z|$ and $z_i \neq z_{i+1}$. While waiting for his friends from the CCB, Andryusha baked a pie, represented by a binary string $s$ of length $n$. To avoid offending anyone, he wants to divide this string into $k$ substrin...
It is sufficient to consider only two types of blocks of consecutive 0s and 1s: those of size $1$ and those of size greater than $1$. For a fixed beauty value $m$ of a substring, there are $O\left(\frac{sz}{m}\right)$ possible values of $k$, where $sz$ is the number of blocks of consecutive 0s and 1s. For a fixed pair ...
[ "brute force", "constructive algorithms", "greedy", "math", "number theory", "strings" ]
2,900
#include <iostream> #include <vector> using namespace std; using ll = long long; void solve() { int n; cin >> n; string s; cin >> s; vector <int> a; int curr = 0; for (int i = 0; i < n; ++i) { if (i && s[i] != s[i - 1]) { if (curr) a.push_back(curr); curr = 1; ...
2093
A
Ideal Generator
We call an array $a$, consisting of $k$ positive integers, palindromic if $[a_1, a_2, \dots, a_k] = [a_k, a_{k-1}, \dots, a_1]$. For example, the arrays $[1, 2, 1]$ and $[5, 1, 1, 5]$ are palindromic, while the arrays $[1, 2, 3]$ and $[21, 12]$ are not. We call a number $k$ an ideal generator if any integer $n$ ($n \g...
If we consider some palindromic array $a$ of the form $[a_1, a_2, \dots, a_k]$ and its sum, we should discuss two different cases. When $k$ is even ($k = 2m$), the array $a$ looks as follows: $[a_1, a_2, \dots, a_{m - 1}, a_m, a_m, a_{m - 1}, \dots, a_2, a_1]$. Its sum in this case is the number $2 \cdot (a_1 + a_2 + \...
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; if (n % 2 == 1) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; }
2093
B
Expensive Number
The cost of a positive integer $n$ is defined as the result of dividing the number $n$ by the sum of its digits. For example, the cost of the number $104$ is $\frac{104}{1 + 0 + 4} = 20.8$, and the cost of the number $111$ is $\frac{111}{1 + 1 + 1} = 37$. You are given a positive integer $n$ that does not contain lea...
We will prove that the minimum possible cost of the resulting number is always equal to $1$. Consider an arbitrary positive number $n = \overline{a_1a_2\ldots a_k}$, where $a_i$ are its digits in order. We evaluate the cost of this number as $cost(n) = \frac{\overline{a_1a_2\ldots a_k}}{a_1+a_2+\ldots+a_k} = \frac{a_1 ...
[ "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int n = s.size(); bool met_positive = false; int cnt_zero = 0; for (auto i = n - 1; i >= 0; --i) { if (s[i] != '0') { ...
2093
C
Simple Repetition
Pasha loves prime numbers$^{\text{∗}}$! Once again, in his attempts to find a new way to generate prime numbers, he became interested in an algorithm he found on the internet: - To obtain a new number $y$, repeat $k$ times the decimal representation of the number $x$ (without leading zeros). For example, for $x = 52$...
Let the number $x$ have $b$ digits in its decimal representation. What does it mean to write it $k$ times? It can be shown that $y = x \cdot 10^0 + x \cdot 10^b + x \cdot 10^{2b} + \dots + x \cdot 10^{(k - 1)b} = x \cdot (10^0 + 10^b + 10^{2b} + \dots + 10^{(k-1)b})$ We are left to consider 2 cases: $k = 1$, in this ca...
[ "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; bool is_prime(int x) { if (x <= 1) { return false; } for (int i = 2; i * i <= x; i++) { if (x % i == 0) { return false; } } return true; } void solve() { int x, k; cin >> x >> k; if (k > 1 && x > 1) {...
2093
D
Skibidi Table
Vadim loves filling square tables with integers. But today he came up with a way to do it for fun! Let's take, for example, a table of size $2 \times 2$, with rows numbered from top to bottom and columns numbered from left to right. We place $1$ in the top left cell, $2$ in the bottom right, $3$ in the bottom left, and...
Note that there are $4$ possible positions of the cell and the values within it: $x,y \le 2^{n-1} \Leftrightarrow d \le 2^{2n-2}$; $x,y > 2^{n-1} \Leftrightarrow 2^{2n-2} < d \le 2 \cdot 2^{2n-2}$; $x > 2^{n-1}, y \le 2^{n-1} \Leftrightarrow 2 \cdot 2^{2n-2} < d \le 3 \cdot 2^{2n-2}$; $x \le 2^{n-1}, y > 2^{n-1} \Leftr...
[ "bitmasks", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, q; cin >> n >> q; while (q--) { string type; cin >> type; if (type == "->") { int x, y; ...