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 ⌀ |
|---|---|---|---|---|---|---|---|
1767 | B | Block Towers | There are $n$ block towers, numbered from $1$ to $n$. The $i$-th tower consists of $a_i$ blocks.
In one move, you can move one block from tower $i$ to tower $j$, but only if $a_i > a_j$. That move increases $a_j$ by $1$ and decreases $a_i$ by $1$. You can perform as many moves as you would like (possibly, zero).
What... | Notice that it never makes sense to move blocks between the towers such that neither of them is tower $1$ as that can only decrease the heights. Moreover, it never makes sense to move blocks away from the tower $1$. Thus, all operations will be moving blocks from some towers to tower $1$. At the start, which towers can... | [
"data structures",
"greedy",
"sortings"
] | 800 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
x = a[0]
a = sorted(a[1:])
for y in a:
if y > x:
x += (y - x + 1) // 2
print(x) |
1767 | C | Count Binary Strings | You are given an integer $n$. You have to calculate the number of binary (consisting of characters 0 and/or 1) strings $s$ meeting the following constraints.
For every pair of integers $(i, j)$ such that $1 \le i \le j \le n$, an integer $a_{i,j}$ is given. It imposes the following constraint on the string $s_i s_{i+1... | Suppose we build the string from left to right, and when we place the $i$-th character, we ensure that all substrings ending with the $i$-th character are valid. What do we need to know in order to calculate the number of different characters in the string ending with the $i$-th character? Suppose the character $s_i$ i... | [
"data structures",
"dp"
] | 2,100 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
const int N = 143;
int n;
int a[N][N];
int dp[N][N];
bool check(int cnt, i... |
1767 | D | Playoff | $2^n$ teams participate in a playoff tournament. The tournament consists of $2^n - 1$ games. They are held as follows: in the first phase of the tournament, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$, and so on (so, $2^{n-1}$ games are played in that phase). When a ... | Firstly, let's prove that the order of characters in $s$ is interchangeable. Suppose we have a tournament of four teams with skills $a$, $b$, $c$ and $d$ such that $a < b < c < d$; and this tournament has the form $01$ or $10$. It's easy to see that $a$ and $d$ cannot be winners, since $a$ will be eliminated in the rou... | [
"combinatorics",
"constructive algorithms",
"dp",
"greedy",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
string s;
cin >> n >> s;
int k = count(s.begin(), s.end(), '1');
for (int x = 1 << k; x <= (1 << n) - (1 << (n - k)) + 1; ++x)
cout << x << ' ';
} |
1767 | E | Algebra Flash | \begin{quote}
Algebra Flash 2.2 has just been released!Changelog:
- New gamemode!
Thank you for the continued support of the game!
\end{quote}
Huh, is that it? Slightly disappointed, you boot up the game and click on the new gamemode. It says "Colored platforms".
There are $n$ platforms, numbered from $1$ to $n$, p... | Imagine we bought some subset of colors. How to check if there exists a path from $1$ to $n$? Well, we could write an easy dp. However, it's not immediately obvious where to proceed from that. You can't really implement buying colors inside the dp, because you should somehow know if you bought the current color before,... | [
"bitmasks",
"brute force",
"dp",
"graphs",
"math",
"meet-in-the-middle",
"trees"
] | 2,500 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int n, m;
scanf("%d%d", &n, &m);
vector<int> c(n);
forn(i, n){
scanf("%d", &c[i]);
--c[i];
}
vector<int> x(m);
forn(i, m) scanf("%d", &x[i]);
vector<lon... |
1767 | F | Two Subtrees | You are given a rooted tree consisting of $n$ vertices. The vertex $1$ is the root. Each vertex has an integer written on it; this integer is $val_i$ for the vertex $i$.
You are given $q$ queries to the tree. The $i$-th query is represented by two vertices, $u_i$ and $v_i$. To answer the query, consider all vertices $... | Original solution (by shnirelman) First, let's solve the following problem: we need to maintain a multiset of numbers and process queries of $3$-th types: add a number to the multiset, remove one occurrence of a number from the multiset (it is guaranteed that it exists), calculate the mode on this multiset. To do this,... | [
"data structures",
"trees"
] | 3,100 | #include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
using li = long long;
using ld = long double;
using pii = pair<int, int>;
const int INF = 2e9 + 13;
const li INF64 = 2e18 + 13;
const int M = 998244353;
const int A = 2e5 + 13;
const int N = 2e5 + 13;
const int B = 2000;
const int SQRTA ... |
1768 | A | Greatest Convex | You are given an integer $k$. Find the largest integer $x$, where $1 \le x < k$, such that $x! + (x - 1)!^\dagger$ is a multiple of $^\ddagger$ $k$, or determine that no such $x$ exists.
$^\dagger$ $y!$ denotes the factorial of $y$, which is defined recursively as $y! = y \cdot (y-1)!$ for $y \geq 1$ with the base cas... | Is $x = k - 1$ always suitable? The answer is yes, as $x! + (x - 1)! = (x - 1)! \times (x + 1) = ((k - 1) - 1)! \times ((k - 1) + 1) = (k - 2)! \times (k)$, which is clearly a multiple of $k$. Therefore, $x = k - 1$ is the answer. Time complexity: $\mathcal{O}(1)$ | [
"greedy",
"math",
"number theory"
] | 800 | answer = [print(int(input()) - 1) for testcase in range(int(input()))] |
1768 | B | Quick Sort | You are given a permutation$^\dagger$ $p$ of length $n$ and a positive integer $k \le n$.
In one operation, you:
- Choose $k$ \textbf{distinct} elements $p_{i_1}, p_{i_2}, \ldots, p_{i_k}$.
- Remove them and then add them sorted in increasing order to the end of the permutation.
For example, if $p = [2,5,1,3,4]$ and... | Suppose we can make operations so that $x$ elements do not participate in any operation. Then these $x$ elements in the final array will end up at the beginning in the order in which they were in the initial array. And since this $x$ must be maximized to minimize the number of operations, we need to find the maximal su... | [
"greedy",
"math"
] | 900 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vector<int> p(n);
for (int i = 0... |
1768 | C | Elemental Decompress | You are given an array $a$ of $n$ integers.
Find two permutations$^\dagger$ $p$ and $q$ of length $n$ such that $\max(p_i,q_i)=a_i$ for all $1 \leq i \leq n$ or report that such $p$ and $q$ do not exist.
$^\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrar... | Two cases produce no answers: One element appears more than twice in $a$. One element appears more than twice in $a$. After sorting, there is some index that $a[i] < i$ ($1$-indexed). After sorting, there is some index that $a[i] < i$ ($1$-indexed). Consider there is some index that $a[i] <i$, then both $p[i] < i$ and ... | [
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 1,300 | #include <iostream>
#include <vector>
using namespace std;
int query()
{
/// Input number of element
int n;
cin >> n;
/// Input the array a[1..n]
vector<int> a(n + 1);
for (int i = 1; i <= n; ++i)
cin >> a[i];
/// Storing position of each a[i]
vector<vector<int> > b(n + 1);
... |
1768 | D | Lucky Permutation | You are given a permutation$^\dagger$ $p$ of length $n$.
In one operation, you can choose two indices $1 \le i < j \le n$ and swap $p_i$ with $p_j$.
Find the minimum number of operations needed to have \textbf{exactly one} inversion$^\ddagger$ in the permutation.
$^\dagger$ A permutation is an array consisting of $n... | For some fixed $n$, there are $n - 1$ permutations that have exactly $1$ inversion in them (the inversion is colored): $\color{red}{2}, \color{red}{1}, 3, 4, \ldots, n - 1, n$ $1, \color{red}{3}, \color{red}{2}, 4, \ldots, n - 1, n$ $1, 2, \color{red}{4}, \color{red}{3}, \ldots, n - 1, n$... ... $1, 2, 3, 4, \ldots, \c... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | 1,800 | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> p(n);
for (int i = 0; i < n; i++) {
ci... |
1768 | E | Partial Sorting | Consider a permutation$^\dagger$ $p$ of length $3n$. Each time you can do one of the following operations:
- Sort the first $2n$ elements in increasing order.
- Sort the last $2n$ elements in increasing order.
We can show that every permutation can be made sorted in increasing order using only these operations. Let's... | We need at most $3$ operations to sort the permutation: $1 -> 2 -> 1$ For $f(p) = 0$, there is only one case: the initially sorted permutation. return (38912738912739811 & 1) For $f(p) \leq 1$, this scenario appears when the first $n$ numbers or the last $n$ numbers are in the right places. Both cases have $n$ fixed po... | [
"combinatorics",
"math",
"number theory"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
long long n, M;
long long frac[3000005], inv[3000005];
long long powermod(long long a, long long b, long long m)
{
if (b == 0) return 1;
unsigned long long k = powermod(a, b / 2, m);
k = k * k;
k %= m;
if (b & 1) k = (k * a) % m;
return k;
}
void Ready()
{
frac[... |
1768 | F | Wonderful Jump | You are given an array of positive integers $a_1,a_2,\ldots,a_n$ of length $n$.
In one operation you can jump from index $i$ to index $j$ ($1 \le i \le j \le n$) by paying $\min(a_i, a_{i + 1}, \ldots, a_j) \cdot (j - i)^2$ eris.
For all $k$ from $1$ to $n$, find the minimum number of eris needed to get from index $1... | There is a very easy $\mathcal{O}(n^2)$ dp solution, we will show one possible way to optimize it to $\mathcal{O}(n \cdot \sqrt{A})$, where $A$ is the maximum possible value of $a_i$. Let $dp_k$ be the minimum number of eris required to reach index $k$, $dp_1 = 0$. Suppose we want to calculate $dp_j$ and we already kno... | [
"dp",
"greedy"
] | 2,900 | #include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <cassert>
std::mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());
int main() {
std::ios_base::sync_with_stdio(false); std::cin.tie(NULL);
int n;
std::cin >> n;
std::vector<int> a(n);
f... |
1770 | A | Koxia and Whiteboards | Kiyora has $n$ whiteboards numbered from $1$ to $n$. Initially, the $i$-th whiteboard has the integer $a_i$ written on it.
Koxia performs $m$ operations. The $j$-th operation is to choose one of the whiteboards and change the integer written on it to $b_j$.
Find the maximum possible sum of integers written on the whi... | Exactly $n$ items out of of $a_1,\ldots,a_n,b_1,\ldots,b_m$ will remain on the whiteboard at the end. $b_m$ will always remain on the board at the end. Consider the case where $n=2$ and $m=2$. As we mentioned in hint 2, $b_2$ will always be written, but what about $b_1$? This problem can be solved naturally with a gree... | [
"brute force",
"greedy"
] | 1,000 | #include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define Inf32 1000000001
#define Inf64 4000000000000000001
int main(){
int _t;
cin>>_t;
rep(_,_t){
int n,m;
cin>>n>>m;
vector<long long> a(n+m);
rep(i,n+m)scanf("%lld",&a[i]);
sort(a.begi... |
1770 | B | Koxia and Permutation | Reve has two integers $n$ and $k$.
Let $p$ be a permutation$^\dagger$ of length $n$. Let $c$ be an array of length $n - k + 1$ such that $$c_i = \max(p_i, \dots, p_{i+k-1}) + \min(p_i, \dots, p_{i+k-1}).$$ Let the cost of the permutation $p$ be the maximum element of $c$.
Koxia wants you to construct a permutation wi... | For $k = 1$, the cost is always $2n$ for any permutation. For $k \geq 2$, the minimal cost is always $n + 1$. When $k = 1$ every permutation has the same cost. When $k \geq 2$, the minimal cost will be at least $n+1$. This is because there will always be at least one segment containing the element $n$ in the permutatio... | [
"constructive algorithms"
] | 1,000 | #include <iostream>
#define MULTI int _T; cin >> _T; while(_T--)
using namespace std;
typedef long long ll;
int n, k;
int main () {
ios::sync_with_stdio(0);
cin.tie(0);
MULTI {
cin >> n >> k;
int l = 1, r = n, _ = 1;
while (l <= r) cout << ((_ ^= 1) ? l++ : r--) << ' ';
cout << endl;
}
} |
1770 | C | Koxia and Number Theory | Joi has an array $a$ of $n$ \textbf{positive} integers. Koxia wants you to determine whether there exists a \textbf{positive} integer $x > 0$ such that $\gcd(a_i+x,a_j+x)=1$ for all $1 \leq i < j \leq n$.
Here $\gcd(y, z)$ denotes the greatest common divisor (GCD) of integers $y$ and $z$. | If $a_i$ are not pairwise distinct we get a trivial NO. If all $a_i$ are pairwise distinct, can you construct an example with $n = 4$ that gives an answer NO? Perhaps you are thinking about properties such as parity? Try to generalize the idea. Consider every prime. Consider Chinese Remainder Theorem. How many primes s... | [
"brute force",
"chinese remainder theorem",
"math",
"number theory"
] | 1,700 | #include <iostream>
#include <algorithm>
#define MULTI int _T; cin >> _T; while(_T--)
using namespace std;
typedef long long ll;
const int N = 105;
const int INF = 0x3f3f3f3f;
template <typename T> bool chkmin (T &x, T y) {return y < x ? x = y, 1 : 0;}
template <typename T> bool chkmax (T &x, T y) {return y > x ? x =... |
1770 | D | Koxia and Game | Koxia and Mahiru are playing a game with three arrays $a$, $b$, and $c$ of length $n$. Each element of $a$, $b$ and $c$ is an integer between $1$ and $n$ inclusive.
The game consists of $n$ rounds. In the $i$-th round, they perform the following moves:
- Let $S$ be the multiset $\{a_i, b_i, c_i\}$.
- Koxia removes on... | If all of $a$, $b$ and $c$ are fixed, how to determine who will win? If $a$ and $b$ are fixed, design an algorithm to check if there is an array $c$ that makes Koxia wins. If you can't solve the problem in Hint 2, try to think about how it's related to graph theory. Try to discuss the structure of components in the gra... | [
"constructive algorithms",
"data structures",
"dfs and similar",
"dsu",
"flows",
"games",
"graph matchings",
"graphs",
"implementation"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const int P = 998244353;
int n, a[N], b[N];
vector <int> G[N];
bool vis[N];
int vertex, edge, self_loop;
void dfs(int x) {
if (vis[x]) return ;
vis[x] = true;
vertex++;
for (auto y : G[x]) {
edge++;
dfs(y);
if (y == x) {
self_loop++;
... |
1770 | E | Koxia and Tree | Imi has an undirected tree with $n$ vertices where edges are numbered from $1$ to $n-1$. The $i$-th edge connects vertices $u_i$ and $v_i$. There are also $k$ butterflies on the tree. Initially, the $i$-th butterfly is on vertex $a_i$. All values of $a$ are pairwise distinct.
Koxia plays a game as follows:
- For $i =... | Solve a classic problem - find the sum of pairwise distances of $k$ chosen nodes in a tree. If we add the move operations while the direction of edges are fixed, find the sum of pairwise distances of $k$ chosen nodes. If you can't solve the problem in Hint 2, consider why writers make each edge passed by butterflies fo... | [
"combinatorics",
"dfs and similar",
"dp",
"dsu",
"math",
"probabilities",
"trees"
] | 2,400 | #include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
const int N = 3e5 + 5;
const int mod = 998244353;
const int inv2 = 499122177;
ll qpow (ll n, ll m) {
ll ret = 1;
while (m) {
if (m & 1) ret = ret * n % mod;
n = n * n % mod;
m >>= 1;
}
return ret;
}
ll getinv (ll a) {
return... |
1770 | F | Koxia and Sequence | Mari has three integers $n$, $x$, and $y$.
Call an array $a$ of $n$ \textbf{non-negative} integers good if it satisfies the following conditions:
- $a_1+a_2+\ldots+a_n=x$, and
- $a_1 \, | \, a_2 \, | \, \ldots \, | \, a_n=y$, where $|$ denotes the bitwise OR operation.
The score of a good array is the value of $a_1 ... | From symmetry, for any non-negative integer $t$, the number of good sequences with $a_1=t$, the number of good sequences with $a_2=t$, ... are equal. It is useful to consider the contribution of each bit to the answer independently. Since XOR is undone twice, considering the contribution to the answer can be regarded a... | [
"bitmasks",
"combinatorics",
"dp",
"math",
"number theory"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se second
#define endl '\n'
#define debug(x) cout << #x << ": " << x << endl
#define pub push_back
#define pob pop_back
#define puf push_front
#define pof ... |
1770 | G | Koxia and Bracket | Chiyuu has a bracket sequence$^\dagger$ $s$ of length $n$. Let $k$ be the minimum number of characters that Chiyuu has to remove from $s$ to make $s$ balanced$^\ddagger$.
Now, Koxia wants you to count the number of ways to remove $k$ characters from $s$ so that $s$ becomes balanced, modulo $998\,244\,353$.
Note that ... | and errorgorn What special properties does the deleted bracket sequence have? Try to solve this with $O(n^2)$ DP. If there is no balance requirement, can multiple brackets be processed quickly with one operation? Can you combine the last idea with divide-and-conquer or something? Let us consider what properties the rem... | [
"divide and conquer",
"fft",
"math"
] | 3,400 | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define int long long
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se s... |
1770 | H | Koxia, Mahiru and Winter Festival | \begin{quote}
Wow, what a big face!
\hfill {{\small Kagura Mahiru}}
\end{quote}
Koxia and Mahiru are enjoying the Winter Festival. The streets of the Winter Festival can be represented as a $n \times n$ undirected grid graph. Formally, the set of vertices is $\{(i,j) \; | \; 1 \leq i,j\leq n \}$ and two vertices $(i_1... | In what scenario the maximum congestion is $1$? Assume you have a blackbox that can solve any problem instance of size $n-2$, use it to solve a problem instance of size $n$. This is a special case for a problem called congestion minimization. While in general this problem is NP-hard, for this special structure it can b... | [
"constructive algorithms"
] | 3,500 | #include <bits/stdc++.h>
#define FOR(i,s,e) for (int i=(s); i<(e); i++)
#define FOE(i,s,e) for (int i=(s); i<=(e); i++)
#define FOD(i,s,e) for (int i=(s)-1; i>=(e); i--)
#define PB push_back
using namespace std;
struct Paths{
/* store paths in order */
vector<vector<pair<int, int>>> NS, EW;
Paths(){
NS.clear();... |
1771 | A | Hossam and Combinatorics | Hossam woke up bored, so he decided to create an interesting array with his friend Hazem.
Now, they have an array $a$ of $n$ positive integers, Hossam will choose a number $a_i$ and Hazem will choose a number $a_j$.
Count the number of interesting pairs $(a_i, a_j)$ that meet all the following conditions:
- $1 \le i... | Firstly, let's find $\max_{1 \le p, q \le n} |a_p - a_q| = max(a) - min(a)$ if it's equal to zero, then any pair is valid, so answer if $n \cdot (n - 1)$ Otherwise, let's calculate $count\_min$ and $count\_max$. Answer is $2 \cdot count\_min \cdot count\_max$ | [
"combinatorics",
"math",
"sortings"
] | 900 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, a[N];
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
#endif
int t;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
for(int i = 0 ; i < n ; ++i)
scanf("%d", a + i);
s... |
1771 | B | Hossam and Friends | Hossam makes a big party, and he will invite his friends to the party.
He has $n$ friends numbered from $1$ to $n$. They will be arranged in a queue as follows: $1, 2, 3, \ldots, n$.
Hossam has a list of $m$ pairs of his friends that don't know each other. Any pair not present in this list are friends.
A subsegment ... | Just $a_i < b_i$ in non-friends pairs. Let's calculate $r_i =$ minimum non-friend for all people. So, we can't start subsegment in $a_i$ and finish it righter $r_i$. Let's process people from right to left and calculate the rightmost positions there subsegment can end. Initially, $R = n-1$. Then we go to $a_i$ just do ... | [
"binary search",
"constructive algorithms",
"dp",
"two pointers"
] | 1,400 | #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,no-stack-protector,fast-math")
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define IO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
const int N = 1e5 + 5, M = 1e5 + 5;
int n, m;
int mn[N];
int main()
{
#if... |
1771 | C | Hossam and Trainees | Hossam has $n$ trainees. He assigned a number $a_i$ for the $i$-th trainee.
A pair of the $i$-th and $j$-th ($i \neq j$) trainees is called successful if there is an integer $x$ ($x \geq 2$), such that $x$ divides $a_i$, and $x$ divides $a_j$.
Hossam wants to know if there is a successful pair of trainees.
Hossam is... | If exists $x \geq 2$ such that $a_i$ divides $x$ and $a_j$ divides $x$ then exists prime number $p$ such that $a_i$ and $a_j$ divides $p$. We can choose $p =$ any prime divisor of $x$. So, let's factorize all numbers and check, if two of them divides one prime number. We can use default factorization, and it will be $O... | [
"greedy",
"math",
"number theory"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, M = 2 * N + 5;
bool vis[N], ans;
void Sieve(){
memset(vis, true, sizeof(vis));
vis[0] = vis[1] = false;
for(int i = 4 ; i < N ; i += 2)
vis[i] = false;
for(int i = 3 ; i < N / i ; i += 2){
if(!vis[i])continue;
... |
1771 | D | Hossam and (sub-)palindromic tree | Hossam has an unweighted tree $G$ with letters in vertices.
Hossam defines $s(v, \, u)$ as a string that is obtained by writing down all the letters on the unique simple path from the vertex $v$ to the vertex $u$ in the tree $G$.
A string $a$ is a subsequence of a string $s$ if $a$ can be obtained from $s$ by deletio... | Let's use dynamic programming method. Let $dp_{v, \, u}$ as length of the longest maximal sub-palindrome on the path between vertexes $v$ and $u$. Then the answer to the problem is $\max\limits_{1 \le v, \, u \le n}{dp_{v, \, u}}$. Define $go_{v, \, u}$ $(v \neq u)$ vertex $x$ such that it is on way between $v$ and $u$... | [
"brute force",
"data structures",
"dfs and similar",
"dp",
"strings",
"trees"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
void dfs(int v, vector<vector<int>> &g, vector<vector<int>> &go, vector<vector<pair<int, int>>> &kek, int s, int t = -1, int p = -1, int len = 0){
if(len == 1)
t = v;
if(len > 1)
go[s][v] = t;
kek[len].push_back({s, v});
for(int u : g[v]... |
1771 | E | Hossam and a Letter | Hossam bought a new piece of ground with length $n$ and width $m$, he divided it into an $n \cdot m$ grid, each cell being of size $1\times1$.
Since Hossam's name starts with the letter 'H', he decided to draw the capital letter 'H' by building walls of size $1\times1$ on some squares of the ground. Each square $1\tim... | Let's preprocess the following data for each cell. 1. first medium cell above current cell. 2. first medium cell below current cell. 3. first bad cell above current cell. 4. first bad cell below current cell. Then we will try to solve the problem for each row (i), and 2 columns (j, k). Now we have a horizontal line in ... | [
"brute force",
"dp",
"implementation",
"two pointers"
] | 2,500 | #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,no-stack-protector,fast-math")
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define IO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
const int N = 4e2 + 5;
int n, m;
char a[N][N];
int upM[N][N];
int upB[N]... |
1771 | F | Hossam and Range Minimum Query | Hossam gives you a sequence of integers $a_1, \, a_2, \, \dots, \, a_n$ of length $n$. Moreover, he will give you $q$ queries of type $(l, \, r)$. For each query, consider the elements $a_l, \, a_{l + 1}, \, \dots, \, a_r$. Hossam wants to know the \textbf{smallest} number in this sequence, such that it occurs in this ... | Note that we were asked to solve the problem in online mode. If this were not the case, then the Mo Algorithm could be used. How to solve this task in online mode? Consider two ways. The first way is as follows. Let's build a persistent bitwise trie $T$ on a given array, where the $i$-th version of the trie will store ... | [
"binary search",
"bitmasks",
"data structures",
"hashing",
"probabilities",
"strings",
"trees"
] | 2,500 | #pragma optimize("SEX_ON_THE_BEACH")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("unroll-all-loops")
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("fast-math")
//#define _FORTIFY_SOURCE 0
#pragma GCC optimize("no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse... |
1772 | A | A+B? | You are given an expression of the form $a{+}b$, where $a$ and $b$ are integers from $0$ to $9$. You have to evaluate it and print the result. | There are multiple ways to solve this problem. Most interpreted languages have some function that takes the string, evaluates it as code, and then returns the result. One of the examples is the eval function in Python. If the language you use supports something like that, you can read the input as a string and use it a... | [
"implementation"
] | 800 | t = int(input())
for i in range(t):
print(eval(input())) |
1772 | B | Matrix Rotation | You have a matrix $2 \times 2$ filled with \textbf{distinct} integers. You want your matrix to become beautiful. The matrix is beautiful if the following two conditions are satisfied:
- in each row, the first element is smaller than the second element;
- in each column, the first element is smaller than the second ele... | Sure, you can just implement the rotation operation and check all $4$ possible ways to rotate the matrix, but it's kinda boring. The model solution does the different thing. If a matrix is beautiful, then its minimum is in the upper left corner, and its maximum is in the lower right corner (and vice versa). If you rota... | [
"brute force",
"implementation"
] | 800 | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int _ = 0; _ < t; _++)
{
vector<int> a(4);
for(int i = 0; i < 4; i++)
cin >> a[i];
int maxpos = max_element(a.begin(), a.end()) - a.begin();
int minpos = min_element(a.begin(), a.... |
1772 | C | Different Differences | An array $a$ consisting of $k$ integers is \textbf{strictly increasing} if $a_1 < a_2 < \dots < a_k$. For example, the arrays $[1, 3, 5]$, $[1, 2, 3, 4]$, $[3, 5, 6]$ are strictly increasing; the arrays $[2, 2]$, $[3, 7, 5]$, $[7, 4, 3]$, $[1, 2, 2, 3]$ are not.
For a strictly increasing array $a$ of $k$ elements, let... | We can transform the problem as follows. Let $d_i = a_{i+1} - a_i$. We need to find an array $[d_1, d_2, \dots, d_{k-1}]$ so that the sum of elements in it is not greater than $n-1$, all elements are positive integers, and the number of different elements is the maximum possible. Suppose we need $f$ different elements ... | [
"constructive algorithms",
"greedy",
"math"
] | 1,000 | def construct(f, k):
return [(i + 2 if i < f - 1 else 1) for i in range(k)]
t = int(input())
for i in range(t):
k, n = map(int, input().split())
ans = 1
for f in range(1, k):
d = construct(f, k - 1)
if sum(d) <= n - 1:
ans = f
res = [1]
d = construct(ans, k - 1)
... |
1772 | D | Absolute Sorting | You are given an array $a$ consisting of $n$ integers. The array is sorted if $a_1 \le a_2 \le \dots \le a_n$.
You want to make the array $a$ sorted by applying the following operation \textbf{exactly once}:
- choose an integer $x$, then for every $i \in [1, n]$, replace $a_i$ by $|a_i - x|$.
Find any value of $x$ t... | What does it actually mean for an array $a_1, a_2, \dots, a_n$ to be sorted? That means $a_1 \le a_2$ and $a_2 \le a_3$ and so on. For each pair of adajacent elements, let's deduce which values $x$ put them in the correct order. Any value of $x$ that puts all pairs in the correct order will be the answer. Consider any ... | [
"constructive algorithms",
"math"
] | 1,400 | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
int n;
cin >> n;
vector<int> a(n);
for(int j = 0; j < n; j++)
cin >> a[j];
int mn = 0, mx = int(1e9);
for(int j = 0; j + 1 < n; j++)
... |
1772 | E | Permutation Game | Two players are playing a game. They have a permutation of integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once). The permutation is not sorted in either ascending or descending order (i. e. the permutation does not have the form $[1, 2, \dots, n]$ or $[n, n-1, \... | Note that it makes no sense to use the first type of operation if it does not lead to an instant win, because the opponent can return the previous state of the array with their next move. So the winner is the one who has time to color "their" elements in blue first. Let's denote $a$ as the number of elements that only ... | [
"games"
] | 1,700 | for tc in range(int(input())):
n = int(input())
p = list(map(int, input().split()))
a, b, c = 0, 0, 0
for i in range(n):
if p[i] != i + 1 and p[i] != n - i:
c += 1
elif p[i] != i + 1:
a += 1
elif p[i] != n - i:
b += 1
if a + c <= b:
print("First")
elif b + c < a:
print(... |
1772 | F | Copy of a Copy of a Copy | It all started with a black-and-white picture, that can be represented as an $n \times m$ matrix such that all its elements are either $0$ or $1$. The rows are numbered from $1$ to $n$, the columns are numbered from $1$ to $m$.
Several operations were performed on the picture (possibly, zero), each of one of the two k... | Notice the following: once you apply the recolor operation to some cell, you can never recolor it again. That happens because you can't recolor its neighbors too as each of them has at least one neighbor of the same color - this cell itself. In particular, that implies that applying a recolor operation always decreases... | [
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation",
"sortings"
] | 2,000 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
struct op{
int t, x, y, i;
};
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int main(){
int n, m, k;
cin >> n >> m >> k;
vector<vector<string>> a(k + 1, vector<string>(n));
forn(z, k + 1) fo... |
1772 | G | Gaining Rating | Monocarp is playing chess on one popular website. He has $n$ opponents he can play with. The $i$-th opponent has rating equal to $a_i$. Monocarp's initial rating is $x$. Monocarp wants to raise his rating to the value $y$ ($y > x$).
When Monocarp is playing against one of the opponents, he will win if his \textbf{curr... | After parsing the statement, you can understand that Monocarp plays cyclically: in one cycle, he chooses some order of opponents and play with them in that order. Then repeats again and again, until he gains desired rating at some moment. So, firstly, let's prove that (in one cycle) it's optimal to play against opponen... | [
"binary search",
"greedy",
"implementation",
"math",
"sortings",
"two pointers"
] | 2,200 | #include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
typedef long long li;
int n;
li x, y;
vector<li> a;
inline bool read() {
if(!(cin >> n >> x >> y))
return false;
a.resize(n);
fore (i, 0, n)
cin >> a[i];... |
1774 | A | Add Plus Minus Sign | AquaMoon has a string $a$ consisting of only $0$ and $1$. She wants to add $+$ and $-$ between all pairs of consecutive positions to make the absolute value of the resulting expression as small as possible. Can you help her? | The answer is the number of $1$s modulo $2$. We can get that by adding '-' before the $\text{2nd}, \text{4th}, \cdots, 2k\text{-th}$ $1$, and '+' before the $\text{3rd}, \text{5th}, \cdots, 2k+1\text{-th}$ $1$. | [
"constructive algorithms",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
char c[1005];
int main() {
int t;
scanf("%d", &t);
int n;
while (t--) {
scanf("%d", &n);
scanf("%s", c + 1);
int u = 0;
for (int i = 1; i <= n; ++i) {
bool fl = (c[i] == '1') && u;
u ^= (c[i] - '0');
if (i != 1) putchar(fl ? '-' : ... |
1774 | B | Coloring | Cirno_9baka has a paper tape with $n$ cells in a row on it. As he thinks that the blank paper tape is too dull, he wants to paint these cells with $m$ kinds of colors. For some aesthetic reasons, he thinks that the $i$-th color must be used exactly $a_i$ times, and for every $k$ consecutive cells, their colors have to ... | First, We can divide $n$ cells into $\left\lceil\frac{n}{k}\right\rceil$ segments that except the last segment, all segments have length $k$. Then in each segment, the colors in it are pairwise different. It's easy to find any $a_i$ should be smaller than or equal to $\left\lceil\frac{n}{k}\right\rceil$. Then we can co... | [
"constructive algorithms",
"greedy",
"math"
] | 1,500 | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
int fl = 0;
for (int i = 1; i <= m; ++i) {
int a;
scanf("%d", &a);
if (a == (n + k - 1) / k) ++fl;
if (a > (n + k - 1) / k) fl = 1 <... |
1774 | C | Ice and Fire | Little09 and his friends are playing a game. There are $n$ players, and the temperature value of the player $i$ is $i$.
The types of environment are expressed as $0$ or $1$. When two players fight in a specific environment, if its type is $0$, the player with a lower temperature value in this environment always wins; ... | We define $f_i$ to mean that the maximum $x$ satisfies $s_{i-x+1}=s_{i-x+2}=...=s_{i}$. It can be proved that for $x$ players, $f_{x-1}$ players are bound to lose and the rest have a chance to win. So the answer to the first $i$ battles is $ans_i=i-f_i+1$. Next, we prove this conclusion. Suppose there are $n$ players a... | [
"constructive algorithms",
"dp",
"greedy"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int N = 300005;
int T, n, ps[2];
char a[N];
void solve() {
scanf("%d %s", &n, a + 1);
ps[0] = ps[1] = 0;
for (int i = 1; i < n; ++i) {
ps[a[i] - 48] = i;
if (a[i] == '0')
printf("%d ", ps[1] + 1);
else
printf("%d ", ps[0] + 1);
}
pu... |
1774 | D | Same Count One | ChthollyNotaSeniorious received a special gift from AquaMoon: $n$ binary arrays of length $m$. AquaMoon tells him that in one operation, he can choose any two arrays and any position $pos$ from $1$ to $m$, and swap the elements at positions $pos$ in these arrays.
He is fascinated with this game, and he wants to find t... | Considering that we need to make the number of $1\text{s}$ in each array the same, we should calculate the sum of $1\text{s}$, and every array has $sum / n$ $1\text{s}$. Because only the same position of two different arrays can be selected for exchange each time, for a position $pos$, we traverse each array each time.... | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"two pointers"
] | 1,600 | #include <bits/stdc++.h>
int main() {
int T;
scanf("%d", &T);
while (T--) {
int n, m;
scanf("%d %d", &n, &m);
std::vector<std::vector<int>> A(n, std::vector<int>(m, 0));
std::vector<int> sum(n, 0);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &A[i][j])... |
1774 | E | Two Chess Pieces | Cirno_9baka has a tree with $n$ nodes. He is willing to share it with you, which means you can operate on it.
Initially, there are two chess pieces on the node $1$ of the tree. In one step, you can choose any piece, and move it to the neighboring node. You are also given an integer $d$. You need to ensure that the dis... | We can find that for any $d$-th ancestor of some $b_i$, the first piece must pass it some time. Otherwise, we will violate the distance limit. The second piece must pass the $d$-th ancestor of each $b_i$ as well. Then we can add the $d$-th ancestor of each $a_i$ to the array $b$, and add the $d$-th ancestor of each $b_... | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int t[N * 2], nxt[N * 2], cnt, h[N];
int n, d;
void add(int x, int y) {
t[++cnt] = y;
nxt[cnt] = h[x];
h[x] = cnt;
}
int a[N], b[N];
bool f[2][N];
void dfs1(int x, int fa, int dis) {
a[dis] = x;
if (dis > d)
b[x] = a[dis - d];
else
... |
1774 | F1 | Magician and Pigs (Easy Version) | \textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$ and $x$. You can make hacks only if both versions of the problem are solved.}
Little09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perfo... | Let $X=\max x$. Think about what 'Repeat' is doing. Assuming the total damage is $tot$ ($tot$ is easy to calculate because it will be multiplied by $2$ after each 'Repeat' and be added after each 'Attack'). After repeating, each pig with a current HP of $w$ ($w > tot$) will clone a pig with a HP of $w-tot$. Why? 'Repea... | [
"brute force",
"data structures",
"implementation"
] | 2,400 | // Author: Little09
// Problem: F. Magician and Pigs (Easy Version)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod = 998244353, inv = (mod + 1) / 2;
int n;
map<ll, ll> s;
ll tot, mul = 1, ts = 1;
inline void add(ll &x, ll y) { (x += y) >= mod && (x -= mod); }
int main() {
ios_base:... |
1774 | F2 | Magician and Pigs (Hard Version) | \textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$ and $x$. You can make hacks only if both versions of the problem are solved.}
Little09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perfo... | For F1, there is another way. Consider every pig. When Repeat, it will clone, and when Attack, all its clones will be attacked together. Therefore, considering all the operations behind each pig, you can choose to reduce $x$ (the current total damage) or not when Repeat, and you must choose to reduce $x$ when Attack. A... | [
"binary search",
"brute force",
"data structures",
"implementation"
] | 2,700 | // Author: Little09
// Problem: F. Magician and Pigs
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mem(x) memset(x, 0, sizeof(x))
#define endl "\n"
#define printYes cout << "Yes\n"
#define printYES cout << "YES\n"
#define printNo cout << "No\n"
#define printNO cout << "NO\n"
#define lowbi... |
1774 | G | Segment Covering | ChthollyNotaSeniorious gives DataStructures a number axis with $m$ distinct segments on it. Let $f(l,r)$ be the number of ways to choose an even number of segments such that the union of them is exactly $[l,r]$, and $g(l,r)$ be the number of ways to choose an odd number of segments such that the union of them is exactl... | If there exist two segments $(l_1, r_1), (l_2, r_2)$ such that $l_1 \le l_2 \le r_2 \le r_1$ and we choose $(l_1, r_1)$, number of ways of choosing $(l_2, r_2)$ at the same time will be equal to that of not choosing. Hence if we choose $(l_1, r_1)$, the signed number of ways will be $0$. So we can delete $(l_1, r_1)$. ... | [
"brute force",
"combinatorics",
"constructive algorithms",
"data structures",
"dp",
"trees"
] | 3,200 | #include <bits/stdc++.h>
#define File(a) freopen(a ".in", "r", stdin), freopen(a ".out", "w", stdout)
using tp = std::tuple<int, int, int>;
const int sgn[] = {1, 998244352};
const int N = 200005;
int x[N], y[N];
std::vector<tp> V;
bool del[N];
int fa[20][N];
int m, q;
int main() {
scanf("%d %d", &m, &q);
for (i... |
1774 | H | Maximum Permutation | Ecrade bought a deck of cards numbered from $1$ to $n$. Let the value of a permutation $a$ of length $n$ be $\min\limits_{i = 1}^{n - k + 1}\ \sum\limits_{j = i}^{i + k - 1}a_j$.
Ecrade wants to find the most valuable one among all permutations of the cards. However, it seems a little difficult, so please help him! | When it seems to be hard to come up with the whole solution directly, simplified questions can often be a great helper. So first let us consider the case where $n$ is the multiple of $k$. Let $t=\frac{n}{k}$. What is the largest value one can obtain theoretically? Pick out $t$ subsegments $a_{[1:k]},a_{[k+1:2k]},\dots,... | [
"constructive algorithms"
] | 3,500 | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll t,n,k,seq[100009],ans[100009];
inline ll read(){
ll s = 0,w = 1;
char ch = getchar();
while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}
while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();
... |
1775 | A1 | Gardener and the Capybaras (easy version) | \textbf{This is an easy version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.}
Kazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.
Recently C... | To solve this problem, it was enough just to consider all options of splitting the string into three substrings, and there are only $O(n^2)$ ways to do it. | [
"brute force",
"constructive algorithms",
"implementation"
] | 800 | "#include <bits/stdc++.h>\n#define sz(x) ((int)x.size())\nusing namespace std;\nstring s;\nint n;\n\nvoid Solve() {\n cin >> s;\n n = sz(s);\n\n if (s[0] == s[1]) {\n cout << s[0] << \" \" << s[1] << \" \" << s.substr(2) << '\\n';\n return;\n }\n if (s[n - 2] == s[n - 1]) {\n cout <<... |
1775 | A2 | Gardener and the Capybaras (hard version) | \textbf{This is an hard version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.}
Kazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.
Recently C... | Consider five cases to solve the task: If the string starts with $aa$, then we can split it into $a = s[0]$, $b = s[1]$, $c = s[2 ... n - 1]$. If the string starts with $bb$, then we can split it into $a = s[0]$, $b = s[1]$, $c = s[2 ... n - 1]$. If the string starts with $ba$, then we can split it into $a = s[0]$, $b ... | [
"constructive algorithms",
"greedy"
] | 900 | "#include <bits/stdc++.h>\n#define sz(x) ((int)x.size())\nusing namespace std;\nstring s;\nint n;\n\nvoid Solve() {\n cin >> s;\n n = sz(s);\n\n if (s[0] == s[1]) {\n cout << s[0] << \" \" << s[1] << \" \" << s.substr(2) << '\\n';\n return;\n }\n if (s[n - 2] == s[n - 1]) {\n cout <<... |
1775 | B | Gardener and the Array | The gardener Kazimir Kazimirovich has an array of $n$ integers $c_1, c_2, \dots, c_n$.
He wants to check if there are two different subsequences $a$ and $b$ of the original array, for which $f(a) = f(b)$, where $f(x)$ is the bitwise OR of all of the numbers in the sequence $x$.
A sequence $q$ is a subsequence of $p$ ... | The problem can be solved as follows: for each bit count the number of its occurrences in all numbers in the test. If each number has a bit which occurs in all numbers exactly once, then the answer is "NO", otherwise the answer is "YES". Let's try to prove this solution. Let there be a number in which all bits occurs i... | [
"bitmasks",
"constructive algorithms"
] | 1,300 | "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <ctime>\n#include <cmath>\n#include <map>\n#include <assert.h>\n#include <fstream>\n#include <cstdlib>\n#include <random>\n#include <iomanip>\n#include <queue>\n#include <random>\n#include <unordered_map>\n \nusing namespace std;\n ... |
1775 | C | Interesting Sequence | Petya and his friend, robot Petya++, like to solve exciting math problems.
One day Petya++ came up with the numbers $n$ and $x$ and wrote the following equality on the board: $$n\ \&\ (n+1)\ \&\ \dots\ \&\ m = x,$$ where $\&$ denotes the bitwise AND operation. Then he suggested his friend Petya find such a minimal $m$... | Note that the answer $-1$ will be when $n$ AND $x \neq x$. This holds if there is a bit with number $b$ which exists in number $x$, but it does not exist in number $n$. What is clear now is that some bits in $n$ must be zeroed. Since we have bitwise AND going sequentially with numbers larger than $n$, we change the bit... | [
"bitmasks",
"math"
] | 1,600 | "#pragma GCC optimize(\"O3\")\n#include<bits/stdc++.h>\n\n#define ll long long\n#define pb push_back\n#define ld long double\n#define f first\n#define s second\n\nusing namespace std;\nconst ll inf = (1ll << 62);\nint32_t main() {\n\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n ll t;\n c... |
1775 | D | Friendly Spiders | Mars is home to an unusual species of spiders — Binary spiders.
Right now, Martian scientists are observing a colony of $n$ spiders, the $i$-th of which has $a_i$ legs.
Some of the spiders are friends with each other. Namely, the $i$-th and $j$-th spiders are friends if $\gcd(a_i, a_j) \ne 1$, i. e., there is some in... | Note that if we construct the graph by definition, it will be large. This will lead us to the idea to make it more compact. Let us create a bipartite graph whose left part consists of $n$ vertices with numbers $a_i$. And in the right part each vertex corresponds to some prime number, not larger than the maximal number ... | [
"dfs and similar",
"graphs",
"math",
"number theory",
"shortest paths"
] | 1,800 | "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int N = 300100;\nconst int kMaxA = 300100;\nconst int oo = 1e9;\nvector<int> edges[kMaxA];\nint dist[kMaxA], prv[kMaxA];\nbool used[kMaxA];\nint prv_id[kMaxA];\nint min_prime[kMaxA];\nint n, a[N];\nint boss[kMaxA];\nint mem_id[kMaxA];\nint so... |
1775 | E | The Human Equation | Petya and his friend, the robot Petya++, went to BFDMONCON, where the costume contest is taking place today.
While walking through the festival, they came across a scientific stand named after Professor Oak and Golfball, where they were asked to solve an interesting problem.
Given a sequence of numbers $a_1, a_2, \do... | Let's calculate an array of prefix sums. What do the operations look like in this case? If we calculate the array of prefix sums, we'll see that the operations now look like "add 1 on a subsequence" or "take away 1 on a subsequence". Why? If we take the indices $i$ and $j$ and apply our operation to them (i.e. $a_i = a... | [
"greedy",
"implementation"
] | 2,100 | "#include <iostream>\n\nusing namespace std;\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int t;\n cin >> t;\n while (t--) {\n int n;\n cin >> n;\n int64_t mn = 0;\n int64_t mx = 0;\n int64_t cur = 0;\n for (int i = 0; i < n; i++) {\n ... |
1775 | F | Laboratory on Pluto | As you know, Martian scientists are actively engaged in space research. One of the highest priorities is Pluto. In order to study this planet in more detail, it was decided to build a laboratory on Pluto.
It is known that the lab will be built of $n$ square blocks of equal size. For convenience, we will assume that Pl... | Let us find out the minimal perimeter for a fixed $n$ in $O(1)$. Let $a = \lfloor \sqrt{n} \rfloor$: If $a^2 < n$ and $n \leq a \cdot (a+1)$, then the minimum perimeter will be $2 \cdot (2 \cdot a + 1)$. If $a \cdot a + a < n$ and $n \leq (a + 1)^2$, then the minimum perimeter will be $4 \cdot (a + 1)$. If 1) and 2) ar... | [
"constructive algorithms",
"dp",
"greedy",
"math"
] | 2,500 | "#include <bits/stdc++.h>\n#define el \"\\n\"\nusing namespace std;\n\nconst int N = 4e5 + 50;\n\nint f[5][1500][1500], M, a;\n\nint get_P(int n) {\n int a = sqrt(n);\n if (a * a < n && a * a + a >= n) {\n return 2 * a + 1;\n }\n if (a * a + a < n && n <= (a + 1) * (a + 1)) {\n return 2 * (a +... |
1777 | A | Everybody Likes Good Arrays! | An array $a$ is good if for all pairs of adjacent elements, $a_i$ and $a_{i+1}$ ($1\le i \lt n$) are of \textbf{different} parity. Note that an array of size $1$ is trivially good.
You are given an array of size $n$.
In one operation you can select any pair of adjacent elements in which both elements are of the \text... | Solution Replace even numbers with $0$ and odd numbers with $1$ in the array $a$. Now we observe that the given operation is equivalent to selecting two equal adjacent elements and deleting one of them. Now the array can be visualized as strips of zeros (in green) and ones (in red) like this $[\color{green}{0,0,0},\col... | [
"greedy",
"math"
] | 800 | def main():
T = int(input())
while T > 0:
T = T - 1
n = int(input())
a = [int(x) for x in input().split()]
ans = 0
for i in range(1, n):
ans += 1 - ((a[i] + a[i - 1]) & 1)
print(ans)
if __name__ == '__main__':
main() |
1777 | B | Emordnilap | A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). There are $n! =... | Observation: Every permutation has the same beauty. Consider two indices $i$ and $j$ ($i < j$) in a permutation $p$. These elements appear in the order $[p_i, p_j, p_j, p_i]$ in array $A$. Now we have two cases: Case $1$: $p_i > p_j$ The first $p_i$ appears before both $p_j$'s in this case, accounting for $2$ inversion... | [
"combinatorics",
"greedy",
"math"
] | 900 | t = int(input())
for _ in range(t):
n = int(input())
nf = 1
mod = int(1e9 + 7)
for i in range(n):
nf = nf * (i + 1)
nf %= mod
ans = n * (n - 1) * nf
ans %= mod
print(ans) |
1777 | C | Quiz Master | A school has to decide on its team for an international quiz. There are $n$ students in the school. We can describe the students using an array $a$ where $a_i$ is the smartness of the $i$-th ($1 \le i \le n$) student.
There are $m$ topics $1, 2, 3, \ldots, m$ from which the quiz questions will be formed. The $i$-th st... | We can sort the smartness values and use two pointers. The two pointers indicate the students we are considering in our team. Let $l$ be the left pointer and $r$ be the right pointer. $a_l$ is the minimum smartness of our team and $a_r$ is the maximum. If this team is collectively proficient in all topics, then the dif... | [
"binary search",
"math",
"number theory",
"sortings",
"two pointers"
] | 1,700 | #include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define var(x, y, z) cout << x << " " << y << " " << z << endl;
#define ll long long int
#define pii pair<ll, ll>
#define pb push_back
#define ff first
#define ss second
#define FASTIO \
ios ::sync_with_stdio(0); \
cin.tie(0); ... |
1777 | D | Score of a Tree | You are given a tree of $n$ nodes, rooted at $1$. Every node has a value of either $0$ or $1$ at time $t=0$.
At any integer time $t>0$, the value of a node becomes the bitwise XOR of the values of its children at time $t - 1$; the values of leaves become $0$ since they don't have any children.
Let $S(t)$ denote the s... | We will focus on computing the expected value of $F(A)$ rather than the sum, as the sum is just $2^n \times \mathbb{E}(F(A))$. Let $F_u(A)$ denote the sum of all values at node $u$ from time $0$ to $10^{100}$, if the initial configuration is $A$. Clearly, $F(A) = \sum {F_u(A)}$. With linearity of expectations, $\mathbb... | [
"bitmasks",
"combinatorics",
"dfs and similar",
"dp",
"math",
"probabilities",
"trees"
] | 1,900 | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
long long power(long long a, int b)
{
long long ans = 1;
while (b)
{
if (b & 1)
{
ans *= a;
ans %= MOD;
}
a *= a;
a %= MOD;
b >>= 1;
}
return ans;
}
int ... |
1777 | E | Edge Reverse | You will be given a weighted directed graph of $n$ nodes and $m$ directed edges, where the $i$-th edge has a weight of $w_i$ ($1 \le i \le m$).
You need to reverse some edges of this graph so that there is at least one node in the graph from which every other node is reachable. The cost of these reversals is equal to ... | If the cost for completing the task is $c$, we can reverse any edge with cost $\le c$. This is equivalent to making those edges bidirectional since when checking for reachability, we only need to traverse an edge once, and we can choose to reverse it or not, depending upon the need. We can apply a binary search on the ... | [
"binary search",
"dfs and similar",
"graphs",
"trees"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
// Using Kosa Raju, we guarantee the topmost element (indicated by root) of stack is from the root SCC
void DFS(int v, bool visited[], int &root, vector<int> edges[])
{
visited[v] = true;
for (auto it : edges[v])
if (!visited[it])
DFS(it, vis... |
1777 | F | Comfortably Numb | You are given an array $a$ consisting of $n$ non-negative integers.
The numbness of a subarray $a_l, a_{l+1}, \ldots, a_r$ (for arbitrary $l \leq r$) is defined as $$\max(a_l, a_{l+1}, \ldots, a_r) \oplus (a_l \oplus a_{l+1} \oplus \ldots \oplus a_r),$$ where $\oplus$ denotes the bitwise XOR operation.
Find the maxim... | The problem can be solved recursively. Keep dividing the array into subarrays at the maximum element of the current subarray. Let's say the maximum element of the initial array is at index $x$, so the array gets divided into two subarrays $a[1...x-1]$ and $a[x+1,...n]$. Say we have already calculated the answer for the... | [
"bitmasks",
"data structures",
"divide and conquer",
"strings",
"trees"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
struct Trie{
struct Trie *child[2]={0};
};
typedef struct Trie trie;
void insert(trie *dic, int x)
{
trie *temp = dic;
for(int i=30;i>=0;i--)
{
int curr = x>>i&1;
if(temp->child[curr])
temp = temp->child[curr];
else
{
temp->child[curr] = new trie;
... |
1778 | A | Flip Flop Sum | You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$. The integers are either $1$ or $-1$. You have to perform the following operation \textbf{exactly once} on the array $a$:
- Choose an index $i$ ($1 \leq i < n$) and flip the signs of $a_i$ and $a_{i+1}$. Here, flipping the sign means $-1$ will be $1$ and $... | Let's say we've chosen index $i$. What will happen? If the values of $a_i$ and $a_{i+1}$ have opposite signs, flipping them won't change the initial $sum$. if $a_i$ = $a_{i+1}$ = $1$, flipping them will reduce the $sum$ by $4$. if $a_i$ = $a_{i+1}$ = $-1$, flipping them will increase the $sum$ by $4$. So, for each $i <... | [
"greedy",
"implementation"
] | 800 | #include <bits/stdc++.h>
using namespace std;
const int sz = 1e5 + 10;
int ara[sz];
int main()
{
int t;
scanf("%d", &t);
while(t--) {
int n;
scanf("%d", &n);
int sum = 0;
for(int i = 1; i <= n; i++) {
scanf("%d", &ara[i]);
sum += ara[i];
... |
1778 | B | The Forbidden Permutation | You are given a permutation $p$ of length $n$, an array of $m$ \textbf{distinct} integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le n$), and an integer $d$.
Let $\mathrm{pos}(x)$ be the index of $x$ in the permutation $p$. The array $a$ is \textbf{not good} if
- $\mathrm{pos}(a_{i}) < \mathrm{pos}(a_{i + 1}) \le \mathr... | If the array $a$ is good, the answer is obviously $0$. Now, how can we optimally transform a not good array $a$ to a good array? Let, we are on the index $i$ $(i<m)$ and $x = a_i$, $y = a_{i+1}$. If we observe carefully, we will find that there are basically two cases that will make the array $a$ good: Move $x$ and $y$... | [
"greedy",
"math"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int sz = 1e5+10;
int p[sz], a[sz], pos[sz];
int main()
{
int t;
scanf("%d", &t);
while(t--) {
int n, m, d;
scanf("%d %d %d", &n, &m, &d);
for(int i = 1; i <= n; i++) {
scanf("%d", &p[i]);
pos[ p[i] ] ... |
1778 | C | Flexible String | You have a string $a$ and a string $b$. Both of the strings have length $n$. There are \textbf{at most $10$ different characters} in the string $a$. You also have a set $Q$. Initially, the set $Q$ is empty. You can apply the following operation on the string $a$ any number of times:
- Choose an index $i$ ($1\leq i \le... | If we can replace all the characters of the string $a$, we can transform the string $a$ to the string $b$. So, replacing more characters is always beneficial. For a fixed string $a$ and another fixed string $b$, if the answer is $x_1$ for $k_1$ and $x_2$ for $k_2$ $(k_1 < k_2)$, it can be shown that $x_1 \leq x_2$ alwa... | [
"bitmasks",
"brute force",
"strings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define EL '\n'
#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
string a, b;
string char_list;
bool mark[26];
ll ans, k;
ll count_matching_pair()
{
ll tot_pair = 0, match_count = 0;
... |
1778 | D | Flexible String Revisit | You are given two binary strings $a$ and $b$ of length $n$. In each move, the string $a$ is modified in the following way.
- An index $i$ ($1 \leq i \leq n$) is chosen uniformly at random. The character $a_i$ will be flipped. That is, if $a_i$ is $0$, it becomes $1$, and if $a_i$ is $1$, it becomes $0$.
What is the e... | Let $k$ be the number of indices where the characters between two strings are different and $f(x)$ be the expected number of moves to make two strings equal given that the strings have $x$ differences. We have to find the value of $f(k)$. For all $x$ where $1 \leq x \leq n-1$, $\begin{align} f(x) = \frac{x}{n} \cdot [1... | [
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,100 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
template<int MOD>
struct ModInt {
unsigned x;
ModInt() : x(0) { }
ModInt(signed sig) : x(sig) { }
ModInt(signed long long sig) : x(sig%MOD) { }
int get() const { return (int)x; }
ModInt pow(ll p) { ModInt res = 1, a = *this; while (p) {... |
1778 | E | The Tree Has Fallen! | Recently, a tree has fallen on Bob's head from the sky. The tree has $n$ nodes. Each node $u$ of the tree has an integer number $a_u$ written on it. But the tree has no fixed root, as it has fallen from the sky.
Bob is currently studying the tree. To add some twist, Alice proposes a game. First, Bob chooses some node ... | At first, we can think of another problem. Given an array. You need to find the maximum subset $XOR$. How can we solve it? We can solve this problem very efficiently using a technique called "$XOR$ Basis". You can read about it from here. In problem E, at first, we can fix any node as the root of the tree. Let's call t... | [
"bitmasks",
"dfs and similar",
"math",
"trees"
] | 2,500 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define nn '\n'
#define fastio std::ios_base::sync_with_stdio(false); cin.tie(NULL);
const int sz = 2e5 + 10, d = 30;
vector <int> g[sz], Tree[sz];
int a[sz], discover_time[sz], finish_time[sz], nodeOf[sz], tim;
struct BASIS {... |
1778 | F | Maximizing Root | You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. Vertex $1$ is the root of the tree. Each vertex has an integer value. The value of $i$-th vertex is $a_i$. You can do the following operation at most $k$ times.
- Choose a vertex $v$ \textbf{that has not been chosen before} and an integer... | Let, $x_u$ be the value of node $u$ and $dp[u][d]$ be the minimum number of moves required to make the GCD of the subtree of $u$ equal to a multiple of $d$. Now, $dp[u][d] = 0$ if the subtree GCD of node $u$ is already a multiple of $d$ and $dp[u][d] = \infty$ if $(x_u \cdot x_u)$ is not a multiple of $d$. For each div... | [
"dfs and similar",
"dp",
"graphs",
"math",
"number theory",
"trees"
] | 2,600 | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
const int mod = 998244353;
int val[N];
vector<int> g[N];
vector<int> divisor[N];
int subtree_gcd[N], par[N];
int dp[N][1003];
int gcdd[1003][1003];
inline long long ___gcd(long long a, long long b){
if(gcdd[a][b]) return gcdd[a][b];
r... |
1779 | A | Hall of Fame | Thalia is a Legendary Grandmaster in chess. She has $n$ trophies in a line numbered from $1$ to $n$ (from left to right) and a lamp standing next to each of them (the lamps are numbered as the trophies).
A lamp can be directed either to the left or to the right, and it illuminates all trophies in that direction (but n... | What happens when $\texttt{L}$ appears after some $\texttt{R}$ in the string? Suppose that there exists an index $i$ such that $s_i = \texttt{R}$ and $s_{i+1} = \texttt{L}$. Lamp $i$ illuminates trophies $i+1,i+2,\ldots n$ and lamp $i+1$ illuminates $1,2,\ldots i$. We can conclude that all trophies are illuminated if $... | [
"constructive algorithms",
"greedy",
"strings"
] | 800 | null |
1779 | B | MKnez's ConstructiveForces Task | MKnez wants to construct an array $s_1,s_2, \ldots , s_n$ satisfying the following conditions:
- Each element is an integer number different from $0$;
- For each pair of adjacent elements their sum is equal to the sum of the whole array.
More formally, $s_i \neq 0$ must hold for each $1 \leq i \leq n$. Moreover, it m... | There always exists an answer for even $n$. Can you find it? There always exists an answer for odd $n \geq 5$. Can you find it? If $n$ is even, the array $[-1,1,-1,1, \ldots ,-1,1]$ is a solution. The sum of any two adjacent elements is $0$, as well as the sum of the whole array. Suppose that $n$ is odd now. Since $s_{... | [
"constructive algorithms",
"math"
] | 900 | null |
1779 | C | Least Prefix Sum | Baltic, a famous chess player who is also a mathematician, has an array $a_1,a_2, \ldots, a_n$, and he can perform the following operation several (possibly $0$) times:
- Choose some index $i$ ($1 \leq i \leq n$);
- multiply $a_i$ with $-1$, that is, set $a_i := -a_i$.
Baltic's favorite number is $m$, and he wants $a... | Try a greedy approach. What data structure supports inserting an element, finding the maximum and erasing the maximum? That is right, a binary heap, or STL priority_queue. Let $p_i = a_1 + a_2 + \ldots a_i$ and suppose that $p_x < p_m$ for some $x < m$. Let $x$ be the greatest such integer. Performing an operation to a... | [
"data structures",
"greedy"
] | 1,600 | null |
1779 | D | Boris and His Amazing Haircut | Boris thinks that chess is a tedious game. So he left his tournament early and went to a barber shop as his hair was a bit messy.
His current hair can be described by an array $a_1,a_2,\ldots, a_n$, where $a_i$ is the height of the hair standing at position $i$. His desired haircut can be described by an array $b_1,b_... | If $a_i < b_i$ for some $i$, then an answer does not exist since a cut cannot make a hair taller. If you choose to perform a cut on some segment $[l,r]$ with a razor of size $x$, you can "greedily" extend it (decrease $l$ and increase $r$) as long as $x \geq b_i$ for each $i$ in that segment and still obtain a correct ... | [
"constructive algorithms",
"data structures",
"dp",
"dsu",
"greedy",
"sortings"
] | 1,700 | null |
1779 | E | Anya's Simultaneous Exhibition | This is an interactive problem.
Anya has gathered $n$ chess experts numbered from $1$ to $n$ for which the following properties hold:
- For any pair of players one of the players wins every game against the other (and no draws ever occur);
- Transitivity does not necessarily hold — it might happen that $A$ always bea... | A tournament graph is given. Player $i$ is a candidate master if for every other player there exists a path from $i$ to them. Can you find one candidate master? (which helps in finding all of them) Statement: If player $i$ has the highest out-degree, then they are a candidate master. Proof: Let's prove a stronger claim... | [
"constructive algorithms",
"graphs",
"greedy",
"interactive",
"sortings"
] | 2,400 | null |
1779 | F | Xorcerer's Stones | Misha had been banned from playing chess for good since he was accused of cheating with an engine. Therefore, he retired and decided to become a xorcerer.
One day, while taking a walk in a park, Misha came across a rooted tree with nodes numbered from $1$ to $n$. The root of the tree is node $1$.
For each $1\le i\le ... | If XOR of all stones equals $0$, then by performing one spell to the root we obtain an answer. Solve the task for even $n$. If $n$ is even, performing a spell to the root guarantees that all nodes will have the same number of stones, meaning that the total XOR of the tree is $0$, thus performing the same spell again ma... | [
"bitmasks",
"constructive algorithms",
"dp",
"trees"
] | 2,500 | null |
1779 | G | The Game of the Century | The time has finally come, MKnez and Baltic are to host The Game of the Century. For that purpose, they built a village to lodge its participants.
The village has the shape of an equilateral triangle delimited by three roads of length $n$. It is cut into $n^2$ smaller equilateral triangles, of side length $1$, by $3n-... | Consider the sides of the big triangle. If they have the same orientation (clockwise or counter-clockwise), $0$ segments have to be inverted since the village is already biconnected. If the three sides do not all have the same orientation, inverting some segments is necessary. The following picture represents them (or ... | [
"constructive algorithms",
"graphs",
"shortest paths"
] | 3,000 | null |
1779 | H | Olympic Team Building | Iron and Werewolf are participating in a chess Olympiad, so they want to practice team building. They gathered $n$ players, where $n$ is a power of $2$, and they will play sports. Iron and Werewolf are among those $n$ people.
One of the sports is tug of war. For each $1\leq i \leq n$, the $i$-th player has strength $s... | Huge thanks to dario2994 for helping me solve and prepare this problem. Try reversing the process. Start with some multiset ${ x }$ containing only $1$ element. We will try to make $x$ an absolute winner. Extend it by repeatedly adding subsets of equal sizes to it (which have sum less than or equal to the current one).... | [
"brute force",
"meet-in-the-middle"
] | 3,500 | null |
1780 | A | Hayato and School | Today Hayato came home from school with homework.
In the assignment, Hayato was given an array $a$ of length $n$. The task was to find $3$ numbers in this array whose sum is \textbf{odd}. At school, he claimed that there are such $3$ numbers, but Hayato was not sure, so he asked you for help.
Answer if there are such... | Note that there are two variants of which numbers to take to make their amount odd: $3$ odd number; $2$ even and $1$ odd. Let's save all indices of even and odd numbers into two arrays, and check both cases. | [
"constructive algorithms",
"greedy"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<int> odd, even;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
if (x % 2 == 0) {
even.push_back(i);
... |
1780 | B | GCD Partition | While at Kira's house, Josuke saw a piece of paper on the table with a task written on it.
The task sounded as follows. There is an array $a$ of length $n$. On this array, do the following:
- select an integer $k > 1$;
- split the array into $k$ subsegments $^\dagger$;
- calculate the sum in each of $k$ subsegments a... | Let's note that it doesn't make sense for us to divide into more than $k = 2$ subsegments. Let's prove it. Let us somehow split the array $a$ into $m > 2$ subsegments : $b_1, b_2, \ldots, b_m$. Note that $\gcd(b_1, b_2, \ldots, b_m) \le \gcd(b_1 + b_2, b_3, \ldots, b_m)$, since if $b_1$ and $b_2$ were multiples of $\gc... | [
"brute force",
"greedy",
"math",
"number theory"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
long long s = accumulate(a.begin(), ... |
1780 | D | Bit Guessing Game | This is an interactive problem.
Kira has a hidden positive integer $n$, and Hayato needs to guess it.
Initially, Kira gives Hayato the value $\mathrm{cnt}$ — the number of unit bits in the binary notation of $n$. To guess $n$, Hayato can only do operations of one kind: choose an integer $x$ and subtract it from $n$. ... | There are two similar solutions to this problem, we will tell you both. Subtract $1$. What can we say now about the number of units at the beginning of the binary notation of a number? There are exactly $cnt - cnt_w + 1$, where $cnt$ is the number of unit bits after subtracting the unit, and $cnt_w$ is - before subtrac... | [
"binary search",
"bitmasks",
"constructive algorithms",
"interactive"
] | 1,800 | #include <iostream>
using namespace std;
int ask (int x) {
cout << "- " << x << endl;
if (x == -1)
exit(0);
cin >> x;
return x;
}
int main() {
int t;
cin >> t;
while (t--) {
int cnt;
cin >> cnt;
int n = 0;
int was = 0;
while (cnt > 0) {
... |
1780 | E | Josuke and Complete Graph | Josuke received a huge undirected weighted complete$^\dagger$ graph $G$ as a gift from his grandfather. The graph contains $10^{18}$ vertices. The peculiarity of the gift is that the weight of the edge between the different vertices $u$ and $v$ is equal to $\gcd(u, v)^\ddagger$. Josuke decided to experiment and make a ... | Let's fix $g$ and check that the $g$ weight edge exists in $G'$. The first number, which is divided into $g$, starting with $L$ - $\lceil \frac{L}{g} \rceil \cdot g$, and the second - $(\lceil \frac{L}{g} \rceil + 1) \cdot g$, note that their $\gcd$ is $g$, so the edge between these vertices weighs $g$. If the second n... | [
"binary search",
"brute force",
"data structures",
"math",
"number theory"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
for (int test_case = 0; test_case < t; test_case++){
ll L, R;
cin >> L >> R;
ll ans = max(0ll, R / 2 - L + 1);
for (l... |
1780 | F | Three Chairs | One day Kira found $n$ friends from Morioh and decided to gather them around a table to have a peaceful conversation. The height of friend $i$ is equal to $a_i$. It so happened that the height of each of the friends \textbf{is unique}.
Unfortunately, there were only $3$ chairs in Kira's house, and obviously, it will n... | Let's sort the array and process the triples $i, j, k$, assuming that $i < j < k$ and $a_i < a_j < a_k$. Now if $\gcd(a_i, a_k) = 1$, then the number of ways to take the index $j$ is $k - i - 1$. We will consider the answer to the problem for each $k$ from $1$ to $n$, assuming that $a_k$ is the maximum number in the tr... | [
"bitmasks",
"brute force",
"combinatorics",
"data structures",
"dp",
"number theory",
"sortings"
] | 2,300 | #include "bits/stdc++.h"
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
#define sz(v) ((int)(v).size())
#define all(a) (a).begin(), (a).end()
#define rall(a) a.rbegin(), a.rend()
#define F first
#define S second
#define pb push_back
#define ppb pop_back
#define eb empla... |
1780 | G | Delicious Dessert | Today is an important day for chef Tonio — an auditor has arrived in his hometown of Morioh. He has also arrived at Tonio's restaurant and ordered dessert. Tonio has not been prepared for this turn of events.
As you know, dessert is a string of lowercase English letters. Tonio remembered the rule of desserts — a strin... | This problem has several solutions using different suffix structures. We will tell two of them - using suffix array, and using suffix automaton. Let's build suffix array $suf$ and array $lcp$ (largest common prefixes) on the string $s$. Fix some $k > 1$ and consider about all substring $s$ length $k$. Match $1$ to posi... | [
"binary search",
"dsu",
"hashing",
"math",
"number theory",
"string suffix structures"
] | 2,400 | /* Includes */
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
/* Using libraries */
using namespace std;
/* Defines */
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ld long double
#define pb push_back
#define vc vector
#define sz(a) (int)a.size()
#define forn(i, n) for (i... |
1781 | A | Parallel Projection | Vika's house has a room in a shape of a rectangular parallelepiped (also known as a rectangular cuboid). Its floor is a rectangle of size $w \times d$, and the ceiling is right above at the constant height of $h$. Let's introduce a coordinate system on the floor so that its corners are at points $(0, 0)$, $(w, 0)$, $(w... | Note that bending the cable on the wall is not necessary: we can always bend it on the floor and on the ceiling, while keeping the vertical part of the cable straight. Thus, we can just disregard the height of the room, view the problem as two-dimensional, and add $h$ to the answer at the end. In the two-dimensional fo... | [
"geometry",
"math"
] | 800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int w, d, h;
cin >> w >> d >> h;
int a, b;
cin >> a >> b;
int f, g;
cin >> f >> g;
int ans = b + abs(a - f) + g;
ans = min(ans, a + abs(b - g) + f);
ans = min(ans, (d - b) + abs(a - f... |
1781 | B | Going to the Cinema | A company of $n$ people is planning a visit to the cinema. Every person can either go to the cinema or not. That depends on how many other people will go. Specifically, every person $i$ said: "I want to go to the cinema if and only if at least $a_i$ other people will go, \textbf{not counting myself}". That means that p... | Let's fix the number of people going to the cinema $k$ and try to choose a set of this exact size. What happens to people with different $a_i$? If $a_i < k$, person $i$ definitely wants to go. If $a_i > k$, person $i$ definitely does not want to go. If $a_i = k$, there is actually no good outcome for person $i$. If per... | [
"brute force",
"greedy",
"sortings"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
int ans = 0;
for (int k = 0; k <= n; k++) {
if (k == 0 || a[k - 1] < ... |
1781 | C | Equal Frequencies | Let's call a string balanced if all characters that are present in it appear the same number of times. For example, "coder", "appall", and "ttttttt" are balanced, while "wowwow" and "codeforces" are not.
You are given a string $s$ of length $n$ consisting of lowercase English letters. Find a balanced string $t$ of the... | Instead of "finding $t$ that differs from $s$ in as few positions as possible", let's formulate it as "finding $t$ that matches $s$ in as many positions as possible", which is obviously the same. First of all, let's fix $k$, the number of distinct characters string $t$ will have. Since the string must consist of lowerc... | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"sortings",
"strings"
] | 1,600 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
string s;
cin >> s;
vector<vector<int>> at(26);
for (int i = 0; i < n; i++) {
at[(int) (s[i] - 'a')].push_back(i);
}
vector<int> order(26);
iota(order.begin(), ... |
1781 | D | Many Perfect Squares | You are given a set $a_1, a_2, \ldots, a_n$ of distinct positive integers.
We define the squareness of an integer $x$ as the number of perfect squares among the numbers $a_1 + x, a_2 + x, \ldots, a_n + x$.
Find the maximum squareness among all integers $x$ between $0$ and $10^{18}$, inclusive.
Perfect squares are in... | The answer is obviously at least $1$. Can we make it at least $2$? In this case, let's check all possible pairs of indices $i < j$ and try to figure out for what values of $x$ both $a_i + x$ and $a_j + x$ are perfect squares. We can write down two equations: $a_i + x = p^2$ and $a_j + x = q^2$, for some non-negative in... | [
"brute force",
"math",
"number theory"
] | 1,800 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int ans = 1;
auto Test = [&](long long x) {
int cnt = 0;
for (int v : a) {
long long ... |
1781 | E | Rectangle Shrinking | You have a rectangular grid of height $2$ and width $10^9$ consisting of unit cells. There are $n$ rectangles placed on this grid, and the borders of these rectangles pass along cell borders. The $i$-th rectangle covers all cells in rows from $u_i$ to $d_i$ inclusive and columns from $l_i$ to $r_i$ inclusive ($1 \le u_... | It turns out that it is always possible to cover all cells that are covered by the initial rectangles. If the grid had height $1$ instead of $2$, the solution would be fairly simple. Sort the rectangles in non-decreasing order of their left border $l_i$. Maintain a variable $p$ denoting the rightmost covered cell. Then... | [
"binary search",
"brute force",
"data structures",
"greedy",
"implementation",
"two pointers"
] | 2,300 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> r1(n), c1(n), r2(n), c2(n);
for (int i = 0; i < n; i++) {
cin >> r1[i] >> c1[i] >> r2[i] >> c2[i];
assert(1 <= r1[i] ... |
1781 | F | Bracket Insertion | Vika likes playing with bracket sequences. Today she wants to create a new bracket sequence using the following algorithm. Initially, Vika's sequence is an empty string, and then she will repeat the following actions $n$ times:
- Choose a place in the current bracket sequence to insert new brackets uniformly at random... | Instead of looking at a probabilistic process, we can consider all possible ways of inserting brackets. There are $1 \cdot 3 \cdot 5 \cdot \ldots \cdot (2n - 1) = (2n - 1)!!$ ways of choosing places, and $2^n$ ways of choosing "()" or ")(" at every point. Let $r$ be the sum of $p^k \cdot (1-p)^{n-k}$ over all such ways... | [
"combinatorics",
"dp",
"math",
"trees"
] | 2,700 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
T inverse(T a, T m) {
T u = 0, v = 1;
while (a != 0) {
T t = m / a;
m -= t * a; swap(a, m);
u -= t * v; swap(u, v);
}
assert(m == 1);
return u;
}
template <typename T>
class Modular {
public:
using Type = typename decay<decl... |
1781 | G | Diverse Coloring | In this problem, we will be working with rooted binary trees. A tree is called a rooted binary tree if it has a fixed root and every vertex has at most two children.
Let's assign a color — white or blue — to each vertex of the tree, and call this assignment a coloring of the tree. Let's call a coloring diverse if ever... | It turns out that it is always possible to construct a diverse coloring with disbalance $0$ or $1$ (depending on the parity of $n$), except for the case of a tree with $4$ vertices with one vertex of degree $3$ (which is given in the example). Let's traverse the tree from bottom to top. For each subtree, we will try to... | [
"constructive algorithms",
"trees"
] | 3,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> p(n);
for (int i = 1; i < n; i++) {
cin >> p[i];
--p[i];
}
for (int i = 2; i <= n; i++) {
if (i == 4 &&... |
1781 | H2 | Window Signals (hard version) | \textbf{This is the hard version of the problem. In this version, the constraints on $h$ and $w$ are higher.}
A house at the sea has $h$ floors, all of the same height. The side of the house facing the sea has $w$ windows at equal distances from each other on every floor. Thus, the windows are positioned in cells of a... | Let's iterate over the dimensions of the bounding box of the image of windows with lights on, $h' \times w'$ ($1 \le h' \le h; 1 \le w' \le w$), count images with such bounding box, and sum all these values up. An image has a bounding box of size exactly $h' \times w'$ if and only if: it fits inside an $h' \times w'$ r... | [] | 3,500 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
T inverse(T a, T m) {
T u = 0, v = 1;
while (a != 0) {
T t = m / a;
m -= t * a; swap(a, m);
u -= t * v; swap(u, v);
}
assert(m == 1);
return u;
}
template <typename T>
class Modular {
public:
using Type = typename decay<decl... |
1783 | A | Make it Beautiful | An array $a$ is called ugly if it contains \textbf{at least one} element which is equal to the \textbf{sum of all elements before it}. If the array is not ugly, it is beautiful.
For example:
- the array $[6, 3, 9, 6]$ is ugly: the element $9$ is equal to $6 + 3$;
- the array $[5, 5, 7]$ is ugly: the element $5$ (the ... | If we put the maximum in the array on the first position, then for every element, starting from the third one, the sum of elements before it will be greater than it (since that sum is greater than the maximum value in the array). So, the only element that can make our array ugly is the second element. We need to make s... | [
"constructive algorithms",
"math",
"sortings"
] | 800 | t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
if a[0] == a[n - 1]:
print('NO')
else:
print('YES')
print(a[n - 1], end = ' ')
print(*(a[0:n-1])) |
1783 | B | Matrix of Differences | For a square matrix of integers of size $n \times n$, let's define its \textbf{beauty} as follows: for each pair of side-adjacent elements $x$ and $y$, write out the number $|x-y|$, and then find the number of different numbers among them.
For example, for the matrix $\begin{pmatrix} 1 & 3\\ 4 & 2 \end{pmatrix}$ the n... | The first step is to notice that beauty doesn't exceed $n^2-1$, because the minimum difference between two elements is at least $1$, and the maximum difference does not exceed $n^2-1$ (the difference between the maximum element $n^2$ and the minimum element $1$). At first, finding a matrix with maximum beauty seems to ... | [
"constructive algorithms",
"math"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> a(n, vector<int>(n));
int l = 1, r = n * n, t = 0;
forn(i, n) {
forn(j, n) {
if (t) a[i][j] = l++;... |
1783 | C | Yet Another Tournament | You are participating in Yet Another Tournament. There are $n + 1$ participants: you and $n$ other opponents, numbered from $1$ to $n$.
Each two participants will play against each other exactly once. If the opponent $i$ plays against the opponent $j$, he wins if and only if $i > j$.
When the opponent $i$ plays again... | Suppose, at the end, you won $x$ matches, what can be your final place? Look at each opponent $i$ with $i < x$ ($0$-indexed). Since the $i$-th opponent ($0$-indexed) won $i$ games against the other opponents, even if they win against you, they'll gain $i + 1 \le x$ wins in total and can't affect your place (since your ... | [
"binary search",
"greedy",
"sortings"
] | 1,700 | #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, m;
cin >> n >> m;
vector<int> a(n);
for (auto &x : a) cin >> x;
auto b = a;
sort(b.begin(), b.end());
int ans = 0;
for (int i = 0; i < n && ... |
1783 | D | Different Arrays | You are given an array $a$ consisting of $n$ integers.
You \textbf{have to} perform the sequence of $n-2$ operations on this array:
- during the first operation, you either add $a_2$ to $a_1$ and subtract $a_2$ from $a_3$, or add $a_2$ to $a_3$ and subtract $a_2$ from $a_1$;
- during the second operation, you either ... | One of the key observations to this problem is that, after the first $i$ operations, the first $i$ elements of the array are fixed and cannot be changed afterwards. Also, after the $i$-th operation, the elements on positions from $i+3$ to $n$ are the same as they were before applying the operations. This allows us to w... | [
"brute force",
"dp",
"implementation"
] | 2,000 | #include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
const int ZERO = 100000;
int dp[2][ZERO * 2];
void recalc(int x)
{
for(int i = 0; i < ZERO * 2; i++)
dp[1][i] = 0;
... |
1783 | E | Game of the Year | Monocarp and Polycarp are playing a computer game. This game features $n$ bosses for the playing to kill, numbered from $1$ to $n$.
They will fight \textbf{each} boss the following way:
- Monocarp makes $k$ attempts to kill the boss;
- Polycarp makes $k$ attempts to kill the boss;
- Monocarp makes $k$ attempts to kil... | Consider some value of $k$. When is it included in the answer? When Monocarp spends a lower or an equal amount of "blocks" of attempts than Polycarp for killing every boss. Formally, $\lceil \frac{a_i}{k} \rceil \le \lceil \frac{b_i}{k} \rceil$ for all $i$ from $1$ to $n$. Let's reverse this condition. $k$ is not in th... | [
"brute force",
"data structures",
"math",
"number theory"
] | 2,300 | #include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--){
int n;
scanf("%d", &n);
vector<int> a(n), b(n);
forn(i, n) scanf("%d", &a[i]);
forn(i, n) scanf("%d", &b[i]);
vector<int> dx(n + 1);
forn(i, n) if (b[i... |
1783 | F | Double Sort II | You are given two permutations $a$ and $b$, both of size $n$. A permutation of size $n$ is an array of $n$ elements, where each integer from $1$ to $n$ appears exactly once. The elements in each permutation are indexed from $1$ to $n$.
You can perform the following operation any number of times:
- choose an integer $... | The solution to this problem uses cyclic decomposition of permutations. A cyclic decomposition of a permutation is formulated as follows: you treat a permutation as a directed graph on $n$ vertices, where each vertex $i$ has an outgoing arc $i \rightarrow p_i$. This graph consists of several cycles, and the properties ... | [
"dfs and similar",
"flows",
"graph matchings",
"graphs"
] | 2,500 | #include<bits/stdc++.h>
using namespace std;
const int N = 5043;
vector<int> g[N];
int mt[N];
int u[N];
vector<vector<int>> cycle[2];
vector<int> a[2];
int n;
int vs[2];
vector<vector<int>> inter;
bool kuhn(int x)
{
if(u[x]) return false;
u[x] = true;
for(auto y : g[x])
{
if(mt[y] == x) cont... |
1783 | G | Weighed Tree Radius | You are given a tree of $n$ vertices and $n - 1$ edges. The $i$-th vertex has an initial weight $a_i$.
Let the distance $d_v(u)$ from vertex $v$ to vertex $u$ be the number of edges on the path from $v$ to $u$. Note that $d_v(u) = d_u(v)$ and $d_v(v) = 0$.
Let the weighted distance $w_v(u)$ from $v$ to $u$ be $w_v(u)... | Firstly, let's define the weight of path $(u, v)$ as $w_p(u, v) = a_u + d_u(v) + a_v$. On contrary to weighted distances, $w_p(u, v) = w_p(v, u)$ and also $w_p(v, v) = 2 a_v$. Now, let's define the diameter of a tree as path $(u, v)$ with maximum $w_p(u, v)$. It's okay if diameter may be explicit case $(v, v)$. The use... | [
"data structures",
"divide and conquer",
"implementation",
"trees"
] | 2,800 |
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(ostream& out, const pair<A... |
1784 | A | Monsters (easy version) | {This is the easy version of the problem. In this version, you only need to find the answer once. In this version, hacks are \textbf{not allowed}.}
In a computer game, you are fighting against $n$ monsters. Monster number $i$ has $a_i$ health points, all $a_i$ are integers. A monster is alive while it has at least $1$... | First, let's prove that it's always optimal to use a spell of type 2 as your last spell in the game and kill all monsters with it. Indeed, suppose you use a spell of type 2 earlier and it deals $x$ damage to all monsters. Suppose that some monsters are still alive. For any such monster, say they had $y$ health points b... | [
"brute force",
"greedy"
] | 1,000 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
vector<int> b(n);
b[0] = 1;
for (int i = 1; i < n; i++) {
b[i] = ... |
1784 | B | Letter Exchange | A cooperative game is played by $m$ people. In the game, there are $3m$ sheets of paper: $m$ sheets with letter 'w', $m$ sheets with letter 'i', and $m$ sheets with letter 'n'.
Initially, each person is given three sheets (possibly with equal letters).
The goal of the game is to allow each of the $m$ people to spell ... | For each person, there are three essential cases of what they could initially have: Three distinct letters: "win". No need to take part in any exchanges. Two equal letters and another letter, e.g. "wii". An extra 'i' must be exchanged with someone's 'n'. Three equal letters, e.g. "www". One 'w' must be exchanged with s... | [
"constructive algorithms"
] | 1,900 | private fun IntArray.countOf(value: Int) = count { it == value }
private fun solve() {
val s = "win"
fun IntArray.bad() = (0 until 3).singleOrNull { c -> count { it == c } > 1 }
val data = List(readInt()) { readLn().map { s.indexOf(it) }.toIntArray() }
val ans = mutableListOf<String>()
fun exchange... |
1784 | C | Monsters (hard version) | This is the hard version of the problem. In this version, you need to find the answer for every prefix of the monster array.
In a computer game, you are fighting against $n$ monsters. Monster number $i$ has $a_i$ health points, all $a_i$ are integers. A monster is alive while it has at least $1$ health point.
You can... | Continuing on the solution to the easy version: now we have a set of integers $A$, we need to add elements into $A$ one by one and maintain the answer to the problem. Recall that for every $i$, either $b_i = b_{i-1}$ or $b_i = b_{i-1} + 1$. Note that $b_i = b_{i-1}$ can only happen when $b_i = a_i$. Let's call such an ... | [
"data structures",
"greedy"
] | 2,200 | #include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> mn(2 * n - 1);
vector<int> add(2 * n - 1, 0);
vector<int> pos(2 * n - 1);
auto Pull =... |
1784 | D | Wooden Spoon | $2^n$ people, numbered with distinct integers from $1$ to $2^n$, are playing in a single elimination tournament. The bracket of the tournament is a full binary tree of height $n$ with $2^n$ leaves.
When two players meet each other in a match, a player with the \textbf{smaller} number always wins. The winner of the tou... | Let's focus on the sequence of players beating each other $1 = a_0 < a_1 < \ldots < a_n$: $a_0$ is the tournament champion, $a_0$ beats $a_1$ in the last match, $a_1$ beats $a_2$ in the second-to-last match, $\ldots$, $a_{n-1}$ beats $a_n$ in the first match. For a fixed such sequence, how many ways are there to fill t... | [
"combinatorics",
"dp"
] | 2,400 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
T inverse(T a, T m) {
T u = 0, v = 1;
while (a != 0) {
T t = m / a;
m -= t * a; swap(a, m);
u -= t * v; swap(u, v);
}
assert(m == 1);
return u;
}
template <typename T>
class Modular {
public:
using Type = typename decay<decl... |
1784 | E | Infinite Game | Alice and Bob are playing an infinite game consisting of sets. Each set consists of rounds. In each round, one of the players wins. The first player to win two rounds in a set wins this set. Thus, a set always ends with the score of $2:0$ or $2:1$ in favor of one of the players.
Let's call a game scenario a finite str... | For a fixed game scenario $s$, let's build a weighted functional graph on $4$ vertices that correspond to set scores $0:0$, $1:0$, $0:1$, and $1:1$. For each score $x$, traverse the scenario from left to right, changing the score after each letter, and starting a new set whenever necessary. If the set score by the end ... | [
"brute force",
"combinatorics",
"dp",
"games",
"probabilities"
] | 3,100 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
class Modular {
public:
using Type = typename decay<decltype(T::value)>::type;
constexpr Modular() : value() {}
template <typename U>
Modular(const U& x) {
value = normalize(x);
}
template <typename U>
static Type normalize(const... |
1784 | F | Minimums or Medians | Vika has a set of all consecutive positive integers from $1$ to $2n$, inclusive.
Exactly $k$ times Vika will choose and perform one of the following two actions:
- take two smallest integers from her current set and remove them;
- take two median integers from her current set and remove them.
Recall that medians are... | Let's denote removing minimums with L, and removing medians with M. Now a sequence of Vika's actions can be described with a string $s$ of length $k$ consisting of characters L and M. Observe that if we have a substring LMM, we can replace it with MLM, and the set of removed numbers will not change. We can keep applyin... | [] | 3,400 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
T inverse(T a, T m) {
T u = 0, v = 1;
while (a != 0) {
T t = m / a;
m -= t * a; swap(a, m);
u -= t * v; swap(u, v);
}
assert(m == 1);
return u;
}
template <typename T>
class Modular {
public:
using Type = typename decay<decl... |
1786 | A2 | Alternating Deck (hard version) | This is a hard version of the problem. In this version, there are two colors of the cards.
Alice has $n$ cards, each card is either black or white. The cards are stacked in a deck in such a way that the card colors alternate, starting from a white card. Alice deals the cards to herself and to Bob, dealing at once seve... | Note that on the $i$-th step, Alice takes $i$ cards from the deck. It means that after $k$ steps, $\frac{k(k + 1)}{2}$ steps are taken from the deck. Thus, after $O(\sqrt{n})$ steps, the deck is empty. We can simulate the steps one by one by taking care of whose turn it is and what is the color of the top card. Using t... | [
"implementation"
] | 800 | NT = int(input())
for T in range(NT):
n = int(input())
answer = [0, 0, 0, 0]
first_card = 1
for it in range(1, 20000):
who = 0 if it % 4 == 1 or it % 4 == 0 else 1
cnt = it
if n < cnt:
cnt = n
cnt_white = (cnt + first_card % 2) // 2
cnt_black = cnt - cnt_white
answer[who * 2 + 0] += cnt_white
ans... |
1786 | B | Cake Assembly Line | A cake assembly line in a bakery was once again optimized, and now $n$ cakes are made at a time! In the last step, each of the $n$ cakes should be covered with chocolate.
Consider a side view on the conveyor belt, let it be a number line. The $i$-th cake occupies the segment $[a_i - w, a_i + w]$ on this line, each pai... | Obviously, the $i$-th cake should be below the $i$-th dispenser. The leftmost possible position of the cake is when the chocolate would touch the right border. If $c_i$ is the new position of the cake's center, then in this case $c_i + w = b_i + h$. The rightmost possible position is, similarly, when $c_i - w = b_i - h... | [
"brute force",
"sortings"
] | 1,300 | #include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n, w, h;
cin >> n >> w >> h;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> b(n);
for (int i = 0; i < n; i++) {
cin >>... |
1787 | A | Exponential Equation | You are given an integer $n$.
Find any pair of integers $(x,y)$ ($1\leq x,y\leq n$) such that $x^y\cdot y+y^x\cdot x = n$. | For even $n$, a key observation is that $x=1,y=\dfrac{n}{2}$ is always legit. And for odd $n$, notice that $x^yy+y^xx=xy(x^{y-1}+y^{x-1})$. So if $x$ or $y$ is an even number, obviously $x^y y+y^x x$ is an even number. Otherwise if both $x$ and $y$ are all odd numbers , $x^{y-1}$ and $y^{x-1}$ are all odd numbers, so $... | [
"constructive algorithms",
"math"
] | 800 | null |
1787 | B | Number Factorization | Given an integer $n$.
Consider all pairs of integer arrays $a$ and $p$ of the same length such that $n = \prod a_i^{p_i}$ (i.e. $a_1^{p_1}\cdot a_2^{p_2}\cdot\ldots$) ($a_i>1;p_i>0$) and $a_i$ is the product of some (possibly one) \textbf{distinct} prime numbers.
For example, for $n = 28 = 2^2\cdot 7^1 = 4^1 \cdot 7^... | First, $a_i^{p_i}$ is equivalent to the product of $a_i^{1}$ for $p$ times, so it is sufficient to set all $p_i$ to $1$. Decomposite $n$ to some prime factors, greedily choose the most number of distinct prime numbers, the product is the maximum. | [
"greedy",
"math",
"number theory"
] | 1,100 | #include <bits/stdc++.h>
using namespace std;
#define mp make_pair
pair<int, int> s[110];
int d[110];
void get() {
int n, l = 0, i, c;
cin >> n;
for (i = 2; i * i <= n; i++) {
if (n % i == 0) {
c = 0;
while (n % i == 0) c++, n /= i;
s[++l] = make_pair(c, i);
}
}
if (n != 1) s[++l] = make_pair(1, n);
... |
1787 | C | Remove the Bracket | RSJ has a sequence $a$ of $n$ integers $a_1,a_2, \ldots, a_n$ and an integer $s$. For each of $a_2,a_3, \ldots, a_{n-1}$, he chose a pair of \textbf{non-negative integers} $x_i$ and $y_i$ such that $x_i+y_i=a_i$ and $(x_i-s) \cdot (y_i-s) \geq 0$.
Now he is interested in the value $$F = a_1 \cdot x_2+y_2 \cdot x_3+y_3... | Idea & Solution: rsj This is the reason why the problem was named as Remove the Bracket. $\begin{aligned} \text{Product} &= a_1 \cdot a_2 \cdot a_3 \cdot \ldots \cdot a_n = \\ &= a_1 \cdot (x_2+y_2) \cdot (x_3+y_3) \cdot \ldots \cdot (x_{n-1}+y_{n-1}) \cdot a_n = \\ &\overset{\text{?}}{=} a_1 \cdot x_2+y_2 \cdot x_3+y_... | [
"dp",
"greedy",
"math"
] | 1,600 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.