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 ⌀ |
|---|---|---|---|---|---|---|---|
2037 | G | Natlan Exploring | You are exploring the stunning region of Natlan! This region consists of $n$ cities, and each city is rated with an attractiveness $a_i$. A directed edge exists from City $i$ to City $j$ if and only if $i < j$ and $\gcd(a_i,a_j)\neq 1$, where $\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y... | Denote $dp[i]=$ the number of ways to get to city $i$. Brute-forcing all possible previous cities is out of the question, as this solution will take $O(n^2\cdot\log({\max{a_i}}))$ time complexity. What else can we do? Instead, consider caseworking on what the greatest common factor can be. Let's keep track of an array ... | [
"bitmasks",
"combinatorics",
"data structures",
"dp",
"math",
"number theory"
] | 2,000 | import sys
def input():
return sys.stdin.buffer.readline().strip()
MOD = 998244353
ma = int(1e6 + 5)
P = [1] * ma
D = [[] for _ in range(ma)]
for i in range(2, ma):
if P[i] == 1:
for j in range(i, ma, i):
P[j] = i
F = [0] * ma
LU = [0] * ma
BMS = [[] for _ in range(ma)]
RES = []
from itert... |
2039 | A | Shohag Loves Mod | Shohag has an integer $n$. Please help him find an \textbf{increasing} integer sequence $1 \le a_1 \lt a_2 \lt \ldots \lt a_n \le 100$ such that $a_i \bmod i \neq a_j \bmod j$ $^{\text{∗}}$ is satisfied over all pairs $1 \le i \lt j \le n$.
It can be shown that such a sequence always exists under the given constraints... | THOUGHT: A general approach to tackle ad-hoc problems is to play around with the conditions and see if we can add more constraints to limit the search space. ACTION: Let's analyze the modular condition $a_i \bmod i$. We know that $a_i \bmod i < i$, and all $a_i \bmod i$ values are distinct. Let's explore this step by s... | [
"constructive algorithms",
"number theory"
] | 800 | #include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 9;
using ll = long long;
void solve() {
int n; cin >> n;
for (int i = 1; i <= n; i++) {
cout << 2 * i - 1 << ' ';
}
cout << '\n';
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
cin >> t;
while (t--) {
... |
2039 | B | Shohag Loves Strings | For a string $p$, let $f(p)$ be the number of distinct non-empty substrings$^{\text{∗}}$ of $p$.
Shohag has a string $s$. Help him find a non-empty string $p$ such that $p$ is a substring of $s$ and $f(p)$ is even or state that no such string exists.
\begin{footnotesize}
$^{\text{∗}}$A string $a$ is a substring of a ... | THOUGHT: The condition seems hard to track. So a good way is to play around with smaller cases and see if we can make some observations. ACTION: Let's start with the smallest string. When $s=$ a, the number of unique substrings $f(s) = 1$, so it's odd and not valid. OBSERVATION: No one length strings are valid. ACTION:... | [
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | 1,000 | #include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 9;
using ll = long long;
void solve() {
string s; cin >> s;
int n = s.size();
for (int i = 0; i + 1 < n; i++) {
if (s[i] == s[i + 1]) {
cout << s.substr(i, 2) << '\n';
return;
}
}
for (int i = 0; i + 2 < n; i++) {
if (s... |
2039 | C1 | Shohag Loves XOR (Easy Version) | \textbf{This is the easy version of the problem. The differences between the two versions are highlighted in bold. You can only make hacks if both versions of the problem are solved.}
Shohag has two integers $x$ and $m$. Help him count the number of integers $1 \le y \le m$ such that $\mathbf{x \neq y}$ and $x \oplus ... | THOUGHT: Here $x > 0$ and $y > 0$. So $x \oplus y$ is neither equal to $x$ nor $y$. So $x \oplus y$ is a divisor of $x$ or $y$ and $x \oplus y < x$ or $x \oplus y < y$. OBSERVATION: Any divisor $d$ of $p$ such that $d < p$ we know that $d \le \lfloor \frac{p}{2} \rfloor$. Also, the highest bits of $d$ and $p$ are diffe... | [
"bitmasks",
"brute force",
"math",
"number theory"
] | 1,200 | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int x; ll m; cin >> x >> m;
int ans = 0;
for (int y = 1; y <= min(2LL * x, m); y++) {
if (x != y and ((x % (x ^ y)) == 0 or (y % (x ^ y) == 0))) {
++ans;
}
}
cout << ans << '\n';
}
int32_t main() {
ios_base::... |
2039 | C2 | Shohag Loves XOR (Hard Version) | \textbf{This is the hard version of the problem. The differences between the two versions are highlighted in bold. You can only make hacks if both versions of the problem are solved.}
Shohag has two integers $x$ and $m$. Help him count the number of integers $1 \le y \le m$ such that $x \oplus y$ is \textbf{divisible$... | THOUGHT: Consider the three cases of when $x \oplus y$ is divisible by $x$, $y$, or both separately. Case 1: $x \oplus y$ is divisible by $x$. THOUGHT: Let $p = x \oplus y$. So $y = p \oplus x$. So we can rephrase the problem as counting the number of integers $p$ such that $p$ is divisible by $x$ and $1 \le p \oplus x... | [
"bitmasks",
"brute force",
"math",
"number theory"
] | 1,800 | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int x; ll m; cin >> x >> m;
// divisible by x
ll p = m - m % x;
ll ans = p / x - (x < p);
if ((x ^ p) >= 1 and (x ^ p) <= m) ++ans;
p += x;
if ((x ^ p) >= 1 and (x ^ p) <= m) ++ans;
// divisibly by y
for (int y = 1; ... |
2039 | D | Shohag Loves GCD | Shohag has an integer $n$ and a set $S$ of $m$ unique integers. Help him find the lexicographically largest$^{\text{∗}}$ integer array $a_1, a_2, \ldots, a_n$ such that $a_i \in S$ for each $1 \le i \le n$ and $a_{\operatorname{gcd}(i, j)} \neq \operatorname{gcd}(a_i, a_j)$$^{\text{†}}$ is satisfied over all pairs $1 \... | THOUGHT: For problems where we need to construct something under some conditions, then a good idea is to first see the nature of the sequences that satisfy the conditions. And to find the properties of such sequences we can try to find some necessary conditions that must have to be met for the sequence to satisfy the c... | [
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,700 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
using ll = long long;
vector<int> d[N];
void solve() {
int n, m; cin >> n >> m;
vector<int> s(m + 1);
for (int i = 1; i <= m; i++) {
cin >> s[i];
}
vector<int> a(n + 1, -1);
for (int i = 1; i <= n; i++) {
set<int> banned;
for ... |
2039 | E | Shohag Loves Inversions | Shohag has an array $a$ of integers. Initially $a = [0, 1]$. He can repeatedly perform the following operation any number of times:
- Let $k$ be the number of inversions$^{\text{∗}}$ in the current array $a$.
- Insert $k$ at any position in $a$, including the beginning or the end.
For example, if $a = [4, 6, 2, 4]$, ... | It's hard to track the array when we insert new inversions as the inversion number can quickly become very large. The key observation here is to notice what happens when the inversion count becomes more than $1$. As the initial array has only $0$ and $1$ as elements when we insert an inversion count that is more than $... | [
"combinatorics",
"dp",
"implementation",
"math"
] | 2,200 | #include <bits/stdc++.h>
#include <chrono>
std::mt19937 eng(std::chrono::steady_clock::now().time_since_epoch().count());
int rnd(int l, int r) { return std::uniform_int_distribution<int>(l, r)(eng); }
namespace FastIO {
// char buf[1 << 21], *p1 = buf, *p2 = buf;
// #define getchar() (p1 == p2 && (p1 = buf, p2 = (p1... |
2039 | F1 | Shohag Loves Counting (Easy Version) | \textbf{This is the easy version of the problem. The only differences between the two versions of this problem are the constraints on $t$, $m$, and the sum of $m$. You can only make hacks if both versions of the problem are solved.}
For an integer array $a$ of length $n$, define $f(k)$ as the greatest common divisor (... | Let $s_k$ be the sequence of $k$ length subarray maximums of the array. Then $s_{k + 1}$ is just the adjacent maximum sequence of $s_k$. Also, let $g_k$ be the GCD of the elements of $s_k$. Then notice that every element of $s_{k + 1}$ is also divisible by $g_k$. That is $g_k$ divides $g_{k + 1}$. For the array to be g... | [
"combinatorics",
"dp",
"math",
"number theory"
] | 2,800 | #include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 9, mod = 998244353;
using ll = long long;
int add(int a, int b){
a += b;
if(a > mod) a -= mod;
if(a < 0) a += mod;
return a;
}
// dp[i][j] = number of arrays where starting element is i and gcd of the array is j
int dp[N], cur[N], uni[N];
int sum[N... |
2039 | F2 | Shohag Loves Counting (Hard Version) | \textbf{This is the hard version of the problem. The only differences between the two versions of this problem are the constraints on $t$, $m$, and the sum of $m$. You can only make hacks if both versions of the problem are solved.}
For an integer array $a$ of length $n$, define $f(k)$ as the greatest common divisor (... | First, check the editorial of F1. Note that for F2 there is no limit on the sum of $m$, so we need to change the approach a bit. And for F2 you need to remove the length from the dp state (which I described at the end of the editorial of F1). Now instead of iterating $i$ from $m$ to $1$, we iterate from $1$ to $m$. And... | [
"dp",
"number theory"
] | 3,200 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 9, mod = 998244353;
inline void add(int &x, int y) {
x = x + y >= mod ? x + y - mod : x + y;
}
int spf[N];
void sieve() {
vector<int> p;
for(int i = 2; i < N; i++) {
if (spf[i] == 0) spf[i] = i, p.push_back(i);
int sz = p.size();
for... |
2039 | G | Shohag Loves Pebae | Shohag has a tree with $n$ nodes.
Pebae has an integer $m$. She wants to assign each node a value — an integer from $1$ to $m$. So she asks Shohag to count the number, modulo $998\,244\,353$, of assignments such that following conditions are satisfied:
- For each pair $1 \le u \lt v \le n$, the least common multiple ... | Let's say we assign $a_u$ to the node $u$. Let $h_u$ be the maximum length of a simple path that passes through $u$. Then a necessary condition is that $a_u$ can not be a multiple of any number $\le h_u$. Because if $a_u$ is a multiple of $k \le h_u$ and $v$ is a node such that the unique simple path from $u$ to $v$ ha... | [
"math",
"number theory"
] | 3,500 | #include<bits/stdc++.h>
using namespace std;
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d... |
2039 | H1 | Cool Swap Walk (Easy Version) | \textbf{This is the easy version of the problem. The only difference is the maximum number of operations you can perform. You can only make hacks if both versions are solved.}
You are given an array $a$ of size $n$.
A cool swap walk is the following process:
- In an $n \times n$ grid, we note the cells in row $i$ an... | We can observe that this kind of path is imporatnt - when we are in $(x, x)$, we only perform one of the following two kind of moves: Move 1 $(x, x) \rightarrow (x, x+1) \rightarrow (x+1, x+1)$ This move transforms $[\ldots,a_x, a_{x+1},\ldots]$ into $[\ldots,a_{x+1}, a_{x},\ldots]$. Move 2 $(x, x) \rightarrow (x, x+1)... | [
"constructive algorithms",
"implementation",
"sortings"
] | 3,500 | #include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <bitset>
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ... |
2039 | H2 | Cool Swap Walk (Hard Version) | \textbf{This is the hard version of the problem. The only difference is the maximum number of operations you can perform. You can only make hacks if both versions are solved.}
You are given an array $a$ of size $n$.
A cool swap walk is the following process:
- In an $n \times n$ grid, we note the cells in row $i$ an... | First, read the editorial of the easy version. We can see that the bottleneck lies in the fact that after every round of odd-even sorting, we need to perform a walk operation to ensure that $a_1 = mn$. The following method can break through this bottleneck: for simplicity, let's assume $n$ is even. Define the numbers s... | [
"constructive algorithms",
"implementation",
"sortings"
] | 3,500 | #include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <bitset>
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ... |
2040 | A | Game of Division | You are given an array of integers $a_1, a_2, \ldots, a_n$ of length $n$ and an integer $k$.
Two players are playing a game. The first player chooses an index $1 \le i \le n$. Then the second player chooses a different index $1 \le j \le n, i \neq j$. The first player wins if $|a_i - a_j|$ is not divisible by $k$. Oth... | $|x - y|$ is divisible by $k$ if and only if $x \mod k = y \mod k$. Let's split all numbers into groups according to the value $x \mod k$. The second player wins if he chooses a number from the same group. This means that the first player must choose the number that is the only one in its group. | [
"games",
"math"
] | 800 | for _ in range(int(input())):
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = [[] for _ in range(k)]
for i in range(0, n):
x = a[i]
b[x % k].append(i + 1)
res = -1
for i in range(k):
if len(b[i]) == 1:
res = b[i][0]
break
... |
2040 | B | Paint a Strip | You have an array of \textbf{zeros} $a_1, a_2, \ldots, a_n$ of length $n$.
You can perform two types of operations on it:
- Choose an index $i$ such that $1 \le i \le n$ and $a_i = 0$, and assign $1$ to $a_i$;
- Choose a pair of indices $l$ and $r$ such that $1 \le l \le r \le n$, $a_l = 1$, $a_r = 1$, $a_l + \ldots ... | At each moment of time, the array contains a number of non-intersecting segments consisting only of ones. Using an operation of the first type can increase the number of these segments by $1$. Using an operation of the second type decreases the number of these segments by $x - 1$, where $x$ - is the number of segments ... | [
"constructive algorithms",
"greedy",
"math"
] | 1,000 | tt = int(input())
for _ in range(tt):
n = int(input())
ans = 1
cur = 1
while True:
if cur >= n:
print(ans)
break
ans += 1
cur = cur * 2 + 2 |
2040 | C | Ordered Permutations | Consider a permutation$^{\text{∗}}$ $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$. We can introduce the following sum for it$^{\text{†}}$:
$$S(p) = \sum_{1 \le l \le r \le n} \min(p_l, p_{l + 1}, \ldots, p_r)$$
Let us consider all permutations of length $n$ with the maximum possible value of $S(p)$. Output the ... | These permutations are generated as follows. We will greedily go through the numbers in order from $1$ to $n$, and we will put each one either in the first free cell or in the last one. For example, if we want to put $4$ in the permutation $1, 3, \circ, \circ, \dots, \circ, 2$, we can put it either in the third cell or... | [
"bitmasks",
"combinatorics",
"constructive algorithms",
"greedy",
"math",
"two pointers"
] | 1,600 | tt = int(input())
for _ in range(tt):
n, k = map(int, input().split())
a, b = [], []
if n <= 60 and (1 << (n - 1)) < k:
print(-1)
continue
k -= 1
d = []
while k:
d.append(k % 2)
k //= 2
while len(d) < n - 1:
d.append(0)
a, b = [], []
j = 1
... |
2040 | D | Non Prime Tree | You are given a tree with $n$ vertices.
You need to construct an array $a_1, a_2, \ldots, a_n$ of length $n$, consisting of \textbf{unique} integers from $1$ to $2 \cdot n$, and such that for each edge $u_i \leftrightarrow v_i$ of the tree, the value $|a_{u_i} - a_{v_i}|$ is not a prime number.
Find any array that sa... | There are many array construction tactics that can be devised here. We will show two of them. We will perform a depth-first traversal of the graph and write a number $1$ greater than the previous one in the traversal order into each subsequent vertex. If the next vertex is not a leaf, then some number has already been ... | [
"brute force",
"constructive algorithms",
"dfs and similar",
"greedy",
"number theory",
"trees",
"two pointers"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void dfs(int v, vector<vector<int>>& g, vector<int>& h, int p) {
h[v] = h[p] + 1;
for (int u : g[v]) {
if (u == p)
continue;
dfs(u, g, h, v);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
... |
2040 | E | Control of Randomness | You are given a tree with $n$ vertices.
Let's place a robot in some vertex $v \ne 1$, and suppose we initially have $p$ coins. Consider the following process, where in the $i$-th step (starting from $i = 1$):
- If $i$ is odd, the robot moves to an adjacent vertex in the direction of vertex $1$;
- Else, $i$ is even. Y... | To begin with, let's solve it without queries and forced movements. Let's consider the nature of the path. The current vertex $v$ has a parent of parent $u$. Let there be an odd move now, and the robot will go to the parent of $v$. If we're lucky, it'll go to $u$. Otherwise, it will go to the brother of vertex $v$. But... | [
"combinatorics",
"dfs and similar",
"dp",
"graphs",
"greedy",
"math",
"probabilities",
"trees"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n, q;
cin >> n >> q;
vector < vector <int> > g(n);
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--, v--;
g[u].push_back(v);
g[v].push_back(u);
}
vector <int> dept... |
2040 | F | Number of Cubes | Consider a rectangular parallelepiped with sides $a$, $b$, and $c$, that consists of unit cubes of $k$ different colors. We can apply cyclic shifts to the parallelepiped in any of the three directions any number of times$^{\text{∗}}$.
There are $d_i$ cubes of the $i$-th color ($1 \le i \le k$). How many different para... | Recall Burnside's lemma - the number of elements up to an action group is: $\frac{1}{|G|} \cdot \sum_{g \in G} {\sum_{x \in X}{[g x = x]}}$ , where $[x] = 1$ if $x = true$ and $[x] = 0$ if $x = false$. Let's try to iterate over the elements of the action group - all triplets of numbers $[0, a)$, $[0, b)$, $[0, c)$. Whe... | [
"combinatorics",
"dp",
"math",
"number theory"
] | 2,700 | #include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3000010;
const int mod = 998244353;
int fact[N], ifact[N];
int pos[N];
int powmod(int a, int n) {
int res = 1;
while (n) {
if (n % 2 == 0) {
a = (a * a) % mod;
n /= 2;
}
else {... |
2042 | A | Greedy Monocarp | There are $n$ chests; the $i$-th chest initially contains $a_i$ coins. For each chest, you can choose any non-negative ($0$ or greater) number of coins to add to that chest, with one constraint: the total number of coins in all chests must become \textbf{at least $k$}.
After you've finished adding coins to the chests,... | Consider several first chests that Monocarp will take before exceeding the limit if we don't add any coins; so, this will be the set of several largest chests such that the sum of this set is $s \le k$, but if the next chest is taken, the sum would exceed $k$. For this set, the minimum number of coins that should be ad... | [
"greedy",
"sortings"
] | 800 | #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;
sort(a.begin(), a.end(), greater<int>());
int sum = 0;
for (auto& x : a) {
if (sum + x <= k) sum += x;
else br... |
2042 | B | Game with Colored Marbles | Alice and Bob play a game. There are $n$ marbles, the $i$-th of them has color $c_i$. The players take turns; Alice goes first, then Bob, then Alice again, then Bob again, and so on.
During their turn, a player \textbf{must} take \textbf{one} of the remaining marbles and remove it from the game. If there are no marble... | It's fairly intuitive that if there is at least one unique marble available (a marble is unique if there are no other marbles with the same color), taking it is optimal: if Alice takes that marble, she gets $2$ points, and if Bob takes that marble, he denies $2$ points to Alice. So, initially, both players take unique ... | [
"games",
"greedy"
] | 900 | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
for(int _ = 0; _ < t; _++)
{
int n;
scanf("%d", &n);
vector<int> c(n);
for(int i = 0; i < n; i++)
{
scanf("%d", &c[i]);
--c[i];
}
vector<int... |
2042 | C | Competitive Fishing | Alice and Bob participate in a fishing contest! In total, they caught $n$ fishes, numbered from $1$ to $n$ (the bigger the fish, the greater its index). Some of these fishes were caught by Alice, others — by Bob.
Their performance will be evaluated as follows. First, an integer $m$ will be chosen, and all fish will be... | The main idea we need to solve this problem is the following one. For each fish, its value will be equal to the number of groups before its group. So, each "border" between two groups increases the value of every fish after the border by $1$. Let $s_i$ be the number of Bob's fishes minus the number of Alice's fishes am... | [
"greedy"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
string s;
cin >> n >> k >> s;
vector<int> vals;
int sum = 0;
for (int i = n - 1; i > 0; --i) {
sum += (s[i] == '1' ? 1 : -1);
if (sum > 0) vals.push_back(sum);
}
sort(... |
2042 | D | Recommendations | Suppose you are working in some audio streaming service. The service has $n$ active users and $10^9$ tracks users can listen to. Users can like tracks and, based on likes, the service should recommend them new tracks.
Tracks are numbered from $1$ to $10^9$. It turned out that tracks the $i$-th user likes form a segmen... | Firstly, if several segments are equal, then the answer for all of them is zero. Now let's move to the problem where all segments are distinct. User $j$ is a predictor for user $i$ iff $l_j \le l_i \le r_i \le r_j$. Also, a track is strongly recommended if it is in all predictor segments, i. e. the track belongs to the... | [
"data structures",
"implementation",
"sortings",
"two pointers"
] | 1,900 | #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())
struct Seg {
int l, r;
bool operator< (const Seg &oth) const {
if (l != oth.l)
return l < oth.l;
return r < oth.r;
};
};
void solve() {
int n;
cin >> n;
vector<Seg> seg(... |
2042 | E | Vertex Pairs | You are given a tree consisting of $2n$ vertices. Recall that a tree is a connected undirected graph with no cycles. Each vertex has an integer from $1$ to $n$ written on it. Each value from $1$ to $n$ is written on \textbf{exactly two} different vertices. Each vertex also has a cost —vertex $i$ costs $2^i$.
You need ... | Note that the cost function of a subset actually states the following: you are asked to choose the minimum lexicographic subset if the vertices are ordered in descending order. This can be shown by looking at the binary representations of the subset costs. Intuitively, we want to implement the following process. Iterat... | [
"binary search",
"brute force",
"data structures",
"dfs and similar",
"divide and conquer",
"greedy",
"implementation",
"trees"
] | 2,900 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
vector<vector<int>> g;
struct LCA {
vector<vector<pair<int, int>>> st;
vector<int> pw;
void build(vector<pair<int, int>> a) {
int n = a.size();
int lg = 32 - __builtin_clz(n);
st.resize(lg, vector<pair<i... |
2042 | F | Two Subarrays | You are given two integer arrays $a$ and $b$, both of size $n$.
Let's define the cost of the subarray $[l, r]$ as $a_l + a_{l + 1} + \cdots + a_{r - 1} + a_r + b_l + b_r$. If $l=r$, then the cost of the subarray is $a_l + 2 \cdot b_l$.
You have to perform queries of three types:
- "$1$ $p$ $x$" — assign $a_{p} := x$... | To begin with, let's understand how to calculate the answer if we consider only one query of the third type. For this, we can use the following dynamic programming: $dp_{i, k}$ - the maximum result if we have considered the first $i$ elements and chosen $k$ boundaries of subsegments (i.e., $k=0$ - the first segment has... | [
"data structures",
"dp",
"implementation",
"matrices"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const int N = 200 * 1000 + 13;
const int K = 5;
using li = long long;
using mat = array<array<li, K>, K>;
const li INF = 1e18;
int n, q;
li a[N], b[N];
mat t[4 * N];
mat init(li a, li b) {
mat c;
forn(i, K) for... |
2043 | A | Coin Transformation | Initially, you have a coin with value $n$. You can perform the following operation any number of times (possibly zero):
- transform one coin with value $x$, where $x$ is \textbf{greater than $3$} ($x>3$), into two coins with value $\lfloor \frac{x}{4} \rfloor$.
What is the maximum number of coins you can have after p... | Let's try to solve this problem "naively": obviously, while we have at least one coin with value $>3$, we should transform it, since it increases the number of coins we get. We can simulate this process, but the number of transformations we get might be really large, so we need to speed this up. Let's make it faster th... | [
"brute force",
"math"
] | 800 | t = int(input())
for i in range(t):
n = int(input())
ans = 1
while n > 3:
n //= 4
ans *= 2
print(ans) |
2043 | B | Digits | Artem wrote the digit $d$ on the board exactly $n!$ times in a row. So, he got the number $dddddd \dots ddd$ (exactly $n!$ digits).
Now he is curious about which \textbf{odd} digits from $1$ to $9$ divide the number written on the board. | There are several ways to solve this problem. I will describe two of them. Using divisibility rules (a lot of math involved): We can try divisibility rules for all odd integers from $1$ to $9$ and find out whether they work for our numbers: $1$ is always the answer, since every integer is divisible by $1$: a number is ... | [
"math",
"number theory"
] | 1,100 | import sys
sys.set_int_max_str_digits(6000)
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
t = int(input())
for i in range(t):
n, k = map(int, input().split())
n = min(n, 7)
s = int(str(k) * fact(n))
for i in range(1, 10, 2):
if s % i == 0:
print(i, end... |
2043 | C | Sums on Segments | You are given an array $a$ of $n$ integers, where all elements except for \textbf{at most one} are equal to $-1$ or $1$. The remaining element $x$ satisfies $-10^9 \le x \le 10^9$.
Find all possible sums of subarrays of $a$, including the empty subarray, whose sum is defined as $0$. In other words, find all integers $... | What could the answer to the problem be if all elements were equal to $1$ or $-1$? Let's consider all segments with a fixed left boundary $l$. The empty segment $[l; l-1]$ has a sum of $0$. As we move the right boundary to the right, the sum will change by $\pm1$. That is, we can obtain all sums from the minimum sum to... | [
"binary search",
"brute force",
"data structures",
"dp",
"greedy",
"math"
] | 1,600 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
l1, r1 = 0, 0
l2, r2 = 2*10**9, -2*10**9
pr = 0
mnl, mxl = 0, 0
mnr, mxr = 2*10**9, -2*10**9
for i in range(n):
pr += a[i]
if a[i] != -1 and a[i] != 1:
mnr, mxr = mnl, mxl
mnl, mxl = pr, pr
l1 = min(l1, pr - mxl)
... |
2043 | D | Problem about GCD | Given three integers $l$, $r$, and $G$, find two integers $A$ and $B$ ($l \le A \le B \le r$) such that their greatest common divisor (GCD) equals $G$ and the distance $|A - B|$ is maximized.
If there are multiple such pairs, choose the one where $A$ is minimized. If no such pairs exist, output "-1 -1". | First, let's try to solve this problem with $G=1$. We can check the pair $(l, r)$. If its greatest common divisor is not $1$, then we should check $(l, r-1)$ and $(l+1, r)$, i. e. the pairs on the distance $(r-l-1)$. If these don't work, we can check $(l, r-2)$, $(l+1, r-1)$ and $(l+2, r)$, and so on, and the answer wi... | [
"brute force",
"flows",
"math",
"number theory"
] | 1,800 | #include<bits/stdc++.h>
using namespace std;
long long gcd(long long x, long long y)
{
if(x == 0) return y;
else return gcd(y % x, x);
}
void solve()
{
long long l, r, g;
scanf("%lld %lld %lld", &l, &r, &g);
long long L = l + (l % g == 0 ? 0 : g - (l % g));
long long R = r - r % g;
for... |
2043 | E | Matrix Transformation | You are given two matrices $A$ and $B$ of size $n \times m$, filled with integers between $0$ and $10^9$. You can perform the following operations \textbf{on matrix $A$} in any order and any number of times:
- &=: choose two integers $i$ and $x$ ($1 \le i \le n$, $x \ge 0$) and replace each element in row $i$ with the... | Every operation which affects multiple bits can be split into several operations which only affect one bit. For example, if you make an |= operation with $x=11$, it is the same as making three |= operations with $x=1$, $x=2$ and $x=8$. So, let's solve the problem for each bit separately. If we consider only one bit, th... | [
"bitmasks",
"brute force",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"implementation"
] | 2,300 | #include<bits/stdc++.h>
using namespace std;
struct graph
{
int V;
vector<vector<int>> g;
vector<int> color;
bool dfs(int v)
{
if(color[v] != 0) return false;
color[v] = 1;
bool res = false;
for(auto y : g[v])
{
if(color[y] == 2) continue;
... |
2043 | F | Nim | Recall the rules of the game "Nim". There are $n$ piles of stones, where the $i$-th pile initially contains some number of stones. Two players take turns choosing a non-empty pile and removing any positive (strictly greater than $0$) number of stones from it. The player unable to make a move loses the game.
You are gi... | Let's recall the condition for the second player to win in the game of "Nim". The XOR of the sizes of the piles must be equal to $0$. That is, we are asked to remove as many piles as possible so that the XOR becomes $0$. Notice the following fact. Suppose there are $c$ piles of size $x$ on a segment. If we remove an ev... | [
"bitmasks",
"brute force",
"combinatorics",
"dp",
"games",
"greedy",
"implementation",
"shortest paths"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int MOD = 998244353;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
return a;
}
int mul(int a, int b){
return a * 1ll * b % MOD;
}
struct state{
int mx, cnt;
};
void merge(state &a, int m... |
2043 | G | Problem with Queries | You are given an array $a$, consisting of $n$ integers. Your task is to process $q$ queries of two types:
- $1~p~x$ — set the value of the element at index $p$ equal to $x$;
- $2~l~r$ — count the number of pairs of indices $(i, j)$ such that $l \le i < j \le r$ and $a_i \ne a_j$.
Note that the queries in this task ar... | First, let's reformulate the problem. Instead of counting the number of pairs of distinct elements in a segment, we will count the number of pairs of identical elements and subtract it from the total number of pairs. To solve this problem, we will use square root decomposition on the array. Let's divide the original ar... | [
"brute force",
"data structures",
"implementation"
] | 3,000 | null |
2044 | A | Easy Problem | Cube is given an integer $n$. She wants to know how many ordered pairs of positive integers $(a,b)$ there are such that $a=n-b$. Since Cube is not very good at math, please help her! | For any $n$, Cube can set $a$ = any integer between $1$ and $n-1$ inclusive, and set $b = n - a$. $a$ cannot be less than $1$, because then it would be non-positive, and $a$ cannot be greater than $n-1$, because then $b$ would be less than $1$, which would make it non-positive. Therefore the answer is just $n-1$ for al... | [
"brute force",
"math"
] | 800 | input = sys.stdin.readline
for _ in range(int(input())):
print(int(input())-1) |
2044 | B | Normal Problem | A string consisting of only characters 'p', 'q', and 'w' is painted on a glass window of a store. Ship walks past the store, standing directly in front of the glass window, and observes string $a$. Ship then heads inside the store, looks directly at the same glass window, and observes string $b$.
Ship gives you string... | The letters she reads that comprise string $b$ are just the letters that comprise string $a$, flipped left-to-right. This means that 'p' becomes 'q', 'q' becomes 'p', and 'w' stays 'w', since it is vertically symmetrical. The order in which the letters are read is also reversed, because what used to be the left side of... | [
"implementation",
"strings"
] | 800 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pll pair<ll, ll>
int t;
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> t;
while (t--) {
string s;
cin >> s;
reverse(s.begin(), s.end());
for (char &c : s) if (c == 'q') c = 'p'; else if (c == 'p') c = 'q';
cout << s << '\n';
... |
2044 | C | Hard Problem | Ball is the teacher in Paperfold University. The seats of his classroom are arranged in $2$ rows with $m$ seats each.
Ball is teaching $a + b + c$ monkeys, and he wants to assign as many monkeys to a seat as possible. Ball knows that $a$ of them only want to sit in row $1$, $b$ of them only want to sit in row $2$, and... | Let $A$, $B$, $C$ be three sets of monkeys, such that monkeys in $A$ can only sit in row $1$, $B$ in row $2$, and $C$ can sit anywhere. It is clear that if there is free space in row $1$, and there are monkeys left in set $A$, it is optimal to seat a monkey from set $A$ onto row $1$. This is because a monkey from set $... | [
"greedy",
"math"
] | 800 | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt;
cin>>tt;
while(tt--)
{
int m,a,b,c;
cin>>m>>a>>b>>c;
int ans=0,rem=0;
ans+=min(m,a);rem+=m-min(m,a);
ans+=min(m,b);rem+=... |
2044 | D | Harder Problem | Given a sequence of positive integers, a positive integer is called a mode of the sequence if it occurs the maximum number of times that any positive integer occurs. For example, the mode of $[2,2,3]$ is $2$. Any of $9$, $8$, or $7$ can be considered to be a mode of the sequence $[9,9,8,8,7,7]$.
You gave UFO an array ... | Observe that if you have an array where all elements are unique, they will all have frequency $1$, therefore they can all be classified as the mode. Therefore, it follows that the strategy for the construction is to just construct an array where for each prefix, the last element of this prefix appears in the array at l... | [
"constructive algorithms",
"greedy",
"math"
] | 1,100 | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt;
cin>>tt;
while(tt--)
{
int n;
cin>>n;
vector<int> a(n+1),b(n);
for(int i=0;i<n;i++)
{
int x;
cin... |
2044 | E | Insane Problem | Wave is given five integers $k$, $l_1$, $r_1$, $l_2$, and $r_2$. Wave wants you to help her count the number of ordered pairs $(x, y)$ such that all of the following are satisfied:
- $l_1 \leq x \leq r_1$.
- $l_2 \leq y \leq r_2$.
- There exists a non-negative integer $n$ such that $\frac{y}{x} = k^n$. | Clearly, trying to bruteforce over all possible values of $x$ or $y$ is too slow, because the bounds are $1 \leq l_1 \leq r_1 \leq 10^9$. However, there is another variable that you can actually bruteforce over - and that is $n$. This is because exponentiation famously makes numbers very big very quickly - and if we se... | [
"binary search",
"greedy",
"implementation",
"math",
"number theory"
] | 1,300 | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt;
cin>>tt;
while(tt--)
{
ll k,l1,r1,l2,r2;
cin>>k>>l1>>r1>>l2>>r2;
ll kn=1,ans=0;
for(int n=0;r2/kn>=l1;n++)
{
... |
2044 | F | Easy Demon Problem | For an arbitrary grid, Robot defines its beauty to be the sum of elements in the grid.
Robot gives you an array $a$ of length $n$ and an array $b$ of length $m$. You construct a $n$ by $m$ grid $M$ such that $M_{i,j}=a_i\cdot b_j$ for all $1 \leq i \leq n$ and $1 \leq j \leq m$.
Then, Robot gives you $q$ queries, eac... | This is an anti-hash test for python sets and dictionaries. Before you call us evil, we saved you from getting hacked in open hack phase. Beware! Let's denote the beauty of the matrix as $B$, and denote $\text{SumA}$ as the sum of all the elements in the array $a$, and $\text{SumB}$ as the sum of all the elements in th... | [
"binary search",
"brute force",
"data structures",
"math",
"number theory"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define int long long
#define vt vector
#define endl "\n"
const int N = 4e5 + 5;
bool apos[N], aneg[N], bpos[N], bneg[N], posspos[N], possneg[N];
signed main() {
ios_base::sync_with_stdio(f... |
2044 | G1 | Medium Demon Problem (easy version) | \textbf{This is the easy version of the problem. The key difference between the two versions is highlighted in bold.}
A group of $n$ spiders has come together to exchange plushies. Initially, each spider has $1$ plushie. Every year, if spider $i$ has at least one plushie, he will give exactly one plushie to spider $r_... | This problem deals with a specific subclass of graphs called "functional graphs", also known as "successor graphs". The key feature that they have is that each node only has one successor. Therefore, the graph in the problem will necessarily be split into $k \geq 1$ components, where each component necessarily contains... | [
"dfs and similar",
"graph matchings",
"graphs",
"implementation",
"trees"
] | 1,700 | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt;
cin>>tt;
while(tt--)
{
int n;
cin>>n;
vector<int> r(n+1),d(n+1);
for(int i=1;i<=n;i++)
{
cin>>r[i];
... |
2044 | G2 | Medium Demon Problem (hard version) | \textbf{This is the hard version of the problem. The key difference between the two versions is highlighted in bold.}
A group of $n$ spiders has come together to exchange plushies. Initially, each spider has $1$ plushie. Every year, if spider $i$ has at least one plushie, he will give exactly one plushie to spider $r_... | Note that similarly to G1, once all plushies end up in the hands of spiders who are in a loop, the process becomes stable. Let's model the input as a collection of rooted forests. For each spider $i$, if $i$ is part of a loop, then let's compress the loop into a single node and use that as the root of a tree. Otherwise... | [
"dfs and similar",
"dp",
"dsu",
"graphs",
"implementation",
"trees"
] | 1,900 | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt;
cin>>tt;
while(tt--)
{
int n;
cin>>n;
vector<int> r(n+1),d(n+1),v(n+1,1);
for(int i=1;i<=n;i++)
{
cin>>r[i];... |
2044 | H | Hard Demon Problem | Swing is opening a pancake factory! A good pancake factory must be good at flattening things, so Swing is going to test his new equipment on 2D matrices.
Swing is given an $n \times n$ matrix $M$ containing positive integers. He has $q$ queries to ask you.
For each query, he gives you four integers $x_1$, $y_1$, $x_2... | Consider translating the sum back onto the matrix. For simplicity we discuss about querying the whole matrix. The sum we would like to find is $\sum_i i\cdot A_i$. Here, $A_i$ corresponds to $M_{(x,y)}$, so we will translate this to $\sum_{x,y} i\cdot M_{(x,y)}$. The issue left is on the $i$ multiplied to it. Remember ... | [
"constructive algorithms",
"data structures",
"dp",
"implementation",
"math"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector <ll>;
using ii = pair <ll, ll>;
using vii = vector <ii>;
void tc () {
ll n, Q;
cin >> n >> Q;
vector <vll> mat(n, vll(n));
for (vll &ve : mat) {
for (ll &i : ve) cin >> i;
}
vector <vll> psR(n, vll(n+... |
2046 | A | Swap Columns and Find a Path | There is a matrix consisting of $2$ rows and $n$ columns. The rows are numbered from $1$ to $2$ from top to bottom; the columns are numbered from $1$ to $n$ from left to right. Let's denote the cell on the intersection of the $i$-th row and the $j$-th column as $(i,j)$. Each cell contains an integer; initially, the int... | We can divide the columns in the matrix into three different groups: the columns where we go through the top cell; the columns where we go through the bottom cell; the columns where we go through both cells. There should be exactly one column in the $3$-rd group - this will be the column where we shift from the top row... | [
"greedy",
"sortings"
] | 1,200 | for _ in range(int(input())):
n = int(input())
a = []
for i in range(2):
a.append(list(map(int, input().split())))
best = [max(a[0][i], a[1][i]) for i in range(n)]
full = [a[0][i] + a[1][i] for i in range(n)]
sum_best = sum(best)
ans = -10 ** 19
for i in range(n):
ans = m... |
2046 | B | Move Back at a Cost | You are given an array of integers $a$ of length $n$. You can perform the following operation zero or more times:
- In one operation choose an index $i$ ($1 \le i \le n$), assign $a_i := a_i + 1$, and then move $a_i$ to the back of the array (to the rightmost position). For example, if $a = [3, 5, 1, 9]$, and you choo... | The first idea is to notice, that each element is moved to the back at most once. Indeed, if we fix a subset of elements that we ever move to the back, we can perform the operation once on each of them in any order we like, and that becomes their final order with the smallest possible increase. The optimal order is, of... | [
"binary search",
"data structures",
"greedy",
"sortings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
#define pb push_back
#de... |
2046 | C | Adventurers | Once, four Roman merchants met in a Roman mansion to discuss their trading plans. They faced the following problem: they traded the same type of goods, and if they traded in the same city, they would inevitably incur losses. They decided to divide up the cities between them where they would trade.
The map of Rome can ... | First, we will use the idea of binary search on the answer. Let's assume we are currently checking if we can achieve the answer $k$. We will iterate over all the necessary coordinates of the vertical lines. To do this, we note that it makes sense to iterate only over those where the lines coincide in the Y-coordinate w... | [
"binary search",
"data structures",
"greedy",
"sortings",
"ternary search",
"two pointers"
] | 2,100 | #include <math.h>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <array>
#include <cstring>
#include <ctime>
#include <cassert>
#include <string_view>
#include <functional>
#include <sstream>
#include <numeric>
#include <... |
2046 | D | For the Emperor! | In Ancient Rome, a plan to defeat the barbarians was developed, but for its implementation, each city must be informed about it.
The northern part of the Roman Empire consists of $n$ cities connected by $m$ one-way roads. Initially, the $i$-th city has $a_i$ messengers, and each messenger can freely move between citie... | We will compress the graph into strongly connected components. Inside a component, each runner can move between any pair of vertices and thus visit all. We will now solve the problem for a directed acyclic graph. We will check for the existence of an answer. Suppose all runners already know the winning plan, and we wil... | [
"flows",
"graphs"
] | 3,100 | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<array>
#include<unordered_set>
#include<unordered_map>
#include<cstring>
#include<string>
#include<memory>
#include<iomanip>
#include<cassert>
#include<cmath>
#incl... |
2046 | E2 | Cheops and a Contest (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is that in this version, $m$ is arbitrary. You can hack only if you solved all versions of this problem.}
There is a problem-solving competition in Ancient Egypt with $n$ participants, numbered from $1$ to $n$. Each participant comes ... | For convenience, we will call groups that include certain cities. The key condition is that each specialization can correspond to no more than one task. Thus, cities from different groups must have "practically sorted" strength values as the group order increases. Let $[l_i, r_i]$ denote the segment that includes all t... | [
"greedy",
"implementation"
] | 3,500 | /**
* author: tourist
* created: 01.12.2024 18:36:51
**/
#undef _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "algo/debug.h"
#else
#define debug(...) 42
#endif
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt;
cin >> tt;
while (tt--) {
in... |
2046 | F1 | Yandex Cuneiform (Easy Version) | \textbf{This is the easy version of the problem. The difference between the versions is that in this version, there are no question marks. You can hack only if you solved all versions of this problem.}
For a long time, no one could decipher Sumerian cuneiform. However, it has finally succumbed to pressure! Today, you ... | It can be noted that if the string contains the correct number of symbols 'Y', 'D', 'X' and does not have two consecutive identical symbols, then it can be obtained using the given operations. To demonstrate this, we will provide an algorithm that constructs a sequence of operations leading to the desired string. We wi... | [
"constructive algorithms",
"data structures",
"greedy"
] | 3,300 | null |
2046 | F2 | Yandex Cuneiform (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is that in this version, there is no restriction on the number of question marks. You can hack only if you solved all versions of this problem.}
For a long time, no one could decipher Sumerian cuneiform. However, it has finally succum... | We will isolate substrings from the string that consist entirely of '?'. For each, we will denote its length as $len_i$ and the two neighboring symbols (standing to the left and right) as $l_i$, $r_i$. (If the right and/or left symbol is absent, we will take it as '#', a symbol that does not match any of our interests)... | [
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 3,500 | #pragma GCC optimize("Ofast")
#include <iostream>
#include <cmath>
#include <cstdint>
#include <vector>
#include <string>
#include <iomanip>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <queue>
#include <fstream>
#include <random>
//... |
2047 | A | Alyona and a Square Jigsaw Puzzle | Alyona assembles an unusual square Jigsaw Puzzle. She does so in $n$ days in the following manner:
- On the first day, she starts by placing the central piece in the center of the table.
- On each day after the first one, she places a certain number of pieces around the central piece in clockwise order, always finishi... | Alyona is happy when there are no unfinished layers - that is, in front of her is a perfect square with odd side length. Since the order of pieces is fixed, it is enough to keep track of the total current size $s$ of the puzzle, and after each day check, if the $s$ is a perfect square of an odd number. The easiest way ... | [
"implementation",
"math"
] | 800 | NT = int(input())
sqs = set()
k = 1
while k * k <= 100 * 1000:
sqs.add(k * k)
k += 2
for T in range(NT):
n = int(input())
a = list(map(int, input().split()))
answer = 0
cursum = 0
for t in a:
cursum += t
if cursum in sqs:
answer += 1
print(answer) |
2047 | B | Replace Character | You're given a string $s$ of length $n$, consisting of only lowercase English letters.
You must do the following operation exactly once:
- Choose any two indices $i$ and $j$ ($1 \le i, j \le n$). You can choose $i = j$.
- Set $s_i := s_j$.
You need to minimize the number of distinct permutations$^\dagger$ of $s$. Ou... | Find the character which appears the lowest number of times - if tied, take the earlier character in the alphabet. Find the character which appears the highest number of times - if tied, take the later character in the alphabet. Then, replace any of the lowest-occurrence characters with the highest-occurrence character... | [
"brute force",
"combinatorics",
"greedy",
"strings"
] | 900 | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
string s;
cin >> s;
vector<int> occ(26);
for (int i=0; i<n; i++)
occ[s[i] - 'a'] += 1;
pair<pai... |
2048 | A | Kevin and Combination Lock | Kevin is trapped in Lakeside Village by Grace. At the exit of the village, there is a combination lock that can only be unlocked if Kevin solves it.
The combination lock starts with an integer $ x $. Kevin can perform one of the following two operations zero or more times:
- If $ x \neq 33 $, he can select two consec... | When we transform $\overline{x33y}$ into $\overline{xy}$ (where $x$ and $y$ are decimal numbers), the actual value changes from $10^{p+2} \cdot x + 33 \cdot 10^p + y$ to $10^p \cdot x + y$. The decrease is $99 \cdot 10^p \cdot x + 33 \cdot 10^p$. It is easy to see that $33 \mid (99 \cdot 10^p \cdot x + 33 \cdot 10^p)$.... | [
"brute force",
"greedy",
"implementation",
"math",
"number theory"
] | 800 | null |
2048 | A | Kevin and Combination Lock | Kevin is trapped in Lakeside Village by Grace. At the exit of the village, there is a combination lock that can only be unlocked if Kevin solves it.
The combination lock starts with an integer $ x $. Kevin can perform one of the following two operations zero or more times:
- If $ x \neq 33 $, he can select two consec... | When we transform $\overline{x33y}$ into $\overline{xy}$ (where $x$ and $y$ are decimal numbers), the actual value changes from $10^{p+2} \cdot x + 33 \cdot 10^p + y$ to $10^p \cdot x + y$. The decrease is $99 \cdot 10^p \cdot x + 33 \cdot 10^p$. It is easy to see that $33 \mid (99 \cdot 10^p \cdot x + 33 \cdot 10^p)$.... | [
"brute force",
"greedy",
"implementation",
"math",
"number theory"
] | 800 | null |
2048 | B | Kevin and Permutation | Kevin is a master of permutation-related problems. You are taking a walk with Kevin in Darkwoods, and during your leisure time, he wants to ask you the following question.
Given two positive integers $ n $ and $ k $, construct a permutation$^{\text{∗}}$ $ p $ of length $ n $ to minimize the sum of the minimum values o... | In the entire permutation, at most $k$ subintervals can contain $1$. Similarly, at most $k$ subintervals can contain $2, 3, \ldots$. To maximize the number of subintervals where the minimum value is as small as possible, we use the following construction: $p_k=1,p_{2k}=2,\dots,p_{\lfloor{\frac{n}{k}}\rfloor\cdot k}=\le... | [
"constructive algorithms",
"greedy"
] | 900 | null |
2048 | B | Kevin and Permutation | Kevin is a master of permutation-related problems. You are taking a walk with Kevin in Darkwoods, and during your leisure time, he wants to ask you the following question.
Given two positive integers $ n $ and $ k $, construct a permutation$^{\text{∗}}$ $ p $ of length $ n $ to minimize the sum of the minimum values o... | In the entire permutation, at most $k$ subintervals can contain $1$. Similarly, at most $k$ subintervals can contain $2, 3, \ldots$. To maximize the number of subintervals where the minimum value is as small as possible, we use the following construction: $p_k=1,p_{2k}=2,\dots,p_{\lfloor{\frac{n}{k}}\rfloor\cdot k}=\le... | [
"constructive algorithms",
"greedy"
] | 900 | null |
2048 | C | Kevin and Binary Strings | Kevin discovered a binary string $s$ that \textbf{starts with 1} in the river at Moonlit River Park and handed it over to you. Your task is to select two non-empty substrings$^{\text{∗}}$ of $s$ (which can be overlapped) to maximize the XOR value of these two substrings.
The XOR of two binary strings $a$ and $b$ is de... | To maximize the XOR sum of the two substrings, we aim to maximize the number of binary digits in the XOR result. To achieve this, the substring $[1,n]$ must always be selected. Suppose the first character of the other substring is $1$. If it is not $1$, we can remove all leading zeros. Next, find the position of the fi... | [
"bitmasks",
"brute force",
"greedy",
"implementation",
"strings"
] | 1,200 | null |
2048 | C | Kevin and Binary Strings | Kevin discovered a binary string $s$ that \textbf{starts with 1} in the river at Moonlit River Park and handed it over to you. Your task is to select two non-empty substrings$^{\text{∗}}$ of $s$ (which can be overlapped) to maximize the XOR value of these two substrings.
The XOR of two binary strings $a$ and $b$ is de... | To maximize the XOR sum of the two substrings, we aim to maximize the number of binary digits in the XOR result. To achieve this, the substring $[1,n]$ must always be selected. Suppose the first character of the other substring is $1$. If it is not $1$, we can remove all leading zeros. Next, find the position of the fi... | [
"bitmasks",
"brute force",
"greedy",
"implementation",
"strings"
] | 1,200 | null |
2048 | D | Kevin and Competition Memories | Kevin used to get into Rio's Memories, and in Rio's Memories, a series of contests was once held. Kevin remembers all the participants and all the contest problems from that time, but he has forgotten the specific rounds, the distribution of problems, and the exact rankings.
There are $ m $ problems in total, with the... | Read all the hints. First, remove all contestants with a rating lower than yours, making you the contestant with the lowest rating. Since any problem you can solve can also be solved by everyone else, this does not affect your ranking. These problems can effectively be treated as having infinite difficulty. At this poi... | [
"binary search",
"brute force",
"data structures",
"greedy",
"sortings",
"two pointers"
] | 1,600 | null |
2048 | D | Kevin and Competition Memories | Kevin used to get into Rio's Memories, and in Rio's Memories, a series of contests was once held. Kevin remembers all the participants and all the contest problems from that time, but he has forgotten the specific rounds, the distribution of problems, and the exact rankings.
There are $ m $ problems in total, with the... | Read all the hints. First, remove all contestants with a rating lower than yours, making you the contestant with the lowest rating. Since any problem you can solve can also be solved by everyone else, this does not affect your ranking. These problems can effectively be treated as having infinite difficulty. At this poi... | [
"binary search",
"brute force",
"data structures",
"greedy",
"sortings",
"two pointers"
] | 1,600 | null |
2048 | E | Kevin and Bipartite Graph | The Arms Factory needs a poster design pattern and finds Kevin for help.
A poster design pattern is a bipartite graph with $ 2n $ vertices in the left part and $ m $ vertices in the right part, where there is an edge between each vertex in the left part and each vertex in the right part, resulting in a total of $ 2nm ... | The graph has a total of $2nm$ edges, and each color forms a forest. Therefore, for any given color, there are at most $2n + m - 1$ edges. Thus, the total number of edges cannot exceed $(2n + m - 1)n$. This gives the condition: $(2n+m-1)n\ge 2nm$. Simplifying, we find $m \leq 2n - 1$. Next, we only need to construct a ... | [
"constructive algorithms",
"graphs",
"greedy"
] | 2,000 | null |
2048 | E | Kevin and Bipartite Graph | The Arms Factory needs a poster design pattern and finds Kevin for help.
A poster design pattern is a bipartite graph with $ 2n $ vertices in the left part and $ m $ vertices in the right part, where there is an edge between each vertex in the left part and each vertex in the right part, resulting in a total of $ 2nm ... | The graph has a total of $2nm$ edges, and each color forms a forest. Therefore, for any given color, there are at most $2n + m - 1$ edges. Thus, the total number of edges cannot exceed $(2n + m - 1)n$. This gives the condition: $(2n+m-1)n\ge 2nm$. Simplifying, we find $m \leq 2n - 1$. Next, we only need to construct a ... | [
"constructive algorithms",
"graphs",
"greedy"
] | 2,000 | null |
2048 | F | Kevin and Math Class | Kevin is a student from Eversleeping Town, currently attending a math class where the teacher is giving him division exercises.
On the board, there are two rows of positive integers written, each containing $ n $ numbers. The first row is $ a_1, a_2, \ldots, a_n $, and the second row is $ b_1, b_2, \ldots, b_n $.
For... | Construct a min Cartesian tree for the sequence $b$. It is easy to observe that we will only operate on the intervals defined by this Cartesian tree. To solve the problem, we can use DP on the Cartesian tree. Let $f_{u,i}$ represent the minimum possible maximum value of $a_x$ within the subtree rooted at $u$ after perf... | [
"brute force",
"data structures",
"divide and conquer",
"dp",
"implementation",
"math",
"trees"
] | 2,500 | null |
2048 | F | Kevin and Math Class | Kevin is a student from Eversleeping Town, currently attending a math class where the teacher is giving him division exercises.
On the board, there are two rows of positive integers written, each containing $ n $ numbers. The first row is $ a_1, a_2, \ldots, a_n $, and the second row is $ b_1, b_2, \ldots, b_n $.
For... | Construct a min Cartesian tree for the sequence $b$. It is easy to observe that we will only operate on the intervals defined by this Cartesian tree. Proof: For any $b_x$, find the last $b_p \leq b_x$ on its left and the first $b_q < b_x$ on its right. If we want to divide the interval by $b_x$, the operation interval ... | [
"brute force",
"data structures",
"divide and conquer",
"dp",
"implementation",
"math",
"trees"
] | 2,500 | null |
2048 | G | Kevin and Matrices | Kevin has been transported to Sacred Heart Hospital, which contains all the $ n \times m $ matrices with integer values in the range $ [1,v] $.
Now, Kevin wants to befriend some matrices, but he is willing to befriend a matrix $ a $ if and only if the following condition is satisfied:
$$ \min_{1\le i\le n}\left(\max_... | Let us assume the left-hand side attains its maximum at position $L$, and the right-hand side attains its maximum at position $R$. For any $L, R$, let $P$ be the position in the same row as $L$ and the same column as $R$. Then we have $a_L \geq a_P \geq a_R$, which implies $a_L \geq a_R$. Hence, we only need to conside... | [
"brute force",
"combinatorics",
"dp",
"math"
] | 2,800 | null |
2048 | G | Kevin and Matrices | Kevin has been transported to Sacred Heart Hospital, which contains all the $ n \times m $ matrices with integer values in the range $ [1,v] $.
Now, Kevin wants to befriend some matrices, but he is willing to befriend a matrix $ a $ if and only if the following condition is satisfied:
$$ \min_{1\le i\le n}\left(\max_... | Let us assume the left-hand side attains its maximum at position $L$, and the right-hand side attains its maximum at position $R$. For any $L, R$, let $P$ be the position in the same row as $L$ and the same column as $R$. Then we have $a_L \geq a_P \geq a_R$, which implies $a_L \geq a_R$. Hence, we only need to conside... | [
"brute force",
"combinatorics",
"dp",
"math"
] | 2,800 | null |
2048 | H | Kevin and Strange Operation | Kevin is exploring problems related to binary strings in Chinatown. When he was at a loss, a stranger approached him and introduced a peculiar operation:
- Suppose the current binary string is $ t $, with a length of $ \vert t \vert $. Choose an integer $ 1 \leq p \leq \vert t \vert $. For all $ 1 \leq i < p $, \textb... | Assume that after performing several operations on the $01$ string $s$, we get the $01$ string $t$. It's not hard to notice that each element in $t$ corresponds to the $\max$ of a subset of elements from $s$. Further observation shows that this subset must form a continuous segment, so we can express $t_i$ as $\max\lim... | [
"data structures",
"dp"
] | 3,100 | null |
2048 | H | Kevin and Strange Operation | Kevin is exploring problems related to binary strings in Chinatown. When he was at a loss, a stranger approached him and introduced a peculiar operation:
- Suppose the current binary string is $ t $, with a length of $ \vert t \vert $. Choose an integer $ 1 \leq p \leq \vert t \vert $. For all $ 1 \leq i < p $, \textb... | Assume that after performing several operations on the $01$ string $s$, we get the $01$ string $t$. It's not hard to notice that each element in $t$ corresponds to the $\max$ of a subset of elements from $s$. Further observation shows that this subset must form a continuous segment, so we can express $t_i$ as $\max\lim... | [
"data structures",
"dp"
] | 3,100 | null |
2048 | I1 | Kevin and Puzzle (Easy Version) | \textbf{This is the easy version of the problem. The difference between the versions is that in this version, you need to find any one good array. You can hack only if you solved all versions of this problem.}
Kevin is visiting the Red Church, and he found a puzzle on the wall.
For an array $ a $, let $ c(l,r) $ indi... | Lemma: Suppose the largest value filled is $mx$, and the number of distinct values is $c$. Let $d = c - mx$. Then, $d = 0$ or $d = 1$. Proof: Clearly, $c \le mx + 1$. If $c < mx$, observe where $mx$ is placed, and a contradiction arises. Now, consider the leftmost and rightmost characters in sequence $s$: We recursivel... | [
"constructive algorithms"
] | 3,500 | null |
2048 | I1 | Kevin and Puzzle (Easy Version) | \textbf{This is the easy version of the problem. The difference between the versions is that in this version, you need to find any one good array. You can hack only if you solved all versions of this problem.}
Kevin is visiting the Red Church, and he found a puzzle on the wall.
For an array $ a $, let $ c(l,r) $ indi... | Lemma: Suppose the largest value filled is $mx$, and the number of distinct values is $c$. Let $d = c - mx$. Then, $d = 0$ or $d = 1$. Proof: Clearly, $c \le mx + 1$. If $c < mx$, observe where $mx$ is placed, and a contradiction arises. Now, consider the leftmost and rightmost characters in sequence $s$: If they are L... | [
"constructive algorithms"
] | 3,500 | null |
2048 | I2 | Kevin and Puzzle (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to count the number of good arrays. You can hack only if you solved all versions of this problem.}
Kevin is visiting the Red Church, and he found a puzzle on the wall.
For an array $ a $, let $ c(l,r... | According to the easy version, we can see that most cases have very few solutions because for LR, LL, and RR, after filling in the inner part, the outer layer only has one unique way to fill. Therefore, if there is no RL layer, the answer must be $1$. Next, consider the case where RL is present. Let's assume that RL is... | [
"bitmasks",
"fft",
"math"
] | 3,500 | null |
2048 | I2 | Kevin and Puzzle (Hard Version) | \textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to count the number of good arrays. You can hack only if you solved all versions of this problem.}
Kevin is visiting the Red Church, and he found a puzzle on the wall.
For an array $ a $, let $ c(l,r... | According to the easy version, we can see that most cases have very few solutions because for LR, LL, and RR, after filling in the inner part, the outer layer only has one unique way to fill. Therefore, if there is no RL layer, the answer must be $1$. Next, consider the case where RL is present. Let's assume that RL is... | [
"bitmasks",
"fft",
"math"
] | 3,500 | null |
2049 | A | MEX Destruction | Evirir the dragon snuck into a wizard's castle and found a mysterious contraption, and their playful instincts caused them to play with (destroy) it...
Evirir the dragon found an array $a_1, a_2, \ldots, a_n$ of $n$ non-negative integers.
In one operation, they can choose a non-empty subarray$^{\text{∗}}$ $b$ of $a$ ... | Case 1: All elements are $0$. Then the answer is $0$. Case 2: Some element is non-zero, and all non-zero elements form a contiguous subarray. Then the answer is $1$ since we can choose that subarray and replace it with a $0$. Case 3: Otherwise, the answer is $2$. We can replace the entire array with a non-zero element ... | [
"greedy",
"implementation"
] | 800 | #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];
while (!a.empty() && a.back() == 0)
a.pop_back();
reverse(a.begin(), a.end());
while (!a.empty() && a.back() == 0)
a.pop_back();
... |
2049 | B | pspspsps | Cats are attracted to pspspsps, but Evirir, being a dignified dragon, is only attracted to pspspsps with oddly specific requirements...
Given a string $s = s_1s_2\ldots s_n$ of length $n$ consisting of characters p, s, and . (dot), determine whether a permutation$^{\text{∗}}$ $p$ of length $n$ exists, such that for al... | Since the entire $p$ must be a permutation, if $s_1 =$s, we can set $s_1 =$., and if $s_n =$p, we can set $s_n =$.. After that, the answer is YES if and only if all non-dot characters in $s$ are all p or s. If all non-dot characters are p, we can choose the permutation $p = [1, 2, \ldots, n]$. If all non-dot characters... | [
"brute force",
"constructive algorithms",
"graph matchings",
"implementation"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
void solve()
{
int n; cin >> n;
string s; cin >> s;
if (s[0] == 's') s[0] = '.';
if (s.back() == 'p') s.back() = '.';
bool found_p = false;
bool found_s = false;
for (const auto c : s)
{
switch (c)
{
case 'p':
... |
2049 | C | MEX Cycle | Evirir the dragon has many friends. They have 3 friends! That is one more than the average dragon.
You are given integers $n$, $x$, and $y$. There are $n$ dragons sitting in a circle. The dragons are numbered $1, 2, \ldots, n$. For each $i$ ($1 \le i \le n$), dragon $i$ is friends with dragon $i - 1$ and $i + 1$, wher... | There are many possible solutions. The simplest one we can find (thanks to Kaey) is as follows: Set $a_x = 0, a_{x+1} = 1, a_{x+2} = 0, \ldots$, alternating between 0 and 1, wrapping around accordingly. Formally, using 0-based indexing, set $a_{(x+i) \bmod n} = i \bmod 2$ for all $i$ ($0 \le i \le n - 1$). If $n$ is od... | [
"brute force",
"constructive algorithms",
"greedy",
"implementation"
] | 1,500 | #include <iostream>
#include <vector>
using namespace std;
void solve() {
int n, x, y;
cin >> n >> x >> y;
--x; --y;
vector<int> ans(n);
for (int i = 0; i < n; ++i) ans[(x + i) % n] = i % 2;
if (n % 2 || (x - y) % 2 == 0)
ans[x] = 2;
for (auto x : ans)cout << x << ' ';
cout << e... |
2049 | D | Shift + Esc | After having fun with a certain contraption and getting caught, Evirir the dragon decides to put their magical skills to good use — warping reality to escape fast!
You are given a grid with $n$ rows and $m$ columns of non-negative integers and an integer $k$. Let $(i, j)$ denote the cell in the $i$-th row from the top... | Let $f(i,j)$ be the minimum cost to move to cell $(i,j)$ after shifting and Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] For simplicity sake, we will add a row with all zeros above the first row. Also ... | [
"brute force",
"dp"
] | 1,900 | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll dp[511][511],a[511][511];
void solve()
{
int n,m,k;
cin>>n>>m>>k;
for(int i=1;i<=n;i++){
for(int j=0;j<m;j++)cin>>a[i][j];
}
for(int i=0;i<=n;i++){
for(int j=0;j<m;j++)dp[i][j] = 1e18;
}
dp[0][0] = 0;... |
2049 | E | Broken Queries | You, a wizard whose creation was destroyed by a dragon, are determined to hunt it down with a magical AOE tracker. But it seems to be toyed with...
This is an interactive problem.
There is a hidden binary array $a$ of length $n$ ($\mathbf{n}$ \textbf{is a power of 2}) and a hidden integer $k\ (2 \le k \le n - 1)$. Th... | Make 2 queries Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Make 1 query: query Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX... | [
"binary search",
"bitmasks",
"brute force",
"constructive algorithms",
"implementation",
"interactive"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
int qry(int l, int r, bool rev = 0, int n = 0) {
if (rev) {
int t = n - l;
l = n - r;
r = t;
}
cout << "? " << l + 1 << ' ' << r << endl;
cin >> r;
return r;
}
void solve() {
int n;
cin >> n;
int a = qry(0, n / 4);
... |
2049 | F | MEX OR Mania | An integer sequence $b_1, b_2, \ldots, b_n$ is good if $\operatorname{mex}(b_1, b_2, \ldots, b_n) - (b_1 | b_2 | \ldots | b_n) = 1$. Here, $\operatorname{mex(c)}$ denotes the MEX$^{\text{∗}}$ of the collection $c$, and $|$ is the bitwise OR operator.
Shohag has an integer sequence $a_1, a_2, \ldots, a_n$. He will perf... | Let's figure out when a sequence is good. Let $m$ be the maximum element of the sequence. Notice that the bitwise OR of the sequence is at least Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to p... | [
"bitmasks",
"brute force",
"data structures",
"dsu",
"implementation"
] | 2,700 | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9, Q = 3e5 + 9;
using ll = long long;
struct GoodSet { // insert, erase and track distinct and total elements
map<int, int> mp;
int size;
int k;
GoodSet() {}
GoodSet(int _k): k(_k), size(0) { };
void insert(int x, int c = 1) {
mp[x] +=... |
2050 | A | Line Breaks | Kostya has a text $s$ consisting of $n$ words made up of Latin alphabet letters. He also has two strips on which he must write the text. The first strip can hold $m$ characters, while the second can hold as many as needed.
Kostya must choose a number $x$ and write the first $x$ words from $s$ on the first strip, while... | An important condition in the problem: we can take $x$ words on the first line from the beginning and we cannot skip any word. The main idea is to compute the total length of words as we keep adding them, and stop when we reach a word where adding the next word would exceed the capacity of the first strip (which equals... | [
"implementation"
] | 800 | def solve():
n, m = [int(i) for i in input().split()]
ans = 0
for i in range(n):
l = input()
if len(l) <= m:
m -= len(l)
ans += 1
else:
for i in range(i + 1, n):
input()
break
print(ans)
t = int(input())
for i in... |
2050 | B | Transfusion | You are given an array $a$ of length $n$. In one operation, you can pick an index $i$ from $2$ to $n-1$ inclusive, and do one of the following actions:
- Decrease $a_{i-1}$ by $1$, then increase $a_{i+1}$ by $1$.
- Decrease $a_{i+1}$ by $1$, then increase $a_{i-1}$ by $1$.
After each operation, all the values must be... | The main idea of this problem is that these operations only change elements on the positions with the same parity. So, we can solve for elements on odd and even positions independently. Let's make two arrays $od$ and $ev$ - the first one will consist of all the elements on the odd positions, and the second one will con... | [
"brute force",
"greedy",
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
long long ods = 0, evs = 0;
for (int i = 0; i < n; i++) {
if (i & 1) ods += a[i];
else evs += a[i];
}
int odc = n / 2, evc = n / 2;
if (n & 1)... |
2050 | C | Uninteresting Number | You are given a number $n$ with a length of no more than $10^5$.
You can perform the following operation any number of times: choose one of its digits, square it, and replace the original digit with the result. The result must be a digit (that is, if you choose the digit $x$, then the value of $x^2$ must be less than ... | The requirement that a digit must remain a digit imposes the following restrictions on transformations: we can transform $0$ into $0$, $1$ into $1$, $2$ into $4$, and $3$ into $9$. Any other digit squared will exceed 9, therefore, it cannot be transformed. Transformations involving $0$ and $1$ are useless, leaving us w... | [
"brute force",
"dp",
"math"
] | 1,200 | def solve():
s = [int(x) for x in list(input())]
sm = sum(s)
twos = s.count(2)
threes = s.count(3)
for i in range(min(10, twos + 1)):
for j in range(min(10, threes + 1)):
if (sm + i * 2 + j * 6) % 9 == 0:
print('YES')
return
print('NO')
t =... |
2050 | D | Digital string maximization | You are given a string $s$, consisting of digits from $0$ to $9$. In one operation, you can pick any digit in this string, except for $0$ or the leftmost digit, decrease it by $1$, and then swap it with the digit left to the picked.
For example, in one operation from the string $1023$, you can get $1103$ or $1022$.
F... | Let's look at digit $s_i$. We can see that we can't move it to the left more than $s_i$ times because it will be $0$ after. So, we can say that only digits on indices from $i$ to $i+9$ can stand on index $i$, because the maximum digit $9$ can be moved to the left no more than $9$ times. Thus, for each $i$ we can brute ... | [
"brute force",
"greedy",
"math",
"strings"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
void solve() {
string s; cin >> s;
for (int i = 0; i < s.size(); i++) {
int best = s[i] - '0', pos = i;
for (int j = i; j < min(i + 10, (int) s.size()); j++) {
if (s[j] - '0' - (j - i) > best) {
best = s[j] - '0' - (j - ... |
2050 | E | Three Strings | You are given three strings: $a$, $b$, and $c$, consisting of lowercase Latin letters. The string $c$ was obtained in the following way:
- At each step, either string $a$ or string $b$ was randomly chosen, and the first character of the chosen string was removed from it and appended to the end of string $c$, until one... | Let's use the idea of dynamic programming. Let $dp[i][j]$ be the answer to the problem when considering string $a$ as its own prefix of length $i$, string $b$ as its own prefix of length $j$, and string $c$ as its own prefix of length $i+j$. Then the dynamic programming recurrence is easy: we need to iterate over where... | [
"dp",
"implementation",
"strings"
] | 1,500 | #include <iostream>
#include <algorithm>
static const int inf = 1e9;
void solve() {
std::string a, b, res;
std::cin >> a >> b >> res;
int n = (int) a.size(), m = (int) b.size();
int dp[n + 1][m + 1];
std::fill(&dp[0][0], &dp[0][0] + (n + 1) * (m + 1), inf);
dp[0][0] = 0;
for (int i = 0; i ... |
2050 | F | Maximum modulo equality | You are given an array $a$ of length $n$ and $q$ queries $l$, $r$.
For each query, find the maximum possible $m$, such that all elements $a_l$, $a_{l+1}$, ..., $a_r$ are equal modulo $m$. In other words, $a_l \bmod m = a_{l+1} \bmod m = \dots = a_r \bmod m$, where $a \bmod b$ — is the remainder of division $a$ by $b$.... | Let's look at two arbitrary integers $x$ and $y$. Now we want to find the maximum $m$, which satisfies $x\bmod m = y\bmod m$. We know that $x\bmod m = y\bmod m$, then $|x - y|\bmod m = 0$, because they have the same remainder by $m$. That means that any $m$ which is a divisor of $|x - y|$ will satisfy the required cond... | [
"data structures",
"divide and conquer",
"math",
"number theory"
] | 1,700 | #include <bits/stdc++.h>
using namespace std;
const int LOGN = 20;
vector<vector<int>> stGCD;
int get_gcd(int l, int r) {
int k = __lg(r - l + 1);
return __gcd(stGCD[k][l], stGCD[k][r - (1 << k) + 1]);
}
void solve() {
stGCD.clear();
int n, q; cin >> n >> q;
vector<int> a(n);
for (int &x : ... |
2050 | G | Tree Destruction | Given a tree$^{\text{∗}}$ with $n$ vertices. You can choose two vertices $a$ and $b$ once and remove all vertices on the path from $a$ to $b$, including the vertices themselves. If you choose $a=b$, only one vertex will be removed.
Your task is to find the maximum number of connected components$^{\text{†}}$ that can b... | Let's choose some vertices $a$ and $b$, between which there are $k$ edges. Then, when removing this path, the tree will split into $s - 2 \cdot k$, where $s$ is the sum of the degrees of the vertices on the path (this is exactly how many edges are connected to the chosen path). Let's suspend the tree from vertex $1$, a... | [
"dfs and similar",
"dp",
"trees"
] | 1,900 | #include <bits/stdc++.h>
#define int long long
#define x first
#define y second
using namespace std;
void dfs(int v, int p, vector<vector<int>> &sl, vector<pair<int, int>> &dp){
dp[v].x = sl[v].size();
int m1 = -1, m2 = -1;
for(int u: sl[v]){
if(u == p){
continue;
}
df... |
2051 | A | Preparing for the Olympiad | Monocarp and Stereocarp are preparing for the Olympiad. There are $n$ days left until the Olympiad. On the $i$-th day, if Monocarp plans to practice, he will solve $a_i$ problems. Similarly, if Stereocarp plans to practice on the same day, he will solve $b_i$ problems.
Monocarp can train on any day he wants. However, ... | Let's consider what contribution each day that Monokarp trains makes to the difference. For each day, except the last one, if Monokarp trains on that day, then the number of problems he has solved will increase by $a_i$, and the number of problems solved by Stereokarp will increase by $b_{i+1}$. Therefore, if $a_i - b_... | [
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n), b(n);
for (auto &x : a) cin >> x;
for (auto &x : b) cin >> x;
int ans = a[n - 1];
for (int i = 0; i < n - 1; ++i)
ans += max(0, a[i] - b[i + 1]);
co... |
2051 | B | Journey | Monocarp decided to embark on a long hiking journey.
He decided that on the first day he would walk $a$ kilometers, on the second day he would walk $b$ kilometers, on the third day he would walk $c$ kilometers, on the fourth day, just like on the first, he would walk $a$ kilometers, on the fifth day, just like on the ... | Processing every day separately is too slow. Instead, we will use the fact that every three days, the number of kilometers Monocarp walks repeats, and process days in "triples". During every three days, Monocarp walks exactly $(a+b+c)$ kilometers, so we can do the following: while $n \ge a + b + c$, subtract $(a+b+c)$ ... | [
"binary search",
"math"
] | 800 | t = int(input())
for i in range(t):
n, a, b, c = map(int, input().split())
sum = a + b + c
d = n // sum * 3
if n % sum == 0:
print(d)
elif n % sum <= a:
print(d + 1)
elif n % sum <= a + b:
print(d + 2)
else:
print(d + 3)
|
2051 | C | Preparing for the Exam | Monocarp is preparing for his first exam at the university. There are $n$ different questions which can be asked during the exam, numbered from $1$ to $n$. There are $m$ different lists of questions; each list consists of exactly $n-1$ different questions. Each list $i$ is characterized by one integer $a_i$, which is t... | For every question list, we should check if Monocarp knows all questions from the list, i. e. all numbers $1, 2, \dots, a_{i-1}, a_{i+1}, \dots, n$ appear in the list $[q_1, q_2, \dots, q_k]$. Searching for every number in the list $q$ naively is too slow; instead, we can make a boolean array such that the $j$-th eleme... | [
"constructive algorithms",
"implementation"
] | 1,000 | for _ in range(int(input())):
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
q = list(map(int, input().split()))
used = [False for i in range(n + 1)]
for i in q:
used[i] = True
l = len(q)
for i in range(m):
if l == n or (l == n-1 and not used[a[i]]):
... |
2051 | D | Counting Pairs | You are given a sequence $a$, consisting of $n$ integers, where the $i$-th element of the sequence is equal to $a_i$. You are also given two integers $x$ and $y$ ($x \le y$).
A pair of integers $(i, j)$ is considered interesting if the following conditions are met:
- $1 \le i < j \le n$;
- if you simultaneously remov... | There is a common trick in problems of the form "count something on segment $[l, r]$": calculate the answer for $[0, r]$, and then subtract the answer for $[0, l-1]$. We can use this trick in our problem as follows: calculate the number of pairs $i,j$ such that the sum of all other elements is less than $y+1$, and subt... | [
"binary search",
"sortings",
"two pointers"
] | 1,200 | def calcLessThanX(a, x):
n = len(a)
s = sum(a)
j = 0
ans = 0
for i in range(n-1, -1, -1):
while j < n and s - a[i] - a[j] >= x:
j += 1
ans += (n - j)
for i in range(n):
if s - a[i] - a[i] < x:
ans -= 1
return ans // 2
for _ in range(int... |
2051 | E | Best Price | A batch of Christmas trees has arrived at the largest store in Berland. $n$ customers have already come to the store, wanting to buy them.
Before the sales begin, the store needs to determine the price for one tree (the price is the same for all customers). To do this, the store has some information about each custome... | First, let's design a solution in $O(n^2)$. We can solve the problem in $O(n \cdot max b_i)$, if we iterate on the price $p$ we use, and for every price, calculate the number of trees bought and the number of negative reviews. However, we don't need to check every possible price from $1$ to $max b_i$: let's instead che... | [
"binary search",
"brute force",
"data structures",
"greedy",
"sortings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> a(n), b(n);
for (auto &x : a) cin >> x;
for (auto &x : b) cin >> x;
vector<pair<int, int>> ev;
for (int i = 0; i ... |
2051 | F | Joker | Consider a deck of $n$ cards. The positions in the deck are numbered from $1$ to $n$ from top to bottom. A joker is located at position $m$.
$q$ operations are applied sequentially to the deck. During the $i$-th operation, you need to take the card at position $a_i$ and move it either to the beginning or to the end of... | Let's represent the positions where the joker can be as a set of non-overlapping segments $[l_1, r_1]$, $[l_2, r_2]$, .... Let's consider what happens to the segment $[l, r]$ after applying the $i$-th operation: if $a_i < l$, the possible positions segment becomes $[l - 1, r]$ (since moving the $a_i$-th card to the fro... | [
"brute force",
"greedy",
"implementation",
"math"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, m, q;
cin >> n >> m >> q;
vector<pair<int, int>> segs({{1, -q}, {m, m}, {n + q + 1, n}});
while (q--) {
int x;
cin >> x;
bool ins = false;
for (auto& [l, r] : segs) {
... |
2051 | G | Snakes | Suppose you play a game where the game field looks like a strip of $1 \times 10^9$ square cells, numbered from $1$ to $10^9$.
You have $n$ snakes (numbered from $1$ to $n$) you need to place into some cells. Initially, each snake occupies exactly one cell, and you can't place more than one snake into one cell. After t... | Note that when you place snakes on the strip in some order, they form some permutation. And when you fix that permutation, you can place them greedily. In other words, when you know in what order you'll place snakes, it's always optimal to place them as close to each other as possible. Since the bigger the initial dist... | [
"bitmasks",
"dp",
"dsu",
"graphs"
] | 2,100 | #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())
const int INF = int(1e9);
int n, q;
vector<int> id, ch;
bool read() {
if (!(cin >> n >> q))
return false;
id.resize(q);
ch.resize(q);
fore (i, 0, q) {
... |
2053 | A | Tender Carpenter | \begin{quote}
I would use a firework to announce, a wave to bid farewell, and a bow to say thanks: bygones are bygones; not only on the following path will I be walking leisurely and joyfully, but also the footsteps won't halt as time never leaves out flowing; for in the next year, we will meet again.
\hfill — Cocoly19... | Can you find a partition that is always valid? Suppose you are given a set $S$. How do you judge whether $S$ is stable in $\mathcal O(\lvert S\rvert)$? Are sets that are very large really necessary? Note that: we always have a partition like $[a_1], [a_2], \dots, [a_n]$, since $(x, x, x)$ always forms a non-degenerate ... | [
"dp",
"geometry",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
#define MAXN 1001
int a[MAXN];
void solve() {
int n; std::cin >> n;
for (int i = 1; i <= n; ++i) std::cin >> a[i];
for (int i = 1; i < n; ++i) if (2 * std::min(a[i], a[i + 1]) > std::max(a[i], a[i + 1]))
{ std::cout << "YES\n"; return; }
std::cout << "NO\n";
}
int main() {
std::ios:... |
2053 | B | Outstanding Impressionist | \begin{quote}
If it was so, then let's make it a deal...
\hfill — MayDay, Gentleness
\end{quote}
Even after copying the paintings from famous artists for ten years, unfortunately, Eric is still unable to become a skillful impressionist painter. He wants to forget something, but the white bear phenomenon just keeps han... | What if for all $1 \leq i \leq n$, $l_i \ne r_i$ holds? How do you prove it? Use prefix sums or similar to optimize your solution. For each $1 \leq i \leq n$, for each $l_i \leq x \leq r_i$, we want to check if it is okay for impression $i$ being unique at the value of $x$. Note that: for each $j \neq i$, we can always... | [
"binary search",
"brute force",
"data structures",
"greedy"
] | 1,200 | #include <bits/stdc++.h>
#define MAXN 400001
int l[MAXN], r[MAXN], sum[MAXN], cnt[MAXN];
void solve() {
int n; std::cin >> n;
for (int i = 1; i <= 2 * n; ++i) sum[i] = cnt[i] = 0;
for (int i = 1; i <= n; ++i) {
std::cin >> l[i] >> r[i];
if (l[i] == r[i]) sum[l[i]] = 1, ++cnt[l[i]];
}
for (int i = 2; i <= 2 *... |
2053 | C | Bewitching Stargazer | \begin{quote}
I'm praying for owning a transparent heart; as well as eyes with tears more than enough...
\hfill — Escape Plan, Brightest Star in the Dark
\end{quote}
Iris looked at the stars and a beautiful problem emerged in her mind. She is inviting you to solve it so that a meteor shower is believed to form.
There... | Process many segments simultaneously. What kind of segments do we process at a time? The length. The point that must be noted is: that if we call the process of splitting a large segment into two smaller segments a round, then all segments are of the same length when the $i$-th round of the observation is conducted; an... | [
"bitmasks",
"divide and conquer",
"dp",
"math"
] | 1,500 | #include <bits/stdc++.h>
#define int long long
using namespace std;
int T;
int n, k;
signed main() {
cin >> T;
while (T--) {
cin >> n >> k;
int mul = n + 1, sum = 0, cur = 1;
while (n >= k) {
if (n & 1) sum += cur;
n >>= 1;
cur <<= 1;
}
cout << mul * sum / 2 << endl;
}
return 0;
} |
2053 | D | Refined Product Optimality | \begin{quote}
As a tester, when my solution has a different output from the example during testing, I suspect the author first.
\hfill — Chris, a comment
\end{quote}
Although Iris occasionally sets a problem where the solution is possibly wrong, she still insists on creating problems with her imagination; after all, e... | What if $q = 0$? How do you keep the array sorted? The problem makes no difference when both $a$ and $b$ can be rearranged. Let the rearranged arrays of $a$ and $b$ be $c$ and $d$ respectively. If $q = 0$, we can write $c$ as $\operatorname{SORTED}(a_1, a_2 \ldots, a_n)$ and $d$ as $\operatorname{SORTED}(b_1, b_2 \ldot... | [
"binary search",
"data structures",
"greedy",
"math",
"schedules",
"sortings"
] | 1,700 | #include <bits/stdc++.h>
constexpr int MOD = 998244353;
int qpow(int a, int x = MOD - 2) {
int res = 1;
for (; x; x >>= 1, a = 1ll * a * a % MOD) if (x & 1) res = 1ll * res * a % MOD;
return res;
}
#define MAXN 200001
int a[MAXN], b[MAXN], c[MAXN], d[MAXN];
void solve() {
int n, q, res = 1; std::cin >> n >> q;
... |
2053 | E | Resourceful Caterpillar Sequence | \begin{quote}
Endless Repeating 7 Days
\hfill — r-906, Panopticon
\end{quote}
There is a tree consisting of $n$ vertices. Let a caterpillar be denoted by an integer pair $(p, q)$ ($1 \leq p, q \leq n$, $p \neq q$): its head is at vertex $p$, its tail is at vertex $q$, and it dominates all the vertices on the simple pa... | Suppose somebody wins. In which round does he or she win? A player can always undo what his opponent did in the previous turn. Can you find the necessary and sufficient condition for $(p, q)$ to be a caterpillar that makes Aron win? Denote Nora's first move as round $1$, Aron's first move as round $2$, and so on. Suppo... | [
"dfs and similar",
"dp",
"games",
"graphs",
"greedy",
"trees"
] | 1,900 | #include <bits/stdc++.h>
#define MAXN 200001
std::vector<int> g[MAXN];
inline int deg(int u) { return g[u].size(); }
int d[MAXN];
void solve() {
int n; std::cin >> n; long long ans = 0;
for (int i = 1, u, v; i < n; ++i) {
std::cin >> u >> v;
g[u].push_back(v), g[v].push_back(u);
}
int c1 = 0, c2 = 0;
for (in... |
2053 | F | Earnest Matrix Complement | \begin{quote}
3, 2, 1, ... We are the — RiOI Team!
\hfill — Felix & All, Special Thanks 3
\end{quote}
- Peter: Good news: My problem T311013 is approved!
- $\delta$: I'm glad my computer had gone out of battery so that I wouldn't have participated in wyrqwq's round and gained a negative delta.
- Felix: [thumbs_up] The... | What are we going to fill into the matrix? In other words, is there any relationship between the filed numbers? Try to come up with a naive DP solution that works in large time complexity, such as $\mathcal O(nk^2)$. For many different numbers between two consecutive rows, however, the transition is almost the same. If... | [
"brute force",
"data structures",
"dp",
"greedy",
"implementation",
"math"
] | 2,600 | #include <bits/stdc++.h>
namespace FastIO {
char buf[1 << 21], *p1 = buf, *p2 = buf;
#define getchar() (p1 == p2 && (p1 = buf, p2 = (p1 + fread(buf, 1, 1 << 21, stdin))) == p1 ? EOF : *p1++)
template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), c... |
2053 | G | Naive String Splits | \begin{quote}
And I will: love the world that you've adored; wish the smile that you've longed for. Your hand in mine as we explore, please take me to tomorrow's shore.
\hfill — Faye Wong, As Wished
\end{quote}
Cocoly has a string $t$ of length $m$, consisting of lowercase English letters, and he would like to split i... | (If we do not have to be deterministic) We do not need any hard string algorithm. In what cases won't greed work? Why? Is your brute forces actually faster (maybe you can explain it by harmonic series)? Let's call the prefix $s_1$ the short string and the suffix $s_2$ the long string. If $\lvert s_1\rvert\gt \lvert s_2... | [
"binary search",
"brute force",
"greedy",
"hashing",
"math",
"number theory",
"strings"
] | 3,400 | #include <bits/stdc++.h>
using namespace std;
template <int P>
class mod_int
{
using Z = mod_int;
private:
static int mo(int x) { return x < 0 ? x + P : x; }
public:
int x;
int val() const { return x; }
mod_int() : x(0) {}
template <class T>
mod_int(const T &x_) : x(x_ >= 0 && x_ < P ? sta... |
2053 | H | Delicate Anti-monotonous Operations | \begin{quote}
I shall be looking for you who would be out of Existence.
\hfill — HyuN, Disorder
\end{quote}
There are always many repetitive tasks in life. Iris always dislikes them, so she refuses to repeat them. However, time cannot be turned back; we only have to move forward.
Formally, Iris has an integer sequenc... | What if $w = 2$? Is it optimal to increase $\sum\limits_{i=0}^n [a_i \neq a_{i+1}]$ (suppose $a_0 = a_{n+1} = 2$)? If $w \geq 3$, what's the answer to the first question? If $a_i = a_{i+1}$, after the operation we can obtain $a_{i-1} = a_i$ or $a_{i+1} = a_{i+2}$ (and possibly, both). Try to think of the whole process ... | [
"constructive algorithms",
"implementation"
] | 3,500 | #include <bits/stdc++.h>
#define MAXN 200005
int a[MAXN];
void solve() {
int N, w; scanf("%d%d", &N, &w);
for (int i = 1; i <= N; ++i) scanf("%d", a + i);
if (N == 1) return (void)printf("%d 0\n", a[1]);
if (*std::min_element(a + 1, a + N + 1) == w)
return (void)printf("%lld 0\n", 1ll * w * N);
if (w == 2) {
... |
2053 | I1 | Affectionate Arrays (Easy Version) | \begin{quote}
You are the beginning of the letter, the development of a poem, and the end of a fairy tale.
\hfill — ilem, Pinky Promise
\end{quote}
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, you need to compute the minimum length of the arrays. You can... | What is the minimized LIS? How do you prove that it is an achievable lower bound? Go for a brute DP first. We claim that the minimized LIS is $\sum a_i$. Let $p$ be $\sum a_i$. Since it is required that $\operatorname{LIS}(b) = p$ while $\sum b_i = p$, we point out that it is equivalent to each of the prefix sums of th... | [
"data structures",
"dp",
"greedy"
] | 2,800 | #include <bits/stdc++.h>
namespace FastIO {
template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }
template <typename T> inline void write... |
2053 | I2 | Affectionate Arrays (Hard Version) | \textbf{Note that this statement is different to the version used in the official round. The statement has been corrected to a solvable version. In the official round, all submissions to this problem have been removed.}
\textbf{This is the hard version of the problem. The difference between the versions is that in thi... | Try insert numbers into spaces between the elements of $a$ (including the beginning and the end). Note that an array be can be formed in multiple ways (for example, you can insert a number $x$ to the left or right of the original number $x$ in array $a$). What's the number of different ways? It's actually the "value", ... | [
"data structures",
"dp",
"graphs",
"greedy",
"math",
"shortest paths",
"two pointers"
] | 3,500 | #include <bits/stdc++.h>
namespace FastIO {
template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }
template <typename T> inline void write... |
2055 | A | Two Frogs | \begin{center}
\begin{tabular}{c}
\hline
{\small Roaming through the alligator-infested Everglades, Florida Man encounters a most peculiar showdown.} \
\hline
\end{tabular}
\end{center}
There are $n$ lilypads arranged in a row, numbered from $1$ to $n$ from left to right. Alice and Bob are frogs initially positioned o... | Look at the distance between the frogs. Notice that regardless of how the players move, the difference between the numbers of the lilypads the two players are standing on always alternates even and odd, depending on the starting configuration. Then, the key observation is that exactly one player has the following winni... | [
"constructive algorithms",
"games",
"greedy",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int T; cin >> T;
while (T--) {
int N, A, B; cin >> N >> A >> B;
if ((A ^ B) & 1) cout << "NO\n";
else cout << "YES\n";
}
cout.flush();
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.