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
⌀ |
|---|---|---|---|---|---|---|---|
1822
|
D
|
Super-Permutation
|
A permutation is a sequence $n$ integers, where each integer from $1$ to $n$ appears exactly once. For example, $[1]$, $[3,5,2,1,4]$, $[1,3,2]$ are permutations, while $[2,3,2]$, $[4,3,1]$, $[0]$ are not.
Given a permutation $a$, we construct an array $b$, where $b_i = (a_1 + a_2 +~\dots~+ a_i) \bmod n$.
A permutation of numbers $[a_1, a_2, \dots, a_n]$ is called a super-permutation if $[b_1 + 1, b_2 + 1, \dots, b_n + 1]$ is also a permutation of length $n$.
Grisha became interested whether a super-permutation of length $n$ exists. Help him solve this non-trivial problem. Output any super-permutation of length $n$, if it exists. Otherwise, output $-1$.
|
Let $k$ be the position of the number $n$ in the permutation $a$, that is, $a_k = n$, then if $k > 1$, then $b_k = (b_{k-1} + a_k) \mod n = b_{k-1}$ therefore, $b$ is not a permutation, so $k = 1$. Now note that if $n > 1$ is odd, then $b_n = (a_1~+~a_2~+~\dots~+~a_n) \mod n = (1 +2 +~\dots~+ n) \mod n= n \cdot\frac{(n + 1)}{2} \mod n = 0 = b_1$. So there is no answer. If $n$ is even, then one possible example would be $a = [n,~1,~n-2,~3,~n-4,~5,~\dots,~n - 1,~2]$, since then $b = [0,~1,~n-1,~2,~n-2,~3,~n-3,~\dots,~\frac{n}{2}]$.
|
[
"constructive algorithms",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int q;
cin >> q;
while (q--) {
int n;
cin >> n;
if (n == 1) {
cout << "1\n";
continue;
}
if (n % 2) {
cout << "-1\n";
} else {
for (int i = 0; i < n; ++i) {
if (i % 2) {
cout << i << " ";
} else {
cout << n - i << " ";
}
}
cout << "\n";
}
}
return 0;
}
|
1822
|
E
|
Making Anti-Palindromes
|
You are given a string $s$, consisting of lowercase English letters. In one operation, you are allowed to swap any two characters of the string $s$.
A string $s$ of length $n$ is called an anti-palindrome, if $s[i] \ne s[n - i + 1]$ for every $i$ ($1 \le i \le n$). For example, the strings "codeforces", "string" are anti-palindromes, but the strings "abacaba", "abc", "test" are not.
Determine the minimum number of operations required to make the string $s$ an anti-palindrome, or output $-1$, if this is not possible.
|
If $n$ is odd, then there is no solution, since $s[(n + 1) / 2] = s[(n + 1) - (n + 1) / 2]$. If $n$ is even, then all symbols are split into pairs $s[i], s[n + 1 - i]$. Let's denote the number of occurrences of the symbol $c$ as $cnt[c]$. Note that if $cnt[c] > n / 2$ for some $c$, then after applying the operations there will be a pair where both characters are equal to $c$, then it is impossible to make the string $s$ anti-palindrome. Otherwise, we will calculate $k$ - the number of pairs, where $s[i] = s[n + 1 - i]$, we will also find $m$ - the maximum number of pairs, where $s[i] = s[n + 1 - i] = c$, for all characters $c$. Let $x$ be a symbol for which the number of such pairs is equal to $m$. Note that $ans\ge m$, because in one operation the number of pairs where $s[i] = s[n + 1 - i] = x$ cannot decrease by more than $1$. Also note that $ans \ge \lceil \frac{k}{2} \rceil$, because for each operation we reduce the number of pairs where $s[i] = s[n + 1 - i]$ by no more than $2$. It turns out that $ans = max(m, \lceil \frac{k}{2} \rceil)$, to show this, you can act greedily - until $k > 0$: If $k=m$, then we find a pair $s[i] = s[n + 1 - i] = x$, since $cnt[x] \le n / 2$, then there is a pair where $s[j] \ne x$ and $s[n + 1 - j] \ne x$. Then swap $s[i]$ and $s[j]$. Otherwise, find the pair $s[i] = s[n + 1 - i] = x$, and the pair $s[j] = s[n + 1 - j] \ne x$. Then swap $s[i]$ and $s[j]$. It is not difficult to check that in both cases, $max(m, \lceil k/2\rceil)$ will decrease by exactly $1$, which means $ans$ is achieved with this algorithm.
|
[
"greedy",
"math",
"strings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
void solve(int n, string & s) {
if (n % 2 == 1) {
cout << -1 << endl;
return;
}
vector<int> cnt(26);
for (int i = 0; i < n; ++i) {
++cnt[s[i] - 'a'];
}
for (int i = 0; i < 26; ++i) {
if (cnt[i] * 2 > n) {
cout << -1 << endl;
return;
}
}
int pairs = 0;
vector<int> cnt_pairs(26);
for (int i = 0; i * 2 < n; ++i) {
if (s[i] == s[n - i - 1]) {
++pairs;
++cnt_pairs[s[i] - 'a'];
}
}
for (int i = 0; i < 26; ++i) {
if (cnt_pairs[i] * 2 > pairs) {
cout << cnt_pairs[i] << endl;
return;
}
}
cout << (pairs + 1) / 2 << endl;
}
int32_t main() {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
int n;
cin >> n;
string s;
cin >> s;
solve(n, s);
}
}
|
1822
|
F
|
Gardening Friends
|
Two friends, Alisa and Yuki, planted a tree with $n$ vertices in their garden. A tree is an undirected graph without cycles, loops, or multiple edges. Each edge in this tree has a length of $k$. Initially, vertex $1$ is the root of the tree.
Alisa and Yuki are growing the tree not just for fun, they want to sell it. The cost of the tree is defined as the maximum distance from the root to a vertex among all vertices of the tree. The distance between two vertices $u$ and $v$ is the sum of the lengths of the edges on the path from $u$ to $v$.
The girls took a course in gardening, so they know how to modify the tree. Alisa and Yuki can spend $c$ coins to shift the root of the tree to one of the \textbf{neighbors of the current root}. This operation can be performed any number of times (possibly zero). Note that the structure of the tree is left unchanged; the only change is which vertex is the root.
The friends want to sell the tree with the maximum profit. The profit is defined as the difference between the cost of the tree and the total cost of operations. \textbf{The profit is cost of the tree minus the total cost of operations}.
Help the girls and find the maximum profit they can get by applying operations to the tree any number of times (possibly zero).
|
Let's first calculate its depth for each vertex. Let for a vertex $v$ its depth is $depth[v]$. All the values of $depth[v]$ can be calculated by a single depth-first search. We introduce several auxiliary quantities. Let for vertex $v$ the values $down_1[v], down_2[v]$ are the two largest distances to the leaves in the subtree of vertex $v$ of the source tree. We will also introduce the value $up[v]$ - the maximum distance to the leaf outside the subtree of the vertex $v$. The values of $down_1[v]$ and $down_2[v]$ are easily recalculated by walking up the tree from the bottom and maintaining two maximum distances to the leaves. Let $p$ be the ancestor of the vertex $v$. Then to recalculate $up[v]$, you need to go up to $p$ and find the maximum distance to a leaf outside the subtree $v$. If the leaf farthest from $p$ is in the subtree $v$, then you will need to take $down_2[p]$, otherwise $down_1[p]$. For $v$, we define the maximum distance to the leaf, as $dist[v] = max(down_1[v], up[v])$. Now let's calculate for each vertex $v$ the cost of the tree if $v$ becomes the root. It is not profitable for us to take extra steps, so the cost of operations will be equal to $c\cdot depth[v]$. Then the cost of the tree will be equal to the value of $k\cdot dist[v] - c\cdot depth[v]$. It remains to go through all the vertices, take the maximum of the tree values and get an answer. It is easy to see that such a solution works for $O(n)$.
|
[
"brute force",
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,700
|
#include<bits/stdc++.h>
using namespace std;
struct Value {
int64_t value = 0;
int vertex = 0;
};
vector<vector<int>> nei;
vector<vector<int>> depth_vertex;
vector<int> depth;
vector<int> parent;
void dfs(int v, int p = -1, int cnt = 0) {
depth_vertex[cnt].push_back(v);
depth[v] = cnt;
parent[v] = p;
for (int u : nei[v]) {
if (u == p) continue;
dfs(u, v, cnt + 1);
}
}
void solve() {
int n, root = 1;
int64_t k_wei, cost;
cin >> n >> k_wei >> cost;
nei.clear();
nei.resize(n + 1);
depth_vertex.clear();
depth_vertex.resize(n + 1);
depth.clear();
depth.resize(n + 1);
parent.clear();
parent.resize(n + 1);
for (int _ = 0; _ < n - 1; ++_) {
int u, v;
cin >> u >> v;
nei[u].push_back(v);
nei[v].push_back(u);
}
dfs(root);
vector<pair<Value, Value>> down(n + 1);
for (int tin = n; tin >= 0; --tin) {
for (int v : depth_vertex[tin]) {
for (int u : nei[v]) {
if (u == parent[v]) continue;
if (down[u].first.value + 1 > down[v].first.value) {
down[v].first.value = down[u].first.value + 1;
down[v].first.vertex = u;
}
}
for (int u : nei[v]) {
if (u == parent[v] || u == down[v].first.vertex) continue;
if (down[u].first.value + 1 > down[v].second.value) {
down[v].second.value = down[u].first.value + 1;
}
}
}
}
vector<int64_t> up(n + 1, 0);
for (int tin = 1; tin <= n; ++tin) {
for (int v : depth_vertex[tin]) {
int p = parent[v];
up[v] = up[p] + 1;
if (down[p].first.vertex == v) {
up[v] = max(up[v], down[p].second.value + 1);
} else {
up[v] = max(up[v], down[p].first.value + 1);
}
}
}
int64_t ans = -1'000'000'000'000'000'002;
for (int v = 1; v <= n; ++v) {
ans = max(ans, k_wei * max(up[v], down[v].first.value) - cost * int64_t(depth[v]));
}
cout << ans << endl;
}
int main()
{
int t;
cin >> t;
for (int _ = 1; _ <= t; ++_) {
solve();
}
return 0;
}
|
1822
|
G1
|
Magic Triples (Easy Version)
|
\textbf{This is the easy version of the problem. The only difference is that in this version, $a_i \le 10^6$.}
For a given sequence of $n$ integers $a$, a triple $(i, j, k)$ is called magic if:
- $1 \le i, j, k \le n$.
- $i$, $j$, $k$ are pairwise distinct.
- there exists a positive integer $b$ such that $a_i \cdot b = a_j$ and $a_j \cdot b = a_k$.
Kolya received a sequence of integers $a$ as a gift and now wants to count the number of magic triples for it. Help him with this task!
Note that there are no constraints on the order of integers $i$, $j$ and $k$.
|
Let $M = \max {a_i}$, obviously $M\le 10^6$, $cnt[x]$ - the number of occurrences of the number $x$ in the array $a$. Separately, let's count the number of magic triples for $b=1$. The total number of such triples will be $\sum_{i=1}^{n}{(cnt[a_i] - 1) \cdot (cnt[a_i] - 2)}$. Next, we will count $b\ge 2$. Note that $a_i \cdot b \cdot b = a_k$, so $b \le \sqrt{a_k /a_i} \le \sqrt{M}$. Thus, after sorting through all possible $i$ from $1$ to $n$, as well as all $b\le\sqrt{M}$ and adding $cnt[a_i\cdot b] \cdot cnt[a_i\cdot b\cdot b]$ to the answer, we get a solution for $O(\sqrt{M}\cdot n)$.
|
[
"brute force",
"data structures",
"math",
"number theory"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MAX_VAL = 1e6;
int cnt[MAX_VAL + 1];
int32_t main() {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
++cnt[a[i]];
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += (cnt[a[i]] - 1) * (cnt[a[i]] - 2);
for (int b = 2; a[i] * b * b <= MAX_VAL; ++b) {
ans += cnt[a[i] * b] * cnt[a[i] * b * b];
}
}
cout << ans << "\n";
for (int i = 0; i < n; ++i) {
--cnt[a[i]];
}
}
return 0;
}
|
1822
|
G2
|
Magic Triples (Hard Version)
|
\textbf{This is the hard version of the problem. The only difference is that in this version, $a_i \le 10^9$.}
For a given sequence of $n$ integers $a$, a triple $(i, j, k)$ is called magic if:
- $1 \le i, j, k \le n$.
- $i$, $j$, $k$ are pairwise distinct.
- there exists a positive integer $b$ such that $a_i \cdot b = a_j$ and $a_j \cdot b = a_k$.
Kolya received a sequence of integers $a$ as a gift and now wants to count the number of magic triples for it. Help him with this task!
Note that there are no constraints on the order of integers $i$, $j$ and $k$.
|
Let $M = \max {a_i}$, obviously $M \le 10^9$, $cnt[x]$ - the number of occurrences of the number $x$ in the array $a$. Separately, let's count the number of magic triples for $b=1$. The total number of such triples will be $\sum_{i=1}^{n}{(cnt[a_i] - 1) \cdot (cnt[a_i] - 2)}$. Next, we will count $b \ge 2$. We will iterate over $a_j$, if $a_j \ge M ^ \frac{2}{3}$, then $a_j \cdot b = a_k \le M$, then $b\le M^\frac{1}{3}$. Otherwise, $a_j \le M^\frac{2}{3}$, since $a_i \cdot b = a_j$, then $b$ is a divisor of $a_j$, which means it is enough to iterate as $b$ the divisors of the number $a_j$, the divisors of such the numbers can be found for $O(M^\frac{1}{3})$, which means the total complexity will be $O(n\cdot M^\frac{1}{3})$ if you use the hash table $cnt[x]$, or $O(n\cdot M^\frac{1}{3}\cdot\log{n})$ if you use std::map.
|
[
"brute force",
"data structures",
"math",
"number theory"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int K = 1e6;
const int MAX_VAL = 1e9;
int32_t main() {
int t;
scanf("%d", &t);
for (int _ = 0; _ < t; ++_) {
int n;
scanf("%d", &n);
vector<int> a(n);
map<int, int> cnt;
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
++cnt[a[i]];
}
ll ans = 0;
for (int i = 0; i < n; ++i) {
ans += (ll)(cnt[a[i]] - 1) * (cnt[a[i]] - 2);
}
for (auto el : cnt) {
int num = el.first;
int val = el.second;
if (num > K) {
for (int b = 2; b * num <= MAX_VAL; ++b) {
if (num % b == 0 && cnt.find(num / b) != cnt.end() && cnt.find(num * b) != cnt.end()) {
ans += (ll)(cnt[num / b]) * (cnt[num * b]) * val;
}
}
} else {
for (int b = 2; b * b <= num; ++b) {
if (num % b == 0) {
if ((ll)num * b <= (ll)MAX_VAL && cnt.find(num / b) != cnt.end() && cnt.find(num * b) != cnt.end()) {
ans += (ll)(cnt[num / b]) * (cnt[num * b]) * val;
}
if (b * b != num) {
if ((ll)num * num / b <= (ll)MAX_VAL && cnt.find(b) != cnt.end() && cnt.find(num / b * num) != cnt.end()) {
ans += (ll)(cnt[b]) * (cnt[num / b * num]) * val;
}
}
}
}
if (num > 1 && (ll)num * num <= (ll)MAX_VAL && cnt.find(1) != cnt.end() && cnt.find(num * num) != cnt.end()) {
ans += (ll)(cnt[1]) * (cnt[num * num]) * val;
}
}
}
printf("%lld\n", ans);
}
return 0;
}
|
1823
|
A
|
A-characteristic
|
Consider an array $a_1, a_2, \dots, a_n$ consisting of numbers $1$ and $-1$. Define $A$-characteristic of this array as a number of pairs of indices $1 \le i < j \le n$, such that $a_i \cdot a_j = 1$.
Find any array $a$ with given length $n$ with $A$-characteristic equal to the given value $k$.
|
Note that the $A$-characteristic depends only on the number of $1$-s. Let the number of $1$-s be equal to $x$, then the number of $-1$-s is equal to $n - x$, and the $A$-characteristic is equal to $f(x) = \frac{(x - 1) \cdot x}{ 2} + \frac{(n - x - 1) \cdot (n - x)}{2}$. Let's iterate over all $x$ from $0$ to $n$, and check if there is such $x$ that $f(x) = k$. Then print $x$ numbers $1$ and $n - x$ numbers $-1$.
|
[
"combinatorics",
"constructive algorithms",
"math"
] | 800
|
for tt in range(int(input())):
n, k = map(int, input().split())
x = -1
for i in range(0, n + 1):
if i * (i - 1) / 2 + (n - i) * (n - i - 1) / 2 == k:
x = i
if x == -1:
print("NO")
else:
print("YES")
for i in range(0, n):
if i < x:
print("1 ", end = '')
else:
print("-1 ", end = '')
print("")
|
1823
|
B
|
Sort with Step
|
Let's define a permutation of length $n$ as an array $p$ of length $n$, which contains every number from $1$ to $n$ exactly once.
You are given a permutation $p_1, p_2, \dots, p_n$ and a number $k$. You need to sort this permutation in the ascending order. In order to do it, you can repeat the following operation any number of times (possibly, zero):
- pick two elements of the permutation $p_i$ and $p_j$ such that $|i - j| = k$, and swap them.
Unfortunately, some permutations can't be sorted with some fixed numbers $k$. For example, it's impossible to sort $[2, 4, 3, 1]$ with $k = 2$.
That's why, before starting the sorting, you can make at most one preliminary exchange:
- choose any pair $p_i$ and $p_j$ and swap them.
Your task is to:
- check whether is it possible to sort the permutation \textbf{without} any preliminary exchanges,
- if it's not, check, whether is it possible to sort the permutation using exactly \textbf{one} preliminary exchange.
For example, if $k = 2$ and permutation is $[2, 4, 3, 1]$, then you can make a preliminary exchange of $p_1$ and $p_4$, which will produce permutation $[1, 4, 3, 2]$, which is possible to sort with given $k$.
|
Let's fix a number $0 \le x < k$ and consider all indices $i$ such that $i \bmod k = x$. Note that numbers in these positions can be reordered however we want, but they can't leave this set of positions, since $i \bmod k$ stay the same. Moreover, in the sorted permutation these positions must contain numbers $j$ such that $(j - 1) \bmod k = x$. In total, itm means that the permutation can be sorted if $(p[i] - 1) \bmod k = i \bmod k$ holds for all $i$. By preliminary exchange, we can swap two elements from different sets. Therefore, if the last equality fails for exactly two elements, they can be swapped, making sorting possible. Otherwise, the answer is $-1$.
|
[
"brute force",
"math",
"sortings"
] | 900
|
for tt in range(int(input())):
n, k = map(int, input().split())
p = list(map(int, input().split()))
for i in range(0, n):
p[i] -= 1
bad = 0
for i in range(0, n):
if p[i] % k != i % k:
bad += 1
if bad == 0:
print(0)
elif bad == 2:
print(1)
else:
print(-1)
|
1823
|
C
|
Strongly Composite
|
A prime number is an integer greater than $1$, which has exactly two divisors. For example, $7$ is a prime, since it has two divisors $\{1, 7\}$. A composite number is an integer greater than $1$, which has more than two different divisors.
Note that the integer $1$ is neither prime nor composite.
Let's look at some composite number $v$. It has several divisors: some divisors are prime, others are composite themselves. If the number of prime divisors of $v$ is \textbf{less or equal} to the number of composite divisors, let's name $v$ as strongly composite.
For example, number $12$ has $6$ divisors: $\{1, 2, 3, 4, 6, 12\}$, two divisors $2$ and $3$ are prime, while three divisors $4$, $6$ and $12$ are composite. So, $12$ is strongly composite. Other examples of strongly composite numbers are $4$, $8$, $9$, $16$ and so on.
On the other side, divisors of $15$ are $\{1, 3, 5, 15\}$: $3$ and $5$ are prime, $15$ is composite. So, $15$ is not a strongly composite. Other examples are: $2$, $3$, $5$, $6$, $7$, $10$ and so on.
You are given $n$ integers $a_1, a_2, \dots, a_n$ ($a_i > 1$). You have to build an array $b_1, b_2, \dots, b_k$ such that following conditions are satisfied:
- Product of all elements of array $a$ is equal to product of all elements of array $b$: $a_1 \cdot a_2 \cdot \ldots \cdot a_n = b_1 \cdot b_2 \cdot \ldots \cdot b_k$;
- All elements of array $b$ are integers greater than $1$ and strongly composite;
- The size $k$ of array $b$ is the maximum possible.
Find the size $k$ of array $b$, or report, that there is no array $b$ satisfying the conditions.
|
Let's understand criteria for a number $x$ being strongly composite. Let's factorize the number $x = {p_1}^{d_1} \cdot {p_2}^{d_2} \cdot \dots \cdot {p_m}^{d_m}$. The number of all divisors of $x$ is $D = \prod\limits_{i = 1}^{m} (d_i + 1)$. Since the number of prime divisors is $m$, then the number of composite divisors of $x$ is $D - m - 1$. Then a number $x$ is strongly composite if $m \le D - m - 1$ or $2 \cdot m + 1 \le D$. Since $m$ is the number of $d_i + 1 \ge 2$, then $D \ge 2^m$. Consider a weakened condition for a strongly composite number: $2 \cdot m + 1 \le 2^m$. If $m = 1$, then the condition is satisfied only if $d_1 \ge 2$. If $m = 2$, then the condition is satisfied only if $\max{(d_1, d_2)} \ge 2$. If $m \ge 3$, then the condition is always satisfied. In summary, a number is not strongly composite if it is either a prime or the product of two distinct primes. Now let's solve the problem. Let's split all numbers into primes. Assume we have pairs $(p_i, c_i)$, where $p_i$ is a prime number and $c_i$ is the number of its occurrences. We can take either two same prime numbers or three of any prime numbers. The optimal strategy is to create the maximum number of pairs of same prime numbers $\sum\limits_i{\left\lfloor \frac{c_i}{2} \right\rfloor}$, and when there will be only $r = \sum\limits_i{(c_i \bmod 2)}$ different prime numbers remaining. We can merge these remaining primes in triples to get extra $\left\lfloor \frac{r}{3} \right\rfloor$ strongly composite numbers. If, after merging triples, we have some primes left, we can add them to any already strongly composite number, and it won't change its total number. There were initially more complex version of this task. Can you solve it? You are given $n$ integers $a_1, a_2, \dots, a_n$ ($a_i > 1$). You can perform the following operation with array $a$ any number of times: choose two indices $i$ and $j$ ($i < j$); choose two indices $i$ and $j$ ($i < j$); erase elements $a_i$ and $a_j$ from $a$; erase elements $a_i$ and $a_j$ from $a$; insert element $a_i \cdot a_j$ in $a$. insert element $a_i \cdot a_j$ in $a$. After performing one such operation, the length of $a$ decreases by one. Let's say that array $a$ is good, if it contains only strongly composite numbers. What is the minimum number of operation you need to perform to make array $a$ good?
|
[
"greedy",
"math",
"number theory"
] | 1,300
|
def is_prime(x):
i = 2
while i * i <= x:
if x % i == 0:
return False
i += 1
return True
def is_strongly_composite(x):
m = []
i = 2
while i * i <= x:
while x % i == 0:
x = x // i
m.append(i)
i += 1
if not x == 1:
m.append(i)
return (len(m) >= 3 or (len(m) == 2 and m[0] == m[1]))
for tt in range(int(input())):
n = int(input())
lst = list(map(int, input().split()))
a = {}
for x in lst:
i = 2
while i * i <= x:
while x % i == 0:
x = x // i
if i in a:
a[i] += 1
else:
a[i] = 1
i += 1
if x != 1:
if x in a:
a[x] += 1
else:
a[x] = 1
res, rem = 0, 0
for num in a:
cnt = a[num]
res += cnt // 2
rem += cnt % 2
res += rem // 3
print(res)
|
1823
|
D
|
Unique Palindromes
|
A palindrome is a string that reads the same backwards as forwards. For example, the string abcba is palindrome, while the string abca is not.
Let $p(t)$ be the number of unique palindromic substrings of string $t$, i. e. the number of substrings $t[l \dots r]$ that are palindromes themselves. Even if some substring occurs in $t$ several times, it's counted exactly once. (The whole string $t$ is also counted as a substring of $t$).
For example, string $t$ $=$ abcbbcabcb has $p(t) = 6$ unique palindromic substrings: a, b, c, bb, bcb and cbbc.
Now, let's define $p(s, m) = p(t)$ where $t = s[1 \dots m]$. In other words, $p(s, m)$ is the number of palindromic substrings in the prefix of $s$ of length $m$. For example, $p($abcbbcabcb$, 5)$ $=$ $p($abcbb$) = 5$.
You are given an integer $n$ and $k$ "conditions" ($k \le 20$). Let's say that string $s$, consisting of $n$ lowercase Latin letters, is \textbf{good} if all $k$ conditions are satisfied \textbf{at the same time}. A condition is a pair $(x_i, c_i)$ and have the following meaning:
- $p(s, x_i) = c_i$, i. e. a prefix of $s$ of length $x_i$ contains exactly $c_i$ unique palindromic substrings.
Find a good string $s$ or report that such $s$ doesn't exist.Look in Notes if you need further clarifications.
|
Let us estimate the possible number of unique palindromes $P$: for $n = 1$: $P = 1$; for $n = 2$: $P = 2$ (in both cases: if symbols are equal and if not); for $n \ge 3$: $3 \le P \le n$. Any combination of the first three characters gives $P = 3$. If you add a character to the string, $P$ will increase by either $0$ or $1$. This can be proven by contradiction. Assume $P_{new} - P_{old} \ge 2$. Choose $2$ of any new palindromes. The shorter one is both a suffix and a prefix of the larger one (since both are palindromes), but we've added all the palindromes. So the smaller one was added earlier. An example of a string with $P = 3$: abcabc.... An example of a string with $P = n$: aaaaaa.... An example of a string with $P = 3$: abcabc.... An example of a string with $P = n$: aaaaaa.... By choosing the prefix of appropriate length that consists of a characters, we can achieve all the values of $3 \le P \le n$. Print $k - 3$ characters a and then characters abc until the end of the string. Let solve the initial task for $k > 1$ conditions. Firstly, we build the answer for the first condition. After that, assume we have answer for first $t$ conditions. If $c_{t + 1} - c_{t} > x_{t + 1} - x_{t}$, then we can't build an answer by lemma. Otherwise, we can do the following: take a symbol, that wasn't used and append it $c_{t + 1} - c_{t}$ times to answer; then append symbols ...abcabca.... The final string will look as following, where | symbol shows conditions boundaries: aaaaaaaaabcabcab|dddddcabcabca|eeebcab Note that, in order not to create unnecessary palindromes, if we finished the previous abcabc... block with some character (for example, a), the next abcabc... block should start with the next character (b). There were initially simpler version of this problem with $k = 1$, but it coincided with other problem. Also, how does checker in this problem works?
|
[
"constructive algorithms",
"math",
"strings"
] | 1,900
|
for tt in range(int(input())):
n, k = map(int, input().split())
x = list(map(int, input().split()))
c = list(map(int, input().split()))
if c[0] < 3 or c[0] > x[0]:
print("NO")
continue
s = ""
cur = 'a'
for i in range(0, c[0] - 3):
s += "a"
for i in range(c[0] - 3, x[0]):
s += cur
cur = chr(ord(cur) + 1)
if cur == 'd':
cur = 'a'
good = True
for j in range(1, k):
dx = x[j] - x[j - 1]
dc = c[j] - c[j - 1]
if dc > dx:
good = False
break
for i in range(0, dc):
s += chr(ord('c') + j)
for i in range(dc, dx):
s += cur
cur = chr(ord(cur) + 1)
if cur == 'd':
cur = 'a'
if good:
print("YES")
print(s)
else:
print("NO")
|
1823
|
E
|
Removing Graph
|
Alice and Bob are playing a game on a graph. They have an undirected graph without self-loops and multiple edges. All vertices of the graph have \textbf{degree equal to $2$}. The graph may consist of several components. Note that if such graph has $n$ vertices, it will have exactly $n$ edges.
Alice and Bob take turn. Alice goes first. In each turn, the player can choose $k$ ($l \le k \le r$; $l < r$) vertices that form \textbf{a connected subgraph} and erase these vertices from the graph, including all incident edges.
The player who can't make a step loses.
For example, suppose they are playing on the given graph with given $l = 2$ and $r = 3$:
A valid vertex set for Alice to choose at the first move is one of the following:
- $\{1, 2\}$
- $\{1, 3\}$
- $\{2, 3\}$
- $\{4, 5\}$
- $\{4, 6\}$
- $\{5, 6\}$
- $\{1, 2, 3\}$
- $\{4, 5, 6\}$
Suppose, Alice chooses subgraph $\{4, 6\}$.Then a valid vertex set for Bob to choose at the first move is one of the following:
- $\{1, 2\}$
- $\{1, 3\}$
- $\{2, 3\}$
- $\{1, 2, 3\}$
Suppose, Bob chooses subgraph $\{1, 2, 3\}$.Alice can't make a move, so she loses.
You are given a graph of size $n$ and integers $l$ and $r$. Who will win if both Alice and Bob play optimally.
|
The solution requires knowledge of the Sprague-Grundy theory. Recall that $a \oplus b$ means the bitwise exclusive or operation, and $\operatorname{mex}(S)$ is equal to the minimum non-negative number that is not in the set $S$. The fact that $l \neq r$ is important. The given graph is a set of cycles, and the game runs independently in each cycle. If we can calculate nim-value for a cycle of each size, then nim-value of the whole game is equal to XOR of these values. To calculate nim-value for the cycle of length $x$ ($cycle[x]$), we need to take $\operatorname{mex}$ of nim-values from all transitions. But since all transitions transform a cycle to a chain, then we will calculate nim-values for chains as well, or $cycle[x] = \operatorname{mex}(chain[x - r], chain[x - r + 1], \dots, chain[x - l])$. To calculate nim-value for the chain $chain[x]$, we need to consider all possible transitions. We can either cut off from the end of the chain, or from the middle of the chain. In either case, we end up with two smaller chains (maybe one of them is empty), which are themselves independent games, so $chain[x] = \operatorname{mex}{\{chain[a] \oplus chain[b] \mid \forall a, b \ge 0 : x - r \le a + b \le x - l\}}$. Implementing this directly requires $O(n^3)$ time. A more accurate implementation with recalculations requires $O(n^2)$ time. For a complete solution, something needs to be noticed in nim-values. Consider an example. Let $l = 4$, $r = 14$. index012345678910111213141516171819$chain$00001111222233334444$cycle$00001111222233334400$\uparrow$$l + r$ $chain[x]$ on $[0, l - 1]$ is obviously equal to $0$; $chain[x] = \left\lfloor \frac{x}{l} \right\rfloor$ on segment $[0, r + l - 1]$ (proof is below); $chain[x] > 0$ for all $x \ge l$: since $l < r$ you can always split the chain $x$ in two equal chains $a$. This transition adds nim-value $chain[a] \oplus chain[a] = 0$ into $\operatorname{mex}$, that's why $chain[x] = \operatorname{mex}{\{\dots\}} > 0$. $cycle[x]$ is equal to $chain[x]$ up to $r + l - 1$: it's because $cycle[x]$ is equal to $\operatorname{mex}{\{chain[0], chain[1], \dots, chain[x - l]\}}$; $cycle[x] = 0$ for $x \ge l + r$, it's because $chain[x] > 0$ for $x \ge l$. So, if $x \le r + l - 1$, then $cycle[x] = \left\lfloor \frac{x}{l} \right\rfloor$, otherwise $cycle[x] = 0$. We have to calculate the sizes of all cycles in the graph and calculate XOR of those values. If it is zero, the winner is Bob, otherwise, winner is Alice. Let's prove that $chain[x] = \left\lfloor \frac{x}{l} \right\rfloor$ on segment $[0, r + l - 1]$: $chain[x] \ge \left\lfloor \frac{x}{l} \right\rfloor$: there are transitions to pairs of chains $(a, b)$ where $a = 0$ and $b$ is any number from $[0, x - l]$. Their nim-value is equal to $chain[0] \oplus chain[b]$ $=$ $chain[b]$, so $chain[x] \ge \operatorname{mex}{\{chain[b] \mid 0 \le b \le x - l\}} = \left\lfloor \frac{x}{l} \right\rfloor$. $chain[x]$ is exactly equal to $\left\lfloor \frac{x}{l} \right\rfloor$: we can prove that for any pair of chains $(a, b)$ with $a + b \le x - l$ value $chain[a] \oplus chain[b]$ $\le$ $\left\lfloor \frac{x}{l} \right\rfloor - 1$: $chain[a] \oplus chain[b] \le chain[a] + chain[b] = \left\lfloor \frac{a}{l} \right\rfloor + \left\lfloor \frac{b}{l} \right\rfloor \le \left\lfloor \frac{a + b}{l} \right\rfloor \le \left\lfloor \frac{x - l}{l} \right\rfloor = \left\lfloor \frac{x}{l} \right\rfloor - 1$ $chain[a] \oplus chain[b] \le chain[a] + chain[b] = \left\lfloor \frac{a}{l} \right\rfloor + \left\lfloor \frac{b}{l} \right\rfloor \le \left\lfloor \frac{a + b}{l} \right\rfloor \le \left\lfloor \frac{x - l}{l} \right\rfloor = \left\lfloor \frac{x}{l} \right\rfloor - 1$
|
[
"brute force",
"dp",
"games",
"graphs",
"math"
] | 2,500
|
from sys import setrecursionlimit
import threading
def main():
n, l, r = map(int, input().split())
g = [[] for i in range(0, n)]
for i in range(0, n):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
res = 0
used = [False for i in range(0, n)]
def dfs(v):
used[v] = True
size = 1
for to in g[v]:
if not used[to]:
size += dfs(to)
return size
for i in range(0, n):
if not used[i]:
size = dfs(i)
if size <= l + r - 1:
res ^= size // l
if res:
print("Alice")
else:
print("Bob")
setrecursionlimit(10 ** 9)
threading.stack_size(2 ** 27)
thread = threading.Thread(target=main)
thread.start()
|
1823
|
F
|
Random Walk
|
You are given a tree consisting of $n$ vertices and $n - 1$ edges, and each vertex $v$ has a counter $c(v)$ assigned to it.
Initially, there is a chip placed at vertex $s$ and all counters, except $c(s)$, are set to $0$; $c(s)$ is set to $1$.
Your goal is to place the chip at vertex $t$. You can achieve it by a series of moves. Suppose right now the chip is placed at the vertex $v$. In one move, you do the following:
- choose one of neighbors $to$ of vertex $v$ \textbf{uniformly at random} ($to$ is neighbor of $v$ if and only if there is an edge $\{v, to\}$ in the tree);
- move the chip to vertex $to$ and increase $c(to)$ by $1$;
You'll repeat the move above until you reach the vertex $t$.
For each vertex $v$ calculate the expected value of $c(v)$ modulo $998\,244\,353$.
|
Let $deg(v)$ be the number of neighbors of vertex $v$. Let's fix a vertex $v$ and its neighboring vertices $c_1, \dots, c_{deg(v)}$. According to the linearity of the expected values: $e_v = \sum_{u \in \{c_1, \dots, c_{deg(v)}\}} \frac{e_u}{deg(u)}$ Solution by Igor_Parfenov: Let's solve the subproblem: given a bamboo with vertices numbered in order from $1$ to $n$, and $s = 1$ and $t = n$. It is easy to see that the equation is satisfied by the expected values $\{n - 1, 2 \cdot (n - 2), 2 \cdot (n - 3), \dots , 6, 4, 2, 1\}$. Now let's solve the problem. Consider the path from $s$ to $t$ (it is the only one in the tree). The chip must go through it, but at the vertices of the path, it can go to third-party vertices. Let us represent a tree as non-intersecting trees whose roots are vertices lying on the path from $s$ to $t$, and all other vertices do not lie on this path. Let's place the numbers $\{n - 1, n - 2, \dots, 2, 1, 0\}$ at the vertices of the path. Let's now fix a tree rooted at vertex $v$ in the path, and let its number be equal to $x$. Then we can see that the equation is satisfied by the values of the mathematical expectation $e_u = x \cdot deg(u)$. Separately, you need to make $e_t = 1$. Solution by adedalic: Let's take a path from $s$ to $t$ and call it $r_0, r_1, \dots, r_k$, where $r_0 = s$ and $r_k = t$. Now we will assume that each of the vertices $r_i$ form its own rooted subtree. Consider a leaf $v$ in an arbitrary subtree: $e_v = \frac{1}{deg(p)} e_p$, where $p$ is the ancestor of $v$. Now, by induction on the subtree size, we prove that for any vertex $v$ in any subtree $r_i$ the expected value is $e_v = \frac{deg(v)}{deg(p)} e_p$. For the leafs, it's obvious. Further, by the inductive hypothesis: $e_v = \sum_{to \neq p}{\frac{1}{deg(to)} e_{to}} + \frac{1}{deg(p)} e_p = \sum_{to \neq p}{\frac{deg(to)}{deg(to) \cdot deg(v)} e_v} + \frac{1}{deg(p)} e_p = \frac{deg(v) - 1}{deg(v)} e_v + \frac{1}{deg(p)} e_p$ $\frac{1}{deg(v)} e_v = \frac{1}{deg(p)} e_p \leftrightarrow e_v = \frac{deg(v)}{deg(p)} e_p$ Now consider the vertices on the path: $e_{r_0} = 1 + \sum_{to \neq r_1}{\frac{1}{deg(to)} e_{to}} + \frac{1}{deg(r_1)} e_{r_1} = 1 + \frac{deg(r_0) - 1}{deg(r_0)} e_{r_0} + \frac{1}{deg(r_1)} e_{r_1}$ $e_{r_0} = deg(r_0) \left( 1 + \frac{1}{deg(r_1)} e_{r_1} \right)$ $e_{r_1} = \frac{1}{deg(r_0)} e_{r_0} + \sum_{to \neq r_0; to \neq r_2}{\frac{1}{deg(to)} e_{to}} + \frac{1}{deg(r_2)} e_{r_2} = \left( 1 + \frac{1}{deg(r_1)} e_{r_1} \right) + \frac{deg(r_1) - 2}{deg(r_1)} e_{r_1} + \frac{1}{deg(r_2)} e_{r_2}$ $e_{r_1} = deg(r_1) \left( 1 + \frac{1}{deg(r_2)} e_{r_2} \right)$ $e_{r_{k-1}} = deg(r_{k-1}) \left( 1 + 0 \right) = deg(r_{k - 1})$ $e_{r_{k-2}} = deg(r_{k-2}) \left( 1 + \frac{1}{deg(r_{k-1})} e_{r_{k-1}} \right) = deg(r_{k-2}) (1 + 1) = 2 \cdot deg(r_{k-2})$ $e_{r_{k-3}} = deg(r_{k-2}) \left( 1 + 2 \right) = 3 \cdot deg(r_{k-2})$ $e_{r_{k-i}} = i \cdot deg(r_{k-i})$ That's all. For any vertex $v$ in the subtree of $r_i$ we get $e_v = (k - i) \cdot deg(v)$.
|
[
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 2,600
|
from sys import setrecursionlimit
import threading
mod = 998244353
def main():
n, s, t = map(int, input().split())
s -= 1
t -= 1
g = [[] for i in range(0, n)]
previous = [-1 for i in range(0, n)]
inPath = [False for i in range(0, n)]
res = [0 for i in range(0, n)]
for i in range(0, n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
def dfs(v, p):
for to in g[v]:
if to == p:
continue
previous[to] = v
dfs(to, v)
def dfs2(v, p, k):
res[v] = k * len(g[v])
for to in g[v]:
if to == p:
continue
dfs2(to, v, k)
dfs(s, -1)
ptr = t
inPath[t] = True
while ptr != s:
res[previous[ptr]] = res[ptr] + 2
ptr = previous[ptr]
inPath[ptr] = True
for v in range(0, n):
if inPath[v]:
res[v] = res[v] // 2 * len(g[v])
for to in g[v]:
if not inPath[to]:
dfs2(to, v, res[v] // len(g[v]))
res[t] += 1
for i in res:
print(i % mod, end = ' ')
print("")
setrecursionlimit(10 ** 9)
threading.stack_size(2 ** 27)
thread = threading.Thread(target=main)
thread.start()
|
1824
|
A
|
LuoTianyi and the Show
|
There are $n$ people taking part in a show about VOCALOID. They will sit in the row of seats, numbered $1$ to $m$ from left to right.
The $n$ people come and sit in order. Each person occupies a seat in one of three ways:
- Sit in the seat next to the left of the leftmost person who is already sitting, or if seat $1$ is taken, then leave the show. If there is no one currently sitting, sit in seat $m$.
- Sit in the seat next to the right of the rightmost person who is already sitting, or if seat $m$ is taken, then leave the show. If there is no one currently sitting, sit in seat $1$.
- Sit in the seat numbered $x_i$. If this seat is taken, then leave the show.
Now you want to know what is the maximum number of people that can take a seat, if you can let people into the show in any order?
|
First we can notice that, if someone with a specific favourite seat(i.e. not $-1$ nor $-2$) has got his seat taken by a $-1$ guy or a $-2$ guy, it's better to let the first man go first, and the $-1$ or $-2$ one go after him. Now, we know it's better to make those with a favourite seat go in first. After they have seated, now we consider filling the space between them with $-1$ and $-2$. It's easy to notice that we can find two non-overlapping prefix and suffix, and fill the blank seats in the prefix with $-1$, and the blanks in the suffix with $-2$. We now only need to find the answer greedily for each division point between the prefix and the suffix. The time complexity is $O(n)$.
|
[
"greedy",
"implementation"
] | 1,400
|
// Problem: C. LuoTianyi and the Theater
// Contest: Codeforces - test vocaloid cf round
// URL: https://codeforces.com/gym/394370/problem/C
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x,y,z) for(int x=(y);x<=(z);x++)
#define per(x,y,z) for(int x=(y);x>=(z);x--)
#define debug(format...) fprintf(stderr, format)
#define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false)
using namespace std;
typedef long long ll;
const int N = 2e5+5;
int T, n, m, a[N], buc[N];
template<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}
template<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}
int main() {
for(scanf("%d", &T); T; T--) {
scanf("%d%d", &n, &m);
rep(i, 1, n) scanf("%d", &a[i]);
int cntL = 0, cntR = 0;
rep(i, 1, n) {
if(a[i] == -1) ++cntL;
else if(a[i] == -2) ++cntR;
else ++buc[a[i]];
}
int nowL = 0, nowR = 0, vis = 0;
rep(i, 1, m) {
if(buc[i]) ++vis;
else ++nowR;
}
int ans = max(cntL, cntR) + vis;
rep(i, 1, m) {
// printf("%d : %d %d; %d %d; %d
", i, cntL, nowL, cntR, nowR, vis);
if(buc[i]) chkmax(ans, min(cntL, nowL) + min(cntR, nowR) + vis);
else ++nowL, --nowR;
// printf(" -> %d
", ans);
}
chkmin(ans, m);
printf("%d
", ans);
rep(i, 1, m) buc[i] = 0;
}
return 0;
}
|
1824
|
B2
|
LuoTianyi and the Floating Islands (Hard Version)
|
\textbf{This is the hard version of the problem. The only difference is that in this version $k\le n$. You can make hacks only if both versions of the problem are solved.}
\begin{center}
{\small Chtholly and the floating islands.}
\end{center}
LuoTianyi now lives in a world with $n$ floating islands. The floating islands are connected by $n-1$ undirected air routes, and any two of them can reach each other by passing the routes. That means, the $n$ floating islands form a tree.
One day, LuoTianyi wants to meet her friends: Chtholly, Nephren, William, .... Totally, she wants to meet $k$ people. She doesn't know the exact positions of them, but she knows that they are in \textbf{pairwise distinct} islands. She define an island is good if and only if the sum of the distances$^{\dagger}$ from it to the islands with $k$ people is the minimal among all the $n$ islands.
Now, LuoTianyi wants to know that, if the $k$ people are randomly set in $k$ distinct of the $n$ islands, then what is the expect number of the good islands? You just need to tell her the expect number modulo $10^9+7$.
$^{\dagger}$The distance between two islands is the minimum number of air routes you need to take to get from one island to the other.
|
Call a node special if there is a person in it. When $k$ is odd, we find that there is only one node satisfying the conditions. $\bf{Proof}.$ Assume distinct node $x$ and node $y$ are good nodes. Let $x$ be the root of the tree. Define $s_i$ as the number of special nodes in subtree $i$. Think about the process we move from $x$ to $y$. If we try to move the chosen node from its father to $i$, the variation of cost is $k-2s_i$. When move from $x$ to its son $i$ which $s_i$ is maximal, $k-2s_i\geq 0$ is held (Otherwise, $x$ isn't a good node). And we can get $k-2s_i>0$ further because $k$ is odd and $2s_i$ is even. Since $\min_{1\leq j\leq n}{k-2s_j}=k-2s_i$, we find $k-2s_j>0$ for all $j$. So $y$ can't be good node. Then think about the situation that $k$ is even. Choose a node as root arbitrarily. With the same method, we find that good nodes satisfy $2s_i=k$. It's also sufficient. Define $p_i$ as the possibility that $s_i=\frac{k}{2}$, then the answer is $1+\sum_{i=1}^{n}p_i$. Define $S_i$ as the size of subtree $i$. When $s_i=\frac{k}{2}$, there are $\frac{k}{2}$ special nodes in subtree $i$ and $\frac{k}{2}$ in the other part. The number of ways to place special nodes is $\binom{n}{k}$, and $\binom{S_i}{\frac{k}{2}}\binom{n-S_i}{\frac{k}{2}}$ of them satisfying the condition. So $p_i=\dfrac{\binom{S_i}{\frac{k}{2}}\binom{n-S_i}{\frac{k}{2}}}{\binom{n}{k}}$. So we can solve the problem in $O(n)$.
|
[
"combinatorics",
"dfs and similar",
"math",
"probabilities",
"trees"
] | 2,300
|
//Was yea ra,rra yea ra synk sphilar yor en me exec hymme METAFALICA waath!
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#include<bits/stdc++.h>
using namespace std;
#define rg register
#define ll long long
#define ull unsigned ll
#define lowbit(x) (x&(-x))
#define djq 1000000007
const double eps=1e-10;
const short sint=0x3f3f;
const int inf=0x3f3f3f3f;
const ll linf=0x3f3f3f3f3f3f3f3f;
const double alpha=0.73;
const double PI=acos(-1);
inline void file(){
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
}
char buf[1<<21],*p1=buf,*p2=buf;
inline int getc(){
return p1==p2&&(p2=(p1=buf)+fread(buf,1,(1<<20)+5,stdin),p1==p2)?EOF:*p1++;
}
//#define getc getchar
inline ll read(){
rg ll ret=0,f=0;char ch=getc();
while(!isdigit(ch)){if(ch==EOF)exit(0);if(ch=='-')f=1;ch=getc();}
while(isdigit(ch)){ret=ret*10+ch-48;ch=getc();}
return f?-ret:ret;
}
inline void rdstr(char* s){
char ch=getc();
while(ch<33||ch>126) ch=getc();
while(ch>=33&&ch<=126) (*s++)=ch,ch=getc();
}
#define ep emplace
#define epb emplace_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define it iterator
#define mkp make_pair
#define naive return 0*puts("Yes")
#define angry return 0*puts("No")
#define fls fflush(stdout)
#define rep(i,a) for(rg int i=1;i<=a;++i)
#define per(i,a) for(rg int i=a;i;--i)
#define rep0(i,a) for(rg int i=0;i<=a;++i)
#define per0(i,a) for(rg int i=a;~i;--i)
#define szf sizeof
typedef vector<int> vec;
typedef pair<int,int> pii;
struct point{ int x,y; point(int x=0,int y=0):x(x),y(y) {} inline bool operator<(const point& T)const{ return x^T.x?x<T.x:y<T.y; }; };
inline int ksm(int base,int p){int ret=1;while(p){if(p&1)ret=1ll*ret*base%djq;base=1ll*base*base%djq,p>>=1;}return ret;}
inline void pls(int& x,const int k){ x=(x+k>=djq?x+k-djq:x+k); }
inline int add(const int a,const int b){ return a+b>=djq?a+b-djq:a+b; }
inline void sub(int& x,const int k){ x=(x-k<0?x-k+djq:x-k); }
inline int inc(const int a,const int b){ return a<b?a-b+djq:a-b; }
inline void ckmn(int& x,const int k){ x=(k<x?k:x); }
inline void ckmx(int& x,const int k){ x=(k>x?k:x); }
const int lim=2e5;
int fac[200005],ifac[200005];
inline int C(int n,int m){ return (m<=n&&m>=0&&n>=0)?1ll*fac[n]*ifac[m]%djq*ifac[n-m]%djq:0; }
void initC(){
fac[0]=ifac[0]=1;
rep(i,lim) fac[i]=1ll*fac[i-1]*i%djq;
ifac[lim]=ksm(fac[lim],djq-2);
per(i,lim-1) ifac[i]=1ll*ifac[i+1]*(i+1)%djq;
}
int n,k,u,v,sz[200005];
vec e[200005];
void dfs(int x,int fa){
sz[x]=1;
for(int y:e[x]) if(y^fa) dfs(y,x),sz[x]+=sz[y];
}
signed main(){
//file();
initC();
n=read(),k=read();
rep(i,n-1) u=read(),v=read(),e[u].epb(v),e[v].epb(u);
dfs(1,0);
if(k&1) return 0*puts("1");
else{
int ans=0;
for(rg int i=2;i<=n;++i) pls(ans,1ll*C(sz[i],k/2)*C(n-sz[i],k/2)%djq);
ans=1ll*ans*ksm(C(n,k),djq-2)%djq;
pls(ans,1);
printf("%d
",ans);
}
return 0;
}
|
1824
|
C
|
LuoTianyi and XOR-Tree
|
LuoTianyi gives you a tree with values in its vertices, and the root of the tree is vertex $1$.
In one operation, you can change the value in one vertex to any non-negative integer.
Now you need to find the minimum number of operations you need to perform to make each path from the root to leaf$^{\dagger}$ has a bitwise XOR value of zero.
$^{\dagger}$A leaf in a rooted tree is a vertex that has exactly one neighbor and is not a root.
|
Hint: Consider a brute force dynamic programming solution and try to optimize it. Denote the minimum number of operations needed to make every path from a leaf inside the subtree of $u$ to the root have the xor value of $w$ as $f_{u,w}$. Observe that for every $u$, there are only $2$ possible different values for $f_{u,w}$. This is because if $f_{u,w_1}-f_{u,w_2}>1$, we can use an operation of xor-ing $a_u$ with $w_1 \ \text{xor} \ w_2$ to make all the xor values from $w_2$ to $w_1$, which takes $f_{u,w_2}+1$ steps instead of $f_{u,w_1}$. Now we only need to calculate $\text{minn}_u=\min f_{u,w}$, and the set $S_u$ of $w$ that makes $f_{u,w}$ minimum. We have $\text{minn}_v=0$ and $S_v={\text{the xor value from root to v}}$ for leaf $v$. It's trivial to calculate $\text{minn}_u$. Note that $S_u$ contains of the numbers appearing the most times in the sets of $u$'s son. We can maintain $S_u$ using a map and merging it heuristically. Consider when merging sets into a new set $S'$. If every element of $S'$ appears only once in the original sets, then we keep $S'$ as the result, otherwise, brute force the whole set $S'$ and find the elements appearing the most times. For the second situation, every element's count of appearance is at least halved(those appearing once have $0$ and others have $1$ afterwards), so the number of brute force checking operations is $O(n\log n)$. The final time complexity is $O(n\log^2 n)$.
|
[
"data structures",
"dfs and similar",
"dp",
"dsu",
"greedy",
"trees"
] | 2,500
|
#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
#include<algorithm>
#include<map>
using namespace std;
int n,a[100005];
vector<int> e[100005];
set<int> s[100005],stmp;
int ans=0,sid[100005],stp=0;
bool cmp(int x,int y)
{
return (int)s[sid[x]].size()>(int)s[sid[y]].size();
}
void set_xor(int x,int y)
{
stmp.clear();
set<int>::iterator it=s[x].begin();
while(it!=s[x].end())
stmp.insert(y^(*(it++)));
s[x]=stmp;
return ;
}
void dfs(int u,int f)
{
vector<int> v;
for(int i=0;i<(int)e[u].size();i++)
if(e[u][i]!=f)
{
dfs(e[u][i],u);
v.push_back(e[u][i]);
}
if((int)v.size()==0)
{
sid[u]=(++stp);
s[sid[u]].insert(0);
return ;
}
sort(v.begin(),v.end(),cmp);
int hv_tg=a[v[0]];
a[v[0]]=0;
a[u]^=hv_tg;
bool flg=false;
set<int> setchk;
for(int i=1;i<(int)v.size();i++)
{
int x=v[i];
set_xor(sid[x],a[x]^hv_tg);
set<int>::iterator it=s[sid[x]].begin();
while(it!=s[sid[x]].end())
{
int val=(*it); it++;
if(s[sid[v[0]]].find(val)!=s[sid[v[0]]].end())
flg=true;
if(setchk.find(val)!=setchk.end())
flg=true;
setchk.insert(val);
}
}
if(flg==false)
{
//cout<<"Node "<<u<<" "<<(int)v.size()-1<<endl;
ans+=(int)v.size()-1;
for(int i=1;i<(int)v.size();i++)
{
int x=v[i];
set<int>::iterator it=s[sid[x]].begin();
while(it!=s[sid[x]].end())
s[sid[v[0]]].insert(*(it++));
}
sid[u]=sid[v[0]];
return ;
}
map<int,int> h;
for(int i=0;i<(int)v.size();i++)
{
int x=v[i];
set<int>::iterator it=s[sid[x]].begin();
while(it!=s[sid[x]].end())
h[*(it++)]++;
}
sid[u]=(++stp);
int mx_app=0;
map<int,int>::iterator it=h.begin();
while(it!=h.end())
{
pair<int,int> p=(*it);
if(p.second>mx_app)
{
mx_app=p.second;
s[sid[u]].clear();
}
if(p.second==mx_app)
s[sid[u]].insert(p.first);
it++;
}
ans+=(int)v.size()-mx_app;
return ;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
e[u].push_back(v);
e[v].push_back(u);
}
dfs(1,0);
set_xor(sid[1],a[1]);
if(s[sid[1]].find(0)==s[sid[1]].end())
ans++;
printf("%d
",ans);
return 0;
}
|
1824
|
D
|
LuoTianyi and the Function
|
LuoTianyi gives you an array $a$ of $n$ integers and the index begins from $1$.
Define $g(i,j)$ as follows:
- $g(i,j)$ is the largest integer $x$ that satisfies $\{a_p:i\le p\le j\}\subseteq\{a_q:x\le q\le j\}$ while $i \le j$;
- and $g(i,j)=0$ while $i>j$.
There are $q$ queries. For each query you are given four integers $l,r,x,y$, you need to calculate $\sum\limits_{i=l}^{r}\sum\limits_{j=x}^{y}g(i,j)$.
|
Consider an alternative method of calculating $g$. Notice that $g(i,j)$ is the minimum of the last appearing position of all colors(let's call different values of $a_x$ colors for short) in the interval $[i,j]$. Consider the sequence from $a_n$ to $a_1$. Adding $a_i$ to the front of the sequence only affects the values $g(i,x)(i\leq x<\text{nxt}_i)$, where $\text{nxt}_i$ is the next position after $i$ having the same $a$ value as it. Or it's to say to modify $g$ values in the submatrix of $[(1,i),(i,\text{nxt}_i-1)]$ to $i$, which can be done in $O(n\log^2 n)$, but it's not fast enough. Because the queries happen after all modifications take place, you can store the queries offline, and calculate a submatrix using $4$ queries of submatrixes having $(1,1)$ as the upper-left corner. Now we need to maintain a data structure that can: 1. set all values in an interval as a same value $x$, 2. query the history sum(sum of values on all previous editions). We can maintain the segments of adjacent positions with the same values, and turn the modification into 'range add' for a segment. An operation makes at most $O(1)$ new segments, and now there's only $O(n)$ range add modifications and $O(m)$ range history sum queries, now the problem can be solved in $O(n\log n)$ time complexity with segment tree.
|
[
"data structures"
] | 3,000
|
#include<bits/stdc++.h>
using namespace std;
#define N 1000005
#define L long long
int n,m,stt,a[N],nxt[N],siz[N],top,ll[N],rr[N],xx[N],yy[N];
L out[N];
struct ds{
L t[2][N],ta;
inline void add(int op,int x,L v){while(x<=n) t[op][x]+=v,x+=(x&-x);}
inline L ask(int op,int x){ta=0;while(x) ta+=t[op][x],x^=(x&-x);return ta;}
void Add(int l,int r,L v){add(0,l,v),add(0,r+1,-v),add(1,l,v*(l-1)),add(1,r+1,-v*r);}
L Ask(int l,int r){return r*ask(0,r)-(l-1)*ask(0,l-1)-ask(1,r)+ask(1,l-1);}
} b1,b2;
struct node{int l,r,v;} st[N];
struct query{int id,op;} pl[2*N];
query *v[N];
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;++i) cin>>a[i],siz[a[i]]=n+1;
for(int i=n;i>=1;--i) nxt[i]=siz[a[i]],siz[a[i]]=i;
memset(siz,0,sizeof siz);
for(int i=1;i<=m;++i){
cin>>ll[i]>>rr[i]>>xx[i]>>yy[i];
siz[ll[i]]++,siz[rr[i]+1]++;
}
for(int i=1;i<=n+1;++i) v[i]=pl+top,top+=siz[i];
memset(siz,0,sizeof siz);
for(int i=1;i<=m;++i) v[ll[i]][siz[ll[i]]++]=(query){i,1},v[rr[i]+1][siz[rr[i]+1]++]=(query){i,-1};
for(int i=n,l,r;i>=1;--i){
l=i,r=nxt[i]-1;
while(stt&&r>=st[stt].r){
node &nw=st[stt];
b1.Add(nw.l,nw.r,1ll*-i*nw.v),b2.Add(nw.l,nw.r,-nw.v);
stt--;
}
if(stt&&st[stt].l<=r){
node &nw=st[stt];
b1.Add(nw.l,r,1ll*-i*nw.v),b2.Add(nw.l,r,-nw.v);
nw.l=r+1;
}
st[++stt]=(node){l,r,i};
b1.Add(l,r,1ll*i*i),b2.Add(l,r,i);
for(int j=0;j<siz[i];++j) out[v[i][j].id]+=1ll*v[i][j].op*(b1.Ask(xx[v[i][j].id],yy[v[i][j].id])-1ll*(i-1)*b2.Ask(xx[v[i][j].id],yy[v[i][j].id]));
}
for(int i=1;i<=m;++i) cout<<out[i]<<'
';
}
|
1824
|
E
|
LuoTianyi and Cartridge
|
LuoTianyi is watching the anime Made in Abyss. She finds that making a Cartridge is interesting. To describe the process of making a Cartridge more clearly, she abstracts the original problem and gives you the following problem.
You are given a tree $T$ consisting of $n$ vertices. Each vertex has values $a_i$ and $b_i$ and each edge has values $c_j$ and $d_j$.
Now you are aim to build a \textbf{tree} $T'$ as follows:
- First, select $p$ vertices from $T$ ($p$ is a number chosen by yourself) as the vertex set $S'$ of $T'$.
- Next, select $p-1$ edges from $T$ one by one (you cannot select one edge more than once).
- May you have chosen the $j$-th edge connects vertices $x_j$ and $y_j$ with values $(c_j,d_j)$, then you can choose two vertices $u$ and $v$ in $S'$ that satisfy the edge $(x_j,y_j)$ is contained in the simple path from $u$ to $v$ in $T$, and link $u$ and $v$ in $T'$ by the edge with values $(c_j,d_j)$ ($u$ and $v$ shouldn't be contained in one connected component before in $T'$).
\begin{center}
{\small A tree with three vertices, $\min(A,C)=1,B+D=7$, the cost is $7$.}
\end{center}
\begin{center}
{\small Selected vertices $2$ and $3$ as $S'$, used the edge $(1,2)$ with $c_j = 2$ and $d_j = 1$ to link this vertices, now $\min(A,C)=2,B+D=4$, the cost is $8$.}
\end{center}
Let $A$ be the minimum of values $a_i$ in $T'$ and $C$ be the minimum of values $c_i$ in $T'$. Let $B$ be the sum of $b_i$ in $T'$ and $D$ be the sum of values $d_i$ in $T'$. Let $\min(A, C) \cdot (B + D)$ be the cost of $T'$. You need to find the maximum possible cost of $T'$.
|
Consider finding the maximum value of $B+D$ for every $\min(A,C)$. Denote $\min(A,C)$ as $x$. We call a vertex $u$ satisfying $a_u\geq x$ or an edge satisfying $c_e\geq x$ optional. Denote as $V$ the optional vertex set and as $E_0$ the optional edge set. Firstly, if all optional vertices are on the same side of an edge, this edge mustn't be chosen. Delete these edges from $E_0$ and we get the edge set $E$. Formally, an edge $e$ is in $E$ if and only if $c_e\geq x$ and there exists $u,v$ so that $e$ is on the path between them. $\bf{Lemma.}$ There exists an optimal $T_{\text{ans}}=(V_\text{ans},E_\text{ans})$ that either $V=V_\text{ans}$ or $E=E_\text{ans}$. $\bf{Proof.}$ Assume an optimal $T'=(V',E')$ with $V'\neq V,E'\neq E$. Choose an edge $e$ that is in $E$ but not in $E'$. Because $V'\neq V$, there must exist two vertices $u,v$ on different sides of edge $e$ and $u\in V',v\notin V'$. Consider adding the edge $e$ and the vertex $v$ into our chosen tree, the resulting graph is obviously a tree. Note that $b_v,d_e\geq 0$, so the resulting choice is no worse than $T'$. When we delete the edges in $E$ from the original tree, we get some connected components. Shrink one component into a single vertex to get $V'$, and then for all edges $(u,v)\in E$, connect $u$'s and $v$'s component together in the new graph and get $E'$. Obviously, the new graph $T'=(V',E')$ is a tree. For any leaf vertex $u'$ on the new tree $T'$, there must exist a vertex $u$ in the component $u'$ that is chosen, otherwise the edge connecting to $u'$, let's say, $e'$ is not chosen either. Adding $u$ and $e'$ into our answer tree achieves a better answer. Assume that now we have chosen a vertex $u$ for every leaf $u'$, denote the set of chosen vertices as $V_x$. Consider an arbitary choice of vertex for components $V_c$ and edge choice $E_c$ satisfying $V_x\subseteq V_c\subseteq V,E_c\subseteq E,|V_c|-1=|E_c|$. It's easy to prove that the choice is a legal answer, given the fact that every $e\in E_c$ has at least one leaf component on each side and every leaf component contains a chosen vertex. Reconsider the lemma, and we can get a solution for a fixed $x$: Find $V,E$. Calculate the components and get $V',E'$. Find the vertex with the maximum $b$ in every leaf-component in $V'$ and get $V_x$. Let $m$ be $\min(|V|,|E|+1)$, and $m'$ be $|V_x|$. Choose the vertices in $V\setminus V_x$ with the first $m-m'$ largest $b$, and the edges in $E$ with the first $m-1$ largest $d$ and get the answer. Consider the process when $x$ gets larger, the sets $V,E$ get smaller and smaller while the components merge into each other. We use segment trees to maintain the $b$ value of the vertices and the $d$ value of the edges, when merging two components, we simply merge the two segment trees. The final time complexity is $O(n\log n)$.
|
[
"data structures",
"trees"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 2e5 + 5;
const int inf = 0x3f3f3f3f;
const ll linf = 0x3f3f3f3f3f3f3f3f;
struct Segment_Tree
{
static const int N = 1<<18, SIZ = N * 2 + 5;
pii mx[SIZ];
Segment_Tree(void){ clear();}
void clear(void)
{
for(int i=0; i<N; ++i)
mx[N+i] = {-inf, i};
for(int i=N-1; i>=1; --i)
mx[i] = max(mx[i<<1], mx[i<<1|1]);
}
void set(int i,int k)
{
i += N;
mx[i].first = k;
while((i >>= 1) != 0)
mx[i] = max(mx[i<<1], mx[i<<1|1]);
}
pii query(int l,int r)
{
pii res = {-inf, -inf};
for(l+=N-1, r+=N+1; l^r^1; l>>=1, r>>=1)
{
if(~l&1) res = max(res, mx[l^1]);
if( r&1) res = max(res, mx[r^1]);
}
return res;
}
}tree;
struct DS
{
multiset<int> l,r;
ll sum;
DS(void){ clear();}
void clear(void){ l.clear(); r.clear(); sum = 0;}
void insert(int x)
{
if(!r.size() || x < *r.begin()) l.emplace(x);
else r.emplace(x), sum += x;
}
void erase(int x)
{
if(l.find(x) != l.end())
l.erase(l.find(x));
else
r.erase(r.find(x)), sum -= x;
}
int size(void) const
{
return (int)l.size() + (int)r.size();
}
ll query(int k)
{
while((int)r.size() > k)
{
int x = *r.begin(); r.erase(r.begin()); sum -= x;
l.emplace(x);
}
while((int)r.size() < k && l.size())
{
int x = *l.rbegin(); l.erase(prev(l.end()));
r.emplace(x); sum += x;
}
return sum;
}
};
array<int,2> p[MAXN];
array<int,4> es[MAXN];
vector<pii> g[MAXN];
int anc[MAXN], ancid[MAXN];
void dfs_tree(int u,int fa)
{
for(auto it: g[u]) if(it.first != fa)
{
int v = it.first;
anc[v] = u;
ancid[v] = it.second;
dfs_tree(v,u);
}
}
int dfnl[MAXN], dfnr[MAXN], seq[MAXN], curdfn;
void dfs_dfn(int u,int fa)
{
dfnl[u] = ++curdfn; seq[curdfn] = u;
for(auto it: g[u]) if(it.first != fa)
dfs_dfn(it.first, u);
dfnr[u] = curdfn;
}
int main(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i)
scanf("%d",&p[i][0]);
for(int i=1; i<=n; ++i)
scanf("%d",&p[i][1]);
for(int i=1; i<n; ++i)
for(int &t: es[i])
scanf("%d",&t);
vector<pii> vec;
for(int i=1; i<=n; ++i)
vec.emplace_back(p[i][0], i << 1 | 0);
for(int i=1; i<n; ++i)
{
vec.emplace_back(es[i][2], i << 1 | 1);
int u = es[i][0], v = es[i][1];
g[u].emplace_back(v,i);
g[v].emplace_back(u,i);
}
sort(vec.begin(), vec.end());
reverse(vec.begin(), vec.end());
ll ans = 0;
vector<pii> eff;
int cntp = 0, cnte = 0;
ll sump = 0, sume = 0;
DS ds;
// Part 1
{
int rt;
{
int i = 0;
while(vec[i].second % 2 == 1) ++i;
rt = vec[i].second >> 1;
}
anc[rt] = 0; ancid[rt] = 0;
dfs_tree(rt,0);
static int tage[MAXN];
auto insert_edge = [&] (int i,int curval)
{
if(tage[i] != 3) return;
// printf("insert_edge %d
",i);
eff.emplace_back(curval, i << 1 | 1);
ds.insert(es[i][3]);
cnte += 1;
sume += es[i][3];
};
auto insert_node = [&] (int u,int curval)
{
// printf("insert_node %d
",u);
eff.emplace_back(curval, u << 1 | 0);
cntp += 1;
sump += p[u][1];
while(u != rt && (tage[ancid[u]] & 1) == 0)
{
tage[ancid[u]] |= 1;
insert_edge(ancid[u], curval);
u = anc[u];
}
};
for(auto t: vec)
{
int i = t.second >> 1, type = t.second & 1;
if(type == 0)
{
insert_node(i, t.first);
}
else
{
tage[i] |= 2;
insert_edge(i, t.first);
}
if(cntp >= 1 && cnte >= cntp - 1)
{
ll cur = sump + ds.query(cntp - 1);
ans = max(ans, t.first * cur);
}
}
}
// Part 2
{
int rtid, rt1, rt2;
{
int i = 0;
while(eff[i].second % 2 == 0) ++i;
rtid = eff[i].second >> 1;
rt1 = es[rtid][0];
rt2 = es[rtid][1];
}
dfs_dfn(rt1,rt2);
dfs_dfn(rt2,rt1);
cntp = cnte = sump = sume = 0;
ds.clear();
map<int,pii> seg;
ll has = 0;
auto insert_seg = [&] (int l,int r)
{
auto it = seg.lower_bound(l);
if(it != seg.end() && it -> second.first <= r) return;
if(it != seg.begin())
{
--it;
if(it -> second.first >= l)
{
int j = it -> second.second;
seg.erase(it);
ds.insert(p[j][1]);
tree.set(dfnl[j], p[j][1]);
has -= p[j][1];
}
}
assert(tree.query(l,r).second != -inf);
int j = seq[ tree.query(l,r).second ];
ds.erase(p[j][1]);
tree.set(dfnl[j], -inf);
has += p[j][1];
seg[l] = {r, j};
};
for(auto t: eff)
{
int i = t.second >> 1, type = t.second & 1;
if(type == 0)
{
bool flag = [&] (void) -> bool
{
auto it = seg.upper_bound(dfnl[i]);
if(it == seg.begin()) return 0;
--it;
if(it -> second.first < dfnl[i]) return 0;
int j = it -> second.second;
if(p[j][1] >= p[i][1]) return 0;
ds.insert(p[j][1]);
tree.set(dfnl[j], p[j][1]);
it -> second.second = i;
has = has - p[j][1] + p[i][1];
return 1;
}();
if(!flag)
{
ds.insert(p[i][1]);
tree.set(dfnl[i], p[i][1]);
}
++cntp; sump += p[i][1];
}
else
{
if(i == rtid)
{
insert_seg(dfnl[rt1], dfnr[rt1]);
insert_seg(dfnl[rt2], dfnr[rt2]);
}
else
{
int u = es[i][0], v = es[i][1];
if(dfnl[u] < dfnl[v]) swap(u, v);
insert_seg(dfnl[u], dfnr[u]);
}
++cnte; sume += es[i][3];
}
if(cntp >= cnte + 1)
{
ll cur = sume + has + ds.query(cnte + 1 - (int)seg.size());
ans = max(ans, t.first * cur);
}
}
}
printf("%lld
",ans);
return 0;
}
|
1825
|
A
|
LuoTianyi and the Palindrome String
|
LuoTianyi gives you \textbf{a palindrome}$^{\dagger}$ string $s$, and she wants you to find out the length of the longest non-empty subsequence$^{\ddagger}$ of $s$ which is not a palindrome string. If there is no such subsequence, output $-1$ instead.
$^{\dagger}$ A palindrome is a string that reads the same backward as forward. For example, strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.
$^{\ddagger}$ A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from $b$. For example, strings "a", "aaa", "bab" are subsequences of string "abaab", but strings "codeforces", "bbb", "h" are not.
|
Consider the substring of $s$ from the second character to the last, or $s_2s_3\cdots s_n$. If it's not palindrome, then the answer must be $n-1$. What if it's palindrome? This implies that $s_2=s_n$, $s_3=s_{n-1}$, and so on. Meanwhile, the fact that $s$ is palindrome implies $s_1=s_n$, $s_2=s_{n-1}$, etc. So we get $s_1=s_n=s_2=s_{n-1}=\cdots$ or that all characters in $s$ is the same. In this situation, every subsequence of $s$ is palindrome of course, so the answer should be $-1$.
|
[
"greedy",
"strings"
] | 800
|
#pragma GCC optimize(3,"Ofast","inline")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
//#define ll int
#define ft first
#define sd second
//#define endl '
'
#define pb push_back
#define ll long long
#define pll pair<ll,ll>
#define no cout<<"NO"<<'
'
#define no_ cout<<"No"<<'
'
#define _no cout<<"no"<<'
'
#define lowbit(a) ((a)&-(a))
#define yes cout<<"YES"<<'
'
#define yes_ cout<<"Yes"<<'
'
#define _yes cout<<"yes"<<'
'
#define ull unsigned long long
#define all(x) x.begin(),x.end()
#define nps fixed<<setprecision(10)<<
#define mem(a,k) memset(a,k,sizeof(a))
#define debug(x) cout<<#x<<"="<<x<<endl
#define rep(i,a,b) for(ll i=(a);i<=(b);i++)
#define per(i,a,b) for(ll i=(a);i>=(b);i--)
const ll mod1=1e9+7;
const ll mod2=998244353;
const ll base=1610612741;
const ll INF=0x3f3f3f3f3f;
const ll inf=9223372036854775807;
const ll Z=mod2;
const ll mod=Z;
using namespace std;
int ddir[2][2]={{0,1},{1,0}};
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int dir3[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
struct custom_hash
{
static ull splitmix64(ull x){x+=0x9e3779b97f4a7c15;x=(x^(x>>30))*0xbf58476d1ce4e5b9;x=(x^(x>>27))*0x94d049bb133111eb;return x^(x>>31);}
size_t operator()(ull x)const{static const ull FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();return splitmix64(x + FIXED_RANDOM);}
//unordered_map<ll,ll,custom_hash>mp;
};
struct mint
{
ll x;
mint(ll y = 0){if(y < 0 || y >= mod) y = (y%mod+mod)%mod; x = y;}
mint(const mint &ope) {x = ope.x;}
mint operator-(){return mint(-x);}
mint operator+(const mint &ope){return mint(x) += ope;}
mint operator-(const mint &ope){return mint(x) -= ope;}
mint operator*(const mint &ope){return mint(x) *= ope;}
mint operator/(const mint &ope){return mint(x) /= ope;}
mint& operator+=(const mint &ope){x += ope.x; if(x >= mod) x -= mod; return *this;}
mint& operator-=(const mint &ope){x += mod - ope.x; if(x >= mod) x -= mod; return *this;}
mint& operator*=(const mint &ope){ll tmp = x; tmp *= ope.x, tmp %= mod; x = tmp; return *this;}
mint& operator/=(const mint &ope){ll n = mod-2; mint mul = ope;while(n){if(n & 1) *this *= mul; mul *= mul; n >>= 1;}return *this;}
mint inverse(){return mint(1) / *this;}
bool operator ==(const mint &ope){return x == ope.x;}
bool operator !=(const mint &ope){return x != ope.x;}
bool operator <(const mint &ope)const{return x < ope.x;}
};
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll gcd(ll a,ll b){return __gcd(a,b);}
ll lcm(ll a,ll b){return a*b/__gcd(a,b);}
ll rnd(ll l,ll r){ll ans=uniform_int_distribution<ll>(l,r)(rng);return ans;}
ll qpow(ll a,ll b){ll res=1;while(b>0){if(b&1)res=res*a;a=a*a;b>>=1;}return res;}
ll qpow(ll a,ll b,ll m){a%=m;ll res=1;while(b>0){if(b&1)res=res*a%m;a=a*a%m;b>>=1;}return res;}
double psqrt(double x,double y,double xx,double yy){double res=((x-xx)*(x-xx)+(y-yy)*(y-yy));return res;}
double ssqrt(double x,double y,double xx,double yy){double res=sqrt(psqrt(x,y,xx,yy));return res;}
ll INV(ll x){return qpow(x,Z-2,Z);}
void cominit(ll fac[],ll inv[]){fac[0]=1;rep(i,1,1000000)fac[i]=fac[i-1]*i%Z;
inv[1000000]=INV(fac[1000000]);per(i,1000000-1,0)inv[i]=inv[i+1]*(i+1)%Z;}
ll t,n,m,k,tt,tp,res,sum,ans,cnt;
const ll N=1e6+5;
ll a[N],b[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
//IO
cin>>t;
while(t--)
{
string s;
cin>>s;
auto check=[&]()
{
for(int i=0;i<s.size()/2;++i)if(s[i]!=s[s.size()-i-1])return 0;
return 1;
};
if(!check())ans=s.size();
else if(s.size()>1)
{
s.pop_back();
if(!check())ans=s.size();
else ans=-1;
}
else ans=-1;
cout<<ans<<"
";
}
}
|
1825
|
B
|
LuoTianyi and the Table
|
LuoTianyi gave an array $b$ of $n \cdot m$ integers. She asks you to construct a table $a$ of size $n \times m$, filled with these $n \cdot m$ numbers, and each element of the array must be used \textbf{exactly once}. Also she asked you to maximize the following value:
\begin{center}
$\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{m}\left(\max\limits_{1 \le x \le i, 1 \le y \le j}a_{x,y}-\min\limits_{1 \le x \le i, 1 \le y \le j}a_{x,y}\right)$
\end{center}
This means that we consider $n \cdot m$ subtables with the upper left corner in $(1,1)$ and the bottom right corner in $(i, j)$ ($1 \le i \le n$, $1 \le j \le m$), for each such subtable calculate the difference of the maximum and minimum elements in it, then sum up all these differences. You should maximize the resulting sum.
Help her find the maximal possible value, you don't need to reconstruct the table itself.
|
Assume that $n>m$. Greedily thinking, we want the maximum possible $a$ to appear as the maximum value of as many subtables as possible, meanwhile, we also want the minimum possible $a$ to appear as the minimum value of as many subtables as possible. This gives us two choices: making the upper-left square the minimum or the maximum. It's symmetrical so we'll only consider the minimum situation. Now all the subtables have the same minimum value, we want to maximize the number of subtables where the maximum $a$ appears as the maximum value. Placing it at $(1,2)$ and $(2,1)$ makes the number $n(m-1),m(n-1)$ each, because $n>m$, we have $m(n-1)>n(m-1)$, so we place the largest $a$ at $(2,1)$ and the second largest at $(1,2)$, the answer for this case is $m(n-1)\times \max+m\times \text{second max}-mn\times\min$.
|
[
"greedy",
"math"
] | 1,000
|
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int mxn=2e5+5;
ll a[mxn];
inline void solve(){
ll n,m;
cin>>n>>m;
for(int i=1;i<=n*m;++i)cin>>a[i];
sort(a+1,a+n*m+1);
if(n>m)swap(n,m);
if(n==1)cout<<(m-1)*(a[n*m]-a[1])<<'
';
else{
ll ans1=(n*m-1)*(a[n*m])-a[1]*(n*(m-1))-a[2]*(n-1);
ll ans2=a[n*m]*(n*(m-1))+a[n*m-1]*(n-1)-a[1]*(n*m-1);
cout<<max(ans1,ans2)<<'
';
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int T;cin>>T;
for(;T--;)solve();
return 0;
}
|
1826
|
A
|
Trust Nobody
|
There is a group of $n$ people. Some of them might be liars, who \textbf{always} tell lies. Other people \textbf{always} tell the truth. The $i$-th person says "There are at least $l_i$ liars amongst us". Determine if what people are saying is contradictory, or if it is possible. If it is possible, output the number of liars in the group. If there are multiple possible answers, output any one of them.
|
Let's iterate over the number $x$ of liars in the group. Now everyone, who says $l_i > x$ is a liar, and vice versa. Let's count the actual number of liars. If those numbers match, output the answer. Now that we've checked all possible $x$'s, we can safely output $-1$, since no number of liars is possible.
|
[
"brute force",
"greedy",
"implementation",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> l(n);
for (auto &i : l) {
cin >> i;
}
for (int cnt_liars = 0; cnt_liars <= n; ++cnt_liars) {
int actual = 0;
for (auto i : l) {
if (!(cnt_liars >= i)) {
++actual;
}
}
if (actual == cnt_liars) {
cout << cnt_liars << '\n';
return;
}
}
cout << "-1\n";
}
signed main() {
int t;
cin >> t;
while (t--) solve();
return 0;
}
|
1826
|
B
|
Lunatic Never Content
|
You have an array $a$ of $n$ non-negative integers. Let's define $f(a, x) = [a_1 \bmod x, a_2 \bmod x, \dots, a_n \bmod x]$ for some positive integer $x$. Find the biggest $x$, such that $f(a, x)$ is a palindrome.
Here, $a \bmod x$ is the remainder of the integer division of $a$ by $x$.
An array is a palindrome if it reads the same backward as forward. More formally, an array $a$ of length $n$ is a palindrome if for every $i$ ($1 \leq i \leq n$) $a_i = a_{n - i + 1}$.
|
For the sequence to be a palindrome, it has to satisfy $b_i = b_{n - i + 1}$. In our case $b_i = a_i \pmod x$. We can rewrite the palindrome equation as $a_i \pmod x = a_{n - i + 1} \pmod x$. Moving all the terms to the left we get $a_i - a_{n - i + 1} \equiv 0 \pmod x$, which basically says $x$ divides $a_i - a_{n - i + 1}$. Now, how to find the biggest $x$, which satisfies all such conditions? Greatest common divisor of course! We just need to calculate the $GCD$ of the numbers $a_i - a_{n - i + 1}$ for all $i$. This results in a $O(n + log(10^9))$ solution, since computing the gcd of $n$ numbers up to $10^9$ takes exactly this much time. A useful assumption here is that $GCD(x, 0) = x$ for any number $x$. This holds true for standard template library implementations. And do not forget that this function should work correctly for negative numbers too. An easy trick here is to just use the absolute value of $a_i - a_{n - i + 1}$.
|
[
"math",
"number theory"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (auto &i : a) cin >> i;
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = __gcd(ans, abs(a[i] - a[n - i - 1]));
}
cout << ans << '\n';
}
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int t;
cin >> t;
while (t--) solve();
return 0;
}
|
1826
|
C
|
Dreaming of Freedom
|
\begin{quote}
Because to take away a man's freedom of choice, even his freedom to make the wrong choice, is to manipulate him as though he were a puppet and not a person.
\hfill — Madeleine L'Engle
\end{quote}
There are $n$ programmers choosing their favorite algorithm amongst $m$ different choice options. Before the first round, all $m$ options are available. In each round, every programmer makes a vote for one of the remaining algorithms. After the round, only the algorithms with the maximum number of votes remain. The voting process ends when there is only one option left. Determine whether the voting process can continue indefinitely or no matter how people vote, they will eventually choose a single option after some finite amount of rounds?
|
First we need to notice, that in order to keep some amount of options indefinetely, this number has to be at least $2$ and divide $n$. Let's find the smallest such number $d$. Now, if $d \leq m$, let's always vote for the first $d$ options evenly. In the other case $(d > m)$ each round would force us to to decrease the number of remaining options, so eventually it will become one. So the answer is YES if and only if $d > m$. Now on how to find the number $d$ fast. Since $d$ is a divisor of $n$ we can say, that $d$ is the smallest divisor of $n$ not equal to $1$. We can find the number $d$ using different approaches. A more straightforward one, is checking all the numbers from $2$ up to $\sqrt{n}$. If no divisors found, then $n$ is prime and $d = n$. This results in a $O(t \cdot \sqrt{n})$ solution. The solution presented before is good, but not fast enough in some languages, like Python. We've decided not to cut it off to not make the problem heavy in IO. We can optimize it via finding the smallest divisor using the sieve of Eratosthenes. This would result in $O(nlogn)$ or even faster precomputation and $O(1)$ to answer a test case, so the total time complexity is $O(nlogn + t)$.
|
[
"greedy",
"math",
"number theory"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 100;
vector<int> min_div(N);
void solve() {
int n, m;
cin >> n >> m;
cout << (n == 1 || min_div[n] > m ? "YES" : "NO") << '\n';
}
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
for (int d = 2; d * d < N; ++d) {
if (min_div[d] == 0) {
min_div[d] = d;
for (int i = d * d; i < N; i += d) {
if (min_div[i] == 0) {
min_div[i] = d;
}
}
}
}
for (int i = 1; i < N; ++i) {
if (min_div[i] == 0) {
min_div[i] = i;
}
}
int t;
cin >> t;
while (t--) solve();
return 0;
}
|
1826
|
D
|
Running Miles
|
There is a street with $n$ sights, with sight number $i$ being $i$ miles from the beginning of the street. Sight number $i$ has beauty $b_i$. You want to start your morning jog $l$ miles and end it $r$ miles from the beginning of the street. By the time you run, you will see sights you run by (including sights at $l$ and $r$ miles from the start). You are interested in the $3$ most beautiful sights along your jog, but every mile you run, you get more and more tired.
So choose $l$ and $r$, such that there are at least $3$ sights you run by, and the sum of beauties of the $3$ most beautiful sights minus the distance in miles you have to run is maximized. More formally, choose $l$ and $r$, such that $b_{i_1} + b_{i_2} + b_{i_3} - (r - l)$ is maximum possible, where $i_1, i_2, i_3$ are the indices of the three maximum elements in range $[l, r]$.
|
There is a fairly straightforward solution using DP, but I'll leave that for the comment section and present a very short and simple solution. First we need to notice, that at two of the maximums are at the ends of $[l, r]$, otherwise we can move one of the boundaries closer to the other and improve the answer. Using this observation we can reduce the problem to the following: choose three indices $l < m < r$, such that $b_l + b_m + b_r - (r - l)$ is maximum. Now, let's iterate over the middle index $m$ and rewrite the function as $b_m + (b_l + l) + (b_r - r)$. We can see, that values in the braces are pretty much independent - on of them depends only on the index $l$ and the second one depends only on the index $r$. So, for a given $m$ we can choose the numbers $l$ and $r$ greedily! To make it fast enough we can precalculate the prefix maximum for the array $b_l + l$ and the suffix maximum for array $b_r - r$. This results in a $O(n)$ time complexity solution.
|
[
"brute force",
"dp",
"greedy"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> b(n);
for (auto &i : b) cin >> i;
vector<int> pref_mx(n), suff_mx(n);
for (int i = 0; i < n; ++i) {
pref_mx[i] = b[i] + i;
suff_mx[i] = b[i] - i;
}
for (int i = 1; i < n; ++i) {
pref_mx[i] = max(pref_mx[i], pref_mx[i - 1]);
}
for (int i = n - 2; i >= 0; --i) {
suff_mx[i] = max(suff_mx[i], suff_mx[i + 1]);
}
int ans = 0;
for (int m = 1; m < n - 1; ++m) {
ans = max(ans, b[m] + pref_mx[m - 1] + suff_mx[m + 1]);
}
cout << ans << '\n';
}
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int t;
cin >> t;
while (t--) solve();
return 0;
}
|
1826
|
E
|
Walk the Runway
|
A fashion tour consists of $m$ identical runway shows in different cities. There are $n$ models willing to participate in the tour, numbered from $1$ to $n$. People in different cities have different views on the fashion industry, so they rate each model differently. In particular, people in city $i$ rate model $j$ with rating $r_{i, j}$.
You are to choose some number of $k$ models, and their order, let the chosen models have indices $j_1, j_2, \dots, j_k$ in the chosen order. In each city, these $k$ models will walk the runway one after another in this order. To make the show exciting, in each city, the ratings of models should be strictly increasing in the order of their performance. More formally, for any city $i$ and index $t$ ($2 \leq t \leq k$), the ratings must satisfy $r_{i,j_{t - 1}} < r_{i,j_t}$.
After all, the fashion industry is all about money, so choosing model $j$ to participate in the tour profits you $p_j$ money. Compute the maximum total profit you can make by choosing the models and their order while satisfying all the requirements.
|
At first, let's define the relation between two models, that go one after another in the show. Their ratings must satisfy $r_{i, j} < r_{i, k}$ for all cities $i$. Now let's precompute this relations for all pairs of models naively in $O(n^2m)$, which is ok for now. Now, we have the relations "model $i$ can go before model $j$", let's build a graph of such relations. This graph has no cycles, since the ratings are strictly increasing. Now we can build the topological sorting of this graph and compute $dp_i =$ the biggest profit, if the last model is model $i$ in $O(n^2)$. Now, how to calculate this relation for all pairs of models fast enough? Let's process each city one by one and update the relations using bitsets! More formally, let's store a bitset of all the models, that can be before model $j$ in city $i$. If we process the models in order of increasing rating, we can update each models bitset of relations in $O(\frac{n}{64})$, so the total time complexity would be $O(\frac{n^2m}{64})$, which is fast enough.
|
[
"bitmasks",
"brute force",
"data structures",
"dp",
"graphs",
"implementation",
"sortings"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using bs = bitset<5000>;
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int m, n;
cin >> m >> n;
vector<ll> c(n);
for (auto &i : c) {
cin >> i;
}
vector<int> ind(n);
iota(ind.begin(), ind.end(), 0);
bs can_bs;
for (int i = 0; i < n; ++i) {
can_bs[i] = true;
}
vector<bs> can(n, can_bs);
for (int d = 0; d < m; ++d) {
vector<int> r(n);
for (auto &r : r) {
cin >> r;
}
sort(ind.begin(), ind.end(), [&](int i, int j) {
return r[i] < r[j];
});
bs prev;
for (int i = 0; i < n; ) {
int j = i;
while (j < n && r[ind[j]] == r[ind[i]]) {
can[ind[j]] &= prev;
++j;
}
while (i < j) {
prev[ind[i]] = true;
++i;
}
}
}
vector<ll> dp = c;
for (auto i : ind) {
for (int j = 0; j < n; ++j) {
if (can[i][j]) {
dp[i] = max(dp[i], c[i] + dp[j]);
}
}
}
cout << *max_element(dp.begin(), dp.end()) << '\n';
return 0;
}
|
1826
|
F
|
Fading into Fog
|
\textbf{This is an interactive problem.}
There are $n$ distinct hidden points with real coordinates on a two-dimensional Euclidean plane. In one query, you can ask some line $ax + by + c = 0$ and get the projections of all $n$ points to this line in some order. The given projections are not exact, please read the interaction section for more clarity.
Using the minimum number of queries, guess all $n$ points and output them in some order. Here minimality means the minimum number of queries required to solve any possible test case with $n$ points.
The hidden points are fixed in advance and do not change throughout the interaction. In other words, the interactor is not adaptive.
A projection of point $A$ to line $ax + by + c = 0$ is the point on the line closest to $A$.
|
At first let's query two non-parallel lines. In this general case building perpendicular lines from projections and intersecting them will give us $O(n^2)$ candidates for the answer. This gives us the intuition, that 2 queries isn't enough. Also, the constraint from the statement suggests, that asking $x = 0$ and $y = 0$ will guarantee, that no two candidates are closer, than $1$ from each other, which will come in handy later. Now let's prove we can solve the problem in 3 queries. Indeed, there will always some space between the candidates. A simple proof of that would go something like this: there are $O(n^2)$ candidates and $O(n^4)$ pairs of candidates; now we can sort the directional vectors by the angle, and there will be at least one angle of at least $\frac{2\pi}{O(n^4)}$ between some two neighbouring vectors by the pigeonhole principle, which is big enough. One way to choose such a line is by queriying random lines, till we find a good enough one, or query some constant amount of lines and choose the one with the biggest distance. Checking one line can be done in $O(n^2logn)$ with a simple sort. How many exactly do we need is an exercise to the reader, but it can be proven, that under the given constraints this number is $O(1)$. Now, when we have the line, let's query it and check all the candidates in $O(n^3)$ or $O(n^2logn)$ or even $O(n^2)$. It doesn't really affect the runtime. The total complexity is $O(n^2logn)$ per testcase.
|
[
"geometry",
"interactive",
"math",
"probabilities"
] | 2,800
|
#pragma GCC optimize("O3", "unroll-loops")
#pragma GCC target("sse4.2")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <ext/random>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using graph = vector<vector<int>>;
const ld eps = 1e-9;
const int mod = 1000000007;
const ll inf = 3000000000000000007ll;
#define pb push_back
#define pf push_front
#define popb pop_back
#define popf pop_front
#define f first
#define s second
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define by_key(...) [](const auto &a, const auto &b) { return a.__VA_ARGS__ < b.__VA_ARGS__; }
#ifdef DEBUG
__gnu_cxx::sfmt19937 gen(857204);
#else
__gnu_cxx::sfmt19937 gen(int(chrono::high_resolution_clock::now().time_since_epoch().count()));
#endif
template<class T, class U> inline bool chmin(T &x, const U& y) { return y < x ? x = y, 1 : 0; }
template<class T, class U> inline bool chmax(T &x, const U& y) { return y > x ? x = y, 1 : 0; }
template<class T> inline int sz(const T &a) { return a.size(); }
template<class T> inline void sort(T &a) { sort(all(a)); }
template<class T> inline void rsort(T &a) { sort(rall(a)); }
template<class T> inline void reverse(T &a) { reverse(all(a)); }
template<class T> inline T sorted(T a) { sort(a); return a; }
struct InitIO {
InitIO() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout << fixed << setprecision(12);
}
~InitIO() {
#ifdef DEBUG
cerr << "Runtime is: " << clock() * 1.0 / CLOCKS_PER_SEC << endl;
#endif
}
} Initter;
void flush() { cout << flush; }
void flushln() { cout << endl; }
void println() { cout << '\n'; }
template<class T> void print(const T &x) { cout << x; }
template<class T> void read(T &x) { cin >> x; }
template<class T, class ...U> void read(T &x, U& ... u) { read(x); read(u...); }
template<class T, class ...U> void print(const T &x, const U& ... u) { print(x); print(u...); }
template<class T, class ...U> void println(const T &x, const U& ... u) { print(x); println(u...); }
template<class T, class U> inline istream& operator>>(istream& str, pair<T, U> &p) { return str >> p.f >> p.s; }
template<class T> inline istream& operator>>(istream& str, vector<T> &a) { for (auto &i : a) str >> i; return str; }
#ifdef DEBUG
namespace TypeTraits {
template<class T> constexpr bool IsString = false;
template<> constexpr bool IsString<string> = true;
template<class T, class = void> struct IsIterableStruct : false_type{};
template<class T>
struct IsIterableStruct<
T,
void_t<
decltype(begin(declval<T>())),
decltype(end(declval<T>()))
>
> : true_type{};
template<class T> constexpr bool IsIterable = IsIterableStruct<T>::value;
template<class T> constexpr bool NonStringIterable = !IsString<T> && IsIterable<T>;
template<class T> constexpr bool DoubleIterable = IsIterable<decltype(*begin(declval<T>()))>;
};
// Declaration (for cross-recursion)
template<class T>
auto pdbg(const T&x) -> enable_if_t<!TypeTraits::NonStringIterable<T>, string>;
string pdbg(const string &x);
template<class T>
auto pdbg(const T &x) -> enable_if_t<TypeTraits::NonStringIterable<T>, string>;
template<class T, class U>
string pdbg(const pair<T, U> &x);
// Implementation
template<class T>
auto pdbg(const T &x) -> enable_if_t<!TypeTraits::NonStringIterable<T>, string> {
stringstream ss;
ss << x;
return ss.str();
}
template<class T, class U>
string pdbg(const pair<T, U> &x) {
return "{" + pdbg(x.f) + "," + pdbg(x.s) + "}";
}
string pdbg(const string &x) {
return "\"" + x + "\"";
}
template<class T>
auto pdbg(const T &x) -> enable_if_t<TypeTraits::NonStringIterable<T>, string> {
auto begin = x.begin();
auto end = x.end();
string del = "";
if (TypeTraits::DoubleIterable<T>) {
del = "\n";
}
string ans;
ans += "{" + del;
if (begin != end) ans += pdbg(*begin++);
while (begin != end) {
ans += "," + del + pdbg(*begin++);
}
ans += del + "}";
return ans;
}
template<class T> string dbgout(const T &x) { return pdbg(x); }
template<class T, class... U>
string dbgout(T const &t, const U &... u) {
string ans = pdbg(t);
ans += ", ";
ans += dbgout(u...);
return ans;
}
#define dbg(...) print("[", #__VA_ARGS__, "] = ", dbgout(__VA_ARGS__)), flushln()
#define msg(...) print("[", __VA_ARGS__, "]"), flushln()
#else
#define dbg(...) 0
#define msg(...) 0
#endif
bool eq(ld a, ld b) { return abs(a - b) < eps; }
struct vec {
ld x, y;
vec() {}
vec(ld x, ld y) { this->x = x; this->y = y; }
vec operator+=(const vec &v) { x += v.x; y += v.y; return *this; }
vec operator-=(const vec &v) { x -= v.x; y -= v.y; return *this; }
vec operator*=(ld k) { x *= k; y *= k; return *this; }
vec operator/=(ld k) { x /= k; y /= k; return *this; }
vec operator-() const { return vec(-x, -y); }
vec orth() const { return vec(-y, x); }
ld len2() const { return x * x + y * y; }
ld len() const { return sqrt(len2()); }
friend vec operator+(vec a, const vec &b) { return a += b; }
friend vec operator-(vec a, const vec &b) { return a -= b; }
friend vec operator*(vec a, const ld &k) { return a *= k; }
friend vec operator/(vec a, const ld &k) { return a /= k; }
friend ld operator*(const vec &a, const vec &b) { return a.x * b.x + a.y * b.y; }
friend ld operator/(const vec &a, const vec &b) { return a.x * b.y - a.y * b.x; }
vec rot(ld sina, ld cosa) { return orth() * sina + *this * cosa; }
vec rot(ld alpha) { return rot(sin(alpha), cos(alpha)); }
friend istream& operator>>(istream& str, vec &v) { return str >> v.x >> v.y; }
friend ostream& operator<<(ostream& str, const vec &v) { return str << v.x << ' ' << v.y; }
friend bool operator==(const vec &a, const vec &b) { return eq(a.x, b.x) && eq(a.y, b.y); }
friend bool operator!=(const vec &a, const vec &b) { return !(a == b); }
friend bool operator<(const vec &a, const vec &b) { return (eq(a.x, b.x) ? a.y < b.y : a.x < b.x); }
};
int n;
vector<vec> query(ld a, ld b, ld c) {
println("? ", a, ' ', b, ' ', c);
flush();
vector<vec> ans(n);
read(ans);
return ans;
}
ld rand(ld a, ld b) {
uniform_real_distribution<ld> uni(a, b);
return uni(gen);
}
void solve() {
read(n);
vector<ld> xs, ys;
for (auto [x, _] : query(0, 1, 0)) {
xs.pb(x);
}
for (auto [_, y] : query(1, 0, 0)) {
ys.pb(y);
}
ld a, b;
vec dir;
static const ld NOISE = 1e-4;
while (true) {
ld angle = rand(0, 3.1415);
a = sin(angle), b = cos(angle);
dir = vec(-b, a);
vector<vec> pt;
for (auto x : xs) {
for (auto y : ys) {
pt.pb(dir * (dir * vec(x, y)));
}
}
bool flag = true;
sort(pt);
for (int i = 0; i + 1 < sz(pt); ++i) {
if ((pt[i + 1] - pt[i]).len() < 6 * NOISE) {
flag = false;
break;
}
}
if (flag) {
break;
}
}
auto pr = query(a, b, 0);
vector<vec> ans;
for (auto x : xs) {
for (auto y : ys) {
vec check = dir * (dir * vec(x, y));
bool flag = false;
for (auto p : pr) {
if ((p - check).len() < 3 * NOISE) {
flag = true;
}
}
if (flag) {
ans.pb({x, y});
}
}
}
print("! ");
for (auto p : ans) print(p, ' ');
flushln();
}
signed main() {
int t;
read(t);
while (t--) solve();
return 0;
}
|
1827
|
A
|
Counting Orders
|
You are given two arrays $a$ and $b$ each consisting of $n$ integers. All elements of $a$ are pairwise distinct.
Find the number of ways to reorder $a$ such that $a_i > b_i$ for all $1 \le i \le n$, modulo $10^9 + 7$.
Two ways of reordering are considered different if the resulting arrays are different.
|
Sort the array $b$, and fix the values from $a_n$ to $a_1$. First, we can sort the array $b$, as it does not change the answer. Let's try to choose the values of $a$ from $a_n$ to $a_1$. How many ways are there to choose the value of $a_i$? The new $a_i$ must satisfies $a_i > b_i$. But some of the candidates are already chosen as $a_j$ for some $j > i$. However, since $a_j > b_j \ge b_i$, we know that there are exactly $(n - i)$ candidates already chosen previously by all values of $j > i$. So, there are (number of $k$ such that $a_k > b_i$) $- (n - i)$ ways to choose the value of $a_i$. We can use two pointers or binary search to efficiently find the (number of $k$ such that $a_k > b_i$) for all $i$. Time complexity: $\mathcal O(n \log n)$.
|
[
"combinatorics",
"math",
"sortings",
"two pointers"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
struct testcase{
testcase(){
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);
for (int i=0; i<n; i++) cin >> b[i];
sort(b.begin(), b.end(), greater<>());
ll result = 1;
for (int i=0; i<n; i++){
int geq_count = a.size() - (upper_bound(a.begin(), a.end(), b[i]) - a.begin());
result = result * max(geq_count - i, 0) % MOD;
}
cout << result << "\n";
}
};
signed main(){
cin.tie(0)->sync_with_stdio(0);
int t; cin >> t;
while (t--) testcase();
}
|
1827
|
B2
|
Range Sorting (Hard Version)
|
\textbf{The only difference between this problem and the easy version is the constraints on $t$ and $n$.}
You are given an array $a$, consisting of $n$ distinct integers $a_1, a_2, \ldots, a_n$.
Define the beauty of an array $p_1, p_2, \ldots p_k$ as the minimum amount of time needed to sort this array using an arbitrary number of range-sort operations. In each range-sort operation, you will do the following:
- Choose two integers $l$ and $r$ ($1 \le l < r \le k$).
- Sort the subarray $p_l, p_{l + 1}, \ldots, p_r$ in $r - l$ seconds.
Please calculate the sum of beauty over all subarrays of array $a$.
A subarray of an array is defined as a sequence of consecutive elements of the array.
|
What is the minimum cost to sort just one subarray? What happens when two operations intersect each other? When can we sort two adjacency ranges independently? Try to calculate the contribution of each position. Let $a[l..r]$ denotes the subarray $a_l,a_{l+1},\ldots,a_r$. Observation 1: In an optimal sequence of operations for one subarray, there will be no two operations that intersect each other. In other words, a subarray will be divided into non-overlapping subarrays, and we will apply a range-sort operation to each subarray. Proof: Suppose there are two operations $[l_1,r_1]$ and $[l_2,r_2]$ that intersect each other, we can replace them with one operation $[\min(l_1,l_2),\max(r_1,r_2)]$ which does not increase the cost. Observation 2: Consider $k$ positions $l\le i_1<i_2<\ldots < i_k < r$, then we can sort subarrays $a[l..i_1],$ $a[i_1+1..i_2],$ $\ldots,$ $a[i_k+1..r]$ independently iff $\max(a[l..i_x])<\min(a[i_x+1..r])$ for all $1\le x\le k$. Proof: The obvious necessary and sufficient condition required to sort subarrays $a[l..i_1],$ $a[i_1+1..i_2],$ $\ldots,$ $a[i_k+1..r]$ independently is $\max(a[i_{x-1}+1..i_x])<\min(a[i_x+1..i_{x+1}])$ for all $1\le x\le k$, here we denote $x_0=l-1$ and $x_{k+1}=r$. It is not hard to prove that this condition is equal to the one stated above. With these observations, we can conclude that the answer for a subarray $a[l..r]$ equals the $r-l$ minus the number of positions $k$ such that $l\le k\lt r$ and $\max(a[l..k])<\min(a[k+1..r])$ $(*)$. Let us analyze how to calculate the sum of this value over all possible $l$ and $r$. Consider a position $i$ ($1\le i\le n$), let's count how many triplets $(l, k, r)$ satisfy $(*)$ and $min(a[k+1..r]) = a_i$. It means that $k$ must be the closest position to the left of $i$ satisfying $a_k<a_i$. Denotes $x$ as the closest position to the left of $k$ such that $a_x>a_i$, and $y$ as the closest position to the right of $i$ such that $a_y<a_i$. We can see that a triplet $(l, k, r)$ with $x<l\le k$ and $i\le r<y$ will match our condition. In other words, we will add to the answer $(k - x) \cdot (y - i)$. In the easy version, we can find such values of $x, k, y$ for each $i$ in $\mathcal{O}(n)$ and end up with a total complexity of $O(n^2)$. We can further optimize the algorithm by using sparse table and binary lifting and achieve a time complexity of $\mathcal{O}(n \log{n})$, which is enough to solve the hard version. There is an $\mathcal{O}(n)$ solution described here. Solve the problem when the beauty of an array is (minimum time needed to sort)$^2$.
|
[
"binary search",
"data structures",
"dp",
"greedy"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n;
int a[N];
pair <int, int> b[N];
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int tests; cin >> tests; while (tests--){
cin >> n;
for (int i = 1; i <= n; i++){
cin >> a[i];
}
for (int i = 1; i <= n; i++){
b[i] = make_pair(a[i], i);
}
sort(b + 1, b + n + 1);
set <int> sttlo = {0, n + 1}, stthi = {0, n + 1};
for (int i = 1; i <= n; i++){
stthi.emplace(i);
}
long long ans = 0;
for (int len = 1; len <= n; len++){
ans += (long long)(len - 1) * (n - len + 1);
}
for (int i = 1; i <= n; i++){
int idx = b[i].se;
stthi.erase(idx); sttlo.emplace(idx);
int x2 = *stthi.lower_bound(idx);
int x1 = *prev(stthi.lower_bound(idx));
if (x2 == n + 1){
continue;
}
int x3 = *sttlo.lower_bound(x2);
ans -= (long long)(idx - x1) * (x3 - x2);
}
cout << ans << endl;
}
}
|
1827
|
C
|
Palindrome Partition
|
A substring is a continuous and non-empty segment of letters from a given string, without any reorders.
An even palindrome is a string that reads the same backward as forward and has an even length. For example, strings "zz", "abba", "abccba" are even palindromes, but strings "codeforces", "reality", "aba", "c" are not.
A beautiful string is an even palindrome or a string that can be partitioned into some smaller even palindromes.
You are given a string $s$, consisting of $n$ lowercase Latin letters. Count the number of \textbf{beautiful substrings} of $s$.
|
Try to construct beautiful string greedily. What happens when we have two even palindromes share one of their endpoints? For the simplicity of the solution, we will abbreviate even palindrome as evp. Lemma: Consider a beautiful string $t$, we can find the unique maximal partition for it by greedily choosing the smallest possible evp in each step from the left. Here maximal means maximum number of parts. Proof: Suppose $t[0..l)$ is smallest prefix which is an evp and $t[0..r)$ is the first part in the partition of $t$, here $t[l..r)$ mean substring $t_l t_{l+1}\ldots t_{r-1}$. We consider two cases: $2l\le r$: In this case, it is clear that $t[0..l)$, $t[l..r - l)$ and $t[r-l..r)$ are evps, so we can replace $t[0..r)$ with them. $2l>r$: In this case, due to the fact that $t[r-l..l)$ and $t[0..l)$ are evps, $t[0..2l-r)$ is also an evp, which contradicts to above assumption that $t[0..l)$ is the smallest. We can use dynamic programming to solve this problem. Let $dp_i$ be the number of beautiful substrings starting at $i$. For all $i$ from $n-1$ to $0$, if there are such $next_i$ satisfying $s[i..next_i)$ is the smallest evp beginning at $i$, then $dp_i=dp_{next_i}+1$, otherwise $dp_i=0$. The answer will be the sum of $dp_i$ from $0$ to $n-1$. To calculate the $next$ array, first, we use Manacher algorithm or hashing to find the maximum $pal_i$ satisfying $s[i-pal_i..i+pal_i)$ is an evp for each $i$. Then for all $0\le i< n$, $next_i=2j-i$ where $j$ is smallest position such that $i<j$ and $j-pal_j\le i$. The time complexity is $\mathcal{O}(n \log{n})$. Solve the problem in $\mathcal{O}(n)$.
|
[
"binary search",
"brute force",
"data structures",
"dp",
"hashing",
"strings"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
const int LOG = 19;
int n, pal[N], rmq[LOG][N], cnt[N];
string s;
int main() {
cin.tie(0)->sync_with_stdio(0);
int t; cin >> t;
while (t--) {
cin >> n >> s;
for (int i = 0, l = 0, r = 0; i < n; i++) {
pal[i] = i >= r ? 0 : min(pal[l + r - i], r - i);
while (i + pal[i] < n && i - pal[i] - 1 >= 0
&& s[i + pal[i]] == s[i - pal[i] - 1]) pal[i]++;
if (i + pal[i] > r) {
l = i - pal[i]; r = i + pal[i];
}
}
for (int i = 0; i < n; i++)
rmq[0][i] = i - pal[i];
for (int k = 1; k < LOG; k++)
for (int i = 0; i + (1 << k) <= n; i++)
rmq[k][i] = min(rmq[k - 1][i],
rmq[k - 1][i + (1 << (k - 1))]);
for (int i = 1; i <= n; i++)
cnt[i] = 0;
for (int i = 0; i < n; i++) {
int j = i + 1;
for (int k = LOG - 1; k >= 0; k--)
if (j + (1 << k) <= n && rmq[k][j] > i)
j += 1 << k;
if (2 * j - i <= n)
cnt[2 * j - i] += cnt[i] + 1;
}
long long res = 0;
for (int i = 1; i <= n; i++)
res += cnt[i];
cout << res << '\n';
}
}
|
1827
|
D
|
Two Centroids
|
You are given a tree (an undirected connected acyclic graph) which initially only contains vertex $1$. There will be several queries to the given tree. In the $i$-th query, vertex $i + 1$ will appear and be connected to vertex $p_i$ ($1 \le p_i \le i$).
After each query, please find out the least number of operations required to make the current tree has \textbf{two} centroids. In one operation, you can add \textbf{one} vertex and \textbf{one} edge to the tree such that it remains a tree.
A vertex is called a centroid if its removal splits the tree into subtrees with at most $\lfloor \frac{n}{2} \rfloor$ vertices each, with $n$ as the number of vertices of the tree. For example, the centroid of the following tree is $3$ because the biggest subtree after removing the centroid has $2$ vertices.
In the next tree, vertex $1$ and $2$ are both centroids.
|
Is the answer related to the centroid of the current tree? How much the centroid will move after one query? Observation: The answer for the tree with $n$ vertices equals $n-2\cdot mx$ where $mx$ is the largest subtree among the centroid's children. Lemma: After one query, the centroid will move at most one edge, and when the centroid move, the tree before the query already has two centroids. Proof: Suppose the tree before the query has $n$ vertices and the current centroid is $u$. Let $v_1, v_2,\ldots,v_k$ are the children of $u$ and the next query vertex $x$ is in subtree $v_1$. Clearly, the centroid is either $u$ or in the subtree $v_1$. Consider the latter case, because the size of subtree $v_1$ does not greater than $\lfloor \frac{n}{2}\rfloor$, the size of newly formed subtree including $u$ is greater or equal to $\lceil \frac{n}{2}\rceil$. Moving one or more edges away from $v_1$ will increase the size of this new subtree by one or more, and the vertex can not become centroid because $\lceil \frac{n}{2}\rceil+1>\lfloor \frac{n+1}{2}\rfloor$. The second part is easy to deduce from the above proof. We will solve this problem offline. First, we compute the Euler tour of the final tree and use "range add query" data structures like Binary indexed tree (BIT) or Segment tree to maintain each subtree's size. We will maintain the size of the largest subtree among the centroid's children $mx$. In the case where the centroid does not move, we just update $mx$ with the size of the subtree including the newly added vertex, otherwise, we set $mx$ to $\lfloor \frac{n}{2}\rfloor$ due to the lemma. The time complexity is $\mathcal{O}(n \log{n})$.
|
[
"data structures",
"dfs and similar",
"greedy",
"trees"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
const int LOG = 19;
vector<int> adj[N];
int tin[N], tout[N], timer;
int par[LOG][N], bit[N], dep[N];
void dfs(int u) {
tin[u] = ++timer;
dep[u] = dep[par[0][u]] + 1;
for (int k = 1; k < LOG; k++)
par[k][u] = par[k - 1][par[k - 1][u]];
for (int v : adj[u]) dfs(v);
tout[u] = timer;
}
void add(int u) {
for (int i = tin[u]; i < N; i += i & -i)
bit[i]++;
}
int get(int u) {
int res = 0;
for (int i = tout[u]; i > 0; i -= i & -i)
res += bit[i];
for (int i = tin[u] - 1; i > 0; i -= i & -i)
res -= bit[i];
return res;
}
int jump(int u, int d) {
for (int k = 0; k < LOG; k++)
if (d >> k & 1) u = par[k][u];
return u;
}
bool cover(int u, int v) {
return tin[u] <= tin[v] && tin[v] <= tout[u];
}
void solve() {
int n; cin >> n;
/// reset
timer = 0;
for (int i = 1; i <= n; i++) {
bit[i] = 0; adj[i].clear();
}
for (int i = 2; i <= n; i++) {
cin >> par[0][i];
adj[par[0][i]].push_back(i);
}
dfs(1); add(1);
int cen = 1, max_siz = 0;
for (int u = 2; u <= n; u++) {
add(u);
if (cover(cen, u)) {
int v = jump(u, dep[u] - dep[cen] - 1);
int siz = get(v);
if (siz >= (u + 1) / 2) {
cen = v; max_siz = u / 2;
} else max_siz = max(max_siz, siz);
} else {
int siz = get(cen);
if (siz < (u + 1) / 2) {
cen = par[0][cen]; max_siz = u / 2;
} else max_siz = max(max_siz, u - siz);
}
cout << u - 2 * max_siz << " \n"[u == n];
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int t; cin >> t;
while (t--) solve();
}
|
1827
|
E
|
Bus Routes
|
There is a country consisting of $n$ cities and $n - 1$ bidirectional roads connecting them such that we can travel between any two cities using these roads. In other words, these cities and roads form a tree.
There are $m$ bus routes connecting the cities together. A bus route between city $x$ and city $y$ allows you to travel between any two cities in the simple path between $x$ and $y$ with this route.
Determine if for every pair of cities $u$ and $v$, you can travel from $u$ to $v$ using at most two bus routes.
|
You do not need to consider all pairs of nodes, only some of them will do. Find an equivalent condition of the statement. Let $S(u)$ be the set of all nodes reachable by u using at most one route. Consider all $S(l)$ where $l$ is a leaf in the tree. First, notice that for a pair of nodes $(u, v)$ such that $u$ is not a leaf, we can find a leaf $l$ such that path $(l, v)$ fully covers path $(u, v)$. Therefore, we only need to care about whether all pairs of leaves can reach each other using at most $2$ routes. Lemma The condition above is equivalent to: There exists a node $c$ such that $c$ can reach all leaves by using at most one route. Proof The necessity part is trivial, so let's prove the sufficiency part. Let the leaves of the tree be $l_1, l_2, \ldots, l_m$. Let $S(u)$ be the induced subgraph of all nodes reachable by $u$ using at most one route. If $u$ and $v$ is reachable within two routes, then the intersection of $S(v)$ and $S(u)$ is non-empty. We need to prove that the intersection of all $S(l_i)$ is non-empty. If $l_i$, $l_j$, and $l_k$ are pairwise reachable within two paths, then the intersection of $S(l_i)$, $S(l_j)$, and $S(l_k)$ must be pairwise non-empty. Since the graph is a tree, it follows trivially that intersection of $S(l_i)$, $S(l_j)$, and $S(l_k)$ must be non-empty. We can generalize this to all leaves, thus proving the sufficiency part. To check if an answer exists or not, we can use this trick from ko_osaga to find how many $S(l_i)$ covers each node in $\mathcal O(n)$. The answer is YES when there is a node $c$ that is covered by all $S(l_i)$. To find the two candidates when the answer is NO, notice that one of them is the first leaf $l_x$ such that there is no node $c$ that is covered by $S(l_1), \ldots, S(l_x)$. We can find $l_x$ with binary search. To find the other one, root the tree at $l_x$ and define $lift_u$ as the lowest node reachable by $u$ using at most one route. The other candidate is a node $l_y$ such that $lift_{l_y}$ is not in $S(l_x)$. Time complexity: $\mathcal O(n \log n)$. Tester's solution: Root the tree at some non-leaf vertex. Define $lift_u$ as the lowest node (minimum depth) reachable by $u$ using at most one route. Take the node $v$ with the deepest (maximum depth) $lift_v$. Then the answer for this problem is $\texttt{YES}$ iff for every leaf $l$, either $l$ lie in $lift_v$ 's subtree or $l$ has a path to $lift_v$.
|
[
"binary search",
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | 3,400
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const int maxn = 2e6 + 10;
const int mod = 1e9 + 7;
const int mo = 998244353;
using pi = pair < ll, ll > ;
using vi = vector < ll > ;
using pii = pair < pair < ll, ll > , ll > ;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
vector < int > G[maxn];
int n, m;
int h[maxn];
int eu[maxn];
pair < int, int > rmq[maxn][21];
int l = 0;
int st[maxn];
int out[maxn];
int low[maxn];
pair < int, int > ed[maxn];
int par[maxn];
int ok[maxn];
int d[maxn];
void dfs(int u, int pa) {
eu[++l] = u;
st[u] = l;
for (auto v: G[u]) {
if (v == pa) continue;
par[v] = u;
h[v] = h[u] + 1;
dfs(v, u);
eu[++l] = u;
}
out[u] = l;
}
void init() {
for (int j = 1; (1 << j) <= l; j++) {
for (int i = 1; i <= l; i++) {
rmq[i][j] = min(rmq[i][j - 1], rmq[i + (1 << (j - 1))][j - 1]);
}
}
}
int LCA(int u, int v) {
if (st[u] > st[v]) {
swap(u, v);
}
int k = log2(st[v] - st[u] + 1);
return min(rmq[st[u]][k], rmq[st[v] - (1 << k) + 1][k]).second;
}
bool check(int u, int pa, int c) {
if (st[pa] <= st[c] && st[c] <= out[pa]) {
if (st[c] <= st[u] && st[u] <= out[c]) {
return true;
}
return false;
}
return false;
}
void solve() {
cin >> n >> m;
l = 0;
for (int i = 1; i <= n; i++) {
G[i].clear();
}
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
dfs(1, -1);
for (int i = 1; i <= l; i++) {
rmq[i][0] = {st[eu[i]], eu[i]};
}
init();
for (int i = 1; i <= n; i++) {
low[i] = i;
ok[i] = 0;
}
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
ed[i] = {x, y};
int u = LCA(x, y);
if (h[low[x]] > h[u]) {
low[x] = u;
}
if (h[low[y]] > h[u]) {
low[y] = u;
}
}
int need = 0;
for (int i = 2; i <= n; i++) {
if (low[i] != 1 && G[i].size() == 1) {
if (need == 0 || h[low[need]] < h[low[i]]) {
need = i;
}
}
}
if (need == 0) {
cout << "YES\n";
return;
}
for (int i = 1; i <= m; i++) {
int u = LCA(ed[i].first, ed[i].second);
if (G[ed[i].first].size() == 1 && check(ed[i].second, u, low[need])) {
ok[ed[i].first] = 1;
}
if (G[ed[i].second].size() == 1 && check(ed[i].first, u, low[need])) {
ok[ed[i].second] = 1;
}
}
for (int i = 1; i <= n; i++) {
if (G[i].size() == 1) {
if (st[low[need]] <= st[i] && st[i] <= out[low[need]]) {
continue;
}
if (ok[i] == 0) {
cout << "NO\n";
cout << need << " " << i << "\n";
return;
}
}
}
cout << "YES\n";
return;
}
signed main() {
cin.tie(0), cout.tie(0) -> sync_with_stdio(0);
int t;
cin >> t;
while (t--) solve();
return 0;
}
|
1827
|
F
|
Copium Permutation
|
You are given a permutation $a_1,a_2,\ldots,a_n$ of the first $n$ positive integers. A subarray $[l,r]$ is called copium if we can rearrange it so that it becomes a sequence of consecutive integers, or more formally, if $$\max(a_l,a_{l+1},\ldots,a_r)-\min(a_l,a_{l+1},\ldots,a_r)=r-l$$ For each $k$ in the range $[0,n]$, print out the \textbf{maximum} number of copium subarrays of $a$ over all ways of rearranging the last $n-k$ elements of $a$.
|
Call the last $n-k$ elements as special numbers. Observation: In optimal rearrangement, every maximal segment of special numbers will be placed on consecutive positions in either ascending order or descending order. For simplicity, from now on we will call maximal segment of special number as maximal segment. For example, take a permutation $p=[7, 5, 8, 1, 4, 2, 6, 3]$ and $k=2$, the maximal segments are $[1, 4]$, $[6, 6]$ and $[8, 8]$. We divide the set of copium subarrays into three parts, one for those lie entirely on prefix $p[1..k]$, one for those lie entirely on suffix $p[k+1..n]$, and one for the rest. The number of subarrays in the first part can be calculated with the algorithm used in 526F - Pudding Monsters. The number of subarrays in the second part can be easily deduced from above observation. Define an array $good=[good_1,good_2,\ldots,good_m]$ such that for each $i$: $good_i<good_{i+1}$ and subarray $p[good_i..k]$ contains consecutive nonspecial numbers. For example, take a permutation $p=[1, 5, 4,3,7,8,9,2,10,6]$ and $k=5$, then $good=[1, 4, 5]$. We will process $good$ array from right to left while adding special numbers from left to right. Let us consider $good_i$, first add all special numbers which are missing from subarray $[good_i, k]$ at the end of current permutation. If $[good_i, k]$ is not already copium, we increase our answer by one. Denote $mn_i$ and $mx_i$ as the minimum and maximum number in subarray $[good_i, k]$. Loot at two maximal segments, one contains $mn_i-1$ and one contains $mx_i+1$. We can place them here to increase the answer. For example, let $n=10$, $k=5$, $good_i=3$ and the current permutation $p=[1, 10, 4, 5, 7, 6]$. The two maximal segments are $[2, 3]$ and $[8, 9]$. We can place them like $[1, 10, 4, 5, 7, 6, 8, 9, 3, 2]$ to increase the answer by 4. Furthermore, we can see that three good positions $3$, $4$ and $5$ benefit from maximal segment $[8, 9]$. In general, consider consecutive good positions $good_i, good_{i+1},\ldots, good_j$ satisfying $mx_i=mx_{i+1}=\ldots=mx_j$, all of them can benefit from the same maximal segment if for all $i\le x< j$, subarray $[good_x..good_{x+1}-1]$ is copium $(*)$. There is a similar condition when we consider consecutive good positions having the same $mn$. So the algorithm goes like this: For each value of $mn$ and $mx$, find the longest segment of good positions satisfying condition $(*)$, then multiply with the length of corresponding maximal segment and add to the answer. We will calculate the answer for each $k$ from $0$ to $n$ in this order. We will store the longest segment for each prefix of $mn$-equivalent and $mx$-equivalent positions. Note that when going from $k-1$ to $k$, only a suffix of $good$ will no longer be good, so we can manually delete them one by one from right to left, then add $k$. There will be at most $2$ good positions we need to consider. The first one, of course, is $k$. If $p_{k-1}<p_k$ or $p_{k-1}>p_k$, let $j$ be the last position satisfying $p_j>p_k$ or $p_j<p_k$, the second one is the first good position after $j$ and it satisfies a property: It must be the last position in the $mn$-equivalent or $mx$-equivalent positions. The proof is left as an exercise. Therefore, updating this position will not affect the positions behind it. The overall complexity is $\mathcal{O}(n\log n)$.
|
[
"constructive algorithms",
"data structures",
"greedy"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 200005;
const int LOG = 18;
int n, a[N], pos[N];
int lef[N], rig[N];
vector<int> st_max, st_min;
void connect(int x, int y) {
rig[x] = y; lef[y] = x;
}
struct range_min {
vector<int> spt[LOG];
void build() {
for (int k = 0; k < LOG; k++)
spt[k].resize(n + 1);
for (int i = 1; i <= n; i++)
spt[0][i] = pos[i];
for (int k = 1; k < LOG; k++)
for (int i = 1; i + (1 << k) <= n + 1; i++) {
spt[k][i] = min(spt[k - 1][i],
spt[k - 1][i + (1 << (k - 1))]);
}
}
int get_min_pos(int l, int r) {
int k = __lg(r - l + 1);
return min(spt[k][l], spt[k][r - (1 << k) + 1]);
}
} rmq;
int get_min(int i) {
return a[*lower_bound(st_min.begin(), st_min.end(), i)];
}
int get_max(int i) {
return a[*lower_bound(st_max.begin(), st_max.end(), i)];
}
struct segtree1 {
#define il i * 2
#define ir i * 2 + 1
struct node {
int val, cnt, tag;
};
node tree[N * 4];
void build(int i, int l, int r) {
tree[i] = {l, 1, 0};
if (l < r) {
int m = (l + r) / 2;
build(il, l, m);
build(ir, m + 1, r);
}
}
void add(int i, int l, int r, int x, int y, int v) {
if (l >= x && r <= y) {
tree[i].val += v; tree[i].tag += v; return;
}
int m = (l + r) / 2;
if (m >= x) add(il, l, m, x, y, v);
if (m < y) add(ir, m + 1, r, x, y, v);
tree[i].val = tree[il].val;
tree[i].cnt = tree[il].cnt;
if (tree[i].val > tree[ir].val) {
tree[i].val = tree[ir].val;
tree[i].cnt = tree[ir].cnt;
} else if (tree[i].val == tree[ir].val)
tree[i].cnt += tree[ir].cnt;
tree[i].val += tree[i].tag;
}
#undef il
#undef ir
} seg1;
struct copium {
int curr, maxx, type;
copium() {}
copium(int curr, int maxx, int type):
curr(curr), maxx(max(maxx, curr)), type(type) {}
};
copium lmin[N], lmax[N];
ll prefix, middle, suffix;
/// cancer
void calc(int i, int j, bool recalc) {
int imin = get_min(i), imax = get_max(i);
int jmin = get_min(j), jmax = get_max(j);
int type;
if (recalc) {
middle -= 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);
middle -= 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);
}
if (imax == jmax) {
if (!recalc)
middle -= 1ll * lmax[i].maxx * (rig[imax] - imax - 1);
if (jmin - imin == j - i) type = 0;
else if (imin + j - i == lef[jmin] + 1) type = 1;
else type = 2;
if (type == 2) lmax[j] = copium(1, lmax[i].maxx, type);
else if (lmax[i].type == 0)
lmax[j] = copium(lmax[i].curr + 1, lmax[i].maxx, type);
else lmax[j] = copium(2, lmax[i].maxx, type);
} else lmax[j] = {1, 1, 3};
if (imin == jmin) {
if (!recalc)
middle -= 1ll * lmin[i].maxx * (imin - lef[imin] - 1);
if (imax - jmax == j - i) type = 0;
else if (imax + i - j == rig[jmax] - 1) type = 1;
else type = 2;
if (type == 2) lmin[j] = copium(1, lmin[i].maxx, type);
else if (lmin[i].type == 0)
lmin[j] = copium(lmin[i].curr + 1, lmin[i].maxx, type);
else lmin[j] = copium(2, lmin[i].maxx, type);
} else lmin[j] = {1, 1, 3};
middle += 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);
middle += 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int t; cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i]; pos[a[i]] = i;
lef[i] = rig[i] = 0;
}
st_min.assign(1, 0);
st_max.assign(1, 0);
set<int> sorted;
sorted.insert(0);
sorted.insert(n + 1);
prefix = 0;
suffix = 1ll * n * (n + 1) / 2;
middle = 0;
// k = 0
cout << suffix << ' ';
lef[n] = 0; rig[0] = n;
seg1.build(1, 1, n); rmq.build();
vector<int> good;
for (int i = 1; i <= n; i++) {
while (good.size()) {
int j = good.back();
int jmin = get_min(j), jmax = get_max(j);
if (rmq.get_min_pos(min(jmin, a[i]), max(jmax, a[i])) < j) {
middle -= 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);
middle -= 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);
good.pop_back();
if (good.size()) {
if (lmax[j].type < 3)
middle += 1ll * lmax[good.back()].maxx * (rig[jmax] - jmax - 1);
if (lmin[j].type < 3)
middle += 1ll * lmin[good.back()].maxx * (jmin - lef[jmin] - 1);
}
} else break;
}
if (good.size()) {
int j = good.back();
int jmin = get_min(j), jmax = get_max(j);
middle -= 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);
middle -= 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);
}
auto it = sorted.upper_bound(a[i]);
suffix -= 1ll * (*it - a[i]) * (a[i] - *prev(it));
connect(*prev(it), a[i]); connect(a[i], *it);
sorted.insert(a[i]);
while (st_max.size() > 1 && a[st_max.back()] < a[i]) {
seg1.add(1, 1, n, st_max[st_max.size() - 2] + 1,
st_max.back(), a[i] - a[st_max.back()]);
st_max.pop_back();
}
while (st_min.size() > 1 && a[st_min.back()] > a[i]) {
seg1.add(1, 1, n, st_min[st_min.size() - 2] + 1,
st_min.back(), a[st_min.back()] - a[i]);
st_min.pop_back();
}
st_max.push_back(i); st_min.push_back(i);
if (good.size()) {
int j = good.back();
int jmin = get_min(j), jmax = get_max(j);
middle += 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);
middle += 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);
calc(j, i, 0);
} else {
lmax[i] = lmin[i] = {1, 1, 3};
middle += rig[a[i]] - lef[a[i]] - 2;
}
good.push_back(i);
if (st_min.size() >= 2) {
int k = upper_bound(good.begin(), good.end(),
st_min[st_min.size() - 2]) - good.begin();
if (k > 0 && k < good.size())
calc(good[k - 1], good[k], 1);
}
if (st_max.size() >= 2) {
int k = upper_bound(good.begin(), good.end(),
st_max[st_max.size() - 2]) - good.begin();
if (k > 0 && k < good.size())
calc(good[k - 1], good[k], 1);
}
cout << prefix + good.size() + middle + suffix << ' ';
prefix += seg1.tree[1].cnt;
}
cout << '\n';
}
}
|
1828
|
A
|
Divisible Array
|
You are given a positive integer $n$. Please find an array $a_1, a_2, \ldots, a_n$ that is perfect.
A perfect array $a_1, a_2, \ldots, a_n$ satisfies the following criteria:
- $1 \le a_i \le 1000$ for all $1 \le i \le n$.
- $a_i$ is divisible by $i$ for all $1 \le i \le n$.
- $a_1 + a_2 + \ldots + a_n$ is divisible by $n$.
|
Remember the sum of the first $n$ positive integers? Every positive integer is divisible by $1$. Consider the array $a = \left[1, 2, \ldots, n\right]$ that satisfies the second condition. It has the sum of $1 + 2 + \dots + n = \frac{n(n+1)}{2}$. One solution is to notice that if we double every element $(a=\left[2, 4, 6, \ldots, 2n\right])$, the sum becomes $\frac{n(n+1)}{2} \times 2 = n(n + 1)$, which is divisible by $n$. Another solution is to increase the value of $a_1$ until the sum becomes divisible by $n$. This works because every integer is divisible by $1$, and we only need to increase $a_1$ by at most $n$. Time complexity: $\mathcal{O}(n)$
|
[
"constructive algorithms",
"math"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
const int N=2e6+1;
const ll mod=998244353;
ll n,m;
ll a[N],b[N];
void solve(){
cin >> n;
ll s=0;
for(int i=n; i>=2 ;i--){
a[i]=i;
s=(s+i)%n;
}
a[1]=n-s;
for(int i=1; i<=n ;i++) cout << a[i] << ' ';
cout << '\n';
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int t;cin >> t;
while(t--){
solve();
}
}
|
1828
|
B
|
Permutation Swap
|
You are given an \textbf{unsorted} permutation $p_1, p_2, \ldots, p_n$. To sort the permutation, you choose a constant $k$ ($k \ge 1$) and do some operations on the permutation. In one operation, you can choose two integers $i$, $j$ ($1 \le j < i \le n$) such that $i - j = k$, then swap $p_i$ and $p_j$.
What is the \textbf{maximum} value of $k$ that you can choose to sort the given permutation?
A permutation 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).
An unsorted permutation $p$ is a permutation such that there is at least one position $i$ that satisfies $p_i \ne i$.
|
In order to move $p_i$ to its right position, what does the value of $k$ have to satisfy? In order to move $p_i$ to position $i$, it is easy to see that $|p_i - i|$ has to be divisible by $k$. So, $|p_1 - 1|, |p_2 - 2|, \ldots, |p_n - n|$ has to be all divisible by $k$. The largest possible value of $k$ turns out to be the greatest common divisor of integers $|p_1 - 1|, |p_2 - 2|, \ldots, |p_n - n|$. Time complexity: $\mathcal{O}(n + \log{n})$
|
[
"math",
"number theory"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int t;
cin >> t;
while (t--) {
int n, res = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
int x; cin >> x;
res = __gcd(res, abs(x - i));
}
cout << res << "\n";
}
}
|
1829
|
A
|
Love Story
|
Timur loves codeforces. That's why he has a string $s$ having length $10$ made containing only lowercase Latin letters. Timur wants to know how many indices string $s$ \textbf{differs} from the string "codeforces".
For example string $s =$ "{co\textbf{ol}for\textbf{s}e\textbf{z}}" differs from "codeforces" in $4$ indices, shown in bold.
Help Timur by finding the number of indices where string $s$ differs from "codeforces".
Note that you can't reorder the characters in the string $s$.
|
You need to implement what is written in the statement. You need to compare the given string $s$ with the string "codeforces" character by character, counting the number of differences. We know that the length of $s$ is $10$, so we can simply iterate through both strings and compare each character at the same index. If the characters are the same, we move on to the next index. If they are different, we count it as a difference and move on to the next index. Once we have compared all $10$ characters, we output the number of differences.
|
[
"implementation",
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
string s, c = "codeforces";
cin >> s;
int ans = 0;
for(int i = 0; i < 10; i++)
{
if(s[i] != c[i])
{
ans++;
}
}
cout << ans << endl;
}
int32_t main(){
int t = 1;
cin >> t;
while (t--) {
solve();
}
}
|
1829
|
B
|
Blank Space
|
You are given a binary array $a$ of $n$ elements, a binary array is an array consisting only of $0$s and $1$s.
A blank space is a segment of \textbf{consecutive} elements consisting of only $0$s.
Your task is to find the length of the longest blank space.
|
We can iterate through the array $a$ and keep track of the length of the current blank space. Whenever we encounter a $0$, we increase the length of the current blank space, and whenever we encounter a $1$, we check if the current blank space is longer than the previous longest blank space. If it is, we update the length of the longest blank space. Finally, we return the length of the longest blank space. The time complexity of this algorithm is $\mathcal{O}(n)$.
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
int a[n];
int cnt = 0, ans = 0;
for(int i = 0; i < n; i++)
{
cin >> a[i];
if(a[i] == 0)
{
cnt++;
}
else
{
ans = max(ans, cnt);
cnt = 0;
}
}
cout << max(ans, cnt) << endl;
}
int32_t main(){
int t = 1;
cin >> t;
while (t--) {
solve();
}
}
|
1829
|
C
|
Mr. Perfectly Fine
|
Victor wants to become "Mr. Perfectly Fine". For that, he needs to acquire a certain set of skills. More precisely, he has $2$ skills he needs to acquire.
Victor has $n$ books. Reading book $i$ takes him $m_i$ minutes and will give him some (possibly none) of the required two skills, represented by a binary string of length $2$.
What is the minimum amount of time required so that Victor acquires all of the two skills?
|
You can classify the books into four types "00", "01", "10", "11". We will take a book of any type at most once and wont take a book that learns a single skill if that skill is already learned, so there are only two cases to look at We take the shortest "01" and the the shortest "10". We take the shortest "11". Out of these options, output the shortest one.
|
[
"bitmasks",
"greedy",
"implementation"
] | 800
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
void solve() {
int n; cin >> n;
map<string, int> mp;
mp["00"] = mp["01"] = mp["10"] = mp["11"] = 1e9;
int ans = 1e9;
for(int i = 0; i < n; ++i) {
int x; cin >> x; string s; cin >> s;
mp[s] = min(mp[s], x);
}
if(min(mp["11"], mp["10"] + mp["01"]) > (int)1e6) {
cout << "-1\n";
} else {
cout << min(mp["11"], mp["10"] + mp["01"]) << "\n";
}
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
solve();
}
}
|
1829
|
D
|
Gold Rush
|
Initially you have a single pile with $n$ gold nuggets. In an operation you can do the following:
- Take any pile and split it into two piles, so that one of the resulting piles has exactly twice as many gold nuggets as the other. (All piles should have an integer number of nuggets.)
\begin{center}
{\small One possible move is to take a pile of size $6$ and split it into piles of sizes $2$ and $4$, which is valid since $4$ is twice as large as $2$.}
\end{center}
Can you make a pile with \textbf{exactly} $m$ gold nuggets using zero or more operations?
|
We can solve this problem recursively. Let the current pile have $n$ gold nuggets. If $n=m$, then we can make a pile with exactly $m$ gold nuggets by not doing any operations. If $n$ is not a multiple of $3$, then it is not possible to make a move, because after a move we split $n$ into $x$ and $2x$, so $n=x+2x=3x$ for some integer $x$, meaning $n$ has to be a multiple of $3$. Finally, if $n$ is a multiple of $3$, then we can split the pile into two piles with $\frac{n}{3}$ and $\frac{2n}{3}$ gold nuggets, and we can recursively check if we can make a pile with exactly $m$ gold nuggets. By the Master Theorem, the time complexity is $\mathcal{O}(n^{\log_32}) \approx \mathcal{O}(n^{0.631})$. Most compilers and languages optimize the recursion enough for this to pass comfortably. (The model solution in C++ runs in 15 milliseconds.)
|
[
"brute force",
"dfs and similar",
"dp",
"implementation"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
bool ok(int n, int m) {
if (n == m) {return true;}
else if (n % 3 != 0) {return false;}
else {return (ok(n / 3, m) || ok(2 * n / 3, m));}
}
void solve() {
int n, m;
cin >> n >> m;
cout << (ok(n, m) ? "YES" : "NO") << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1829
|
E
|
The Lakes
|
You are given an $n \times m$ grid $a$ of non-negative integers. The value $a_{i,j}$ represents the depth of water at the $i$-th row and $j$-th column.
A lake is a set of cells such that:
- each cell in the set has $a_{i,j} > 0$, and
- there exists a path between any pair of cells in the lake by going up, down, left, or right a number of times and without stepping on a cell with $a_{i,j} = 0$.
The volume of a lake is the sum of depths of all the cells in the lake.
Find the largest volume of a lake in the grid.
|
We can approach this problem using Depth First Search (DFS) or Breadth First Search (BFS) on the given grid. The idea is to consider each cell of the grid as a potential starting point for a lake, and explore all the cells reachable from it by only moving up, down, left or right, without stepping on any cell with depth $0$. If we reach a dead end, or a cell with depth $0$, we backtrack and try another direction. During this exploration, we keep track of the sum of depths of all the cells that we have visited. This sum gives us the volume of the current lake. When we have explored all the reachable cells from a starting point, we compare the volume of this lake with the maximum volume found so far, and update the maximum if necessary. To implement this approach, we can use a nested loop to iterate through all the cells of the grid. For each cell, we check if its depth is greater than $0$, and if it has not already been visited in a previous lake. If these conditions are satisfied, we start a DFS/BFS from this cell, and update the maximum volume found so far. See the implementation for more details. The time complexity is $\mathcal{O}(mn)$.
|
[
"dfs and similar",
"dsu",
"graphs",
"implementation"
] | 1,100
|
#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
using namespace std;
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define MOD 1000000007
#define MOD2 998244353
#define MX 1000000000
#define MXL 1000000000000000000
#define PI (ld)2*acos(0.0)
#define pb push_back
#define sc second
#define fr first
#define endl '\n'
#define ld long double
#define NO cout << "NO" << endl
#define YES cout << "YES" << endl
int n, m;
bool vis[1005][1005];
int a[1005][1005];
int dfs(int i, int j)
{
vis[i][j] = true;
int ans = a[i][j];
if(i != 0 && a[i-1][j] != 0 && !vis[i-1][j])
{
ans+=dfs(i-1, j);
}
if(i != n-1 && a[i+1][j] != 0 && !vis[i+1][j])
{
ans+=dfs(i+1, j);
}
if(j != 0 && a[i][j-1] != 0 && !vis[i][j-1])
{
ans+=dfs(i, j-1);
}
if(j != m-1 && a[i][j+1] != 0 && !vis[i][j+1])
{
ans+=dfs(i, j+1);
}
return ans;
}
void solve()
{
cin >> n >> m;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
vis[i][j] = false;
cin >> a[i][j];
}
}
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(!vis[i][j] && a[i][j] != 0)
{
ans = max(ans, dfs(i, j));
}
}
}
cout << ans << endl;
}
int32_t main(){
startt
int t = 1;
cin >> t;
while (t--) {
solve();
}
}
|
1829
|
F
|
Forever Winter
|
A snowflake graph is generated from two integers $x$ and $y$, both greater than $1$, as follows:
- Start with one central vertex.
- Connect $x$ new vertices to this central vertex.
- Connect $y$ new vertices to \textbf{each} of these $x$ vertices.
For example, below is a snowflake graph for $x=5$ and $y=3$. \begin{center}
{\small The snowflake graph above has a central vertex $15$, then $x=5$ vertices attached to it ($3$, $6$, $7$, $8$, and $20$), and then $y=3$ vertices attached to each of those.}
\end{center}
Given a snowflake graph, determine the values of $x$ and $y$.
|
The degree of a vertex is the number of vertices connected to it. We can count the degree of a vertex by seeing how many times it appears in the input. Let's count the degrees of the vertices in a snowflake graph. The starting vertex has degree $x$. Each of the $x$ newly-generated vertices has degree $y+1$ (they have $y$ new neighbors, along with the starting vertex). Each of the $x \times y$ newly-generated vertices has degree $1$ (they are only connected to the previous vertex). CountDegree$1$$x$$x$$y+1$$xy$$1$ However, there is an edge case. If $x=y+1$, then the first two rows combine: CountDegree$x+1$$x = y + 1$$xy$$1$ The time complexity is $\mathcal{O}(n+m)$ per test case.
|
[
"dfs and similar",
"graphs",
"math"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n, m;
cin >> n >> m;
int cnt[n + 1];
for (int i = 1; i <= n; i++) {
cnt[i] = 0;
}
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
cnt[u]++;
cnt[v]++;
}
map<int, int> cnts;
for (int i = 1; i <= n; i++) {
cnts[cnt[i]]++;
}
vector<int> v;
for (auto p : cnts) {
v.push_back(p.second);
}
sort(v.begin(), v.end());
if (v.size() == 3) {
cout << v[1] << ' ' << v[2] / v[1] << '\n';
}
else {
cout << v[0] - 1 << ' ' << v[1] / (v[0] - 1) << '\n';
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1829
|
G
|
Hits Different
|
In a carnival game, there is a huge pyramid of cans with $2023$ rows, numbered in a regular pattern as shown.
\begin{center}
{\small If can $9^2$ is hit initially, then all cans colored red in the picture above would fall.}
\end{center}
You throw a ball at the pyramid, and it hits a single can with number $n^2$. This causes all cans that are stacked on top of this can to fall (that is, can $n^2$ falls, then the cans directly above $n^2$ fall, then the cans directly above those cans, and so on). For example, the picture above shows the cans that would fall if can $9^2$ is hit.
What is the \textbf{sum} of the numbers on all cans that fall? Recall that $n^2 = n \times n$.
|
There are many solutions which involve going row by row and using some complicated math formulas, but here is a solution that requires no formulas and is much quicker to code. The cans are hard to deal with, but if we replace them with a different shape, a diamond, we get the following: To avoid finding the row and column, we can instead iterate through the cells in order $1, 2, 3, \dots$, that is, we go diagonal-by-diagonal in the grid above. Now, make a separate array $\texttt{ans}$, and keep track of the answer for each cell from $1$ to $10^6$ as we find its prefix sum. This avoids having to do any complicated math or binary search to find the row and column for the prefix sum. See the implementation for more details. The time complexity is $\mathcal{O}(n)$ precomputation with $\mathcal{O}(1)$ per test case.
|
[
"data structures",
"dp",
"implementation",
"math"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
long long ans[2000007];
long long a[1500][1500] = {}, curr = 1;
void solve() {
int n;
cin >> n;
cout << ans[n] << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
for (int i = 1; i < 1500; i++) {
for (int j = i - 1; j >= 1; j--) {
a[j][i - j] = a[j - 1][i - j] + a[j][i - j - 1] - a[j - 1][i - j - 1] + curr * curr;
ans[curr] = a[j][i - j];
curr++;
}
}
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1829
|
H
|
Don't Blame Me
|
Sadly, the problem setter couldn't think of an interesting story, thus he just asks you to solve the following problem.
Given an array $a$ consisting of $n$ positive integers, count the number of \textbf{non-empty} subsequences for which the bitwise $\mathsf{AND}$ of the elements in the subsequence has exactly $k$ set bits in its binary representation. The answer may be large, so output it modulo $10^9+7$.
Recall that the subsequence of an array $a$ is a sequence that can be obtained from $a$ by removing some (possibly, zero) elements. For example, $[1, 2, 3]$, $[3]$, $[1, 3]$ are subsequences of $[1, 2, 3]$, but $[3, 2]$ and $[4, 5, 6]$ are not.
Note that $\mathsf{AND}$ represents the bitwise AND operation.
|
We can notice that the numbers are pretty small (up to $63$) and the AND values will be up to $63$ as well. Thus, we can count the number of subsequences that have AND value equal to $x$ for all $x$ from $0$ to $63$. We can do this using dynamic programming. Let's denote $dp_{ij}$ as the number of subsequences using the first $i$ elements that have a total AND value of $j$. The transitions are quite simple. We can iterate over all $j$ values obtained previously and update the values respectively: We have three cases: The first case is when we don't use the $i$-th value. Here we just update the $dp_{ij}$ in the following way: $dp[i][j] = dp[i][j] + dp[i - 1][j]$. The second case is when we use the $i$-th value. Here we update the $dp[i][a[i] \text{&} j]$ in the following way: $dp[i][a[i] \text{&} j] = dp[i][a[i] \text{&} j] + dp[i - 1][j]$. The third case is starting a new subsequence with just the $i$-th element. Thus, we update $dp[i][a[i]] = dp[i][a[i]] + 1$.
|
[
"bitmasks",
"combinatorics",
"dp",
"math"
] | 1,700
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
const int mod = 1e9 + 7;
void solve() {
int n, x; cin >> n >> x;
vector<int> a(n + 1);
vector<vector<int>> dp(n + 1, vector<int>(1 << 6, 0));
for(int i = 1; i <= n; ++i) {
cin >> a[i];
for(int mask = 0; mask < (1 << 6); ++mask) {
dp[i][mask] += dp[i - 1][mask];
if(dp[i][mask] >= mod) dp[i][mask] -= mod;
dp[i][mask & a[i]] += dp[i - 1][mask];
if(dp[i][mask & a[i]] >= mod) dp[i][mask & a[i]] -= mod;
}
dp[i][a[i]] = (dp[i][a[i]] + 1) % mod;
}
int ans = 0;
for(int mask = 0; mask < (1 << 6); ++mask) {
if(__builtin_popcount(mask) == x) {
ans = (ans + dp[n][mask]) % mod;
}
}
cout << ans << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
solve();
}
}
|
1830
|
A
|
Copil Copac Draws Trees
|
Copil Copac is given a list of $n-1$ edges describing a tree of $n$ vertices. He decides to draw it using the following algorithm:
- Step $0$: Draws the first vertex (vertex $1$). Go to step $1$.
- Step $1$: For every edge in the input, in order: if the edge connects an already drawn vertex $u$ to an undrawn vertex $v$, he will draw the undrawn vertex $v$ and the edge. After checking every edge, go to step $2$.
- Step $2$: If all the vertices are drawn, terminate the algorithm. Else, go to step $1$.
The number of readings is defined as the number of times Copil Copac performs step $1$.
Find the number of readings needed by Copil Copac to draw the tree.
|
What is the answer if $n=3$? The previous case can be generalised to find the answer for any tree. This problem can be solved via dynamic programming. From here on out, step $1$ from the statement will be called a "scan". Let $dp[i]$ be the number of scans needed to activate node $i$, and $id[i]$ be the index (in the order from the input) of the edge which activated node $i$. Intially, since only $1$ is active, $dp[1]=1$ and $id[1]=0$. We will perform a dfs traversal starting from node $1$. When we process an edge $(u,v)$, one of the following two cases can happen: If $index((u,v)) \ge id[u]$, we can visit $v$ in the same scan as $u$: $dp[v]=dp[u]$, $id[v]=index((u,v))$ If $index((u,v)) \lt id[u]$, $v$ will be visited in the next scan after $dp[u]$: $dp[v]=dp[u]+1$, $id[v]=index((u,v))$ The answer is $max_{i=1}^n(dp[i])$. Time complexity per test case: $O(n)$
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,400
|
#include <bits/stdc++.h>
const int NMAX = 3e5 + 5, INF = 1e9;
int n, f[NMAX], d[NMAX];
std :: vector < std :: pair < int, int > > G[NMAX];
void DFS(int node, int t) {
f[node] = true;
for (int i = 0; i < G[node].size(); ++ i) {
int u = G[node][i].first, c = G[node][i].second;
if (f[u] == false) {
d[u] = (c < t) + d[node];
DFS(u, c);
}
}
return;
}
int main() {
std :: ios_base :: sync_with_stdio(false);
std :: cin.tie(nullptr);
int tc;
std :: cin >> tc;
while (tc --) {
std :: cin >> n;
for (int i = 1, u, v; i < n; ++ i) {
std :: cin >> u >> v;
G[u].push_back({v, i});
G[v].push_back({u, i});
}
for (int i = 1; i <= n; ++ i)
f[i] = false;
d[1] = 0;
DFS(1, n);
int Max = 0;
for (int i = 1; i <= n; ++ i)
Max = std :: max(Max, d[i]);
std :: cout << Max << "\n";
for (int i = 1; i <= n; ++ i)
G[i].clear();
}
return 0;
}
|
1830
|
B
|
The BOSS Can Count Pairs
|
You are given two arrays $a$ and $b$, both of length $n$.
Your task is to count the number of pairs of integers $(i,j)$ such that $1 \leq i < j \leq n$ and $a_i \cdot a_j = b_i+b_j$.
|
Since $b_i \le n$ and $b_j \le n$, $b_i+b_j = a_i \cdot a_j \le 2 \cdot n$. Since $a_i \cdot a_j \le 2 \cdot n$, then $\min(a_i,a_j) \le \sqrt{2 \cdot n}$. Since $b_i \le n$ and $b_j \le n$, $b_i+b_j = a_i \cdot a_j \le 2 \cdot n$. Therefore, $\min(a_i,a_j) \le \sqrt{2 \cdot n}$. Let $lim=\sqrt{2 \cdot n}$ and $fr[a_i][b_i]$ be the number of pairs $(a_i,b_i)$ from the input such that $a_i \le lim$. A pair $(i,j)$ is good if it satisfies $a_i \cdot a_j=b_i+b_j$. Firstly, we'll count the number of good pairs $(i,j)$ such that $a_i=a_j$. Since $min(a_i,a_j) \le lim$, we can see that $a_i=a_j \le lim$. This sum can be written as: $\frac{\sum_{i=1}^{n}fr[a_i][a_i \cdot a_i - b_i]-\sum_{i=1}^{lim}fr[i][\frac{i \cdot i}{2}]}{2}$ The remaining good pairs will have $a_i \neq a_j$, and instead of counting the pairs which have $i \lt j$, we can count the pairs which have $a_i \gt a_j$. Since $a_j=min(a_i,a_j)$, we can say that $a_j \le lim$. Substituting $a_j$ for $j$, this second sum can be written as: $\sum_{i=1}^n \sum_{j=1}^{min(a_i-1,\frac{2\cdot n}{a_i})}fr[j][a_i \cdot j-b_i]$ Since we've already established that $j \le lim = \sqrt{2 \cdot n}$, calculating this sum takes $O(n\sqrt{n})$ time. Be especially careful when calculating these sums, as $a_i \cdot a_i - b_i$ and $a_i \cdot j-b_i$ can end up being either negative or greater than $n$. Time complexity per testcase: $O(n \sqrt n)$
|
[
"brute force",
"math"
] | 2,000
|
for _ in range(int(input())):
n = int(input())
ta = list(map(int, input().split()))
tb = list(map(int, input().split()))
a = [(x, y) for x, y in zip(ta, tb)]
a.sort()
cnt = [0] * (2 * n + 1)
pr = 0
ans = 0
for i in range(n):
if pr != a[i][0]:
pr = a[i][0]
if pr * pr > 2 * n:
break
cnt = [0] * (2 * n + 1)
for j in range(i + 1, n):
t = a[i][0] * a[j][0] - a[j][1]
if t >= 0 and t <= 2 * n:
cnt[t] += 1
ans += cnt[a[i][1]]
if i + 1 < n:
t = a[i][0] * a[i + 1][0] - a[i + 1][1]
if t >= 0 and t <= 2 * n:
cnt[t] -= 1
print(ans)
|
1830
|
C
|
Hyperregular Bracket Strings
|
You are given an integer $n$ and $k$ intervals. The $i$-th interval is $[l_i,r_i]$ where $1 \leq l_i \leq r_i \leq n$.
Let us call a \textbf{regular} bracket sequence$^{\dagger,\ddagger}$ of length $n$ hyperregular if for each $i$ such that $1 \leq i \leq k$, the substring $\overline{s_{l_i} s_{l_{i}+1} \ldots s_{r_i}}$ is also a regular bracket sequence.
Your task is to count the number of hyperregular bracket sequences. Since this number can be really large, you are only required to find it modulo $998\,244\,353$.
$^\dagger$ A bracket sequence is a string containing only the characters "(" and ")".
$^\ddagger$ A bracket sequence is called regular if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), (()(())) and the empty string are regular, while )(, ((), and (()))( are not.
|
While not necessarily a hint, this problem cannot be solved without knowing that there are $C_n=\frac{1}{n+1}\binom{2n}{n}$ Regular Bracket Strings of length $2 \cdot n$. What's the answer if $q=1$? What's the answer if $q=2$ and the two intervals partially overlap? Based on the previous hint, we can get rid of all partially overlapping intervals. The remaining intervals will have a tree-like structure. Finding the tree is actually unnecessary and also very difficult. The brackets on the positions covered by the same subset of intervals must form an RBS. Hashing. Xor hashing specifically. First and foremost, the number of regular bracket strings of length $2 \cdot n$ is equal to $C_n=\frac{1}{n+1}\binom{2n}{n}$. Secondly, for a bracket string $\overline{s_1s_2 \ldots s_k}$, let: $f(s_i) = \begin{cases} 1, & \text{if }s_i=\text{'('} \\ -1, & \text{if }s_i=\text{')'} \end{cases}$ $\Delta_i=\sum_{j=1}^i f(s_j)$ A bracket string $\overline{s_1s_2 \ldots s_k}$ is a regular bracket string if both of the following statements are true: $\Delta_k=0$ $\Delta_k=0$ $\Delta_i \ge 0, i=\overline{1,k}$ $\Delta_i \ge 0, i=\overline{1,k}$ From now on we'll call a set of indices $i_1 < i_2 < \ldots < i_k$ a group if $\overline{s_{i_1}s_{i_2}\ldots s_{i_k}}$ must be an RBS. There are two main cases to consider, both of which can be proven with the aforementioned conditions for a string to be an RBS: Let's consider two intervals $[l_1,r_1]$ and $[l_2,r_2]$ such that $l_1 \le l_2 \le r_2 \le r_1$. The two groups formed by these intervals are: $[l_2,r_2]$ $[l_1,l_2-1] \cup [r_2+1,r_1]$ Let's consider two intervals $[l_1,r_1]$ and $[l_2,r_2]$ such that $l_1 \lt l_2 \le r_1 \lt r_2$. The three groups formed by these two intervals are: $[l_1,l_2-1]$ $[l_2,r_1]$ $[r_1+1,r_2]$ By taking both of these cases into account, we can conclude that all indices $i_k$ covered by the same subset of intervals are part of the same group. Finding the subset of intervals which cover a certain index $i$ can be implemented using difference arrays and xor hashing. Each interval $[l_i,r_i]$ will be assigned a random 64-bit value $v_i$. The value of a subset of intervals $i_1,i_2,\ldots,i_k$ is equal to $v_{i_1} \wedge v_{i_2} \wedge \ldots \wedge v_{i_k}$. For each interval $[l_i,r_i]$, $\text{diff}[l_i] \wedge = v_i$, $\text{diff}[r_i+1] \wedge = v_i$. The value of the subset of intervals which cover position $i$ is equal to $\text{diff}[1] \wedge \text{diff}[2] \wedge \ldots \wedge \text{diff}[i]$. Time complexity: $O(maxn \cdot log(mod))$ for precomputing every $C_n$, and $O(k\cdot log(k))$ per test case.
|
[
"combinatorics",
"greedy",
"hashing",
"math",
"number theory",
"sortings"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int NMAX=3e5+5, MOD=998244353;
mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());
uniform_int_distribution<ll> rnd(0,LLONG_MAX);
ll fact[NMAX], invfact[NMAX], C[NMAX];
ll binPow(ll x, ll y){
ll ans=1;
for(;y ;y>>=1, x = x*x%MOD)
if(y&1)
ans = ans*x%MOD;
return ans;
}
map<ll,ll> diff,freq;
void add_interval(ll l, ll r){
ll Hash = rnd(gen);
diff[l] ^= Hash, diff[r+1] ^= Hash;
}
void tc(){
ll n,k;
cin>>n>>k;
diff.clear(), freq.clear();
add_interval(1,n); /// the initial string must be an RBS
for(ll i=0;i<k;i++){
ll l,r;
cin>>l>>r;
add_interval(l,r);
}
ll Hash = diff[1];
for(map<ll,ll> :: iterator it=next(diff.begin()); it!=diff.end(); it++){
freq[Hash] += it->first - prev(it)->first;
Hash ^= it->second;
}
ll ans=1;
for(const auto& it : freq)
ans=ans*C[it.second]%MOD;
cout<<ans<<'\n';
}
int main()
{
fact[0] = invfact[0] = 1;
for(ll i=1; i<NMAX; i++){
fact[i] = fact[i-1] * i % MOD;
invfact[i] = binPow(fact[i], MOD - 2);
}
for(ll i=0; i*2<NMAX; i++) C[i*2] = fact[i*2] * invfact[i] % MOD * invfact[i+1] % MOD;
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
ll t;
cin>>t;
while(t--)
tc();
return 0;
}
|
1830
|
D
|
Mex Tree
|
You are given a tree with $n$ nodes. For each node, you either color it in $0$ or $1$.
The value of a path $(u,v)$ is equal to the MEX$^\dagger$ of the colors of the nodes from the shortest path between $u$ and $v$.
The value of a coloring is equal to the sum of values of all paths $(u,v)$ such that $1 \leq u \leq v \leq n$.
What is the maximum possible value of any coloring of the tree?
$^{\dagger}$ The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:
- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.
- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.
- The MEX of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.
|
Why is bipartite coloring not always optimal? How good is a bipartite coloring actually? Disclaimer: I ( tibinyte2006 ) wanted to cut $O(n \sqrt{n})$ memory because I thought that setting 1024 MB memory limit would spoil the solution. So only blame me for this. We will do a complementary problem which is finding the minimum loss of a coloring. The initial cost is the maximum possible cost, $n \cdot (n+1)$. If we analyze how good a bipartite coloring of the given tree is we can note that $loss \le 2 \cdot n$ Now suppose the tree has a connected component of size $k$. We can note that in such a coloring $loss \ge \frac{k \cdot (k+1)}{2}$ By the $2$ claims above, we can note that in an optimal coloring, the maximum size $k$ of a connected component respects $\frac{k \cdot (k+1)}{2} \le 2 \cdot n$. Thus we can safely say $k \le \sqrt{4 \cdot n}$. Now let $dp_{i,j,color}$ be the minimum loss if we color the subtree of $i$ and the connected component of vertex $i$ has size $j$. We can calculate this in a knapsack style by adding subtrees successively. The computation takes $O(n \cdot \sqrt{n})$ if we use the $7$-th trick from this blog. Now we are only left to optimize memory, since now it's $O(n \cdot \sqrt{n})$. We can directly apply this to get linear memory. However, the bound of $k \le \sqrt{4 \cdot n}$ is overestimated, for $n=200000$ it can be proven that the worst case for $k$ is $258$. Assume have a connected component of size $k$ we want it to be colored $0$ across all optimal colorings. Then we can attach to each node some subtrees such that after flipping its whole subtree the total cost doesn't increase. We will assume all subtrees are leaves for simplicity. Doing such, we can get some inequalities about the number of leaves we need to attatch to each node. In a star tree, the number of leaves we should attatch to nodes has the smallest sum.
|
[
"brute force",
"dp",
"trees"
] | 2,800
|
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int lim = 893;
const int inf = 1e16;
struct dp_state
{
vector<int> a;
vector<int> b;
void init()
{
a.resize(lim + 1, inf);
b.resize(lim + 1, inf);
a[1] = 1;
b[1] = 2;
}
};
int32_t main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int q;
cin >> q;
while (q--)
{
int n;
cin >> n;
vector<vector<int>> g(n + 1);
vector<int> sz(n + 1);
for (int i = 1; i < n; ++i)
{
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
function<int(int, int)> shuffle_kids = [&](int node, int parent)
{
int sz = 1;
pair<int, int> best;
for (int i = 0; i < (int)g[node].size(); ++i)
{
if (g[node][i] != parent)
{
int sz2 = shuffle_kids(g[node][i], node);
best = max(best, {sz2, i});
sz += sz2;
}
}
if (!g[node].empty())
{
swap(g[node][0], g[node][best.second]);
}
return sz;
};
shuffle_kids(1, 0);
vector<vector<int>> merged(2 * lim + 1, vector<int>(2, inf));
function<dp_state(int, int)> dfs = [&](int node, int parent)
{
dp_state dp;
sz[node] = 1;
bool hasinit = false;
for (auto i : g[node])
{
if (i != parent)
{
dp_state qui = dfs(i, node);
if (!hasinit)
{
dp.init();
hasinit = true;
}
for (int j = 0; j <= min(sz[node], lim) + min(sz[i], lim); ++j)
{
merged[j][0] = merged[j][1] = inf;
}
for (int k = 1; k <= min(sz[node], lim); ++k)
{
for (int l = 1; l <= min(sz[i], lim); ++l)
{
merged[k][0] = min(merged[k][0], dp.a[k] + qui.b[l]);
merged[k][1] = min(merged[k][1], dp.b[k] + qui.a[l]);
merged[k + l][0] = min(merged[k + l][0], dp.a[k] + qui.a[l] + k * l);
merged[k + l][1] = min(merged[k + l][1], dp.b[k] + qui.b[l] + k * l * 2);
}
}
sz[node] += sz[i];
for (int k = 1; k <= min(sz[node], lim); ++k)
{
dp.a[k] = merged[k][0];
dp.b[k] = merged[k][1];
}
}
}
if (!hasinit)
{
dp.init();
hasinit = true;
}
return dp;
};
dp_state dp = dfs(1, 0);
int ans = inf;
for (int i = 1; i <= lim; ++i)
{
ans = min(ans, dp.a[i]);
ans = min(ans, dp.b[i]);
}
cout << n * (n + 1) - ans << '\n';
}
}
|
1830
|
E
|
Bully Sort
|
On a permutation $p$ of length $n$, we define a bully swap as follows:
- Let $i$ be the index of the largest element $p_i$ such that $p_i \neq i$.
- Let $j$ be the index of the smallest element $p_j$ such that $i < j$.
- Swap $p_i$ and $p_j$.
We define $f(p)$ as the number of bully swaps we need to perform until $p$ becomes sorted. Note that if $p$ is the identity permutation, $f(p)=0$.
You are given $n$ and a permutation $p$ of length $n$. You need to process the following $q$ updates.
In each update, you are given two integers $x$ and $y$. You will swap $p_x$ and $p_y$ and then find the value of $f(p)$.
Note that the updates are persistent. Changes made to the permutation $p$ will apply when processing future updates.
|
First of all, we notice that if some element moves left, it will never move right. Proving this is not hard, imagine $S$ to be the set of suffix minimas. Then if an element is in $S$ we know that $p_x \le x$. Since after every bully swap an element cannot disappear from $S$ and after each bully swap, the $2$ swapped elements can only get closer to their desired position, we conclude the proof. Obviously, if an element moves right, it will never move left since it will continue to move right until it reaches its final position. By the $2$ claims above, we conclude that left and right movers are distinct. Now suppose we swap indicies $i$ and $j$ and note that such swap kills $2 \cdot (j-i) - 1$ inversions and the left mover $j$ moves $j-i$ steps. Now the magic is that if we let $s$ be the sum over $2 \cdot (i-p_i)$ for all left movers we have $s - ans = inversions$, thus our answer is just $s-inversions$. Now to handle the data structure part, we just need to be able to calculate inversions while being able to perform point updates. There are many ways to do this, for example for using a fenwick tree and a bitwise trie/ordered_set in $O(nlog^2n)$.
|
[
"data structures",
"math"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ii pair<int,int>
#define i4 tuple<int,int,int,int>
#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 pop_front
#define lb lower_bound
#define ub upper_bound
#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()
mt19937 rng(chrono::system_clock::now().time_since_epoch().count());
struct FEN{ //we want to count the reverse
int arr[500005];
void update(int i,int k){
i=500005-i;
while (i<500005){
arr[i]+=k;
i+=i&-i;
}
}
int query(int i){
i=500005-i;
int res=0;
while (i){
res+=arr[i];
i-=i&-i;
}
return res;
}
} fen;
int n,q;
int arr[500005];
long long ans[50005];
void dnc(int l,int r,vector<i4> upd,vector<i4> que){
vector<i4> updl,updr;
vector<i4> quel,quer;
int m=l+r>>1;
for (auto [a,b,c,d]:upd){
if (c<=m) updl.pub({a,b,c,d});
else updr.pub({a,b,c,d});
}
for (auto [a,b,c,d]:que){
if (c<=m) quel.pub({a,b,c,d});
else quer.pub({a,b,c,d});
}
int i=0;
for (auto it:quer){
while (i<sz(updl) && get<0>(updl[i])<get<0>(it)){
fen.update(get<1>(updl[i]),get<3>(updl[i]));
i++;
}
ans[get<2>(it)]+=fen.query(get<1>(it))*get<3>(it);
}
while (i){
i--;
fen.update(get<1>(updl[i]),-get<3>(updl[i]));
}
if (l!=m) dnc(l,m,updl,quel);
if (m+1!=r) dnc(m+1,r,updr,quer);
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin.exceptions(ios::badbit | ios::failbit);
cin>>n>>q;
rep(x,1,n+1) cin>>arr[x];
vector<i4> upd,que;
rep(x,1,n+1) upd.pub({x,arr[x],-1,1});
rep(x,1,n+1) que.pub({x,arr[x],0,-1});
rep(x,1,n+1) ans[0]+=abs(x-arr[x]);
rep(x,1,q+1){
int a,b;
cin>>a>>b;
if (a==b) continue;
if (arr[a]<arr[b]) ans[x]--;
else ans[x]++;
upd.pub({a,arr[a],x-1,-1});
upd.pub({b,arr[b],x-1,-1});
ans[x]-=abs(a-arr[a])+abs(b-arr[b]);
swap(arr[a],arr[b]);
upd.pub({a,arr[a],x,1});
upd.pub({b,arr[b],x,1});
ans[x]+=abs(a-arr[a])+abs(b-arr[b]);
que.pub({b,arr[b],x,-2});
que.pub({b,arr[a],x,2});
que.pub({a,arr[b],x,2});
que.pub({a,arr[a],x,-2});
}
sort(all(upd)),sort(all(que));
dnc(-1,q,upd,que);
rep(x,1,q+1) ans[x]+=ans[x-1];
rep(x,1,q+1) cout<<ans[x]<<" "; cout<<endl;
}
|
1830
|
F
|
The Third Grace
|
You are given $n$ intervals and $m$ points on the number line. The $i$-th intervals covers coordinates $[l_i,r_i]$ and the $i$-th point is on coordinate $i$ and has coefficient $p_i$.
Initially, all points are not activated. You should choose a subset of the $m$ points to activate. For each of $n$ interval, we define its cost as:
- $0$, if there are no activated points in the interval;
- the coefficient of the activated point with the \textbf{largest coordinate} within it, otherwise.
Your task is to maximize the sum of the costs of all intervals by choosing which points to activate.
|
Let $dp_i$ be the maximum sum of costs of activated points that are $< i$ over all states that has point $i$ activated. When we transition from $dp_i$ to $dp_j$, we need to add the cost contributed by point $i$. The number of ranges where point $i$ is the largest coordinate within it are the ranges $[l,r]$ which satisfy $l \leq i \leq r < j$. So we have $dp_j = \max\limits_{i < j}(dp_i + p_i \cdot S_{i,j})$ where $S_{i,j}$ is the number of ranges $[l,r]$ which satisfy $l \leq i \leq r < j$. Now, we note that $S_{i,j} z$ With some work, we can get calculate this $dp$ in $O(n^2)$. But this will be too slow, let's try to speed this up. Let us define $dp_{i,j} = \max\limits_{k \leq i}(dp_k + p_k \cdot S_{k,j})$. We have $dp_{j-1,j}=dp_j$. Our goal is to go from (implictly) storing $dp_{i,i+1},dp_{i,i+2},\ldots,dp_{i,n}$ to $dp_{i+1,i+2},dp_{i+1,i+3},\ldots,dp_{i+1,n}$. As $dp_i + p_i \cdot S_{i,j}$ looks like a linear function w.r.t. $S_{i,j}$, we can try to use convex hull data structures to maintain it. Let's figure out how $S_{i+1,j}$ relates to $S_{i,j}$. We need to subtract the number of ranges with $r=i$ and add the number of ranges with $l=i+1$ and $r < j$. This corresponds to $S_{i,*}$ and $S_{i+1,*}$ differing by amortized $O(1)$ suffix increment updates. Also, note that $S_{i,*}$ is non-decreasing. So we want to support the following data structure: Initially we have an arrays $A$ and $X$ that are both initially $0$. Handle the following updates: 1 m c $A_i \gets \max(A_i,m \cdot X_i + c)$ for all $i$ 2 j k $X_i \gets X_i + k$ for all $j \leq i$. It is guaranteed that $X$ will always be non-decreasing. 3 i find $A_i$ This can be maintained in a lichao tree in $O(log ^2)$ time. In each lichao node, we need to store $s,m,e$, the start, middle and end indices and their corresponding $X$ values $X_s,X_m,X_e$ respectively. This way, we can support operations $1$ and $3$ already. To support operation $2$, note that in a lichao tree, you can use $O(log^2)$ time to push down all lines that covers a certain point (refer to https://codeforces.com/blog/entry/86731). This way, all lines in the li chao tree are in $[1,j)$ or $[j,n]$, so you can do lazy updates on both the coordinates of the lines and the $X$ values. The time complexity is $O(n \log^2)$. There is another solution that works in $O(m \log^3)$ that we are unable to optimize further yet. Let us flip the array so that the condition is on the activated point with the smallest coordinate. Then we have $dp_j = \max\limits_{i < j}(dp_i + p_j \cdot S_{i,j})$ where $S_{i,j}$ counts the number of ranges $[l,r]$ such that $i< l \leq j \leq r$. Now, we want to store the linear function $dp_i + x \cdot S_{i,j}$ in some sort of data structure so that we can evaluate the maximum value with $x=p_j$. Unfortunately, the value of $S_{i,j}$ can change by suffix additions, similar to above. But since $S_{i,j}$ is non-increasing here, that means the optimal $i$ that maximizes $dp_i + x \cdot S_{i,j}$ decreases when $x$ increases. That is, for $l_1 \leq r_1< l_2 \leq r_2$ and we have two data structures that can get the maximum $f_j(x)=dp_i+x \cdot S_{i,j}$ for $l_j \leq i \leq r_j$ respectively. We can combine these $2$ data structures to make it for $[l_1,r_1] \cup [l_2,r_2]$ by binary searching the point $X$ where for all $x \leq X$, $f_1(x) \leq f_2(x)$ and for all $X \leq x,f_1(x) \geq f_2(x)$. Since querying this data structure takes $O(\log n)$, it takes $O(\log ^2)$ time to combine two such data structures. If we use a segment tree, we only need to rebuild $O(\log^3)$ different data structures (the rest can be handled using lazy tags), giving us a time complexity of $O(\log^3)$.
|
[
"data structures",
"dp"
] | 3,200
|
#include <bits/stdc++.h>
#define all(x) (x).begin(),(x).end()
using namespace std;
using ll = long long;
using ld = long double;
//#define int ll
#define sz(x) ((int)(x).size())
using pii = pair<ll,ll>;
using tii = tuple<int,int,int>;
const int nmax = 5e5 + 5, qmax = 2e6 + 5;
const ll inf = 1e18 + 5;
struct line {
ll m = 0, b = -inf;
ll operator()(const ll& x) const {
return m * x + b;
}
bool operator ==(const line& x) const { return m == x.m && b == x.b; }
};
int M;
namespace AINT {
struct Node {
int vl = 0, vmid = 0, vr = 0;
line val = line{0, -inf};
Node() {;}
void operator += (const int &x) { vl += x, vmid += x, vr += x; val.b -= val.m * x; }
} aint[qmax * 4];
int lazy[qmax * 4];
void push(int node) {
lazy[2 * node] += lazy[node];
aint[2 * node] += lazy[node];
lazy[2 * node + 1] += lazy[node];
aint[2 * node + 1] += lazy[node];
lazy[node] = 0;
}
void pushline(line x, int node = 1, int cl = 0, int cr = M) {
bool l = x(aint[node].vl) > aint[node].val(aint[node].vl), m = x(aint[node].vmid) > aint[node].val(aint[node].vmid), r = x(aint[node].vr) > aint[node].val(aint[node].vr);
if(m) swap(x, aint[node].val);
if(cl == cr || x == line() || l == r) return;
int mid = cl + cr >> 1;
push(node);
if(m != l) pushline(x, 2 * node, cl, mid);
else pushline(x, 2 * node + 1, mid + 1, cr);
return;
}
void add(int l, int node = 1, int cl = 0, int cr = M) {
if(cl >= l) {
lazy[node]++;
aint[node] += 1;
return;
}
if(cr < l) return;
int mid = cl + cr >> 1;
push(node);
pushline(aint[node].val, 2 * node, cl, mid);
pushline(aint[node].val, 2 * node + 1, mid + 1, cr);
aint[node].val = line{0, -inf};
add(l, 2 * node, cl, mid);
add(l, 2 * node + 1, mid + 1, cr);
aint[node].vl = aint[2 * node].vl;
aint[node].vmid = aint[2 * node].vr;
aint[node].vr = aint[2 * node + 1].vr;
}
pii query(ll p, int node = 1, int cl = 0, int cr = M) {
if(cl == cr) return pii{aint[node].val(aint[node].vl), aint[node].vl};
int mid = cl + cr >> 1;
push(node);
auto [mxv, atrv] = p <= mid? query(p, 2 * node, cl, mid) : query(p, 2 * node + 1, mid + 1, cr);
return pii{max(mxv, aint[node].val(atrv)), atrv};
}
void init(int node = 1, int cl = 0, int cr = M) {
aint[node] = Node();
lazy[node] = 0;
if(cl == cr) return;
int mid = cl + cr >> 1;
init(2 * node, cl, mid);
init(2 * node + 1, mid + 1, cr);
return;
}
};
vector<int> atraddp[qmax];
ll val[qmax];
void testcase() {
int n, m;
cin >> n >> m;
M = m + 2;
for(int i = 0, l, r; i < n; i++) {
cin >> l >> r;
atraddp[l].emplace_back(r + 1);
}
for(int i = 1; i <= m; i++)
cin >> val[i];
AINT::init();
AINT::pushline({0, 0});
for(int i = 0; i < m + 2; i++) {
for(auto x : atraddp[i])
AINT::add(x);
auto [a, b] = AINT::query(i);
//cerr << a << ' ' << b << '\n';
AINT::pushline({val[i], a - val[i] * b});
}
for(int i = 0; i < m + 2; i++)
atraddp[i].clear();
cout << AINT::query(m + 1).first << '\n';
}
signed main() {
cin.tie(0) -> sync_with_stdio(0);
int t;
cin >> t;
while(t--) testcase();
}
/**
Anul asta se da centroid.
-- Surse oficiale
*/
|
1831
|
A
|
Twin Permutations
|
You are given a permutation$^\dagger$ $a$ of length $n$.
Find any permutation $b$ of length $n$ such that $a_1+b_1 \le a_2+b_2 \le a_3+b_3 \le \ldots \le a_n+b_n$.
It can be proven that a permutation $b$ that satisfies the condition above always exists.
$^\dagger$ 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).
|
If $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Building on the idea from the first hint, can we build a permutation $b$ such that $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$? Since $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Therefore, any permutation $b$ which satisfies $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$ is a valid answer. If $b_i=n+1-a_i$, then: $b$ is a permutation; $a_1+b_1=a_2+b_2=\ldots=a_n+b_n=n+1$ Consequently, $b=[n+1-a_1,n+1-a_2,\ldots,n+1-a_i,\ldots,n+1-a_n]$ is a valid answer. Time complexity per test case : $O(N)$
|
[
"constructive algorithms"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void tc(){
ll n;
cin>>n;
for(ll i=0;i<n;i++){
ll x;
cin>>x;
cout<<n+1-x<<' ';
}
cout<<'\n';
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
ll t; cin>>t; while(t--)
tc();
return 0;
}
|
1831
|
B
|
Array merging
|
You are given two arrays $a$ and $b$ both of length $n$.
You will merge$^\dagger$ these arrays forming another array $c$ of length $2 \cdot n$. You have to find the maximum length of a subarray consisting of equal values across all arrays $c$ that could be obtained.
$^\dagger$ A merge of two arrays results in an array $c$ composed by successively taking the first element of either array (as long as that array is nonempty) and removing it. After this step, the element is appended to the back of $c$. We repeat this operation as long as we can (i.e. at least one array is nonempty).
|
When we merge two arrays $a$ and $b$, we can force the resulting array to have $[a_{l_1},a_{l_1+1},\ldots,a_{r_1},b_{l_2},b_{l_2+1},\ldots,b_{r_1}]$ as a subarray, for some $1 \le l_1 \le r_1 \le n$ and $1 \le l_2 \le r_2 \le n$. If $a_{l_1}=b_{l_1}$, then we can achieve a contiguous sequence of $(r_1-l_1+1)+(r_2-l_2+1)$ equal elements in the resulting array. Let $max_a(x)$ be the length of the longest subarray from $a$ containing only elements equal to $x$. If $x$ doesn't appear in $a$, then $max_a(x)=0$. Similarly, let $max_b(x)$ be the length of the longest subarray from $b$ containing only elements equal to $x$. If $x$ doesn't appear in $b$, then $max_b(x)=0$. $max_a$ and $max_b$ can be computed in $O(N)$ by scanning the array while updating current maximal subarray. When merging two arrays, it is possible to force a particular subarray $[a_{l_1},a_{l_1+1},\ldots,a_{r_1}]$ to be adjacent to another particular subarray $[b_{l_2},b_{l_2+1},\ldots,b_{r_2}]$ in the merged array. We can construct the merged array as follows: $[a_1,a_2,\ldots,a_{l_1-1}]+[b_1,b_2,\ldots,b_{l_2-1}]+[a_{l_1},a_{l_1+1},\ldots,a_{r_1},b_{l_2},b_{l_2+1},\ldots,b_{r_2}]+[\ldots]$ If $a_{l_1}=b_{l_2}$, then the merged array will have a subarray consisting of $(r_1-l_1+1)+(r_2-l_2+1)$ equal elements. Therefore, the answer is equal to: $max_{i=1}^{2 \cdot n}(max_a(i)+max_b(i))$ Time complexity per testcase: $O(N)$.
|
[
"constructive algorithms",
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int32_t main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int q;
cin >> q;
while (q--)
{
int n;
cin >> n;
vector<int> a(n + 1);
vector<int> b(n + 1);
for (int i = 1; i <= n; ++i)
{
cin >> a[i];
}
for (int i = 1; i <= n; ++i)
{
cin >> b[i];
}
vector<int> fa(n + n + 1);
vector<int> fb(n + n + 1);
int p = 1;
for (int i = 2; i <= n; ++i)
{
if (a[i] != a[i - 1])
{
fa[a[i - 1]] = max(fa[a[i - 1]], i - p);
p = i;
}
}
fa[a[n]] = max(fa[a[n]], n - p + 1);
p = 1;
for (int i = 2; i <= n; ++i)
{
if (b[i] != b[i - 1])
{
fb[b[i - 1]] = max(fb[b[i - 1]], i - p);
p = i;
}
}
fb[b[n]] = max(fb[b[n]], n - p + 1);
int ans = 0;
for (int i = 1; i <= n + n; ++i)
{
ans = max(ans, fa[i] + fb[i]);
}
cout << ans << '\n';
}
}
|
1832
|
A
|
New Palindrome
|
A palindrome is a string that reads the same from left to right as from right to left. For example, abacaba, aaaa, abba, racecar are palindromes.
You are given a string $s$ consisting of lowercase Latin letters. The string $s$ is a palindrome.
You have to check whether it is possible to rearrange the letters in it to get \textbf{another} palindrome (not equal to the given string $s$).
|
Let's look at the first $\left\lfloor\frac{|s|}{2}\right\rfloor$ characters. If all these characters are equal, then there is no way to get another palindrome. Otherwise, there are at least two different characters, you can swap them (and the characters symmetrical to them on the right half of the string), and get a palindrome different from the given one.
|
[
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
s = s.substr(0, s.size() / 2);
int k = unique(s.begin(), s.end()) - s.begin();
cout << (k == 1 ? "NO" : "YES") << '\n';
}
}
|
1832
|
B
|
Maximum Sum
|
You are given an array $a_1, a_2, \dots, a_n$, where all elements are different.
You have to perform \textbf{exactly} $k$ operations with it. During each operation, you do \textbf{exactly one} of the following two actions (you choose which to do yourself):
- find \textbf{two minimum elements} in the array, and delete them;
- find \textbf{the maximum element} in the array, and delete it.
You have to calculate the maximum possible sum of elements in the resulting array.
|
The first instinct is to implement a greedy solution which removes either two minimums or one maximum, according to which of the options removes elements with smaller sum. Unfortunately, this doesn't work even on the examples (hint to the participants of the round: if your solution gives a different answer on the examples, most probably you should try to find an error in your solution, not send messages to the author that their answers are definitely wrong). Okay, we need something other. Let's notice that the order of operations does not matter: deleting two minimums and then maximum is the same as choosing the other way around. So, we can iterate on the number of operations $m$ when we remove the two minimums; then the resulting array is the array $a$ from which we removed $2m$ minimums and $(k-m)$ maximums. How to quickly calculate the sum of remaining elements? First of all, sorting the original array $a$ won't hurt, since the minimums then will always be in the beginning of the array, and the maximums will be in the end. After the array $a$ is sorted, every operation either deletes two leftmost elements, or one rightmost element. So, if we remove $2m$ minimums and $(k-m)$ maximums, the elements that remain form the segment from the position $(2m+1)$ to the position $(n-(k-m))$ in the sorted array; and the sum on it can be computed in $O(1)$ with prefix sums. Time complexity: $O(n \log n)$.
|
[
"brute force",
"sortings",
"two pointers"
] | 1,100
|
for _ in range(int(input())):
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
ans = 0
pr = [0] * (n + 1)
for i in range(n):
pr[i + 1] = pr[i] + a[i]
for i in range(k + 1):
ans = max(ans, pr[n - (k - i)] - pr[2 * i])
print(ans)
|
1832
|
C
|
Contrast Value
|
For an array of integers $[a_1, a_2, \dots, a_n]$, let's call the value $|a_1-a_2|+|a_2-a_3|+\cdots+|a_{n-1}-a_n|$ the contrast of the array. Note that the contrast of an array of size $1$ is equal to $0$.
You are given an array of integers $a$. Your task is to build an array of $b$ in such a way that all the following conditions are met:
- $b$ is not empty, i.e there is at least one element;
- $b$ is a subsequence of $a$, i.e $b$ can be produced by deleting some elements from $a$ (maybe zero);
- the contrast of $b$ is equal to the contrast of $a$.
What is the minimum possible size of the array $b$?
|
Let's rephrase the problem in the following form: let the elements of the array be points on a coordinate line. Then the absolute difference between two adjacent elements of the array can be represented as the distance between two points, and the contrast of the entire array is equal to the total distance to visit all points in the given order. In this interpretation, it becomes obvious that removing any set of points does not increase contrast. Since the resulting contrast should be equal to the original one, we can only remove elements from the array that do not decrease the contrast. First of all, let's look at consecutive equal elements, it is obvious that you can delete all of them except one, and the contrast of the array will not change. In some languages, you can use a standard function to do this - for example, in C++ you can use unique. After that, let's look at such positions $i$ that $a_{i - 1} < a_i < a_{i + 1}$; you can delete the $i$-th element, because $|a_{i - 1} - a_i| + |a_i - a_{i + 1}| = |a_{i - 1} - a_{i + 1}|$. Similarly, for positions $i$, where $a_{i - 1} > a_i > a_{i + 1}$, the element can be removed. In all other cases, removing the element will decrease the contrast.
|
[
"greedy",
"implementation"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int& x : a) cin >> x;
n = unique(a.begin(), a.end()) - a.begin();
int ans = n;
for (int i = 0; i + 2 < n; ++i) {
ans -= (a[i] < a[i + 1] && a[i + 1] < a[i + 2]);
ans -= (a[i] > a[i + 1] && a[i + 1] > a[i + 2]);
}
cout << ans << '\n';
}
}
|
1832
|
D1
|
Red-Blue Operations (Easy Version)
|
\textbf{The only difference between easy and hard versions is the maximum values of $n$ and $q$}.
You are given an array, consisting of $n$ integers. Initially, all elements are red.
You can apply the following operation to the array multiple times. During the $i$-th operation, you select an element of the array; then:
- if the element is red, it increases by $i$ and becomes blue;
- if the element is blue, it decreases by $i$ and becomes red.
The operations are numbered from $1$, i. e. during the first operation some element is changed by $1$ and so on.
You are asked $q$ queries of the following form:
- given an integer $k$, what can the largest minimum in the array be if you apply \textbf{exactly} $k$ operations to it?
Note that the operations don't affect the array between queries, all queries are asked on the initial array $a$.
|
Let's try applying the operation to a single element multiple times. You can see that when you apply an operation an odd number of times, the element always gets larger. Alternatively, applying an operation an even amount of times always makes it smaller (or equal in case of $0$). Thus, generally, we would want to apply an odd number of operations to as many elements as we can. Let's start by investigating an easy case: $k \le n$. Since there are so few operations, you can avoid subtracting from any element at all. Just one operation to each of $k$ elements. Which elements should get this operation? Obviously, $k$ smallest elements. If you don't pick at least one of them, it'll remain as the minimum of the array. If you do, the minimum will get larger than any of them. Another greedy idea is where to apply each operation to. We should add $k$ to the minimum element, $k-1$ to the second minimum and so on. You can show that it is always optimal by contradiction. What if $k > n$? Then we have to subtract from some elements. First, recognize that there's no more than one element that will become smaller in the optimal answer. Consider an answer where at least two elements get smaller and move the later operation from one to another. Now both of them become larger. Moreover, for parity reasons, if $k \bmod 2 = n \bmod 2$, you can increase all elements. Otherwise, you have to decrease exactly one. Another greedy idea. You somewhat want the pair of operations (increase, decrease) to change the element as small as possible. In particular, you can always make the change equal to $-1$. To show it, you can look at some decreasing operation such that an increasing operation goes right before it and they are applied to different elements. You can swap them. They remain the same types. However, both elements get only larger. In the end, all adjacent increasing and decreasing operations go to the same element. Now, let's think of the answer as the following sequence: adjacent pairs of (increase, decrease) and the separate increase operations that are applied no more than once to each element. Since all blocks do $-1$, only the values in the lone increase operations affect the answer value. Obviously, we would want these lone increases to be $k, k - 1, \dots, k - t$, where $t$ is the number of changed elements ($n-1$ or $n$). Once again, you can show that you can always rearrange the operations to obtain that. Finally, the answer looks like this: add $k$ to the minimum, $k-1$ to the second minimum, $k - (n - (n + k) \bmod 2) - 1$ to the maximum or the second maximum depending on the parity. Before that, add $-1$ to some elements. Since we know where to apply the last operations, let's apply them first. Then we want to apply $-1$'s to make the minimum as large as possible. Well, we should always apply it to the current maximum. First, the minimum would remain as the original minimum. Then all elements will become equal to it at some point. Then we will be spreading the $-1$'s equally among the elements. So every $n$ additional operations, the minimum will be decreasing by $1$. For the easy version, you can simulate this process. Sort the array, apply the last increase operations, find the minimum and the sum of the array, then calculate the result based on that. Let $a' = [a_1 + k, a_2 + k - 1, \dots]$. Let $s = \sum_{i = 1}^n (a' - \min a')$. Then the first $s$ operations of $-1$ will not change the minimum. The rest $\frac{k - (n - (n - k) \bmod 2)}{2} - s$ operations will decrease it by $1$ every $n$ operations. So it will get decreased by $\left\lceil\frac{\max(0, \frac{k - (n - (n - k) \bmod 2)}{2} - s)}{n}\right\rceil$. Overall complexity: $O(n \cdot q \cdot \log n)$.
|
[
"binary search",
"greedy",
"implementation",
"math"
] | 2,100
| null |
1832
|
D2
|
Red-Blue Operations (Hard Version)
|
\textbf{The only difference between easy and hard versions is the maximum values of $n$ and $q$}.
You are given an array, consisting of $n$ integers. Initially, all elements are red.
You can apply the following operation to the array multiple times. During the $i$-th operation, you select an element of the array; then:
- if the element is red, it increases by $i$ and becomes blue;
- if the element is blue, it decreases by $i$ and becomes red.
The operations are numbered from $1$, i. e. during the first operation some element is changed by $1$ and so on.
You are asked $q$ queries of the following form:
- given an integer $k$, what can the largest minimum in the array be if you apply \textbf{exactly} $k$ operations to it?
Note that the operations don't affect the array between queries, all queries are asked on the initial array $a$.
|
Read the editorial to the easy version to get the general idea of the solution. Now, we should only optimize the calculations. First, the sorting can obviously be done beforehand. Now we want to get the minimum and the sum after applying the last increase operations. Consider $(n + k) \bmod 2 = 0$ and $k > n$, the other cases are similar. The minimum is that: $\min_{i=1}^n a_i - (i - 1) + k = k + \min_{i=1}^n a_i - (i - 1)$. Notice how the second part doesn't depend on $k$ and precalculate it. You can calculate prefix minimum array over $a'$. This surely helps with the case of $k < n$. The resulting minimum is $\min(\mathit{pref}_k + k, a_{k+1})$ (since $a$ is sorted, the first element after the changed prefix is the smallest). For $k \bmod 2 = n \bmod 2$, the minimum is $\mathit{pref}_n + k$. For $k \bmod 2 \neq n \bmod 2$, the minimum is $\min(\mathit{pref}_{n-1} + k, a_n)$. The sum is similar: $\sum_{i=1}^n a_i - (i - 1) + k = n \cdot k + \sum_{i=1}^n a_i - (i - 1)$. As easy to precalculate. The rest is the same. Overall complexity: $O(n \log n + q)$.
|
[
"binary search",
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 2,400
|
n, q = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
pr = [10**9 for i in range(n + 1)]
for i in range(n):
pr[i + 1] = min(pr[i], a[i] - i)
s = sum(a) - n * (n - 1) // 2
ans = []
for k in map(int, input().split()):
if k < n:
ans.append(min(pr[k] + k, a[k]))
continue
if k % 2 == n % 2:
ns = s - pr[n] * n
ans.append(pr[n] + k - (max(0, (k - n) // 2 - ns) + n - 1) // n)
else:
nmn = min(pr[n - 1], a[n - 1] - k)
ns = (s + (n - 1) - k) - nmn * n
ans.append(nmn + k - (max(0, (k - (n - 1)) // 2 - ns) + n - 1) // n)
print(*ans)
|
1832
|
E
|
Combinatorics Problem
|
Recall that the binomial coefficient $\binom{x}{y}$ is calculated as follows ($x$ and $y$ are non-negative integers):
- if $x < y$, then $\binom{x}{y} = 0$;
- otherwise, $\binom{x}{y} = \frac{x!}{y! \cdot (x-y)!}$.
You are given an array $a_1, a_2, \dots, a_n$ and an integer $k$. You have to calculate a new array $b_1, b_2, \dots, b_n$, where
- $b_1 = (\binom{1}{k} \cdot a_1) \bmod 998244353$;
- $b_2 = (\binom{2}{k} \cdot a_1 + \binom{1}{k} \cdot a_2) \bmod 998244353$;
- $b_3 = (\binom{3}{k} \cdot a_1 + \binom{2}{k} \cdot a_2 + \binom{1}{k} \cdot a_3) \bmod 998244353$, and so on.
Formally, $b_i = (\sum\limits_{j=1}^{i} \binom{i - j + 1}{k} \cdot a_j) \bmod 998244353$.
\textbf{Note that the array is given in a modified way, and you have to output it in a modified way as well}.
|
Unfortunately, it looks like the constraints were insufficient to cut the convolution solutions off. So it's possible to solve this problem using a very fast convolution implementation, but the model approach is different from that. One of the properties of Pascal's triangle states that $\binom{x}{y} = \binom{x-1}{y} + \binom{x-1}{y-1}$. Using it, we can rewrite the formula for $b_i$ as follows: $b_i = (\sum\limits_{j=1}^{i} \binom{i - j + 1}{k} \cdot a_j)$ $b_i = (\sum\limits_{j=1}^{i} \binom{i-j}{k} \cdot a_j) + (\sum\limits_{j=1}^{i} \binom{i-j}{k-1} \cdot a_j)$ Now, the first sum is almost the same as $b_i$, but with $i$ decreased by $1$. So, it is just $b_{i-1}$. What does the second sum stand for? It's actually $b_{i-1}$, but calculated with $k-1$ instead of $k$. upd: The only exception is $k = 1$, for which the last term in the summation has coefficient $\binom{0}{0} = 1$, that's why it is equal to $b_i$ calculated with $k = 0$, not $b_{i-1}$. Now, let $c_{i,j}$ be equal to the value of $b_i$ if we solve this problem with $k = j$. The formula transformations we used show us that $c_{i,j} = c_{i-1,j} + c_{i-1,j-1}$ (upd: When $j = 1$, the formula is $c_{i,j} = c_{i-1,j} + c_{i,j-1}$ instead), so we can use dynamic programming to calculate $c_{i,k}$ in $O(nk)$. But we need some base values for our dynamic programming. It's quite easy to see that $c_{0,j} = 0$; but what about $c_{i,0}$? $c_{i,0} = \sum\limits_{j=1}^{i} \binom{i - j + 1}{0} \cdot a_j$ And since $\binom{i - j + 1}{0} = 1$, then $c_{i,0} = \sum\limits_{j=1}^{i} a_j$ So, in order to obtain $c_{i,0}$, we can just build prefix sums on the array $a$. In fact, it's possible to show that transitioning from the $j$-th layer of dynamic programming to the $(j+1)$-th is also just applying prefix sums; then the solution would become just replacing $a$ with prefix sums of $a$ exactly $k+1$ times. This observation was not needed to get AC, but it allows us to write a much shorter code. Solution complexity: $O(nk)$.
|
[
"brute force",
"combinatorics",
"dp"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y, int mod = MOD)
{
return ((x + y) % mod + mod) % mod;
}
int mul(int x, int y, int mod = MOD)
{
return (x * 1ll * y) % mod;
}
int binpow(int x, int y, int mod = MOD)
{
int z = add(1, 0, mod);
while(y > 0)
{
if(y % 2 == 1) z = mul(z, x, mod);
y /= 2;
x = mul(x, x, mod);
}
return z;
}
vector<int> psum(vector<int> v)
{
vector<int> ans(1, 0);
for(auto x : v) ans.push_back(add(ans.back(), x));
return ans;
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
cin >> a[0];
int x, y, m, k;
cin >> x >> y >> m >> k;
for(int i = 1; i < n; i++)
a[i] = add(mul(a[i - 1], x, m), y, m);
for(int i = 0; i <= k; i++)
a = psum(a);
long long ans = 0;
for(int i = 1; i <= n; i++)
ans ^= (a[i + 1] * 1ll * i);
cout << ans << endl;
}
|
1832
|
F
|
Zombies
|
Polycarp plays a computer game in a post-apocalyptic setting. The zombies have taken over the world, and Polycarp with a small team of survivors is defending against hordes trying to invade their base. The zombies are invading for $x$ minutes starting from minute $0$. There are $n$ entrances to the base, and every minute one zombie attempts to enter through every entrance.
The survivors can defend the entrances against the zombies. There are two options:
- manually — shoot the zombies coming through a certain entrance;
- automatically — set up an electric fence on a certain entrance to fry the zombies.
If an entrance is defended either or both ways during some minute, no zombie goes through.
Every entrance is defended by a single dedicated survivor. The $i$-th entrance is defended manually from minute $l_i$ until minute $r_i$, non-inclusive — $[l_i, r_i)$.
There are $k$ generators that can be used to defend the entrances automatically. Every entrance should be connected to exactly one generator, but a generator can be connected to multiple entrances (or even none of them). Each generator will work for exactly $m$ \textbf{consecutive} minutes. Polycarp can choose when to power on each generator independently of each other, the $m$ minute long interval should be fully inside the $[0, x)$ time interval.
Polycarp is a weird gamer. He wants the game to be as difficult as possible for him. So he wants to connect each entrance to a generator and choose the time for each generator in such a way that as many zombies as possible enter the base. Please, help him to achieve that!
|
First of all, let's rephrase the problem a bit. For each entrance, we will have two time segments: the segment when it is guarded, and the segment when the corresponding generator works. The zombies will arrive through that entrance at every moment not belonging to these two segments; so, if we want to maximize the number of zombies, we want to minimize the length of the unions of these pairs of segments for the entrances; and since the lengths of the segments are fixed, minimizing the union means maximizing the intersection. So, we need to choose the time segments for the generators and assign entrances to generators so that the sum of intersections of segment pairs for each entrance is the maximum possible. Okay, now we work with the sum of intersections. Suppose there are multiple generators (for which we have already chosen their time segments) and an entrance; is there an easy method how to choose the optimal generator for the entrance? In fact, there is. We need to look at the centers of all segments (both for the generators and the entrance), and choose the generator for which the distance from the center of the entrance-segment to the center of the segment from that generator is the minimum possible (this only works because all generators have the same working time). Mathematically, if the segments for the generators are denoted as $[L_j, R_j)$, and the segment borders for the entrance are $[l_j, r_j)$, we need to choose the generator that minimizes the value of $|(L_j + R_j) - (l_j + r_j)|$, since it also minimizes the distance between the centers of the segments. Do you see where this is going? In fact, this observation allows us to use exchange argument DP. Suppose the segments for the generators are already chosen; we can sort the entrances according to the values $(l_j + r_j)$ for each entrance, and then split the sorted order of entrances into several groups: all entrances in the first group are optimal to hook up to the first generator, all entrances in the second group are optimal to hook up to the second generator, and so on. But since the segments of the generators are not fixed, we will instead split the sorted order of the entrances into $k$ groups, and for each group, optimally choose the segment for the respective generator. So, this leads us to the following dynamic programming: $dp_{i,j}$ - the maximum possible sum of intersections if we have split the first $i$ entrances in sorted order into $j$ groups. The transitions in this dynamic programming are quite simple: we can just iterate on the next group, transitioning from $dp_{i,j}$ to $dp_{i',j+1}$. Unfortunately, there are still two issues with this solution: How to reduce the number of transitions from $O(n^3)$ to something like $O(n^2 \log n)$ or $O(n^2)$? How to choose the best generator placement for a group of entrances, preferably either in $O(1)$ or $O(\log n)$ per one segment of entrances? Okay, the solution to the first issue is not that difficult. Intuitively, it looks like the running time of this dynamic programming can be improved with some of the well-known DP optimizations. The two that probably come to mind first are divide-and-conquer optimization and aliens trick. Both of them seem to work, but unfortunately, we can prove only one of them (the proof is in the paragraph below). You can choose any of these two optimizations. Proof that D&C optimization works We can prove this via quadrangle inequality: let $cost[l..r]$ be the total intersection for the entrances from $l$ to $r$ if the generator for them is chosen optimally, and $opt[l..r]$ be the optimal starting moment of the generator for entrances from $l$ to $r$. We have to show that $cost[a..c] + cost[b..d] \ge cost[a..d] + cost[b..c]$, where $a \le b \le c \le d$. Suppose $opt[a..d] = opt[b..c]$. Then, if we take all entrances $[c+1..d]$ from the first group and add them to the second group, then choosing $opt[a..d]$ as the starting point for these two groups gives us the total intersection equal to exactly $cost[a..d] + cost[b..c]$. So, in this case, $cost[a..c] + cost[b..d] \ge cost[a..d] + cost[b..c]$. Now suppose $opt[a..d] < opt[b..c]$ (the case $opt[a..d] > opt[b..c]$ is similar). Let's again try to move all entrances $[c+1..d]$ from the first group to the second group. If the resulting sum of intersections (without shifting the starting points for the generators) did not decrease, we have shown that $cost[a..c] + cost[b..d] \ge cost[a..d] + cost[b..c]$. Otherwise, at least one entrance from $[c+1..d]$ is closer to $opt[a..d]$ than to $opt[b..c]$ (in terms of distance between the segment centers). This means that since the centers of the segments in $[b..c]$ are not greater than the center of the segments in $[c+1..d]$, then the segments from $[b..c]$ are also closer to $opt[a..d]$ than to $opt[b..c]$. So, the optimal starting moment for $[b..c]$ can be shifted to $opt[a..d]$, and we arrive at the case we analyzed in the previous paragraph. End of proof The solution to the second issue is a bit more complex. First of all, notice that the only possible starting moments for generators we are interested in are of the form $l_i$ and $r_i - m$, so there are only $2n$ of them. Then let's try to understand how to evaluate the sum of intersections for the generator starting at some fixed moment and a segment of entrances. The model solution does some very scary stuff with logarithmic data structures, but the participants of the round showed us a much easier way: create a $2n \times n$ matrix, where the number in the cell $(i, j)$ is the intersection of the segment for the $i$-th starting moment of the generator, and the segment when the $j$-th entrance (in sorted order) is guarded; then, for a segment of entrances and a fixed starting moment of the generator, the total intersection can be calculated in $O(1)$ using prefix sums on this matrix. Unfortunately, trying each starting moment for every group of segments is still $O(n^3)$. But it can be improved using something like Knuth optimization: let $opt_{l,r}$ be the optimal starting point of the generator for the group of entrances $[l..r]$; then $opt_{l,r}$ is between $opt_{l,r-1}$ and $opt_{l+1,r}$, so calculating these optimal starting points in the style of Knuth optimization gives us $O(n^2)$. However, there's one last nasty surprise waiting for us: if we are not careful about choosing optimal starting moments, it's possible that $opt_{l,l} > opt_{l+1,l+1}$ (for example, if the segment for the entrance $l$ includes the segment for the generator $l+1$), which breaks the initialization of Knuth optimization. To resolve this issue, we can initialize the values of $opt_{l,l}$ in a monotonic way, choosing $opt_{l+1,l+1}$ only from values not less than $opt_{l,l}$. Implementing all of this results in a solution that works in $O(n^2 \log n)$.
|
[
"binary search",
"dp"
] | 3,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct seg{
int l, r;
};
int n;
vector<long long> dp_before, dp_cur;
vector<vector<long long>> bst;
void compute(int l, int r, int optl, int optr){
if (l > r) return;
int mid = (l + r) / 2;
pair<long long, int> best = {-1, -1};
for (int k = optl; k <= min(mid, optr); k++)
best = max(best, {(k ? dp_before[k - 1] : 0) + bst[k][mid], k});
dp_cur[mid] = best.first;
int opt = best.second;
compute(l, mid - 1, optl, opt);
compute(mid + 1, r, opt, optr);
}
struct node{
long long c0;
int c1;
};
vector<node> f;
void update(int x, int a, int b){
for (int i = x; i < int(f.size()); i |= i + 1){
f[i].c0 += b;
f[i].c1 += a;
}
}
void update(int l, int r, int a, int b){
update(l, a, b);
update(r, -a, -b);
}
long long get(int pos, int x){
long long res = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1)
res += f[i].c0 + f[i].c1 * 1ll * pos;
return res;
}
int main() {
int k, x, m;
scanf("%d%d%d%d", &n, &k, &x, &m);
vector<seg> a(n);
forn(i, n) scanf("%d%d", &a[i].l, &a[i].r);
sort(a.begin(), a.end(), [&](const seg &a, const seg &b){
return a.l + a.r < b.l + b.r;
});
vector<int> pos;
forn(i, n){
pos.push_back(a[i].l);
pos.push_back(a[i].r - m);
}
sort(pos.begin(), pos.end());
pos.resize(unique(pos.begin(), pos.end()) - pos.begin());
int cds = pos.size();
vector<array<int, 4>> npos(n);
forn(i, n){
npos[i][0] = lower_bound(pos.begin(), pos.end(), a[i].l - m) - pos.begin();
npos[i][1] = lower_bound(pos.begin(), pos.end(), a[i].l) - pos.begin();
npos[i][2] = lower_bound(pos.begin(), pos.end(), a[i].r - m) - pos.begin();
npos[i][3] = lower_bound(pos.begin(), pos.end(), a[i].r) - pos.begin();
}
vector<long long> pr(n + 1);
forn(i, n) pr[i + 1] = pr[i] + x - (m + a[i].r - a[i].l);
auto upd = [&](int i){
if (a[i].r - a[i].l >= m){
update(npos[i][0], npos[i][1], 1, m - a[i].l);
update(npos[i][1], npos[i][2], 0, m);
update(npos[i][2], npos[i][3], -1, a[i].r);
}
else{
update(npos[i][0], npos[i][2], 1, m - a[i].l);
update(npos[i][2], npos[i][1], 0, a[i].r - a[i].l);
update(npos[i][1], npos[i][3], -1, a[i].r);
}
};
bst.resize(n, vector<long long>(n, -1));
vector<vector<int>> opt(n, vector<int>(n));
forn(r, n) for (int l = r; l >= 0; --l){
if (l == r) f.assign(cds, {0, 0});
upd(l);
int L = (l == r ? (l == 0 ? 0 : opt[l - 1][l - 1]) : opt[l][r - 1]);
int R = (l == r ? int(pos.size()) - 1 : opt[l + 1][r]);
for (int k = L; k <= R; ++k){
long long cur = pr[r + 1] - pr[l] + get(pos[k], k);
if (cur > bst[l][r]){
bst[l][r] = cur;
opt[l][r] = k;
}
}
}
dp_before.resize(n);
dp_cur.resize(n);
for (int i = 0; i < n; i++)
dp_before[i] = bst[0][i];
for (int i = 1; i < k; i++){
compute(0, n - 1, 0, n - 1);
dp_before = dp_cur;
}
printf("%lld\n", dp_before[n - 1]);
return 0;
}
|
1833
|
A
|
Musical Puzzle
|
Vlad decided to compose a melody on his guitar. Let's represent the melody as a sequence of notes corresponding to the characters 'a', 'b', 'c', 'd', 'e', 'f', and 'g'.
However, Vlad is not very experienced in playing the guitar and can only record \textbf{exactly two} notes at a time. Vlad wants to obtain the melody $s$, and to do this, he can merge the recorded melodies together. In this case, the last sound of the first melody must match the first sound of the second melody.
For example, if Vlad recorded the melodies "ab" and "ba", he can merge them together and obtain the melody "aba", and then merge the result with "ab" to get "abab".
Help Vlad determine the \textbf{minimum} number of melodies consisting of two notes that he needs to record in order to obtain the melody $s$.
|
Let's construct the melody sequentially. In the first step, we can record the notes $s_1$ and $s_2$. In the next step, we need to record $s_2$ and $s_3$, because there must be a common symbol when gluing and so on. That is, we need to have recorded melodies $s_i$+$s_{i+1}$ for all $1 \le i < n$. We only need to count how many different ones among them, because we don't need to record one melody twice.
|
[
"implementation",
"strings"
] | 800
|
def solve():
n = int(input())
s = input()
cnt = set()
for i in range(1, n):
cnt.add(s[i - 1] + s[i])
print(len(cnt))
t = int(input())
for _ in range(t):
solve()
|
1833
|
B
|
Restore the Weather
|
You are given an array $a$ containing the weather forecast for Berlandia for the last $n$ days. That is, $a_i$ — is the estimated air temperature on day $i$ ($1 \le i \le n$).
You are also given an array $b$ — the air temperature that was actually present on each of the days. However, all the values in array $b$ are mixed up.
Determine which day was which temperature, if you know that the weather never differs from the forecast by more than $k$ degrees. In other words, if on day $i$ the real air temperature was $c$, then the equality $|a_i - c| \le k$ is always true.
For example, let an array $a$ = [$1, 3, 5, 3, 9$] of length $n = 5$ and $k = 2$ be given and an array $b$ = [$2, 5, 11, 2, 4$]. Then, so that the value of $b_i$ corresponds to the air temperature on day $i$, we can rearrange the elements of the array $b$ so: [$2, 2, 5, 4, 11$]. Indeed:
- On the $1$st day, $|a_1 - b_1| = |1 - 2| = 1$, $1 \le 2 = k$ is satisfied;
- On the $2$nd day $|a_2 - b_2| = |3 - 2| = 1$, $1 \le 2 = k$ is satisfied;
- On the $3$rd day, $|a_3 - b_3| = |5 - 5| = 0$, $0 \le 2 = k$ is satisfied;
- On the $4$th day, $|a_4 - b_4| = |3 - 4| = 1$, $1 \le 2 = k$ is satisfied;
- On the $5$th day, $|a_5 - b_5| = |9 - 11| = 2$, $2 \le 2 = k$ is satisfied.
|
Let's solve the problem using a greedy algorithm. Based on the array $a$, form an array of pairs {temperature, day number} and sort it in ascending order of temperature. Also sort the array $b$ in ascending order. Now, the values $a[i].first$ and $b[i]$ are the predicted and real temperature on day $a[i].second$. Indeed, consider the minimum temperatures $b[1]$ and $a[1].first$. The difference between them is $t = |b[1] - a[1].first|$. If we consider the value $|b[i] - a[1].first|$ or $|b[1] - a[i].first|$ at $i \gt 1$, there will be at least $t$ since $a[1] \le a[i]$ and $b[1] \le b[i]$. Since it is guaranteed that it is possible to rearrange the elements in the array $b$, and the elements $b[1]$ and $a[1].first$ have the smallest difference, it is definitely not greater than $k$.
|
[
"greedy",
"sortings"
] | 900
|
#include<bits/stdc++.h>
using namespace std;
void solve(){
int n, k;
cin >> n >> k;
vector<pair<int, int>>a(n);
vector<int>b(n), ans(n);
for(int i = 0; i < n; i++){
cin >> a[i].first;
a[i].second = i;
}
for(auto &i : b) cin >> i;
sort(b.begin(), b.end());
sort(a.begin(), a.end());
for(int i = 0; i < n; i++){
ans[a[i].second] = b[i];
}
for(auto &i : ans) cout << i << ' ';
cout << endl;
}
int main(){
int t;
cin >> t;
while(t--) solve();
}
|
1833
|
C
|
Vlad Building Beautiful Array
|
Vlad was given an array $a$ of $n$ positive integers. Now he wants to build a beautiful array $b$ of length $n$ from it.
Vlad considers an array beautiful if all the numbers in it are positive and have the same parity. That is, all numbers in the beautiful array are \textbf{greater} than zero and are either all even or all odd.
To build the array $b$, Vlad can assign each $b_i$ either the value $a_i$ or $a_i - a_j$, where any $j$ from $1$ to $n$ can be chosen.
To avoid trying to do the impossible, Vlad asks you to determine whether it is possible to build a beautiful array $b$ of length $n$ using his array $a$.
|
If all the numbers in the array already have the same parity, then for each $i$ it is sufficient to assign $b_i=a_i$. Otherwise, it is impossible to make all the numbers even by leaving them positive, because the parity changes only when subtracting an odd number, and we cannot make the minimum odd number an even number. It remains only to make all numbers odd, that is, subtract odd numbers from even numbers. This can be done if the minimum number in the array is odd, because we can subtract it from every even number.
|
[
"greedy",
"math"
] | 800
|
def solve():
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
if a[0] % 2 == 1:
print("YES")
return
for i in range(n):
if a[i] % 2 == 1:
print("NO")
return
print("YES")
t = int(input())
for _ in range(t):
solve()
|
1833
|
D
|
Flipper
|
You are given a permutation $p$ of length $n$.
A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $\{2,3,1,5,4\}$ is a permutation, while $\{1,2,2\}$ is not (since $2$ appears twice), and $\{1,3,4\}$ is also not a permutation (as $n=3$, but the array contains $4$).
To the permutation $p$, you need to apply the following operation \textbf{exactly once}:
- First you choose a segment $[l, r]$ ($1 \le l \le r \le n$, a segment is a continuous sequence of numbers $\{p_l, p_{l+1}, \ldots, p_{r-1}, p_r\}$) and reverse it. Reversing a segment means swapping pairs of numbers $(p_l, p_r)$, $(p_{l+1}, p_{r-1})$, ..., $(p_{l + i}, p_{r - i})$ (where $l + i \le r - i$).
- Then you swap the prefix and suffix: $[r+1, n]$ and $[1, l - 1]$ (note that these segments may be empty).
For example, given $n = 5, p = \{2, \textcolor{blue}{3}, \textcolor{blue}{1}, 5, 4\}$, if you choose the segment $[l = 2, r = 3]$, after reversing the segment $p = \{\textcolor{green}{2}, \textcolor{blue}{1}, \textcolor{blue}{3}, \textcolor{green}{5}, \textcolor{green}{4}\}$, then you swap the segments $[4, 5]$ and $[1, 1]$. Thus, $p = \{\textcolor{green}{5}, \textcolor{green}{4}, 1, 3, \textcolor{green}{2}\}$. It can be shown that this is the maximum possible result for the given permutation.
You need to output the lexicographically \textbf{maximum} permutation that can be obtained by applying the operation described \textbf{exactly once}.
A permutation $a$ is lexicographically greater than permutation $b$ if there exists an $i$ ($1 \le i \le n$) such that $a_j = b_j$ for $1 \le j < i$ and $a_i > b_i$.
|
In these constraints we could solve the problem for $O(n^2)$. Let us note that there can be no more than two candidates for the value $r$. Since the first number in the permutation will be either $p_{r+1}$ if $r < n$, or $p_r$ if $r = n$. Then let's go through the value of $r$ and choose the one in which the first number in the resulting permutation is as large as possible. Next, if $p_n = n$, then we can have two candidates for $r$ is $n, n-1$, but note that it is always advantageous to put $r = n$ in that case, since it will not spoil the answer. Then we can go through $l$ and get the solution by the square, but we can do something smarter. Notice now that the answer already contains all the numbers $p_i$ where $i > r$. And then we write $p_r, p_{r-1}, \ldots, p_l$ where $l$ is still unknown, and then $p_1, p_2, \ldots, p_{l-1}$. In that case, let's write $p_r$ as $l \le r$ and then write $p_{r-1}, p_{r-2}, \ldots$ as long as they are larger than $p_1$. Otherwise, we immediately determine the value of $l$ and finish the answer to the end. Thus, constructively we construct the maximal permutation.
|
[
"brute force",
"constructive algorithms",
"greedy"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define sz(v) (int)v.size()
#define all(v) v.begin(),v.end()
#define eb emplace_back
void solve() {
int n; cin >> n;
vector<int> p(n);
for (auto &e : p) cin >> e;
int r = 0;
for (int i = 0; i < n; ++i) {
if (p[min(n-1, r+1)] <= p[min(n-1, i+1)]) {
r = i;
}
}
vector<int> ans;
for (int i = r + 1; i < n; ++i) ans.eb(p[i]);
ans.eb(p[r]);
for (int i = r-1; i >= 0; --i) {
if (p[i] > p[0]) {
ans.eb(p[i]);
} else {
for (int j = 0; j <= i; ++j) {
ans.eb(p[j]);
}
break;
}
}
for (auto e : ans) cout << e << ' ';
cout << endl;
}
int main() {
int t;
cin >> t;
forn(tt, t) {
solve();
}
}
|
1833
|
E
|
Round Dance
|
$n$ people came to the festival and decided to dance a few round dances. There are at least $2$ people in the round dance and each person has exactly two neighbors. If there are $2$ people in the round dance then they have the same neighbor on each side.
You decided to find out exactly how many dances there were. But each participant of the holiday remembered exactly \textbf{one} neighbor. Your task is to determine what the minimum and maximum number of round dances could be.
For example, if there were $6$ people at the holiday, and the numbers of the neighbors they remembered are equal $[2, 1, 4, 3, 6, 5]$, then the \textbf{minimum} number of round dances is$1$:
- $1 - 2 - 3 - 4 - 5 - 6 - 1$
and the \textbf{maximum} is $3$:
- $1 - 2 - 1$
- $3 - 4 - 3$
- $5 - 6 - 5$
|
Let's build an undirected graph, draw the edges $i \to a_i$. Let's split this graph into connectivity components, denote their number by $k$. There could not be more than $k$ round dances. Since the degree of each vertex is no more than two, the connectivity components are simple cycles and bamboos. If we connect the vertices of degree one in each bamboo, we get a partition into $k$ round dances. Now let's try to get the minimum number of round dances. Nothing can be done with cycles, and all bamboos can be combined into one. If you get $b$ bamboos and $c$ cycles, then the answer is $\langle c + \min(b, 1), c + b \rangle$. Time complexity is $O(n)$.
|
[
"dfs and similar",
"dsu",
"graphs",
"shortest paths"
] | 1,600
|
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
void solve() {
int n;
cin >> n;
vector<int> a(n);
vector<set<int>> g(n);
vector<set<int>> neighbours(n);
vector<int> d(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
a[i]--;
g[i].insert(a[i]);
g[a[i]].insert(i);
}
for (int i = 0; i < n; ++i) {
d[i] = g[i].size();
}
int bamboos = 0, cycles = 0;
vector<bool> vis(n);
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
queue<int> q;
q.push(i);
vis[i] = true;
vector<int> component = {i};
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v: g[u]) {
if (!vis[v]) {
vis[v] = true;
q.push(v);
component.push_back(v);
}
}
}
bool bamboo = false;
for (int j: component) {
if (d[j] == 1) {
bamboo = true;
break;
}
}
if (bamboo) {
bamboos++;
} else {
cycles++;
}
}
}
cout << cycles + min(bamboos, 1) << ' ' << cycles + bamboos << '\n';
}
int main() {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
solve();
}
}
|
1833
|
F
|
Ira and Flamenco
|
Ira loves Spanish flamenco dance very much. She decided to start her own dance studio and found $n$ students, $i$th of whom has level $a_i$.
Ira can choose several of her students and set a dance with them. So she can set a huge number of dances, but she is only interested in magnificent dances. The dance is called magnificent if the following is true:
- \textbf{exactly} $m$ students participate in the dance;
- levels of all dancers are \textbf{pairwise distinct};
- levels of every two dancers have an absolute difference \textbf{strictly less} than $m$.
For example, if $m = 3$ and $a = [4, 2, 2, 3, 6]$, the following dances are magnificent (students participating in the dance are highlighted in red): $[\textcolor{red}{4}, 2, \textcolor{red}{2}, \textcolor{red}{3}, 6]$, $[\textcolor{red}{4}, \textcolor{red}{2}, 2, \textcolor{red}{3}, 6]$. At the same time dances $[\textcolor{red}{4}, 2, 2, \textcolor{red}{3}, 6]$, $[4, \textcolor{red}{2}, \textcolor{red}{2}, \textcolor{red}{3}, 6]$, $[\textcolor{red}{4}, 2, 2, \textcolor{red}{3}, \textcolor{red}{6}]$ are not magnificent.
In the dance $[\textcolor{red}{4}, 2, 2, \textcolor{red}{3}, 6]$ only $2$ students participate, although $m = 3$.
The dance $[4, \textcolor{red}{2}, \textcolor{red}{2}, \textcolor{red}{3}, 6]$ involves students with levels $2$ and $2$, although levels of all dancers must be pairwise distinct.
In the dance $[\textcolor{red}{4}, 2, 2, \textcolor{red}{3}, \textcolor{red}{6}]$ students with levels $3$ and $6$ participate, but $|3 - 6| = 3$, although $m = 3$.
Help Ira count the number of magnificent dances that she can set. Since this number can be very large, count it \textbf{modulo} $10^9 + 7$. Two dances are considered different if the sets of students participating in them are different.
|
Reformulate the definition of magnificent dance. A dance $[x_1, x_2, \ldots, x_m]$ is called magnificent if there exists such a non-negative integer $d$ that $[x_1 - d, x_2 - d, \ldots, x_m - d]$ forms a permutation. Let's build an array $b$ such that it is sorted, all the numbers in it are unique and each number from $a$ occurs in $b$. For each element $b_i$, set $c_i$ as its number of occurrences in the array $a$. This process is called coordinate compression. For example, if $a = [4, 1, 2, 2, 3]$, then $b = [1, 2, 3, 4]$, $c = [1, 2, 1, 1]$. Let the constructed array $b$ has length $k$. In every magnificent dance there is a dancer with a minimum level. Let's fix this minimal level in the array $b$, let its index be $i$, then the desired magnificent dance exists if $i + m \le k$ and $b_{i + m} = b_i + m - 1$. If the desired magnificent dance exists, the number of such dances must be added to the answer, which is equal to $c_i \cdot c_{i + 1} \cdot \ldots \cdot c_{i + m}$. How to quickly calculate such a number? Let's build prefix products $p_i = c_1 \cdot c_2 \cdot \ldots \cdot p_{i - 1}$. Then by Fermat's small theorem $c_i \cdot c_{i + 1} \cdot \ldots \cdot c_{i + m} = p_{i + m} \cdot p_i^{(10^9 + 7) - 2}$. Time complexity is $O(n \log C)$. Let's build a segment tree on a product modulo. Time complexity is $O(n \log n)$ and we don't use that the module is prime. We will use the idea of building a queue on two stacks, but we will support prefix products modulo in these stacks. Time complexity is $O(n)$ and we don't use that the module is prime.
|
[
"combinatorics",
"constructive algorithms",
"data structures",
"implementation",
"math",
"sortings",
"two pointers"
] | 1,700
|
/*
`)
_ \
(( }/ ,_
)))__ /
(((---'
\ '
)|____.---- )
/ \ ` (
/ ' \ ` )
/ ' \ ` /
/ ' _/
/ _!____.-'
/_.-'/ \
|`_ |`_
*/
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> ipair;
const int MAXN = 200200;
const int MAXK = MAXN;
const int MOD = 1000000007;
inline int add(int a, int b) {
return (a + b >= MOD ? a + b - MOD : a + b);
}
inline int mul(int a, int b) {
return 1LL * a * b % MOD;
}
int n, m, k;
int arr[MAXN], brr[MAXN], cnt[MAXK];
void build() {
sort(arr, arr + n);
memcpy(brr, arr, sizeof(int) * n);
k = unique(arr, arr + n) - arr;
for (int j = 0; j < k; ++j)
cnt[j] = upper_bound(brr, brr + n, arr[j]) - lower_bound(brr, brr + n, arr[j]);
}
inline void push(stack<ipair> &S, int x) {
S.emplace(x, mul(x, S.empty() ? 1 : S.top().second));
}
int solve() {
if (k < m) return 0;
stack<ipair> S1, S2;
for (int j = 0; j < m; ++j)
push(S1, cnt[j]);
int ans = 0;
for (int j = m; j <= k; ++j) {
if (arr[j - 1] - arr[j - m] == m - 1)
ans = add(ans, mul(S1.empty() ? 1 : S1.top().second, S2.empty() ? 1 : S2.top().second));
if (S2.empty()) {
for (; !S1.empty(); S1.pop())
push(S2, S1.top().first);
}
S2.pop();
push(S1, cnt[j]);
}
return ans;
}
int main() {
int t; cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 0; i < n; ++i)
cin >> arr[i];
build();
cout << solve() << endl;
}
}
|
1833
|
G
|
Ksyusha and Chinchilla
|
Ksyusha has a pet chinchilla, a tree on $n$ vertices and huge scissors. A tree is a connected graph without cycles. During a boring physics lesson Ksyusha thought about how to entertain her pet.
Chinchillas like to play with branches. A branch is a tree of $3$ vertices.
\begin{center}
{\small The branch looks like this.}
\end{center}
A cut is the removal of some (not yet cut) edge in the tree. Ksyusha has plenty of free time, so she can afford to make enough cuts so that the tree splits into branches. In other words, after several (possibly zero) cuts, each vertex must belong to \textbf{exactly one} branch.
Help Ksyusha choose the edges to be cut or tell that it is impossible.
|
Let's hang the tree by the vertex $1$. This problem can be solved by dynamic programming. $dpc_v$ - the ability to cut a subtree of $v$ if the edges in all children of $v$ must be cut off. $dpo_v$ - the ability to cut a subtree of $v$ if exactly one edge needs to be saved from $v$ to the child. $dp_v$ - ability to cut a subtree of $v$ if an edge above $v$ is cut off. Obviously, the answer will be $dp_1$. Recalculation in such dynamics is offered to the reader as an exercise. There is a simpler greedy solution. Let's call light a vertex that is not a leaf and whose children are all leaves. Let's call heavy a vertex that is not a leaf and that has a light child. If there is a light vertex with at least three children, the desired cut does not exist. If the light vertex $v$ has exactly one child, we will cut off all children from its parent except $v$. If the light vertex $v$ has exactly two children, we cut the edge into the parent $v$. It is easy to understand that in this way the desired cut is restored uniquely. This problem can be solved by an elegant DFS, but the author considers BFS easier to understand. First, let's count the number of children and the number of light children for each vertex. We will store all light vertices in the queue and process them sequentially. Cutting edges will change the number of children and the number of light children at some vertices. It should be handled carefully. This solution works for $O(n)$.
|
[
"constructive algorithms",
"dfs and similar",
"dp",
"dsu",
"greedy",
"implementation",
"trees"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> ipair;
const int MAXN = 200200;
int n;
vector<ipair> gr[MAXN];
vector<int> res;
queue<int> qu;
int par[MAXN], ipar[MAXN], deg[MAXN], hard[MAXN];
void init() {
res.clear();
while (!qu.empty()) qu.pop();
memset(deg, 0, sizeof(int) * n);
memset(hard, 0, sizeof(int) * n);
for (int v = 0; v < n; ++v)
gr[v].clear();
}
void dfs(int v, int p, int ip) {
par[v] = p;
ipar[v] = ip;
for (auto [u, i]: gr[v]) {
if (u == p) continue;
dfs(u, v, i);
++deg[v];
hard[v] += (deg[u] > 0);
}
}
void build() {
dfs(0, -1, -1);
}
bool rempar(int v) {
int u = par[v];
if (u == -1) return true;
par[v] = -1;
res.push_back(ipar[v]);
--deg[u], --hard[u];
if (deg[u]) {
if (!hard[u]) qu.push(u);
return true;
}
if (par[u] == -1) return false;
--hard[par[u]];
if (!hard[par[u]]) qu.push(par[u]);
return true;
}
bool solve() {
if (n % 3) return false;
for (int v = 0; v < n; ++v)
if (!hard[v] && deg[v]) qu.push(v);
while (!qu.empty()) {
int v = qu.front(); qu.pop();
if (deg[v] > 2) return false;
if (deg[v] == 2) {
if (!rempar(v)) return false;
} else if (deg[v] == 1) {
if (par[v] == -1) return false;
for (auto [u, i]: gr[par[v]]) {
if (u == par[par[v]] || u == v || par[u] == -1) continue;
if (!deg[u]) return false;
res.push_back(i);
par[u] = -1;
}
if (!rempar(par[v])) return false;
}
}
return true;
}
int main() {
int t; cin >> t;
while (t--) {
cin >> n, init();
for (int i = 1; i < n; ++i) {
int v, u; cin >> v >> u, --v, --u;
gr[v].emplace_back(u, i);
gr[u].emplace_back(v, i);
}
build();
if (!solve()) {
cout << -1 << endl;
continue;
}
cout << res.size() << endl;
for (int id: res)
cout << id << ' ';
cout << endl;
}
}
|
1834
|
A
|
Unit Array
|
Given an array $a$ of length $n$, which elements are equal to $-1$ and $1$. Let's call the array $a$ good if the following conditions are held at the same time:
- $a_1 + a_2 + \ldots + a_n \ge 0$;
- $a_1 \cdot a_2 \cdot \ldots \cdot a_n = 1$.
In one operation, you can select an arbitrary element of the array $a_i$ and change its value to the opposite. In other words, if $a_i = -1$, you can assign the value to $a_i := 1$, and if $a_i = 1$, then assign the value to $a_i := -1$.
Determine the minimum number of operations you need to perform to make the array $a$ good. It can be shown that this is always possible.
|
First, let's make the sum of the array elements $\ge 0$. To do this, we just need to change some $-1$ to $1$. The number of such replacements can be calculated using a formula or explicitly simulated. After that, there are two possible situations: either the product of all elements is equal to $1$, or the product of all elements is equal to $-1$. In the first case, we don't need to do anything else. In the second case, we need to replace one more $-1$ with $1$ (note that in this case the sum will remain $\ge 0$).
|
[
"greedy",
"math"
] | 800
| null |
1834
|
B
|
Maximum Strength
|
Fedya is playing a new game called "The Legend of Link", in which one of the character's abilities is to combine two materials into one weapon. Each material has its own strength, which can be represented by a positive integer $x$. The strength of the resulting weapon is determined as the sum of the absolute differences of the digits in the \textbf{decimal} representation of the integers at each position.
Formally, let the first material have strength $X = \overline{x_{1}x_{2} \ldots x_{n}}$, and the second material have strength $Y = \overline{y_{1}y_{2} \ldots y_{n}}$. Then the strength of the weapon is calculated as $|x_{1} - y_{1}| + |x_{2} - y_{2}| + \ldots + |x_{n} - y_{n}|$. If the integers have different lengths, then the shorter integer is \textbf{padded with leading zeros}.
Fedya has an unlimited supply of materials with all possible strengths from $L$ to $R$, inclusive. Help him find the maximum possible strength of the weapon he can obtain.
An integer $C = \overline{c_{1}c_{2} \ldots c_{k}}$ is defined as an integer obtained by sequentially writing the digits $c_1, c_2, \ldots, c_k$ from left to right, i.e. $10^{k-1} \cdot c_1 + 10^{k-2} \cdot c_2 + \ldots + c_k$.
|
Let's add leading zeros to $L$ if necessary. Now we can represent the numbers $L$ and $R$ as their longest common prefix, the digit $k$ at which the values differ, and the remaining digits. After digit $k$, any digits can be placed, so it is advantageous to put $9$ in one number and $0$ in the other. Then the answer is equal to $(r_{k} - l_{k}) + 9 \cdot (n - k)$. For example, it is achieved with numbers $A = \overline{l_{1}l_{2} \ldots l_{k} \underbrace{99 \ldots 9}_{n - k}}$ and $B = \overline{r_{1}r_{2} \ldots r_{k} \underbrace{00 \ldots 0}_{n - k}}$.
|
[
"greedy",
"math"
] | 1,000
| null |
1834
|
C
|
Game with Reversing
|
Alice and Bob are playing a game. They have two strings $S$ and $T$ of the same length $n$ consisting of lowercase latin letters. Players take turns alternately, with Alice going first.
On her turn, Alice chooses an integer $i$ from $1$ to $n$, one of the strings $S$ or $T$, and any lowercase latin letter $c$, and replaces the $i$-th symbol in the chosen string with the character $c$.
On his turn, Bob chooses one of the strings $S$ or $T$, and reverses it. More formally, Bob makes the replacement $S := \operatorname{rev}(S)$ or $T := \operatorname{rev}(T)$, where $\operatorname{rev}(P) = P_n P_{n-1} \ldots P_1$.
The game lasts until the strings $S$ and $T$ are equal. As soon as the strings become equal, the game \textbf{ends instantly}.
Define the duration of the game as the total number of moves made by both players during the game. For example, if Alice made $2$ moves in total, and Bob made $1$ move, then the duration of this game is $3$.
Alice's goal is to minimize the duration of the game, and Bob's goal is to maximize the duration of the game.
What will be the duration of the game, if both players play optimally? It can be shown that the game will end in a finite number of turns.
|
Let's show that the specific choice of a turn by Bob (which of the strings to reverse) does not affect Alice's strategy and therefore the answer to the problem. Reversing the string twice does not change anything $\to$ we are only interested in the parity of the number of reverses for both strings. If Bob made an even number of moves in total, then the parity of the number of moves made by Bob with string $s$ coincides with the parity of the number of moves made by Bob with string $t \to$ pairs of characters at the same indices, after all reverses, will be $(s_1, t_1), (s_2, t_2), \ldots, (s_n, t_n)$, possibly in reverse order, but it doesn't matter. Here $s_1, \ldots, s_n$ and $t_1, \ldots, t_n$ are the original indices of the strings, which do not change with reversing. If Bob made an odd number of moves, then exactly one of the strings will be reversed, and the pairs of characters in the same indices will be: $(s_1, t_n), (s_2, t_{n-1}), \ldots, (s_n, t_1)$ (or in reverse order). That is, the specific pairs of corresponding characters are determined only by the parity of the total number of moves made by Bob, and it does not matter which specific moves were made. Therefore, Alice can choose one of two strategies: Make $s_1 = t_1, s_2 = t_2, \ldots, s_n = t_n$, and fix the end of the game when the number of moves made by Bob is even. Make $s_1 = t_n, s_2 = t_{n-1}, \ldots, s_n = t_1$, and fix the end of the game when the number of moves made by Bob is odd. Let's count $cnt$ - the number of indices where $s$ and $t$ differ, and $cnt_{rev}$ - the number of indices where $s$ and $\operatorname{rev}(t)$ differ. For the first strategy, Alice must make at least $cnt$ moves herself, and it is also necessary that the number of moves made by Bob is even $\to$ it is easy to see that for this strategy the game will last $2 \cdot cnt - cnt \% 2$ moves. For the second strategy, everything is roughly similar: the game will last $2 \cdot cnt_{rev} - (1 - cnt_{rev} \% 2)$ moves, but the case $cnt_{rev} = 0$ needs to be handled separately. And the answer to the problem will be the minimum of these two values. Asymptotic: $O(n)$.
|
[
"games",
"greedy",
"math",
"strings"
] | 1,200
| null |
1834
|
D
|
Survey in Class
|
Zinaida Viktorovna has $n$ students in her history class. The homework for today included $m$ topics, but the students had little time to prepare, so $i$-th student learned only topics from $l_i$ to $r_i$ inclusive.
At the beginning of the lesson, each student holds their hand at $0$. The teacher wants to ask some topics. It goes like this:
- The teacher asks the topic $k$.
- If the student has learned topic $k$, then he raises his hand by $1$, otherwise he lower it by $1$.
Each topic Zinaida Viktorovna can ask \textbf{no more than one time}.
Find the maximum difference of the heights of the highest and the lowest hand that can be in class after the survey.
Note that the student's hand \textbf{can go below $0$}.
|
Let's fix the students who will end up with the highest and lowest hands. Then, to maximize the difference, we can ask all the topics that the student with the highest hand knows. Then the second student will raise his hand for each topic in the intersection of their segments, and lower for each topic that only the first student knows. That is, the problem is to find $2$ segments $a$ and $b$ such that the value of $|a| - |a |\cap b|$ is maximal, since the answer is $2 \cdot (|a| - |a \cap b|)$. The segment $b$ can intersect the segment $a$ in four ways: intersect the beginning of $a$, intersect the end of $a$, be completely inside $a$, or not intersect it at all. So, if in the answer segment $b$ intersects the beginning of $a$, then you can choose the segment with the minimal right end as the segment $b$ - the intersection of such a segment with $a$ will be no greater than the intersection of $b$ with $a$. Similarly, for the right end, you can select the segment with the maximal left end. If the answer has one segment in another, then you can consider the shortest segment in the set as the inner segment. If the segments in the answer do not intersect, then the segment does not intersect one of the "edge" segments. Thus, to find the segment with which it has the minimum intersection for a given segment, you need to check 3 candidates: the shortest segment in the set, the segment with the minimal right end, and the one with the maximal left end. In total, to find the answer, you need to check $3n$ pairs of segments.
|
[
"brute force",
"data structures",
"greedy",
"implementation",
"sortings"
] | 1,900
| null |
1834
|
E
|
MEX of LCM
|
You are given an array $a$ of length $n$. A \textbf{positive} integer $x$ is called good if it is \textbf{impossible} to find a subsegment$^{\dagger}$ of the array such that the least common multiple of all its elements is equal to $x$.
You need to find the smallest good integer.
A subsegment$^{\dagger}$ of the array $a$ is a set of elements $a_l, a_{l + 1}, \ldots, a_r$ for some $1 \le l \le r \le n$. We will denote such subsegment as $[l, r]$.
|
Notice that the MEX of $n^2$ numbers will not exceed $n^2+1$. Let's calculate all possible LCM values on segments that do not exceed $n^2$. To do this, we will iterate over the right endpoint of the segments and maintain a set of different LCM values on segments with such a right endpoint. Let these values be $x_1 < x_2 < \ldots < x_k$. Then $k \leq 1 + 2\log_2n$, indeed, for each $1 \leq i < k$, it is true that $x_{i+1}$ is divisible by $x_i$, and therefore $x_{i+1} \geq 2x_i$, that is, $n^2 \geq x^2 \geq 2^{k-1}$, from which the required follows. That is, the values $x_1, \ldots, x_k$ can be stored naively in some dynamic array. Now suppose we want to move the right endpoint, then the array $(x_1, \ldots, x_k)$ should be replaced by $([x_1, a_r], \ldots, [x_k, a_k], a_k)$ and remove values greater than $n^2+1$ from the new array, as well as get rid of duplicates. All these actions can be performed in $O(n \log n)$ time, after which we just need to find the MEX among the known set of values. This solution can also serve as proof that the desired MEX does not exceed $n \cdot (1 + 2 \log_2 n)$, which is less than $10^9$ under the constraints of the problem. Thus, initially, we can only maintain numbers less than $10^9$ and not worry about overflows of a 64-bit integer type.
|
[
"binary search",
"data structures",
"implementation",
"math",
"number theory"
] | 2,300
| null |
1834
|
F
|
Typewriter
|
Recently, Polycarp was given an unusual typewriter as a gift! Unfortunately, the typewriter was defective and had a rather strange design.
The typewriter consists of $n$ cells numbered from left to right from $1$ to $n$, and a carriage that moves over them. The typewriter cells contain $n$ \textbf{distinct} integers from $1$ to $n$, and each cell $i$ initially contains the integer $p_i$. Before all actions, the carriage is at cell number $1$ and there is nothing in its buffer storage. The cell on which the carriage is located is called the \textbf{current} cell.
The carriage can perform five types of operations:
- Take the integer from the current cell, if it is not empty, and put it in the carriage buffer, if it is empty (this buffer can contain \textbf{no more than one} integer).
- Put the integer from the carriage buffer, if it is not empty, into the current cell, if it is empty.
- Swap the number in the carriage buffer with the number in the current cell, if both the buffer and the cell contain integers.
- Move the carriage from the current cell $i$ to cell $i + 1$ (if $i < n$), while the integer in the buffer is preserved.
- Reset the carriage, i.e. move it to cell number $1$, while the integer in the buffer is preserved.
Polycarp was very interested in this typewriter, so he asks you to help him understand it and will ask you $q$ queries of three types:
- Perform a cyclic shift of the sequence $p$ to the left by $k_j$.
- Perform a cyclic shift of the sequence $p$ to the right by $k_j$.
- Reverse the sequence $p$.
Before and after each query, Polycarp wants to know what \textbf{minimum} number of carriage resets is needed for the current sequence in order to distribute the numbers to their cells (so that the number $i$ ends up in cell number $i$).
Note that Polycarp only wants to know the minimum number of carriage resets required to arrange the numbers in their places, but \textbf{he does not actually distribute them}.
Help Polycarp find the answers to his queries!
|
Let's solve the problem if there are no requests. The key object for us will be such cells that the number in them is less than the cell index. Note that for one carriage reset, we can transfer no more than one such number. So we have a lower bound on the answer. Let's build a graph with edges $i\rightarrow a[i]$. Then it will break up into cycles. Let's find the first position where $a[i] \neq i$, take a number from this position, shift it to $a[i]$, take a number from position $a[i]$, and so on. Then we will put the whole cycle in its place. How many carriage drops will there be? Exactly as many edges as there are such that $a[i] < i$. That is, the answer is exactly equal to the number of positions where $a[i] < i$. Let's learn how to solve for shifts. Let's find for each cell such positions of the beginning of the array that it will satisfy $a[i] < i$ in this configuration. It is easy to see that for a particular cell, such indexes will form a segment (possibly a prefix + suffix). Let's create a separate array and add one on these segments. Then in the i-th position there will be an answer if the array starts from the i-th cell. Now let's solve for an array flip. It is easy to see that for this you can simply maintain the entire previous structure, but with the inverted original configuration of cells. Asymptotic: $O(n + q)$.
|
[
"brute force",
"math"
] | 2,500
| null |
1835
|
A
|
k-th equality
|
Consider all equalities of form $a + b = c$, where $a$ has $A$ digits, $b$ has $B$ digits, and $c$ has $C$ digits. All the numbers are \textbf{positive} integers and are written without leading zeroes. Find the $k$-th lexicographically smallest equality when written as a string like above or determine that it does not exist.
For example, the first three equalities satisfying $A = 1$, $B = 1$, $C = 2$ are
- $1 + 9 = 10$,
- $2 + 8 = 10$,
- $2 + 9 = 11$.
An equality $s$ is lexicographically smaller than an equality $t$ with the same lengths of the numbers if and only if the following holds:
- in the first position where $s$ and $t$ differ, the equality $s$ has a smaller digit than the corresponding digit in $t$.
|
The largest possible value for $a$ is $10^6 - 1$, so we can iterate over each possibility. When we fix $a$, we can find the range of values for $b$ such that $10^{C - 1} \leq a + b < 10^C$, and $10^{B - 1} \leq b < 10^B$. For each such value, we have a correct equality. We can easily find this range. We get that $\max \{ 10^{C - 1} - a, 10^{B - 1} \} \leq b < \min \{ 10^C - a, 10^B \}$ and from this inequality, we know how many equations for the given $a$ we have. As we start by minimizing $a$, we can find its value for the $k$-th equation if we iterate from the smallest possible values of $a$. When we have fixed $a$ (or find out that there is no such equation), we iterate over all possible values of $b$ and check if the resulting $c$ has $C$ digits. The complexity is $\mathcal{O}(10^A + 10^B)$.
|
[
"brute force",
"implementation",
"math"
] | 1,700
|
#include <bits/stdc++.h>
int power(int a, int e) {
if (e == 0) return 1;
return e == 1 ? a : a * power(a, e-1);
}
void answer(int a, int b) {
std::cout << a << " + " << b << " = " << a+b << std::endl;
}
int main() {
using ll = long long;
int t;
std::cin >> t;
while (t--) {
int a, b, c;
ll k;
std::cin >> a >> b >> c >> k;
bool good = false;
for (int i = power(10, a-1); i < power(10, a); ++i) {
int left = std::max(power(10, b-1), power(10, c-1) - i);
int right = std::min(power(10, b)-1, power(10, c) - 1 - i);
if (left > right) continue;
int have = right - left + 1;
if (k <= have) {
answer(i, left + k - 1);
good = true;
break;
}
k -= have;
}
if (!good) std::cout << "-1" << std::endl;
}
return 0;
}
|
1835
|
B
|
Lottery
|
$n$ people indexed with integers from $1$ to $n$ came to take part in a lottery. Each received a ticket with an integer from $0$ to $m$.
In a lottery, one integer called target is drawn uniformly from $0$ to $m$. $k$ tickets (or less, if there are not enough participants) with the closest numbers to the target are declared the winners. In case of a draw, a ticket belonging to the person with a smaller index is declared a winner.
Bytek decided to take part in the lottery. He knows the values on the tickets of all previous participants. He can pick whatever value he wants on his ticket, but unfortunately, as he is the last one to receive it, he is indexed with an integer $n + 1$.
Bytek wants to win the lottery. Thus, he wants to know what he should pick to maximize the chance of winning. He wants to know the smallest integer in case there are many such integers. Your task is to find it and calculate his chance of winning.
|
Let's assume that Bytek has selected a certain position $c$. Let the closest occupied position to the left be $d$, and the closest occupied position to the right be $e$. Let's denote the position of the $k$-th person to the left as $a$ and the $k$-th person to the right as $b$ (on the picture $k=3$). Note that for Bytek to win, the target position should be closer to him than $a$ and closer to him than $b$. So his winning range is in the interval $(\frac{a+c}{2}, \frac{b+c}{2})$. It will either have a length of $\lfloor \frac{b-a}{2}-1 \rfloor$ or $\lfloor \frac{b-a}{2}-2 \rfloor$, which depends only on whether he chooses an even or odd position relative to the people on positions $a$ and $b$. So the solution to the task was to consider each pair of people standing next to each other and see what happens if Bytek stands between them. To do this, we find the person $k$ positions to the left and $k$ positions to the right for Bytek and then check what the result will be if Bytek stands on the leftmost position inside this interval and what if Bytek stands on the second position from the left inside this interval. The other positions in this interval would give Bytek the same results but wouldn't be the leftmost. In addition, we should look at what would happen if Bytek stood in a position where someone is already standing (this may help if there is not enough space between consecutive people). There are also two more edge cases - from the left and the right. One of these cases is to look at what would happen if Bytek stands one or two positions in front of the $k$-th person from the left. This position would give Bytek the biggest winning range containing $0$. The other case is analogous from the right. The final complexity is $\mathcal{O}(n)$ or $\mathcal{O}(n \log n)$ based on implementation.
|
[
"binary search",
"brute force",
"greedy",
"math",
"two pointers"
] | 2,500
|
#include <bits/stdc++.h>
#define forr(i, n) for (int i = 0; i < n; i++)
#define FOREACH(iter, coll) for (auto iter = coll.begin(); iter != coll.end(); ++iter)
#define FOREACHR(iter, coll) for (auto iter = coll.rbegin(); iter != coll.rend(); ++iter)
#define lbound(P, K, FUN) ({auto SSS=P, PPP = P-1, KKK=(K)+1; while(PPP+1!=KKK) {SSS = (PPP+(KKK-PPP)/2); if(FUN(SSS)) KKK = SSS; else PPP = SSS;} PPP; })
#define testy() \
int _tests; \
cin >> _tests; \
FOR(_test, 1, _tests)
#define CLEAR(tab) memset(tab, 0, sizeof(tab))
#define CONTAIN(el, coll) (coll.find(el) != coll.end())
#define FOR(i, a, b) for (int i = a; i <= b; i++)
#define FORD(i, a, b) for (int i = a; i >= b; i--)
#define MP make_pair
#define PB push_back
#define ff first
#define ss second
#define deb(X) X;
#define SIZE(coll) ((int)coll.size())
#define M 1000000007
#define INF 1000000007LL
using namespace std;
long long n, m, k;
long long poz_l, poz_p;
vector<long long> v;
long long policz_ile(long long strzal)
{
while (poz_l < n && v[poz_l] < strzal)
poz_l++;
while (poz_p < n && v[poz_p] <= strzal)
poz_p++;
long long pocz = poz_p < k ? 0 : (strzal + v[poz_p - k]) / 2 + 1;
long long kon = poz_l + k - 1 >= n ? m : (v[poz_l + k - 1] + strzal - 1) / 2;
return max(0ll, kon - pocz + 1);
}
int solve()
{
cin >> n >> m >> k;
long long a;
forr(i, n)
{
cin >> a;
v.PB(a);
}
sort(v.begin(), v.end());
v.PB(m + 1);
long long res = policz_ile(0), best = 0;
forr(i, n)
{
long long pocz = i == 0 ? max(0ll, v[i] - 2) : max(v[i] - 2, v[i - 1] + 3);
long long kon = min(m, v[i] + 2);
for (long long s = pocz; s <= kon; s++)
{
long long ile = policz_ile(s);
if (ile > res)
{
res = ile;
best = s;
}
}
}
cout << res << " " << best << '\n';
return 0;
}
int main()
{
std::ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
|
1835
|
C
|
Twin Clusters
|
Famous worldwide astrophysicist Mleil waGrasse Tysok recently read about the existence of twin galaxy clusters. Before he shares this knowledge with the broader audience in his podcast called S.tarT-ok, he wants to prove their presence on his own. Mleil is aware that the vastness of the universe is astounding (almost as astounding as his observation skills) and decides to try his luck and find some new pair of twin clusters.
To do so, he used his TLEscope to observe a part of the night sky that was not yet examined by humanity in which there are exactly $2^{k + 1}$ galaxies in a row. $i$-th of them consist of exactly $0 \le g_i < 4^k$ stars.
A galaxy cluster is any non-empty contiguous segment of galaxies. Moreover, its' trait is said to be equal to the bitwise XOR of all values $g_i$ within this range.
Two galaxy clusters are considered twins if and only if they have the same traits and their corresponding segments are \textbf{disjoint}.
Write a program that, for many scenarios, will read a description of a night sky part observed by Mleil and outputs a location of two intervals belonging to some twin clusters pair, or a single value $-1$ if no such pair exists.
|
Deterministic solution: Let us first look for segments that zeros first $k$ (out of $2k$) bits. Since we have $n = 2^{k + 1}$, then we have $n + 1$ prefix xors of the array (along with en empty prefix). Let us look at the xor prefix modulo $2^k$. Each time we have a prefix xor that has already occurred before let us match it with this previous occurrence. We will find at least $2^k + 1$ such segments. Note that segments have pairwise different ends and pairwise different beginnings. Each of those segments generates some kind of xor value on the other $k$ bits. Since there is only $2^k$ different possible values, due to pigeon principle there will be two segments that generate same xor. We select those two intervals. If they are disjoint then we already found the answer. Otherwise the final answer will be the xor of those two segments (values that are covered only by one of them). It can be showed that we will obtain two disjoint, non-empty segments. Nondeterministic solution: If there are any duplicates in the array, then we can take two one-element arrays and obtain answer. From now on we will assume that no duplicates occur in the array. Let us observe that number of valid segments is equal to ${n \choose 2} + n \ge 2^{2k + 1}$ which is over twice larger than all possible xor values for a segment which is $2^{2k}$. This suggest, that chances of collision of two random segments is quite high. For simplicity let us assume there is exactly $2^{2k + 1}$ segments. Let us look at the final distribution over the xors used by segments. It can be showed by exchange argument, that the the distribution that needs the most random tosses to obtain collision is the one in which every xor value is used by exactly two segments. Since we choose segments randomly, by birthday paradox the expected time of obtaining a collision is around 2^k. Now there is a chance, that we will toss the same segment twice, but if we multiply the number of tossing by $\log(n)$ then chance that we find two different segments is very high (in reality even less random choices are necessary). There is another issue, even if we find two different segments with the same xor values. They can use common elements. But then we can simply take only the elements that belong to the exactly one of them. Still if the segments had common end one of the obtained segments would be empty. To omit this issue let us see that the second obtained segment would have xor equal to $0$. So now we can take any prefix and corresponding suffix as an answer. Unfortunately this segment can have length $1$. But in this case the only element in the segment has to be equal to $0$. There must be at most one number $0$ in the array, so we can simply get rid of it (shorten the array by one). The analysis still holds (with some slight modifications).
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"math",
"probabilities"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int k, n;
scanf("%d", &k);
n = 2 << k;
vector <long long> input(n + 1);
vector <int> memHighBits(1 << k, -1);
vector <pair <int, int> > memLowBits(1 << k, {-1, -1});
auto addInterval = [&memLowBits, &input](int s, int e) {
const int remXor = input[e] ^ input[s - 1];
auto &[os, oe] = memLowBits[remXor];
if (os == -1) {
os = s, oe = e;
return false;
}
if (oe < s) {
printf("%d %d %d %d\n", os, oe, s, e);
} else {
printf("%d %d %d %d\n", min(s, os), max(s, os) - 1, oe + 1, e);
}
return true;
};
memHighBits[0] = 0;
for (int i = 1; i <= n; ++i) {
scanf("%lld", &input[i]);
input[i] ^= input[i - 1];
}
for (int i = 1; i <= n; ++i) {
if (memHighBits[input[i] >> k] != -1) {
if (addInterval(memHighBits[input[i] >> k] + 1, i)) {
break;
}
}
memHighBits[input[i] >> k] = i;
}
}
int main()
{
int cases;
scanf("%d", &cases);
while (cases--) {
solve();
}
return 0;
}
|
1835
|
D
|
Doctor's Brown Hypothesis
|
The rebels have been crushed in the most recent battle with the imperial forces, but there is a ray of new hope.
Meanwhile, on one of the conquered planets, Luke was getting ready for an illegal street race (which should come as no surprise, given his family history). Luke arrived at the finish line with 88 miles per hour on his speedometer. After getting out of the car, he was greeted by a new reality. It turns out that the battle has not happened yet and will start in exactly $k$ hours.
The rebels have placed a single battleship on each of the $n$ planets. $m$ unidirectional wormholes connect the planets. Traversing each wormhole takes exactly one hour. Generals of the Imperium have planned the battle precisely, but their troops cannot dynamically adapt to changing circumstances. Because of this, it is enough for the rebels to move some ships around before the battle to confuse the enemy, secure victory and change the galaxy's fate.
Owing to numerous strategical considerations, which we now omit, the rebels would like to choose two ships that will switch places so that both of them will be on the move for the whole time (exactly $k$ hours). In other words, rebels look for two planets, $x$ and $y$, such that paths of length $k$ exist from $x$ to $y$ and from $y$ to $x$.
Because of the limited fuel supply, choosing one ship would also be acceptable. This ship should fly through the wormholes for $k$ hours and then return to its initial planet.
How many ways are there to choose the ships for completing the mission?
|
As both vertices must visit each other, they must be in the same strongly connected component. We can compute all SCC and solve for them independently. Further, we will assume that we are solving for a fixed SCC. The critical observation is that $n^3$ is enormous, and we can visit an entire graph. This gives us hope that if we fix a vertex $v$, we can represent all vertices that are reachable from it. If we compute the greatest common divisor of all cycles in our graph $g$, then all paths from a fixed vertex $s$ to a vertex $t$ have the same remainder modulo $g$. Moreover, we can always find such if we are looking for a long enough path and the correct remainder. It turns out that $n^3$ is a large enough bound for such paths. Now we have to find the greatest common divisor of all cycles in the graph. There are many ways (including linear), but we are going to present $\mathcal{O}(n \log n)$ here. First, find any cycle in the graph. As $g$ has to divide it, we just have to consider its divisors. We'll develop a quick way to find if a divisor $d$ divides $g$. To do this, we check if there is a colouring with colours from $0$ to $d - 1$, such that for every edge $\langle u, v \rangle$, $colour (v) = (colour (u) + 1) \mod d$. We can check for such colouring with a simple DFS in a linear time. To obtain the right complexity, we'll only check prime divisors (and their powers, and take the least common multiple of the ones which divide $g$. Now we have to find all pairs $\langle s, t \rangle$ such that there are paths from $s$ to $t$ and from $t$ to $s$ of length $k$. We have two cases. Either $g | k$ and $colour(s) = colour(t)$ or $2 | g$ and $k = g / 2 \mod g$ and $colour(s) = (colour(t) + g / 2) \mod g$. After preprocessing, we can check both cases in $\mathcal{O}(g)$ time. The final complexity is $\mathcal{O}(n \log n)$ or $\mathcal{O}(n)$ depending on the implementation.
|
[
"dfs and similar",
"graphs",
"math",
"number theory"
] | 2,900
|
#include<bits/stdc++.h>
using namespace std;
#define sz(s) (int)s.size()
#define all(s) s.begin(), s.end()
#define pb push_back
#define FOR(i, n) for(int i = 0; i < n; i++)
using vi = vector<int>;
using vvi = vector<vi>;
struct SCC {
int cnt = 0;
vi vis, scc_nr;
vvi scc_list, DAG;
SCC(){}
SCC(vvi & G){
// G is 0 indexed!
int n = sz(G);
vvi G_rev(n);
vis = scc_nr = vi(n);
vi postorder;
for(int i = 0; i < n; i++)
if(!vis[i])
dfs_post(i, G, G_rev, postorder);
vis = vi(n);
while(sz(postorder)){
auto akt = postorder.back();
postorder.pop_back();
if(!vis[akt]){
DAG.emplace_back();
scc_list.emplace_back();
dfs_rev(akt, G_rev);
cnt++;
}
}
// optional
for(int i = 0; i < sz(DAG); i++){
sort(all(DAG[i]));
DAG[i].resize(unique(all(DAG[i])) - DAG[i].begin());
}
}
void dfs_post(int start, vvi & G, vvi & G_rev, vi & postorder){
vis[start] = 1;
for(auto & u : G[start]){
G_rev[u].pb(start);
if(!vis[u])
dfs_post(u, G, G_rev, postorder);
}
postorder.pb(start);
}
void dfs_rev(int start, vvi & G_rev){
vis[start] = true;
scc_list.back().pb(start);
scc_nr[start] = cnt;
for(auto & u : G_rev[start])
if(!vis[u])
dfs_rev(u, G_rev);
else if(scc_nr[u] != cnt)
DAG[scc_nr[u]].pb(cnt);
}
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
long long n, m, k;
cin >> n >> m >> k;
vvi G(n);
set<pair<int, int>> edges;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
a--, b--;
G[a].pb(b);
edges.insert({a, b});
}
SCC scc(G);
vi coloring(n, -1);
auto try_coloring = [&](int num_col, const vi& group)
{
vi visited;
function<bool(int)> dfs = [&](int start){
visited.pb(start);
bool good_coloring = true;
for (auto & u : G[start])
{
if (scc.scc_nr[u] != scc.scc_nr[start])
{
continue;
}
if (coloring[u] == -1)
{
coloring[u] = (coloring[start] + 1) % num_col;
good_coloring &= dfs(u);
}
else
{
good_coloring &= coloring[u] == (coloring[start] + 1) % num_col;
}
if (not good_coloring)
{
break;
}
}
return good_coloring;
};
coloring[group[0]] = 0;
if (not dfs(group[0]))
{
for (auto & u : visited)
{
coloring[u] = -1;
}
return vvi();
}
else
{
vvi ret(num_col);
for (auto & u : visited)
{
ret[coloring[u]].push_back(u);
}
return ret;
}
};
long long ans = 0;
vi depths(n, -1);
for (vi& group : scc.scc_list)
{
n = sz(group);
if (n == 1 and edges.count({group[0], group[0]}) == 0)
{
continue;
}
int gcd = -1;
function<void(int)> dfs_depths = [&](int start)
{
for (auto & u : G[start])
{
if (scc.scc_nr[u] != scc.scc_nr[start])
{
continue;
}
if (depths[u] == -1)
{
depths[u] = depths[start] + 1;
dfs_depths(u);
}
else {
int diff = abs(depths[u] - (depths[start] + 1));
if (diff)
{
if (gcd == -1)
{
gcd = diff;
}
else
{
gcd = __gcd(gcd, diff);
}
}
}
}
};
depths[group[0]] = 0;
dfs_depths(group[0]);
assert(gcd != -1);
vvi by_color = try_coloring(gcd, group);
assert(sz(by_color) != 0);
if (k % gcd == 0)
{
FOR (i, gcd)
{
ans += sz(by_color[i]) + 1ll * sz(by_color[i]) * (sz(by_color[i]) - 1) / 2;
}
}
else if (k % gcd * 2 == gcd)
{
FOR (i, gcd / 2)
{
ans += 1ll * sz(by_color[i]) * sz(by_color[i + gcd / 2]);
}
}
}
cout << ans << '\n';
}
|
1835
|
E
|
Old Mobile
|
During the latest mission of the starship U.S.S. Coder, Captain Jan Bitovsky was accidentally teleported to the surface of an unknown planet.
Trying to find his way back, Jan found an artifact from planet Earth's ancient civilization — a mobile device capable of interstellar calls created by Byterola. Unfortunately, there was another problem. Even though Jan, as a representative of humans, knew perfectly the old notation of the cell phone numbers, the symbols on the device's keyboard were completely worn down and invisible to the human eye. The old keyboards had exactly $m + 1$ buttons, one for each digit from the base $m$ numerical system, and one single backspace button allowing one to erase the last written digit (if nothing was written on the screen, then this button does nothing, but it's still counted as pressed).
Jan would like to communicate with his crew. He needs to type a certain number (also from the base $m$ numerical system, that is, digits from $0$ to $m - 1$). He wants to know the expected number of button presses necessary to contact the U.S.S. Coder. Jan always chooses the most optimal buttons based on his current knowledge. Buttons are indistinguishable until pressed. Help him!
|
Let us make some observations. First of them is that if a phone number consists of two or more digits of the same kind then we will always pay exactly $1$ click for each but the first occurrence of it (it follows from the fact, that we have to already the key responsible for this digit). This is why we can reduce the problem to finding a solution for a phone number with unique digits. Secondly, since all the buttons are indistinguishable at the beginning then the order of digits in the input does not matter. This leads to the conclusion that what we want to compute is some kind of $dp[i][j]$, which stands for expected time of completing number if $i$ buttons that we have to eventually click are not yet discovered (good buttons), and $j$ buttons that we don't need are also not yet discovered (bad buttons). Unfortunately the BackSpace key and necessity of clearing incorrect prefix of the phone number complicates things significantly. We will create additional dimension of the $dp$ responsible for the state of the prefix and the information about if we have already clicked backspace. Those four states will be: $EMPTY$ - empty prefix of digits on the screen $GOOD$ - non empty, correct prefix of digits on the screen $BAD$ - non empty prefix that is not prefix of the phone number $BACKSPACE$ - when we have already found a backspace (we assume prefix is correct, or in other words paid in advance) Let us first compute $dp[i][j][BACKSPACE]$. If $i = 0$ then $dp[0][j][BACKSPACE] = 0$. Else we try to click new buttons. If we guess correctly exactly the next button then we get $dp[i][j][BACKSPACE] = 1 + dp[i - 1][j][BACKSPACE]$. Otherwise we could guess one of the remaining good buttons (with probability $\frac{i - 1}{i + j}$. Since we already know backspace location, we can remove it and in future we will pay only $1$ for this digit. We hence get $3 + dp[i - 1][j][BACKSPACE]$ operations. Similarly if we guess bad button we get $dp[i][j][BACKSPACE] = 2 + dp[i][j - 1][BACKSPACE]$. Rest of the states can be computed using similar approach: $dp[i][j][GOOD]= \begin{cases} 0, & \text{if } i = 0 \\ 1 + dp[i - 1][j][GOOD], & \text{when tossing exactly correct digit} \\ 3 + dp[i - 1][j][BAD], & \text{for one of the remaining good digits} \\ & \text{(in future we will have to remove it and use in correct place)} \\ 2 + dp[i][j - 1][BAD], & \text{for guessing bad digit} \\ 2 + dp[i][j][BACKSPACE], & \text{when clicking backspace button} \\ & \text{(removing good digit from the prefix which we need to fix)} \end{cases}$ $dp[i][j][BAD]= \begin{cases} 3 + dp[i - 1][j][BAD], & \text{when guessing any good digit} \\ 2 + dp[i][j - 1][BAD], & \text{for bad digit} \\ dp[i][j][BACKSPACE], & \text{when clicking backspace} \\ & \text{(this click was paid in advance)} \end{cases}$ $dp[i][j][EMPTY]= \begin{cases} 1 + dp[i - 1][j][GOOD], & \text{when tossing correct digit} \\ 3 + dp[i - 1][j][BAD], & \text{when guessing other good digit} \\ 2 + dp[i][j - 1][BAD], & \text{for bad digit} \\ 1 + dp[i][j][BACKSPACE], & \text{when clicking backspace} \end{cases}$ Even though transitions may look scary, they are similar for different dimensions and common implementation can be used.
|
[
"combinatorics",
"dp",
"probabilities"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
constexpr int MAX_M = 1000 + 7;
constexpr int PRECISION = 9;
constexpr long long MOD = 1e9 + 7;
long long mod_inv[MAX_M];
long long DP[MAX_M][MAX_M][2][2];
long long DPprob[MAX_M][MAX_M][2][2];
bool updated[MAX_M][MAX_M][2][2];
// DP[correct][incorrect][backspace][bad suffix]
long long calc_mod_inv(long long n)
{
long long res = 1;
long long exp = MOD - 2;
while (exp)
{
if (exp & 1)
{
res = (res * n) % MOD;
}
exp >>= 1;
n = (n * n) % MOD;
}
return res;
}
void calc_DP(int digits, int needed)
{
DP[0][0][0][0] = 0;
DPprob[0][0][0][0] = 1;
struct ID
{
int x, y, z, s;
};
queue <ID> dp_queue;
dp_queue.push({0, 0, 0, 0});
while(!dp_queue.empty())
{
auto [x, y, z, s] = dp_queue.front();
dp_queue.pop();
if (updated[x][y][z][s])
{
continue;
}
updated[x][y][z][s] = true;
long long left = digits + 1 - x - y - z;
long long corr = needed - x;
long long incorr = digits - needed - y;
long long prob = DPprob[x][y][z][s];
if (corr == 0 and s == 0)
{
// done
continue;
}
// correct suffix
if (s == 0)
{
if (corr > 0)
{
// found the one correct digit (no need to delete)
long long opt_prob = (prob * mod_inv[left]) % MOD;
DPprob[x + 1][y][z][0] = (DPprob[x + 1][y][z][0] + opt_prob) % MOD;
DP[x + 1][y][z][0] = (DP[x + 1][y][z][0] + DP[x][y][z][0] * mod_inv[left]) % MOD;
// found a needed but currently wrong digit (needs to be deleted)
if (corr > 1)
{
if (z == 0) // if backspace is not known, the suffix is bad
{
long long opt_prob = ((prob * (corr - 1) % MOD) * mod_inv[left]) % MOD;
DPprob[x + 1][y][z][1] = (DPprob[x + 1][y][z][1] + opt_prob) % MOD;
DP[x + 1][y][z][1] = (DP[x + 1][y][z][1] + ((corr - 1) * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;
dp_queue.push({x + 1, y, z, 1});
}
else // if backspace is known, the suffix can be instantly repaired
{
long long opt_prob = ((prob * (corr - 1) % MOD) * mod_inv[left]) % MOD;
DPprob[x + 1][y][z][0] = (DPprob[x + 1][y][z][0] + opt_prob) % MOD;
DP[x + 1][y][z][0] = (DP[x + 1][y][z][0] + ((corr - 1) * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;
}
}
dp_queue.push({x + 1, y, z, 0});
}
if (incorr > 0)
{
// found an incorrect digit
if (z == 0)
{
long long opt_prob = (prob * incorr % MOD) * mod_inv[left] % MOD;
DPprob[x][y + 1][z][1] = (DPprob[x][y + 1][z][1] + opt_prob) % MOD;
DP[x][y + 1][z][1] = (DP[x][y + 1][z][1] + (incorr * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;
dp_queue.push({x, y + 1, z, 1});
}
else // suffix can be repaired
{
long long opt_prob = ((prob * incorr % MOD) * mod_inv[left]) % MOD;
DPprob[x][y + 1][z][0] = (DPprob[x][y + 1][z][0] + opt_prob) % MOD;
DP[x][y + 1][z][0] = (DP[x][y + 1][z][0] + (incorr * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;
dp_queue.push({x, y + 1, z, 0});
}
}
if (z == 0)
{
if (x > 0) // deleted correct digit
{
long long opt_prob = prob * mod_inv[left] % MOD;
DPprob[x][y][1][0] = (DPprob[x][y][1][0] + opt_prob) % MOD;
DP[x][y][1][0] = (DP[x][y][1][0] + mod_inv[left] * DP[x][y][0][0] + 2 * opt_prob) % MOD;
}
else // deleted nothing
{
long long opt_prob = prob * mod_inv[left] % MOD;
DPprob[x][y][1][0] = (DPprob[x][y][1][0] + opt_prob) % MOD;
DP[x][y][1][0] = (DP[x][y][1][0] + mod_inv[left] * DP[x][y][0][0] + opt_prob) % MOD;
}
dp_queue.push({x, y, 1, 0});
}
}
if (s == 1)
{
if (corr > 0)
{
// found a needed but currently wrong digit (needs to be deleted)
long long opt_prob = (prob * corr % MOD) * mod_inv[left] % MOD;
DPprob[x + 1][y][z][1] = (DPprob[x + 1][y][z][1] + opt_prob) % MOD;
DP[x + 1][y][z][1] = (DP[x + 1][y][z][1] + (corr * mod_inv[left] % MOD) * DP[x][y][z][1] + 2 * opt_prob) % MOD;
dp_queue.push({x + 1, y, z, 1});
}
if (incorr > 0)
{
// found an incorrect digit
long long opt_prob = (prob * incorr % MOD) * mod_inv[left] % MOD;
DPprob[x][y + 1][z][1] = (DPprob[x][y + 1][z][1] + opt_prob) % MOD;
DP[x][y + 1][z][1] = (DP[x][y + 1][z][1] + (incorr * mod_inv[left] % MOD) * DP[x][y][z][1] + 2 * opt_prob) % MOD;
dp_queue.push({x, y + 1, z, 1});
}
if (z == 0)
{
// deleted bad suffix
long long opt_prob = prob * mod_inv[left] % MOD;
DPprob[x][y][1][0] = (DPprob[x][y][1][0] + opt_prob) % MOD;
DP[x][y][1][0] = (DP[x][y][1][0] + mod_inv[left] * DP[x][y][0][1]) % MOD;
dp_queue.push({x, y, 1, 0});
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
mod_inv[0] = 1;
for (int i = 1; i < MAX_M; ++i) {
mod_inv[i] = calc_mod_inv(i);
assert (mod_inv[i] * i % MOD == 1);
}
int n, m;
cin >> n >> m;
set <int> different_digits;
for (int i = 0; i < n; ++i)
{
int p;
cin >> p;
different_digits.insert(p);
}
int needed = different_digits.size();
calc_DP(m, needed);
long long result = 0;
for (int i = 0; i <= MAX_M; ++i)
{
result = (result + DP[needed][i][0][0]) % MOD;
result = (result + DP[needed][i][1][0]) % MOD;
}
cout << (result + n) % MOD << "\n";
return 0;
}
|
1835
|
F
|
Good Graph
|
You are given a bipartite graph $G$ with the vertex set in the left part $L$, in the right part $R$, and $m$ edges connecting these two sets. We know that $|L| = |R| = n$.
For any subset $S \subseteq L$, let $N(S)$ denote the set of all neighbors of vertices in $S$. We say that a subset $S \subseteq L$ in graph $G$ is tight if $|S| = |N(S)|$. We say that graph $G$ is good if $\forall_{S \subseteq L}, |S| \leq |N(S)|$.
Your task is to verify whether the graph is good and, if so, to optimize it. If the graph is not good, find a subset $S \subseteq L$ such that $|S| > |N(S)|$. However, if the graph is good, your task is to find a good bipartite graph $G'$ with the same set of vertices $L \cup R$, in which $\forall_{S \subseteq L}$, $S$ is tight in $G$ if and only if $S$ is tight in $G'$. If there are multiple such graphs, choose one with the smallest possible number of edges. If there are still multiple such graphs, print any.
|
According to Hall's theorem, a graph is good if and only if a perfect matching exists. We run any reasonable algorithm to find a perfect matching (e.g. the Hopcroft-Karp's algorithm). We call the found matching $\mathcal{M}$ (any perfect matching is fine). We look for a counterexample if we do not find a perfect matching. One way to find it is to run s similar DFS as in the Hopcroft-Karp algorithm from any unmatched vertex on the left side. As a reminder, we visit all neighbours of vertices on the left side and only the vertex with which we are matched for vertices on the right side. As we won't see any unmatched vertex on the right side (otherwise, we'd found an augmenting path), the set of visited vertices on the left side has fewer neighbours than its size - we found our counterexample. As our graph is good, we should examine the construction of tight sets. Lemma 1 Function $N(S)$ is submodular. Proof Consider two sets $A \subseteq B$ and a vertex $v \notin B$. For each vertex $u \in N(B + v) \setminus N(B)$, we know that $u \in N(A + v)$ and $u \notin N(A)$, thus, $u \in N(A + v) \setminus N(A)$. We conclude that $|N(B + v) \setminus N(B)| \leq |N(A + v) \setminus N(A)|$; thus, the function is submodular. Lemma 2 Tight sets are closed under intersection and sum. Proof Consider two tight sets, $A$ and $B$. From Lemma 1, we get that $|A| + |B| = |N(A)| + |N(B)| \geq |N(A \cup B)| + |N(A \cap B)| \geq |A \cup B| + |A \cap B| = |A| + |B|$, where the last inequality results from the graph being good. As we get the same value on both sides, all inequalities become equalities. In particular, with the graph being good, we get that $|N(A \cup B)| = |A \cup B|$ and $|N(A \cap B)| = |A \cap B|$. That proves that sets $A \cup B$, and $A \cap B$ are tight. We define $T(v)$ as the minimal tight set containing vertex $v$. We know such a set exists as tight sets are closed under the intersection. From that, we can conclude that any tight set can be represented as a sum of minimal tight sets. Thus, we are only interested in keeping the same minimal tight sets. We can find the minimal tight sets using the same DFS algorithm as for finding a counterexample. As the graph is large, use bitsets to optimise it. To find the smallest graph, we analyse these sets in order of nondecreasing sizes. For simplicity, we erase duplicates. When we analyse the set, we distinguish the new vertices (the ones that haven't been touched yet). There is always a new vertex, as this is the minimal tight set for at least one vertex (and we removed duplicates). If there is only one new vertex $v$, we can add an edge from $v$ to $M(v)$. Otherwise, we have to connect these vertices $v_1, v_2, \ldots, v_k$ into a cycle - we create edges $\langle v_1, M(v_1) \rangle, \langle M(v_1), v_2, \rangle \ldots, \langle v_k, M(v_k) \rangle, \langle M(v_k), v_1 \rangle$. If we have less than $2 \cdot k$ edges, then there exists a vertex $v_i$ with a degree equal to $1$ - we could pick this vertex, and it'd create a minimal tight set. We still have to handle other vertices in this (i.e. the ones which are not new). We pick a representative $v$ for our cycle, which will become a representative for this set. Similarly, we have a representative for other sets. We find a partition of these vertices into a minimal number of tight sets. We add an edge between these representatives and our vertex $v$. We use a similar argument as before - if we didn't add this edge, we would find different minimal tight sets. To handle representatives, we use a disjoint set union structure. The final complexity of this algorithm is $\mathcal{O}(N^3 / 64)$.
|
[
"bitmasks",
"dfs and similar",
"graph matchings",
"graphs",
"implementation"
] | 3,500
|
#include <bits/stdc++.h>
#define forr(i, n) for (int i = 0; i < n; i++)
#define FOREACH(iter, coll) for (auto iter = coll.begin(); iter != coll.end(); ++iter)
#define FOREACHR(iter, coll) for (auto iter = coll.rbegin(); iter != coll.rend(); ++iter)
#define lbound(P, K, FUN) ({auto SSS=P, PPP = P-1, KKK=(K)+1; while(PPP+1!=KKK) {SSS = (PPP+(KKK-PPP)/2); if(FUN(SSS)) KKK = SSS; else PPP = SSS;} PPP; })
#define testy() \
int _tests; \
cin >> _tests; \
FOR(_test, 1, _tests)
#define CLEAR(tab) memset(tab, 0, sizeof(tab))
#define CONTAIN(el, coll) (coll.find(el) != coll.end())
#define FOR(i, a, b) for (int i = a; i <= b; i++)
#define FORD(i, a, b) for (int i = a; i >= b; i--)
#define MP make_pair
#define PB push_back
#define ff first
#define ss second
#define deb(X) X;
#define SIZE(coll) ((int)coll.size())
using namespace std;
const int MXN = 1007;
int n, m;
vector<int> G[MXN];
bitset<MXN> bs[MXN], edge[MXN];
// MATCHING
const int MXM = 1007 * 2;
int skojX[MXM], skojY[MXM];
bool vis[MXM];
bool dfs_m(int x)
{
vis[x] = 1;
FOREACH(it, G[x])
if (!skojY[*it] || (!vis[skojY[*it]] && dfs_m(skojY[*it])))
{
skojX[x] = *it;
skojY[*it] = x;
return 1;
}
return 0;
}
bool skoj()
{
int czy = 1;
int res = 0;
while (czy)
{
czy = 0;
CLEAR(vis);
FOR(i, 1, n)
if (!vis[i] && !skojX[i] && dfs_m(i))
{
czy = 1;
res++;
}
}
return res == n;
}
// END OF MATCHING
void dfs(int nr, bitset<MXN> &visited, bitset<MXN> &to_visit)
{
visited[nr] = 1;
to_visit[nr] = 0;
to_visit = to_visit | (edge[nr] & (~visited));
for (int i = to_visit._Find_first(); i < SIZE(to_visit); i = to_visit._Find_next(i))
dfs(i, visited, to_visit);
}
int solve()
{
cin >> n >> m;
forr(i, m)
{
int a, b;
cin >> a >> b;
G[a].PB(b);
}
int rres = skoj();
if (rres)
{
FOR(i, 1, n)
{
for (auto j : G[i])
{
edge[i][skojY[j]] = 1;
}
}
unordered_map<bitset<MXN>, vector<int>> mapa;
vector<pair<int, int>> vec, res;
FOR(i, 1, n)
{
bitset<MXN> to_visit;
dfs(i, bs[i], to_visit);
mapa[bs[i]].PB(i);
}
for (auto p : mapa)
{
vector<int> l = p.ss;
vec.PB({bs[l[0]].count(), l[0]});
if (l.size() == 1)
{
res.PB({l[0], l[0]});
continue;
}
for (int i = 0; i < SIZE(l); i++)
{
res.PB({l[i], l[i]});
res.PB({l[i], l[(i + 1) % SIZE(l)]});
}
}
sort(vec.begin(), vec.end());
forr(i, SIZE(vec))
{
int nr = vec[i].ss;
bitset<MXN> b;
for (int j = i - 1; j >= 0; j--)
if (vec[j].ff < vec[i].ff)
{
int nr2 = vec[j].ss;
if (bs[nr][nr2] && !b[nr2])
{
b |= bs[nr2];
res.PB({nr, nr2});
}
}
}
cout << "YES" << '\n';
cout << res.size() << '\n';
for (auto p : res)
cout << p.ff << " " << p.ss + n << '\n';
}
else
{
CLEAR(vis);
FOR(i, 1, n)
{
if (skojX[i] == 0)
{
dfs_m(i);
break;
}
}
vector<int> v;
FOR(i, 1, n)
{
if (vis[i])
v.PB(i);
}
cout << "NO" << '\n';
cout << v.size() << '\n';
for (auto el : v)
cout << el << " ";
cout << '\n';
}
return 0;
}
int main()
{
std::ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
|
1836
|
A
|
Destroyer
|
John is a lead programmer on a destroyer belonging to the space navy of the Confederacy of Independent Operating Systems. One of his tasks is checking if the electronic brains of robots were damaged during battles.
A standard test is to order the robots to form one or several lines, in each line the robots should stand one after another. After that, each robot reports the number of robots standing in front of it \textbf{in its line}.
\begin{center}
{\small An example of robots' arrangement (the front of the lines is on the left). The robots report the numbers above.}
\end{center}
The $i$-th robot reported number $l_i$. Unfortunately, John does not know which line each robot stands in, and can't check the reported numbers. Please determine if it is possible to form the lines in such a way that all reported numbers are correct, or not.
|
We can simplify the statement to the following - can we divide the input sequence into multiple arithmetic sequences starting with $0$ and a common difference equal to $1$? Note that for each such arithmetic sequence, if a number $x > 0$ belongs to it, then $x - 1$ must also be included in it. Thus, if we denote $cnt_x$ as the number of occurrences of $x$ in the input, we must have $cnt_x \geq cnt_{x + 1}$ for each $x \geq 0$. We can note that if such a condition is fulfilled, we can always divide the input into described arithmetic sequences. We can implement it straightforwardly in $\mathcal{O}(N + L)$, where $L$ is the maximum value in the input.
|
[
"implementation",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
int main()
{
int cases;
scanf("%d", &cases);
while (cases--) {
int n;
scanf ("%d", &n);
vector <int> cnt(n + 1);
for (int i = 0; i < n; i++) {
int d;
scanf("%d", &d);
if (d < n) {
cnt[d]++;
} else {
cnt[n] = N;
}
}
bool good = true;
for (int i = 1; i <= n; i++) if (cnt[i] > cnt[i-1]) {
good = false;
break;
}
puts(good ? "YES" : "NO");
}
}
|
1836
|
B
|
Astrophysicists
|
In many, many years, far, far away, there will be a launch of the first flight to Mars. To celebrate the success, $n$ astrophysicists working on the project will be given bonuses of a total value of $k$ gold coins.
You have to distribute the money among the astrophysicists, and to make it easier, you have to assign bonuses in silver coins. Each gold coin is worth $g$ silver coins, so you have to distribute all $k \cdot g$ silver coins among $n$ people.
Unfortunately, the company has some financial troubles right now. Therefore, instead of paying the number of silver coins written on the bonus, they decided to round this amount to the nearest integer number of gold coins.
The rounding procedure is as follows. If an astrophysicist has bonus equal to $x$ silver coins, and we denote $r = x \bmod g$, then:
- If $r \geq \lceil \frac{g}{2} \rceil$, the astrophysicist receives $x + (g - r)$ silver coins;
- Otherwise, an astrophysicists receives $x - r$ silver coins.
Note that due to rounding, the total sum of actually paid money is not, in general, equal to $k \cdot g$ silver coins. The operation $a \bmod b$ denotes the remainder of the division of $a$ by $b$. Sum of values before rounding \textbf{has to be equal to $k \cdot g$ silver coins}, but some workers can be assigned $0$ silver coins.You aim to distribute the bonuses so that the company saves as many silver coins due to rounding as possible. Please note that there is always a distribution in which the company spends no more than $k \cdot g$ silver coins.
|
Note that in the perfect world, we'd give each astrophysicist precisely $\lfloor \frac{G - 1}{2} \rfloor$, and we'd spare $N \cdot \lfloor \frac{G - 1}{2} \rfloor$ silver coins. Unfortunately, two things may happen: First, we may run out of money. This is an easy case; it is enough to output $K \cdot G$ if it is less than $\lfloor \frac{G - 1}{2} \rfloor$. Second, we may have some money left. It turns out that an acceptable solution is to give everything to one astrophysicist. The intuition behind it is simple - we are only interested in bonus sizes modulo $G$, and by decreasing the bonus of one astrophysicist, we can get at most $1$ from another one, and by increasing it, we lose $\lfloor \frac{G - 1}{2} \rfloor$. In both cases, it is not worth changing the value.Thus, we got a formula to calculate in $\mathcal{O}(1)$. Thus, we got a formula to calculate in $\mathcal{O}(1)$.
|
[
"greedy",
"math"
] | 1,100
|
#include "bits/stdc++.h"
using namespace std;
int main()
{
int t;
scanf ("%d", &t);
while (t--) {
long long n, k, g;
scanf ("%lld %lld %lld", &n, &k, &g);
long long stolen = min((g - 1) / 2 * n, k * g);
long long rest = (k * g - stolen) % g;
if (rest > 0) {
stolen -= (g - 1) / 2;
long long last = ((g - 1) / 2 + rest) % g;
if (last * 2 < g) {
stolen += last;
} else {
stolen -= g - last;
}
}
printf ("%lld\n", stolen);
}
}
|
1837
|
A
|
Grasshopper on a Line
|
You are given two integers $x$ and $k$. Grasshopper starts in a point $0$ on an OX axis. In one move, it can jump some integer distance, \textbf{that is not divisible by $k$}, to the left or to the right.
What's the smallest number of moves it takes the grasshopper to reach point $x$? What are these moves? If there are multiple answers, print any of them.
|
When $x$ is not divisible by $k$, the grasshopper can reach $x$ in just one jump. Otherwise, you can show that two jumps are always enough. For example, jumps $1$ and $x-1$. $1$ is not divisible by any $k > 1$. Also, $x$ and $x-1$ can't be divisible by any $k > 1$ at the same time. 1837B - Comparison String
|
[
"constructive algorithms",
"math"
] | 800
|
for _ in range(int(input())):
x, k = map(int, input().split())
if x % k != 0:
print(1)
print(x)
else:
print(2)
print(1, x - 1)
|
1837
|
B
|
Comparison String
|
You are given a string $s$ of length $n$, where each character is either < or >.
An array $a$ consisting of $n+1$ elements is compatible with the string $s$ if, for every $i$ from $1$ to $n$, the character $s_i$ represents the result of comparing $a_i$ and $a_{i+1}$, i. e.:
- $s_i$ is < if and only if $a_i < a_{i+1}$;
- $s_i$ is > if and only if $a_i > a_{i+1}$.
For example, the array $[1, 2, 5, 4, 2]$ is compatible with the string <<>>. There are other arrays with are compatible with that string, for example, $[13, 37, 42, 37, 13]$.
The \textbf{cost} of the array is the number of different elements in it. For example, the cost of $[1, 2, 5, 4, 2]$ is $4$; the cost of $[13, 37, 42, 37, 13]$ is $3$.
You have to calculate the minimum cost among all arrays which are compatible with the given string $s$.
|
Suppose there is a segment of length $k$ that consists of equal characters in $s$. This segment implies that there are at least $k+1$ distinct values in the answer: for example, if the segment consists of < signs, the first element should be less than the second element, the second element should be less than the third element, and so on, so the corresponding segment of the array $a$ contains at least $k+1$ different elements. So, the answer is at least $m+1$, where $m$ is the length of the longest segment of the string that consists of equal characters. Can we construct the array $a$ which will contain exactly $m+1$ distinct values? It turns out we can do it with the following greedy algorithm: let's use integers from $0$ to $m$ for our array $a$, and let's construct it from left to right; every time we place an element, we choose either the largest possible integer we can use (if the next character is >) or the smallest possible integer we can use (if the next character is <). For example, for the string <><<<>, the first $6$ elements of the array will be $[0, 3, 0, 1, 2, 3]$ (and we can use any integer from $0$ to $2$ in the last position). That way, whenever a segment of equal characters begins, the current value in the array will be either $m$ or $0$, and we will be able to decrease or increase it $m$ times, so we won't arrive at a situation where, for example, the current value is $0$ and we have to find a smaller integer. So, the problem basically reduces to finding the longest contiguous subsegment of equal characters in $s$. 1837C - Best Binary String
|
[
"greedy"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
int n;
cin >> n;
string s;
cin >> s;
int ans = 1, cur = 1;
for(int i = 1; i < n; i++)
{
if(s[i] != s[i - 1]) cur = 1;
else cur++;
ans = max(ans, cur);
}
cout << ans + 1 << endl;
}
}
|
1837
|
C
|
Best Binary String
|
You are given a string $s$ consisting of the characters 0, 1 and/or ?. Let's call it a pattern.
Let's say that the binary string (a string where each character is either 0 or 1) matches the pattern if you can replace each character ? with 0 or 1 (for each character, the choice is independent) so that the strings become equal. For example, 0010 matches ?01?, but 010 doesn't match 1??, ??, or ????.
Let's define the cost of the binary string as the minimum number of operations of the form "reverse an arbitrary contiguous substring of the string" required to sort the string in non-descending order.
You have to find a binary string with the minimum possible cost among those that match the given pattern. If there are multiple answers, print any of them.
|
First of all, let's try solving an easier problem - suppose we have a binary string, how many operations of the form "reverse a substring" do we have to perform so that it is sorted? To solve this problem, we need to consider substrings of the form 10 in the string (i. e. situations when a zero immediately follows a one). Sorted binary strings should not contain any such substrings, so our goal is to reduce the number of such strings to zero. Let's try to analyze how can we reduce the number of substrings equal to 10 by reversing a substring. Suppose that we want to "remove" a particular substring 10 from the string without causing any new ones to appear. We can reverse the substring that consists of the block of ones and the block of zeroes adjacent to each other; that way, after reversing the substring, these two blocks will be swapped; the block of zeroes will either merge with the block of zeroes to the left, or move to the beginning of the string; the block of ones will either merge with the block of ones to the right, or move to the end of the string. For example, if, in the string 0011101, you reverse the substring from the $3$-rd to the $6$-th position, you get 0001111, and you reduce the number of substrings 10 by one. What if we want to reduce this number by more than one in just one operation? Unfortunately, this is impossible. Suppose we want to affect two substrings 10 with one reverse operation. There will be a substring 01 between them, so, after reversing, it will turn into 10, and we'll reduce the number of substrings 10 only by one. The same when we try to affect three, four or more substrings 10. So, we can reduce the number of substrings 10 only by one in one operation. So, the answer to the problem "count the number of operations required to sort the binary string" is just the number of substrings 10. Okay, back to the original problem. Now we want to replace every question mark so that the resulting string contains as few substrings 10 as possible. You can use dynamic programming of the form $dp_{i,j}$ - the minimum number of substrings if we considered $i$ first characters of the string and the last of them was $j$. Or you can try the following greedy instead: go through the string from left to right, and whenever you encounter a question mark, replace it with the same character as the previous character in the string (if the string begins with a question mark, it should be replaced with 0). That way, you will create as few "blocks" of characters as possible, so the number of times when a block of 1's changes into a block of 0's will be as small as possible. 1837D - Bracket Coloring
|
[
"constructive algorithms",
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
char x = '0';
for (auto& c : s) {
if (c == '?') c = x;
x = c;
}
cout << s << '\n';
}
}
|
1837
|
D
|
Bracket Coloring
|
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example:
- the bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)");
- the bracket sequences ")(", "(" and ")" are not.
A bracket sequence is called beautiful if one of the following conditions is satisfied:
- it is a regular bracket sequence;
- if the order of the characters in this sequence is reversed, it becomes a regular bracket sequence.
For example, the bracket sequences "()()", "(())", ")))(((", "))()((" are beautiful.
You are given a bracket sequence $s$. You have to color it in such a way that:
- every bracket is colored into one color;
- for every color, there is at least one bracket colored into that color;
- for every color, if you write down the sequence of brackets having that color in the order they appear, you will get a beautiful bracket sequence.
Color the given bracket sequence $s$ into the \textbf{minimum} number of colors according to these constraints, or report that it is impossible.
|
What properties do beautiful bracket sequences have? Well, each beautiful sequence is either an RBS (regular bracket sequence) or a reversed RBS. For RBS, the balance (the difference between the number of opening and closing brackets) is non-negative for every its prefix, and equal to zero at the end of the string. For a reversed RBS, the balance is non-positive for every prefix, and zero at the end of the string. So, every beautiful string has balance equal to $0$, and if the string $s$ has non-zero balance, it is impossible to color it. Let's consider the case when the balance of $s$ is $0$. Suppose we calculated the balance on every prefix of $s$, and split it into parts by cutting it along the positions where the balance is $0$. For example, the string (()())())( will be split into (()()), () and )(. For every part of the string we obtain, the balance in the end is equal to $0$, and the balance in the middle of the part is never equal to $0$ (since positions with balance equal to $0$ were the positions where we split the string). So, the balance is either positive in all positions of the part, or negative in all positions of the part; and every string we obtain from cutting $s$ into parts will be beautiful. A concatenation of two RBS'es is always an RBS. The same can be said about the strings which become RBS after reversing. So, for every part we obtain after cutting $s$ into parts, we can determine whether it is an RBS or a reversed RBS, concatenate all RBS'es into one big RBS (by coloring them into color $1$), and concatenate all reversed RBS'es into one string (by coloring them into color $2$). This construction shows that the maximum number of colors is $2$ and allows to obtain the coloring into two colors; so, all that's left to solve the problem is to check whether it's possible to use just one color (it is the case if and only if the given string $s$ is beautiful). 1837E - Playoff Fixing
|
[
"constructive algorithms",
"greedy"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
int n;
cin >> n;
string s;
cin >> s;
vector<int> bal(n + 1);
for(int j = 0; j < n; j++)
if(s[j] == '(')
bal[j + 1] = bal[j] + 1;
else
bal[j + 1] = bal[j] - 1;
if(bal.back() != 0)
cout << -1 << endl;
else
{
if(*min_element(bal.begin(), bal.end()) == 0 || *max_element(bal.begin(), bal.end()) == 0)
{
cout << 1 << endl;
for(int j = 0; j < n; j++)
{
if(j) cout << " ";
cout << 1;
}
cout << endl;
}
else
{
cout << 2 << endl;
vector<int> ans;
int cur = 0;
while(cur < n)
{
int w = (s[cur] == '(' ? 1 : 2);
do
{
cur++;
ans.push_back(w);
}
while(bal[cur] != 0);
}
for(int j = 0; j < n; j++)
{
if(j) cout << " ";
cout << ans[j];
}
cout << endl;
}
}
}
}
|
1837
|
E
|
Playoff Fixing
|
$2^k$ teams participate in a playoff tournament. The teams are numbered from $1$ to $2^k$, in order of decreasing strength. So, team $1$ is the strongest one, team $2^k$ is the weakest one. A team with a smaller number always defeats a team with a larger number.
First of all, the teams are arranged in some order during a procedure called seeding. Each team is assigned another unique value from $1$ to $2^k$, called a seed, that represents its starting position in the playoff.
The tournament consists of $2^k - 1$ games. They are held as follows: the teams are split into pairs: team with seed $1$ plays against team with seed $2$, team with seed $3$ plays against team with seed $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a team loses a game, it is eliminated.
After that, only $2^{k-1}$ teams remain. If only one team remains, it is declared the champion; otherwise, $2^{k-2}$ games are played: in the first one of them, the winner of the game "seed $1$ vs seed $2$" plays against the winner of the game "seed $3$ vs seed $4$", then the winner of the game "seed $5$ vs seed $6$" plays against the winner of the game "seed $7$ vs seed $8$", and so on. This process repeats until only one team remains.
After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular:
- the winner of the tournament gets place $1$;
- the team eliminated in the finals gets place $2$;
- both teams eliminated in the semifinals get place $3$;
- all teams eliminated in the quarterfinals get place $5$;
- all teams eliminated in the 1/8 finals get place $9$, and so on.
Now that we established the rules, we do a little rigging. In particular, we want:
- team $1$ (not team with seed $1$) to take place $1$;
- team $2$ to take place $2$;
- teams $3$ and $4$ to take place $3$;
- teams from $5$ to $8$ to take place $5$, and so on.
For example, this picture describes one of the possible ways the tournament can go with $k = 3$, and the resulting places of the teams:
Some seeds are already reserved for some teams (we are not the only ones rigging the tournament, apparently). We have to fill the rest of the seeds with the remaining teams to achieve the desired placements. How many ways are there to do that? Since that value might be large, print it modulo $998\,244\,353$.
|
Let's investigate the structure of the tournament, starting from the first round. We know that teams from $2^{k-1}+1$ to $2^k$ have to lose during this round. At the same time, there are exactly $2^{k-1}$ losers in this round. So, every pairing has to look like this: a team from $1$ to $2^{k-1}$ versus a team from $2^{k-1}+1$ to $2^k$. Let's try to solve for zero reserved seeds - all $a_i = -1$. So, we only have to count the number of valid tournaments. Let's try to do that starting from the top. The winner is team $1$. The final is team $1$ against team $2$, but we have an option to choose their order in the finals. Next, the semifinal. One of teams $3$ and $4$ have to play against team $1$ and another one against team $2$. So we have the following options: choose a permutation of the losers on this stage, then choose the order of teams in every game. If we extrapolate that argument further, we will see that the stage with $2^i$ teams multiplies the answer by $2^{i-1}! \cdot 2^{2^{i-1}}$ (arrange the losers, then fix the order in pairs). The product over all stages is the answer. In order to add the reserved seeds, we have to go back to solving bottom-up. Consider the first stage. We want to calculate its contribution to the answer, then promote the winners of each pair to the next stage and continue solving for $k = k - 1$. Some pairs have both teams reserved. If both or neither of the teams are from $1$ to $2^{k-1}$, then the answer is immediately $0$. Otherwise, the winner is known, so we can promote it further. Some pairs have no teams reserved. Here, we can pick the order of the teams (multiply the answer by $2$). And we basically know the winner as well - this is marked as $-1$. The loser is yet to be determined. Some pairs have one team reserved, and that team is from $1$ to $2^{k-1}$. That team has to win in this pair, so we know who to promote. We will determine the loser later as well. Finally, some pairs have one team reserved, and the team is from $2^{k-1}+1$ to $2^k$. We know the loser here, but the winner is marked $-1$. Still, we can promote this $-1$ further and deal with it on the later stages. How do we arrange the losers? Well, it's almost the same as in the case with zero reserved teams. There are some pairs that are missing losers, and there are loser teams yet to be placed. We only have to choose which team goes where. So, it's (the number of pairs with no reserved loser)!. Why can we promote the "winner" $-1$'s furthers without dealing with them immediately? Basically, that factorial term is the only place where we assign the numbers to teams. Obviously, we want to assign each team a number exactly once. And that happens only when the team loses. Once we assign some number to it, we can uniquely trace back to where this team started, since we fixed the order of each pair beforehand. We decrease $k$ until it's equal to $0$. The answer is still the product of the combinations for each stage. Overall complexity: $O(2^k)$. 1837F - Editorial for Two
|
[
"combinatorics",
"trees"
] | 2,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
int main() {
int k;
scanf("%d", &k);
vector<int> a(1 << k);
forn(i, 1 << k){
scanf("%d", &a[i]);
if (a[i] != -1) --a[i];
}
int ans = 1;
for (int st = k - 1; st >= 0; --st){
int big = 1 << st, fr = 0;
vector<int> na(1 << st);
forn(i, 1 << st){
int mn = min(a[2 * i], a[2 * i + 1]);
int mx = max(a[2 * i], a[2 * i + 1]);
if (mn == -1){
if (mx >= (1 << st)){
--big;
na[i] = -1;
}
else if (mx != -1){
na[i] = mx;
}
else{
na[i] = -1;
++fr;
}
continue;
}
if ((a[2 * i] < (1 << st)) == (a[2 * i + 1] < (1 << st))){
puts("0");
return 0;
}
na[i] = mn;
--big;
}
forn(_, fr) ans = ans * 2ll % MOD;
for (int i = 1; i <= big; ++i) ans = ans * 1ll * i % MOD;
a = na;
}
printf("%d\n", ans);
}
|
1837
|
F
|
Editorial for Two
|
Berland Intercollegiate Contest has just finished. Monocarp and Polycarp, as the jury, are going to conduct an editorial. Unfortunately, the time is limited, since they have to finish before the closing ceremony.
There were $n$ problems in the contest. The problems are numbered from $1$ to $n$. The editorial for the $i$-th problem takes $a_i$ minutes. Monocarp and Polycarp are going to conduct an editorial for exactly $k$ of the problems.
The editorial goes as follows. They have a full problemset of $n$ problems before them, in order. They remove $n - k$ problems without changing the order of the remaining $k$ problems. Then, Monocarp takes some prefix of these $k$ problems (possibly, an empty one or all problems). Polycarp takes the remaining suffix of them. After that, they go to different rooms and conduct editorials for their problems in parallel. So, the editorial takes as much time as the longer of these two does.
Please, help Monocarp and Polycarp to choose the problems and the split in such a way that the editorial finishes as early as possible. Print the duration of the editorial.
|
In the problem, we are asked to first choose $k$ problems, then fix a split into a prefix and a suffix. But nothing stops us from doing that in reverse. Let's fix the split of an entire problemset first, then choose some $l$ ($0 \le l \le k$) and $l$ problems to the left of the split and the remaining $k - l$ problems to the right of it. That allows us to proceed with some polynomial solution already. Having fixed the split and $l$, we only have to find $l$ shortest editorials to the left and $k - l$ shortest editorials to the right. It's trivial to show that it's optimal. That can be done in $O(n^2 \log n)$ easily or $O(n^2)$ if you think a bit more. That solution doesn't really help with the full one, so I won't elaborate. Next, when we see something along the lines of "minimize the maximum", we think about binary search. Let's try to apply it here. Binary search over the answer - now we want the sum of the left and the right parts of the split to be less than or equal to some fixed $x$. More specifically, there should exist some $l$ that the sum of $l$ smallest elements to the left is $\le x$ and the sum of $k - l$ smallest elements to the right is $\le x$. Let's say it differently. There should be at least $l$ elements to the left with their sum being $\le x$, same to the right. And once more. The largest set with the sum $\le x$ to the left is of size at least $l$, same to the right. But that doesn't really require that $l$ now, does it? Find the largest set with the sum $\le x$ to the left and to the right. The sum of their sizes should be at least $k$. Let's calculate the size of this largest set for all prefixes and all suffixes of the array. Then we will be able to check the condition in $O(n)$. You can precalculate the sizes for all prefixes in $O(n \log n)$. The idea is the following. Take the set for some prefix $i$. Add the $(i+1)$-st element to it. If its sum is $\le x$, then it's the new set. Otherwise, keep removing the largest element from it until the sum becomes $\le x$. That solution is $O(n \log A \log n)$, where $A$ is the sum of the array, so you should be careful with the constant factor. For example, doing it with a multiset or with a segment tree probably won't pass. priority_queue is fast enough, though. However, we can do it faster. Imagine a solution with the multiset. Let's replace it with a doubly-linked list. In particular, we want the following operations: insert an element in it; check and remove the last element from it. If we never removed any element, we would be able to determine where to insert each element. We can just precalculate that before the binary search in $O(n \log n)$. For each element, find the largest element less than or equal to it and to the left of it. That would be the previous element when this one is inserted. When we remove elements, it can happen that this previous element was already removed when we attempt to insert this one. We can use the specificity of the problem to avoid that issue. Notice that if we removed an element less than or equal to the current one, then the current one could never be inside an optimal multiset. So we can just skip this element. To implement such a list, we can renumerate all elements into values from $0$ to $n-1$ (in order of $(\mathit{value}, i)$). Then, for each $i$ store the value of the previous and the next elements existing in the list. For convenience, you can also add nodes $n$ and $n+1$, denoting the tail and the head of the list. Then insert and remove is just rearranging some links to the previous and the next elements. Overall complexity: $O(n \log A)$ per testcase, where $A$ is the sum of the array.
|
[
"binary search",
"data structures",
"greedy",
"implementation"
] | 2,400
|
#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, k;
scanf("%d%d", &n, &k);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
vector<pair<int, int>> xs(n);
forn(i, n) xs[i] = {a[i], i};
sort(xs.begin(), xs.end());
forn(i, n) a[i] = lower_bound(xs.begin(), xs.end(), make_pair(a[i], i)) - xs.begin();
vector<int> lstpr(n), lstsu(n);
forn(_, 2){
set<int> cur;
forn(i, n){
auto it = cur.insert(a[i]).first;
if (it == cur.begin())
lstpr[i] = n;
else
lstpr[i] = *(--it);
}
swap(lstpr, lstsu);
reverse(a.begin(), a.end());
}
vector<int> pr(n + 1), su(n + 1);
vector<int> prv(n + 2), nxt(n + 2);
auto check = [&](long long x){
forn(_, 2){
int cnt = 0;
prv[n + 1] = n;
nxt[n] = n + 1;
pr[0] = 0;
int mn = 1e9;
long long cursum = 0;
forn(i, n){
if (mn < a[i]){
pr[i + 1] = cnt;
continue;
}
nxt[a[i]] = nxt[lstpr[i]];
prv[nxt[a[i]]] = a[i];
prv[a[i]] = lstpr[i];
nxt[prv[a[i]]] = a[i];
cursum += xs[a[i]].first;
++cnt;
while (cursum > x){
mn = min(mn, prv[n + 1]);
cursum -= xs[prv[n + 1]].first;
prv[n + 1] = prv[prv[n + 1]];
nxt[prv[n + 1]] = n + 1;
--cnt;
}
pr[i + 1] = cnt;
}
reverse(a.begin(), a.end());
swap(lstpr, lstsu);
swap(pr, su);
}
reverse(su.begin(), su.end());
forn(i, n + 1) if (pr[i] + su[i] >= k) return true;
return false;
};
long long l = 1, r = 0;
for (int x : a) r += xs[x].first;
long long res = 0;
while (l <= r){
long long m = (l + r) / 2;
if (check(m)){
res = m;
r = m - 1;
}
else{
l = m + 1;
}
}
printf("%lld\n", res);
}
}
|
1838
|
A
|
Blackboard List
|
Two integers were written on a blackboard. After that, the following step was carried out $n-2$ times:
- Select any two integers on the board, and write the absolute value of their difference on the board.
After this process was complete, the list of $n$ integers was shuffled. You are given the final list. Recover \textbf{one} of the initial two numbers. You do \textbf{not} need to recover the other one.
You are guaranteed that the input can be generated using the above process.
|
Note that any negative integers on the board must have been one of the original two numbers, because the absolute difference between any two numbers is nonnegative. So, if there are any negative numbers, print one of those. If there are only nonnegative integers, note that the maximum number remains the same after performing an operation, because for nonnegative integers $a$, $b$, where $a \le b$, we have $|a-b| = b - a \le b$ Complexity: $O(n)$
|
[
"constructive algorithms",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
for(int tc = 1; tc <= t; ++tc) {
int n; cin >> n;
int mn = INT_MAX, mx = INT_MIN;
for(int i = 0; i < n; ++i) {
int x; cin >> x;
mn = min(mn, x);
mx = max(mx, x);
}
if(mn < 0) cout << mn << '\n';
else cout << mx << '\n';
}
}
|
1838
|
B
|
Minimize Permutation Subarrays
|
You are given a permutation $p$ of size $n$. You want to minimize the number of subarrays of $p$ that are permutations. In order to do so, you must perform the following operation \textbf{exactly} once:
- Select integers $i$, $j$, where $1 \le i, j \le n$, then
- Swap $p_i$ and $p_j$.
For example, if $p = [5, 1, 4, 2, 3]$ and we choose $i = 2$, $j = 3$, the resulting array will be $[5, 4, 1, 2, 3]$. If instead we choose $i = j = 5$, the resulting array will be $[5, 1, 4, 2, 3]$.
Which choice of $i$ and $j$ will minimize the number of subarrays that are permutations?
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).
An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
Let $\mathrm{idx}_x$ be the position of the element $x$ in $p$, and consider what happens if $\mathrm{idx}_n$ is in between $\mathrm{idx}_1$ and $\mathrm{idx}_2$. Notice that any subarray of size greater than $1$ that is a permutation must contain $\mathrm{idx}_1$ and $\mathrm{idx}_2$. So it must also contain every index in between, including $\mathrm{idx}_n$. Therefore, $n$ is an element of the permutation subarray, so it must be of size at least $n$, and therefore must be the whole array. Therefore, if $\mathrm{idx}_n$ is in between $\mathrm{idx}_1$ and $\mathrm{idx}_2$, the only subarrays that are permutations are $[\mathrm{idx}_1, \mathrm{idx}_1]$ and $[1, n]$. These two subarrays will always be permutations, so this is minimal. To achieve this, we have 3 cases: If $\mathrm{idx}_n$ lies in between $\mathrm{idx}_1$ and $\mathrm{idx}_2$, swap $\mathrm{idx}_1$ and $\mathrm{idx}_2$. If $\mathrm{idx}_n < \mathrm{idx}_1, \mathrm{idx}_2$, swap $\mathrm{idx}_n$ with the smaller of $\mathrm{idx}_1$, $\mathrm{idx}_2$. If $\mathrm{idx}_n > \mathrm{idx}_1, \mathrm{idx}_2$, swap $\mathrm{idx}_n$ with the larger of $\mathrm{idx}_1$, $\mathrm{idx}_2$. In all three of these cases, after the swap, $\mathrm{idx}_n$ will lie in between $\mathrm{idx}_1$ and $\mathrm{idx}_2$, minimizing the number of permutation subarrays. Complexity: $O(n)$
|
[
"constructive algorithms",
"math"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
#define N 200010
int idx[N];
int main() {
int t; cin >> t;
for(int tc = 1; tc <= t; ++tc) {
int n; cin >> n;
for(int i = 1; i <= n; ++i) {
int x; cin >> x;
idx[x] = i;
}
if(idx[n] < min(idx[1], idx[2])) {
cout << idx[n] << ' ' << min(idx[1], idx[2]) << '\n';
} else if(idx[n] > max(idx[1], idx[2])) {
cout << idx[n] << ' ' << max(idx[1], idx[2]) << '\n';
} else {
cout << idx[1] << ' ' << idx[2] << '\n';
}
}
}
|
1838
|
C
|
No Prime Differences
|
You are given integers $n$ and $m$. Fill an $n$ by $m$ grid with the integers $1$ through $n\cdot m$, in such a way that for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime number. Two cells in the grid are considered adjacent if they share a side.
It can be shown that under the given constraints, there is always a solution.
|
Note that if we fill in the numbers in order from the top left to the bottom right, for example, for $n=5$, $m=7$, the only adjacent differences are $1$ and $m$. So if $m$ is not prime, this solves the problem. We'll now rearrange the rows so that it works regardless of whether $m$ is prime. Put the first $\lfloor\frac{n}{2}\rfloor$ rows in rows $2$, $4$, $6$, ... and the last $\lceil\frac{n}{2}\rceil$ rows in rows $1$, $3$, $5$, .... In the example above, this would give Note that because we are just rearranging the rows from the above solution, all of the horizontal differences are $1$, and the vertical differences are multiples of $m\ge 4$. Therefore, as long as none of the vertical differences equal $m$ itself, they must be composite. Because $n\ge 4$, no row is next to either of its original neighbors in this ordering, and therefore all vertical differences are greater than $m$, and thus composite. So we can use this final grid regardless of whether $m$ is prime. Complexity: $O(nm)$
|
[
"constructive algorithms",
"math",
"number theory"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
for(int tc = 1; tc <= t; ++tc) {
int n, m; cin >> n >> m;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
if(i % 2 == 0) cout << (n / 2 + i / 2) * m + j + 1 << ' ';
else cout << (i / 2) * m + j + 1 << ' ';
}
cout << '\n';
}
}
}
|
1838
|
D
|
Bracket Walk
|
There is a string $s$ of length $n$ consisting of the characters '(' and ')'. You are walking on this string. You start by standing on top of the first character of $s$, and you want to make a sequence of moves such that you end on the $n$-th character. In one step, you can move one space to the left (if you are not standing on the first character), or one space to the right (if you are not standing on the last character). You may not stay in the same place, however you may visit any character, including the first and last character, \textbf{any} number of times.
At each point in time, you write down the character you are currently standing on. We say the string is walkable if there exists some sequence of moves that take you from the first character to the last character, such that the string you write down is a regular bracket sequence.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.
\begin{center}
{\small One possible valid walk on $s=\mathtt{(())()))}$. The red dot indicates your current position, and the red string indicates the string you have written down. Note that the red string is a regular bracket sequence at the end of the process.}
\end{center}
You are given $q$ queries. Each query flips the value of a character from '(' to ')' or vice versa. After each query, determine whether the string is walkable.
Queries are \textbf{cumulative}, so the effects of each query carry on to future queries.
|
For a string to be walkable, we need $n$ to be even, because the parity of the balance factor changes on each move, and it has to be zero at the end of the process. So if $n$ is odd, the string is never walkable. Now, consider the set $A$ that contains all indices $i$ ($1$-indexed) satisfying one of the below conditions: $i$ is even and $s_i =$ '(' $i$ is odd and $s_i =$ ')' Now, consider a few cases: If $A$ is empty, then $s$ is of the form ()()()(), and is therefore trivially walkable by just moving to the right. If $\min(A)$ is odd, then $s$ is of the form ()()()).... We can show that it is never walkable, because for every ')' in the first section ()()(), when we land on this ')' (before leaving this section of the string for the first time), the balance factor must be $0$. Therefore, when we try to move across the "))", the balance factor will go to $-1$, and the walk will no longer be valid. If $\max(A)$ is even, then $s$ is of the form ....(()()(), and we can show that it is never walkable using a somewhat symmetric argument to the previous case, but considering the ending of the walk instead of the beginning. Otherwise, $\min(A)$ is even and $\max(A)$ is odd. We will prove that it is walkable. In this case, s is of the form ()()()((....))()(). To form a valid walk, keep moving to the right until you hit the "((", then alternate back and forth on the "((" $10^{18}$ times. After this, move to the right until you hit the "))". Note that during this process, the balance factor can never go negative, because it will always be at least $10^{18}-n$. Once you reach the "))", alternate back and forth on it until the balance factor hits $0$. Because n is even, this will happen on the rightmost character of the "))". At this point, just walk to the right until you hit the end, at which point the balance factor will once again be $0$. So we just need to maintain the set $A$ across all of the queries, and do these simple checks after each query to see if $s$ is walkable. Complexity: $O((n + q) log n)$
|
[
"data structures",
"greedy",
"strings"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, q; string s;
cin >> n >> q >> s;
set<int> a;
for(int i = 1; i <= n; ++i)
if((i % 2) != (s[i - 1] == '('))
a.insert(i);
while(q--) {
int i; cin >> i;
if(a.count(i)) a.erase(i);
else a.insert(i);
if(n % 2) cout << "NO\n";
else if(a.size() && (*a.begin() % 2 || !(*a.rbegin() % 2))) cout << "NO\n";
else cout << "YES\n";
}
}
|
1838
|
E
|
Count Supersequences
|
You are given an array $a$ of $n$ integers, where all elements $a_i$ lie in the range $[1, k]$. How many different arrays $b$ of $m$ integers, where all elements $b_i$ lie in the range $[1, k]$, contain $a$ as a subsequence? Two arrays are considered different if they differ in at least one position.
A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements.
Since the answer may be large, print it modulo $10^9 + 7$.
|
Let's first consider a DP solution. Let $dp_{i,j}$ be the number of arrays of length $i$, such that the longest prefix of $a$ that appears as a subsequence of the array is of length $j$. To compute this DP, consider some cases. Let $b'$ be the subarray of the first $i$ elements of $b$, and $a'$ be the subarray of the first $j$ elements of $a$. Every subsequence of $b'$ that equals $a'$ includes position $i$ of $b'$: In this case, position $i$ must be part of the subsequence. This gives us $dp_{i-1, j-1}$ solutions. At least one subsequence of $b'$ that equals $a'$ doesn't include position $i$, and $j < n$: In this case, the value in position $i$ can be anything except for $a_{j+1}$, because that would create a subsequence of length $j+1$. So this gives us $(k-1)dp_{i-1, j}$ solutions. At least one subsequence of $b'$ that equals $a'$ doesn't include position $i$, and $j = n$: This is the same as the previous case, except we don't have a "next" element to worry about, so anything can go in position $i$, and there are $k\cdot dp_{i-1, j}$ solutions. So the final equation for the DP comes out to $dp_{i,j} = \begin{cases} dp_{i-1, j-1} + (k-1)dp_{i-1, j} & j < n \\ dp_{i-1, j-1} + k\cdot dp_{i-1, j} & j = n \end{cases}$ This would be $O(nm)$ to compute, so it will TLE. However, we can notice that the DP does not depend on $a$! This means we can change the $a_i$ values to anything we want, and it won't change the answer. To simplify the problem, let all $a_i = 1$. Now, the problem becomes, how many arrays of size $m$, consisting of the values $[1, k]$, contain at least $n$ ones? To compute this, let's find the number of arrays of size $m$ that contain less than $n$ ones, and subtract it from $k^m$, the total number of arrays. There are $\binom{m}{i}(k-1)^{m-i}$ arrays that contain exactly $i$ ones, so the answer is $k^m - \sum_{i=0}^{n-1} \binom{m}{i}(k-1)^{m-i}$ We use fast exponentiation to compute the powers of $k-1$, and to compute the $\binom{m}{i}$ values, we use the fact that $\binom{m}{0} = 1$ and for $i \ge 1$, $\binom{m}{i} = \frac{m(m-1)\ldots(m-i+1)}{i(i-1)\ldots 1} = \frac{m - i + 1}{i}\binom{m}{i - 1}$ So we can compute the first $n$ $\binom{m}{i}$ values within the time limit. Complexity: $O(n \log M)$ where $M = 10^9 + 7$.
|
[
"combinatorics",
"dp",
"math"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll M = 1000000007;
ll pw(ll a, ll p) { return p ? pw(a * a % M, p / 2) * (p & 1 ? a : 1) % M : 1; }
ll inv(ll a) { return pw(a, M - 2); }
int main() {
ll t; cin >> t;
for(ll tc = 1; tc <= t; ++tc) {
ll n, m, k, ai;
cin >> n >> m >> k;
for(ll i = 0; i < n; ++i) cin >> ai;
ll ans = pw(k, m), mCi = 1;
for(ll i = 0; i < n; ++i) {
ans = (ans + M - mCi * pw(k - 1, m - i) % M) % M;
mCi = mCi * (m - i) % M * inv(i + 1) % M;
}
cout << ans << '\n';
}
}
|
1838
|
F
|
Stuck Conveyor
|
This is an interactive problem.
There is an $n$ by $n$ grid of conveyor belts, in positions $(1, 1)$ through $(n, n)$ of a coordinate plane. Every other square in the plane is empty. Each conveyor belt can be configured to move boxes up ('^'), down ('v'), left ('<'), or right ('>'). If a box moves onto an empty square, it stops moving.
However, one of the $n^2$ belts is stuck, and will always move boxes in the same direction, no matter how it is configured. Your goal is to perform a series of tests to determine which conveyor belt is stuck, and the direction in which it sends items.
To achieve this, you can perform up to $25$ tests. In each test, you assign a direction to all $n^2$ belts, place a box on top of one of them, and then turn all of the conveyors on.
\begin{center}
{\small One possible result of a query with $n=4$. In this case, the box starts at $(2, 2)$. If there were no stuck conveyor, it would end up at $(5, 4)$, but because of the stuck '>' conveyor at $(3, 3)$, it enters an infinite loop.}
\end{center}
The conveyors move the box around too quickly for you to see, so the only information you receive from a test is whether the box eventually stopped moving, and if so, the coordinates of its final position.
|
The key to our solution will be these two "snake" configurations: We will initially query the first snake with the box on the top left, and the second snake with the box on the bottom left (or bottom right, depending on parity of $n$). Note that these two snakes, with the box on the given starting positions, each form a single path such that the box visits all squares, and the second snake visits squares in the reverse order of the first. Now, consider some cases. If the stuck conveyor belt directs items to an empty square, then for both of the above configurations, the box will end up in that empty square. This cannot be the "intended" behavior for both of them, because the intended behavior for both of them is different. So in one snake, we will know that this is unintended behavior. Because each possible empty square is only adjacent to one belt, we know exactly which belt must have sent it there, and therefore which one is broken. If the stuck conveyor belt directs items to another belt, number the conveyor belts from $1$ to $n^2$ in the order they are visited by the first snake, and consider two subcases: If the other belt has a lower number than the stuck belt, then the box will enter an infinite loop for the first snake query, and will terminate for the second snake query. Since the opposite will happen in the other case, this allows us to distinguish these two subcases.Consider what happens if we ask the first snake query again, but place the box on belt $i$ instead of belt $1$. Assume the stuck belt is belt $j$. Because the stuck belt directs items to a belt with smaller number, if $i \le j$, the box will hit the stuck belt, and enter an infinite loop. If $i > j$, the box will never encounter the stuck belt, so it will eventually reach the end of the snake and stop moving. So with one query, by checking whether the box enters an infinite loop, we can determine whether $i \le j$ or $i > j$. This allows us to binary search for $j$ in $\log (n^2)$ queries. Consider what happens if we ask the first snake query again, but place the box on belt $i$ instead of belt $1$. Assume the stuck belt is belt $j$. Because the stuck belt directs items to a belt with smaller number, if $i \le j$, the box will hit the stuck belt, and enter an infinite loop. If $i > j$, the box will never encounter the stuck belt, so it will eventually reach the end of the snake and stop moving. So with one query, by checking whether the box enters an infinite loop, we can determine whether $i \le j$ or $i > j$. This allows us to binary search for $j$ in $\log (n^2)$ queries. The case where the other belt has a higher number than the stuck belt is analogous, using the second snake query rather than the first. So now, in all cases, we know which of the $n^2$ belts is stuck. In order to determine the direction in which it is stuck, we use one more query. Place the box on the stuck conveyor, and direct all belts in the same row or column as the stuck belt away from it (all other belts can be directed arbitrarily). Here is one example for $n=4$ where the stuck belt is $(2, 2)$: So we will get a different final position for the box for each of the four directions in which it could be stuck, and can recover the direction. The total number of queries for these steps is bounded by $2 + log(n^2) + 1$. Since $n \le 100$, this is at most $17$. Complexity: $O(n^2 \log (n^2))$
|
[
"binary search",
"constructive algorithms",
"interactive"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
char grid[110][110];
int n;
vector<pair<int, int>> snake;
map<pair<int, int>, char> getChar = {
{{1, 0}, 'v'},
{{-1, 0}, '^'},
{{0, 1}, '>'},
{{0, -1}, '<'}
};
pair<pair<int, int>, char> getBeltAndDir(pair<int, int> p) {
if(p.first == -1) return {p, 'X'};
pair<int, int> q = p;
if(p.first == 0) q.first++;
if(p.second == 0) q.second++;
if(p.first > n) q.first--;
if(p.second > n) q.second--;
return {q, getChar[{p.first - q.first, p.second - q.second}]};
}
pair<pair<int, int>, char> query(int idx) {
cout << "? " << snake[idx].first << ' ' << snake[idx].second << endl;
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j)
cout << grid[i][j];
cout << endl;
}
int i, j; cin >> i >> j;
return getBeltAndDir({i, j});
}
void fillGrid() {
for(int i = 0; i < n * n; ++i) {
int dx = snake[i + 1].first - snake[i].first;
int dy = snake[i + 1].second - snake[i].second;
grid[snake[i].first][snake[i].second] = getChar[{dx, dy}];
}
}
int main() {
cin >> n;
for(int i = 1; i <= n; ++i)
if(i % 2 == 0)
for(int j = n; j >= 1; --j)
snake.emplace_back(i, j);
else
for(int j = 1; j <= n; ++j)
snake.emplace_back(i, j);
snake.emplace_back(n + 1, (n % 2 ? n : 1));
fillGrid();
auto ans = query(0);
if(ans.second != 'X') {
snake.pop_back();
reverse(snake.begin(), snake.end());
snake.emplace_back(0, 1);
fillGrid();
ans = query(0);
}
if(ans.second == 'X') {
int id = 0;
for(int j = 13; j >= 0; --j)
if(id + (1 << j) < n * n && query(id + (1 << j)).second == 'X')
id += (1 << j);
ans.first = snake[id];
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
if(i < ans.first.first) grid[i][j] = '^';
else if(i > ans.first.first) grid[i][j] = 'v';
else grid[i][j] = j < ans.first.second ? '<' : '>';
ans.second = query(id).second;
}
cout << "! " << ans.first.first << ' ' << ans.first.second << ' ' << ans.second << endl;
}
|
1839
|
A
|
The Good Array
|
You are given two integers $n$ and $k$.
An array $a_1, a_2, \ldots, a_n$ of length $n$, consisting of zeroes and ones is good if for \textbf{all} integers $i$ from $1$ to $n$ \textbf{both} of the following conditions are satisfied:
- at least $\lceil \frac{i}{k} \rceil$ of the first $i$ elements of $a$ are equal to $1$,
- at least $\lceil \frac{i}{k} \rceil$ of the last $i$ elements of $a$ are equal to $1$.
Here, $\lceil \frac{i}{k} \rceil$ denotes the result of division of $i$ by $k$, rounded up. For example, $\lceil \frac{6}{3} \rceil = 2$, $\lceil \frac{11}{5} \rceil = \lceil 2.2 \rceil = 3$ and $\lceil \frac{7}{4} \rceil = \lceil 1.75 \rceil = 2$.
Find the minimum possible number of ones in a good array.
|
Let's find lower bound for answer. In any good array, there are at least $\lceil \frac{n - 1}{k} \rceil$ ones among the first $n - 1$ elements. Also, $a_n$ is always $1$, as $\lceil \frac{1}{k} \rceil = 1$. So there are at least $\lceil \frac{n - 1}{k} \rceil + 1$ ones in any good array. This lower bound can always be achieved by placing ones on position $n$ and on positions $1 + k \cdot x$ for all integers $x$ such that $0 \le x \le \lfloor \frac{n - 2}{k} \rfloor = \lceil \frac{n - 1}{k} \rceil - 1$. The answer to the probelm is $\lceil \frac{n - 1}{k} \rceil + 1$.
|
[
"greedy",
"implementation",
"math"
] | 800
| null |
1839
|
B
|
Lamps
|
You have $n$ lamps, numbered by integers from $1$ to $n$. Each lamp $i$ has two integer parameters $a_i$ and $b_i$.
At each moment each lamp is \textbf{in one of three states}: it may be turned on, turned off, or broken.
Initially all lamps are turned off. In one operation you can select one lamp that is turned off and turn it on (you can't turn on broken lamps). You \textbf{receive} $b_i$ points for turning lamp $i$ on. The following happens after each performed operation:
- Let's denote the number of lamps that are turned on as $x$ (broken lamps \textbf{do not count}). All lamps $i$ such that $a_i \le x$ simultaneously break, whether they were turned on or off.
Please note that broken lamps never count as turned on and that after a turned on lamp breaks, you still keep points received for turning it on.
You can perform an arbitrary number of operations.
Find the maximum number of points you can get.
|
Let's denote number of lamps with $a_i = k$ as $c_k$. If $c_k \ge k$ and you turn $k$ lamps with $a_i = k$ lamps on, all $c_k$ of them will break and you will not be able to receive points for the other $c_k - k$ lamps. If we denote values $b_i$ for all $i$ such that $a_i = k$ as $d_{k, 1}, d_{k, 2}, \ldots, d_{k, c_k}$ ($d_{k, 1} \ge d_{k, 2} \ge \ldots \ge d_{k, c_k}$), then you can't get more than $s_k = d_{k, 1} + d_{k, 2} + \ldots + d_{k, \min(c_k, k)}$ points for lamps with $a_i = k$. So, the total number of points is not bigger than $s_1 + s_2 + \ldots + s_n$. This bound can always be achieved in the following way: while there is at least one lamp that is not turned on and not broken, turn on the one with minimum $a_i$ (if there are multiple lamps with minimum $a_i$, choose the one with maximum $b_i$). This works because if at least $k$ lamps are turned on, then all lamps with $a_i \lt k$ are already broken.
|
[
"greedy",
"sortings"
] | 1,100
| null |
1839
|
C
|
Insert Zero and Invert Prefix
|
You have a sequence $a_1, a_2, \ldots, a_n$ of length $n$, each element of which is either $0$ or $1$, and a sequence $b$, which is initially empty.
You are going to perform $n$ operations. On each of them you will increase the length of $b$ by $1$.
- On the $i$-th operation you choose an integer $p$ between $0$ and $i-1$. You insert $0$ in the sequence $b$ on position $p+1$ (after the first $p$ elements), and then you invert the first $p$ elements of $b$.
- More formally: let's denote the sequence $b$ before the $i$-th ($1 \le i \le n$) operation as $b_1, b_2, \ldots, b_{i-1}$. On the $i$-th operation you choose an integer $p$ between $0$ and $i-1$ and replace $b$ with $\overline{b_1}, \overline{b_2}, \ldots, \overline{b_{p}}, 0, b_{p+1}, b_{p+2}, \ldots, b_{i-1}$. Here, $\overline{x}$ denotes the binary inversion. Hence, $\overline{0} = 1$ and $\overline{1} = 0$.
You can find examples of operations in the Notes section.
Determine if there exists a sequence of operations that makes $b$ equal to $a$. If such sequence of operations exists, find it.
|
It's easy to see that last element of $b$ is always zero, so if $a_n$ is $1$, then the answer is "NO". It turns out that if $a_n$ is $0$, then answer is always "YES". First, let's try to get $b$ equal to array of form $[\, \overbrace{1, 1, \ldots, 1}^{k}, 0 \,]$ for some $k \ge 0$. Further in the editorial I will call such arrays simple. We can insert zero before the first element $k$ times and then insert zero after the last element, inverting all previously inserted zeroes into ones. To get arbitrary $b$ with $b_n = 0$, you can notice that such array can always be divided into simple arrays. For example, array $[1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]$ can be divided into $[1, 1, 0]$, $[0]$, $[1, 1, 1, 1, 0]$, $[1, 0]$. Also it's easy to see that if you can get array $a_1$ with sequence of operation $p_1$ and array $a_2$ with sequence of operations $p_2$, then you can get concatenation of arrays $a_1$ and $a_2$ by first performing all the operations from $p_2$ and then performing all the operations from $p_1$. So, the solution is as follows: If $a_n$ is $1$, output "NO". Otherwise, divide array $a$ into simple arrays of lengths $s_1, s_2, \ldots, s_m$ ($s_1 + s_2 + \ldots + s_m = n$). Then, you can get $b = a$ with sequence of operations $p = [\, \overbrace{0, 0, \ldots, 0}^{s_m - 1}, s_m - 1, \overbrace{0, 0, \ldots, 0}^{s_{m-1} - 1}, s_{m-1} - 1, \ldots, \overbrace{0, 0, \ldots, 0}^{s_1 - 1}, s_1 - 1]$.
|
[
"constructive algorithms"
] | 1,300
| null |
1839
|
D
|
Ball Sorting
|
There are $n$ colorful balls arranged in a row. The balls are painted in $n$ distinct colors, denoted by numbers from $1$ to $n$. The $i$-th ball from the left is painted in color $c_i$. You want to reorder the balls so that the $i$-th ball from the left has color $i$. Additionally, you have $k \ge 1$ balls of color $0$ that you can use in the reordering process.
Due to the strange properties of the balls, they can be reordered only by performing the following operations:
- Place a ball of color $0$ anywhere in the sequence (between any two consecutive balls, before the leftmost ball or after the rightmost ball) while keeping the relative order of other balls. You can perform this operation no more than $k$ times, because you have only $k$ balls of color $0$.
- Choose any ball of \textbf{non-zero} color such that at least one of the balls adjacent to him has color $0$, and move that ball (of non-zero color) anywhere in the sequence (between any two consecutive balls, before the leftmost ball or after the rightmost ball) while keeping the relative order of other balls. You can perform this operation as many times as you want, but for each operation you should pay $1$ coin.
You can perform these operations in any order. After the last operation, all balls of color $0$ magically disappear, leaving a sequence of $n$ balls of non-zero colors.
What is the minimum amount of coins you should spend on the operations of the second type, so that the $i$-th ball from the left has color $i$ for all $i$ from $1$ to $n$ \textbf{after the disappearance of all balls of color zero}? It can be shown that under the constraints of the problem, it is always possible to reorder the balls in the required way.
Solve the problem for all $k$ from $1$ to $n$.
|
Let's solve the problem for some fixed $k$. Consider the set $S$ of all balls that were never moved with operation of type $2$. Let's call balls from $S$ fixed and balls not from $S$ mobile. The relative order of fixed balls never changes, so their colors must form an increasing sequence. Let's define $f(S)$ as the number of segments of mobile balls that the fixed balls divide sequence into. For example, if $n = 6$ and $S = \{ 3, 4, 6 \}$, then these segments are $[1, 2], [5, 5]$ and $f(S)$ is equal to $2$. As every mobile ball has to be moved at least once, there must be at least one zero-colored ball in each such segment, whicn means that $f(S) \le k$. Also, it means that we will need at least $n - |S|$ operations of type $2$. In fact, we can always place mobile balls at correct positions with exactly $n - |S|$ operations. The proof is left as exercise for reader. So the answer for $k$ is equal to minimum value of $n - |S|$ over all sets $S$ of balls such that $f(S) \le k$ and the colors of balls in $S$ form an increasing sequence. This problem can be solved with dynamic programming: let $dp_{i, j}$ be maximum value of $|S|$ if only balls from $1$ to $i$ exist, ball $i$ belongs to $S$ and $f(S)$ is equal to $j$. To perform transitions from $dp_{i, j}$ you need to enumerate $t$ -the next ball from $S$ after $i$. Then, if $t = i + 1$, you transition to $dp_{t, j}$, otherwise you transition to $dp_{t, j + 1}$. After each transition $|S|$ increases by $1$, so you just update $dp_{t, j / j + 1}$ with value $dp_{i, j} + 1$. There are $O(n^2)$ states and at most $n$ transitions from each state, so the complexity is $O(n^3)$. Solution can be optimized to $O(n^2 \log{n})$ with segment tree, but this was not required.
|
[
"data structures",
"dp",
"sortings"
] | 2,100
| null |
1839
|
E
|
Decreasing Game
|
\textbf{This is an interactive problem.}
Consider the following game for two players:
- Initially, an array of integers $a_1, a_2, \ldots, a_n$ of length $n$ is written on blackboard.
- Game consists of rounds. On each round, the following happens:
- The first player selects any $i$ such that $a_i \gt 0$. If there is no such $i$, the first player loses the game (the second player wins) and game ends.
- The second player selects any $j \neq i$ such that $a_j \gt 0$. If there is no such $j$, the second player loses the game (the first player wins) and game ends.
- Let $d = \min(a_i, a_j)$. The values of $a_i$ and $a_j$ are simultaneously decreased by $d$ and the next round starts.
It can be shown that game always ends after the finite number of rounds.
You have to select which player you will play for (first or second) and win the game.
|
I claim that the second player wins if and only if array $a$ can be divided into two sets with equal sum, or, equivalently, there is a subset of $a$ with sum $\frac{a_1 + a_2 + \ldots + a_n}{2}$. The strategy for the second player in this case is quite simple: before the game starts, the second player splits $a$ into two parts with equal sum. On each round, if the first player selected $i$ from the first part, the second player selects $j$ from the second part. Otherwise, he selects $j$ from the first part. Before and after every round, sums of elements in both parts are equal, so if there is a positive element in one part, there is also a positive element in the other part. So the second player is always able to make a correct move. The strategy for the first player in the other case is even simplier: he can just make any correct move on each round. Why? Let's suppose the second player won the game, which lasted $k$ rounds, and elements selected by players on each round were $(i_1, j_1), (i_2, j_2), \ldots, (i_k, j_k)$. After $k$-th round, all elements of $a$ are zeroes, otherwise the first player would still be able to make a correct move. Let's consider graph $G$ with set of vertices $V = \{ 1, 2, \ldots, n \}$ and set of edges $E = \{ (i_1, j_1), (i_2, j_2), \ldots, (i_k, j_k) \}$. It's easy to see that this graph is always a tree (proof left as exercise for reader; hint: after each round, at least one of $a_i$ and $a_j$ becomes zero). If graph is a tree, then it is bipartite, which means that its vertices can be divided into two sets such that each edge connects vertices from different sets. As each operation decreases $a_i$ and $a_j$ by same value, these two sets have the same sum of elements. So we have a contradiction.
|
[
"constructive algorithms",
"dfs and similar",
"dp",
"greedy",
"interactive"
] | 2,400
| null |
1840
|
A
|
Cipher Shifer
|
There is a string $a$ (unknown to you), consisting of lowercase Latin letters, encrypted according to the following rule into string $s$:
- after each character of string $a$, an arbitrary (possibly zero) number of any lowercase Latin letters, different from the character itself, is added;
- after each such addition, the character that we supplemented is added.
You are given string $s$, and you need to output the initial string $a$. In other words, you need to decrypt string $s$.
Note that each string encrypted in this way is decrypted \textbf{uniquely}.
|
Note that during encryption, only characters different from $c$ are added after the character $c$. However, when the character $c$ is encrypted with different characters, another $c$ character is added to the string. This means that for decryption, we only need to read the characters of the string after $c$ until we find the first character equal to $c$. It signals the end of the block of characters that will be converted to the character $c$ during decryption. To decrypt the entire string, we decrypt the first character $s_1$. Let the next occurrence of the character $s_1$ be at position $pos_1$. Then the next character of the original string is $s_{pos_1 + 1}$. We apply the same algorithm to find the next paired character and so on.
|
[
"implementation",
"strings",
"two pointers"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin >> t;
while (t--) {
int n; cin >> n;
string s; cin >> s;
int i = 0;
while (i < n) {
int start = i;
cout << s[i++];
while (s[i++] != s[start]);
}
cout << endl;
}
}
|
1840
|
B
|
Binary Cafe
|
Once upon a time, Toma found himself in a binary cafe. It is a very popular and unusual place.
The cafe offers visitors $k$ different delicious desserts. The desserts are numbered from $0$ to $k-1$. The cost of the $i$-th dessert is $2^i$ coins, because it is a binary cafe! Toma is willing to spend no more than $n$ coins on tasting desserts. At the same time, he is not interested in buying any dessert more than once, because one is enough to evaluate the taste.
In how many different ways can he buy several desserts \textbf{(possibly zero)} for tasting?
|
On the one hand, if Tema had an infinite number of coins, he could buy any set of desserts offered in the coffee shop. This can be done in $2^k$ ways, since each of the desserts can either be taken or not taken. On the other hand, if the coffee shop offered an infinite number of desserts for tasting, Tema could spend any amount of coins he has - from $0$ to $n$. Each number of coins corresponds to its unique set of desserts, since any number $0 \le k \le n$ is uniquely represented as a sum of powers of two. Combining these two observations, we get the final answer - $min(2^k, n + 1)$.
|
[
"bitmasks",
"combinatorics",
"math"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
int32_t main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
k = min(k, 30);
cout << min(n, (1 << k) - 1) + 1 << "\n";
}
return 0;
}
|
1840
|
C
|
Ski Resort
|
Dima Vatrushin is a math teacher at school. He was sent on vacation for $n$ days for his good work. Dima has long dreamed of going to a ski resort, so he wants to allocate several \textbf{consecutive days} and go skiing. Since the vacation requires careful preparation, he will only go for \textbf{at least $k$ days}.
You are given an array $a$ containing the weather forecast at the resort. That is, on the $i$-th day, the temperature will be $a_i$ degrees.
Dima was born in Siberia, so he can go on vacation only if the temperature does not rise above $q$ degrees throughout the vacation.
Unfortunately, Dima was so absorbed in abstract algebra that he forgot how to count. He asks you to help him and count the number of ways to choose vacation dates at the resort.
|
To simplify the task, let's replace all numbers in the array $a$. If the value of $a_i$ is greater than $q$, then replace it with $0$. Otherwise, replace it with $1$. Now Dima can go on this day if $a_i = 1$. Therefore, we need to consider segments consisting only of $1$. Note that if the segment consists of less than $k$ ones, then Dima will not be able to go on these dates, so the segment can be ignored. For all remaining segments, we need to calculate the number of ways for Dima to choose travel dates on this segment. And for a segment of length $l$, the number of ways to choose a trip of at least length $k$ is $\binom{l - k + 2}{l - k}$. The answer to the problem will be the sum of the number of ways to choose travel dates for all segments.
|
[
"combinatorics",
"math",
"two pointers"
] | 1,000
|
testCases = int(input())
for testCase in range(testCases):
n, k, q = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
ans = 0
len = 0
for i in range(n):
if a[i] <= q:
len += 1
else:
if len >= k:
ans += (len - k + 1) * (len - k + 2) // 2
len = 0
if len >= k:
ans += (len - k + 1) * (len - k + 2) // 2
print(ans)
|
1840
|
D
|
Wooden Toy Festival
|
In a small town, there is a workshop specializing in woodwork. Since the town is small, only \textbf{three} carvers work there.
Soon, a wooden toy festival is planned in the town. The workshop employees want to prepare for it.
They know that $n$ people will come to the workshop with a request to make a wooden toy. People are different and may want different toys. For simplicity, let's denote the pattern of the toy that the $i$-th person wants as $a_i$ ($1 \le a_i \le 10^9$).
Each of the carvers can choose an integer pattern $x$ ($1 \le x \le 10^9$) in advance, \textbf{different carvers can choose different patterns}. $x$ is the integer. During the preparation for the festival, the carvers will perfectly work out the technique of making the toy of the chosen pattern, which will allow them to cut it out of wood instantly. To make a toy of pattern $y$ for a carver who has chosen pattern $x$, it will take $|x - y|$ time, because the more the toy resembles the one he can make instantly, the faster the carver will cope with the work.
On the day of the festival, when the next person comes to the workshop with a request to make a wooden toy, the carvers can choose who will take on the job. At the same time, the carvers are very skilled people and can work on orders for different people \textbf{simultaneously}.
Since people don't like to wait, the carvers want to choose patterns for preparation in such a way that the \textbf{maximum} waiting time over all people is as \textbf{small} as possible.
Output the best maximum waiting time that the carvers can achieve.
|
Let the carvers choose patterns $x_1$, $x_2$, $x_3$ for preparation. For definiteness, let us assume that $x_1 \le x_2 \le x_3$, otherwise we will renumber the carvers. When a person comes to the workshop with a request to make a toy of pattern $p$, the best solution is to give his order to the carver for whom $|x_i - p|$ is minimal. It follows that the first cutter will take orders for toys with patterns from $1$ to $\dfrac{x_1 + x_2}{2}$, the second - for toys with patterns from $\dfrac{x_1 + x_2}{2}$ to $\dfrac{x_2 + x_3}{2}$, the third - for toys with patterns from $\dfrac{x_2 + x_3}{2}$ to $10^9$. Therefore, if you look at the sorted array of patterns $a$, the first carver will make some prefix of toys, the third will make some suffix, and the remaining toys will be made by the second carver. Then the answer can be found by binary search. To check if the time $t$ is suitable, you need to give the maximum prefix of toys to the first carver and the maximum suffix of toys to the third carver, and then check that the patterns of the remaining toys are within a segment of length $2 \cdot t$. The maximum prefix and maximum suffix can be found with a $\mathcal{O}(n)$ pass through the array $a$.
|
[
"binary search",
"greedy",
"sortings"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
int l = -1, r = 1e9;
while (r - l > 1) {
int m = (l + r) >> 1;
int i = 0;
while (i + 1 < a.size() && a[i + 1] - a[0] <= 2 * m) {
++i;
}
int j = n - 1;
while (j - 1 >= 0 && a.back() - a[j - 1] <= 2 * m) {
--j;
}
++i; --j;
if (i > j || a[j] - a[i] <= 2 * m) {
r = m;
} else {
l = m;
}
}
cout << r << "\n";
}
return 0;
}
|
1840
|
E
|
Character Blocking
|
You are given two strings of equal length $s_1$ and $s_2$, consisting of lowercase Latin letters, and an integer $t$.
You need to answer $q$ queries, numbered from $1$ to $q$. The $i$-th query comes in the $i$-th second of time. Each query is one of three types:
- block the characters at position $pos$ (indexed from $1$) in both strings for $t$ seconds;
- swap two unblocked characters;
- determine if the two strings are equal at the time of the query, ignoring blocked characters.
Note that in queries of the second type, the characters being swapped can be from the same string or from $s_1$ and $s_2$.
|
Two strings are equal if and only if there is no position $pos$ such that the characters at position $pos$ are not blocked and $s_1[pos] \neq s_2[pos]$ (we will call such a position bad). We will use this observation to maintain the current number of bad positions, denoted by $cnt$. Let $I_{pos}$ be an indicator variable. $I_{pos} = 1$ if position $pos$ is bad, otherwise $I_{pos} = 0$. During an operation (blocking or swapping), we only need to subtract the indicator variables of all positions affected by the operation from $cnt$. There will be $\mathcal{O}(1)$ of them. Then, we modify the string according to the operation and add new indicator variables to $cnt$. To correctly handle blocking queries, or more precisely, to unblock positions in time, we will use a queue. After each blocking query, we will add a pair of numbers to the queue. The first number of the pair is the position to unblock, and the second number is the time to unblock. Now, before each operation, we will unblock positions by looking at the head of the queue.
|
[
"data structures",
"hashing",
"implementation"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int x;
cin >> x;
while (x--) {
vector<string> s(2);
cin >> s[0] >> s[1];
int n = s[0].size();
int bad = 0;
for (int i = 0; i < n; ++i) {
if (s[0][i] != s[1][i]) {
++bad;
}
}
int t, q;
cin >> t >> q;
queue<pair<int, int>> unblock;
for (int i = 0; i < q; ++i) {
while (!unblock.empty() && unblock.front().first == i) {
if (s[0][unblock.front().second] != s[1][unblock.front().second]) {
++bad;
}
unblock.pop();
}
int type;
cin >> type;
if (type == 1) {
int pos;
cin >> pos;
if (s[0][pos - 1] != s[1][pos - 1]) {
--bad;
}
unblock.emplace(i + t, pos - 1);
} else if (type == 2) {
int num1, pos1, num2, pos2;
cin >> num1 >> pos1 >> num2 >> pos2;
--num1; --pos1; --num2; --pos2;
if (s[num1][pos1] != s[1 ^ num1][pos1]) {
--bad;
}
if (s[num2][pos2] != s[1 ^ num2][pos2]) {
--bad;
}
swap(s[num1][pos1], s[num2][pos2]);
if (s[num1][pos1] != s[1 ^ num1][pos1]) {
++bad;
}
if (s[num2][pos2] != s[1 ^ num2][pos2]) {
++bad;
}
} else {
cout << (!bad ? "YES" : "NO") << "\n";
}
}
}
return 0;
}
|
1840
|
F
|
Railguns
|
Tema is playing a very interesting computer game.
During the next mission, Tema's character found himself on an unfamiliar planet. Unlike Earth, this planet is flat and can be represented as an $n \times m$ rectangle.
Tema's character is located at the point with coordinates $(0, 0)$. In order to successfully complete the mission, he needs to reach the point with coordinates $(n, m)$ alive.
Let the character of the computer game be located at the coordinate $(i, j)$. Every second, \textbf{starting from the first}, Tema can:
- either use vertical hyperjump technology, after which his character will end up at coordinate $(i + 1, j)$ at the end of the second;
- or use horizontal hyperjump technology, after which his character will end up at coordinate $(i, j + 1)$ at the end of the second;
- or Tema can choose not to make a hyperjump, in which case his character will not move during this second;
The aliens that inhabit this planet are very dangerous and hostile. Therefore, they will shoot from their railguns $r$ times.
Each shot completely penetrates one coordinate vertically or horizontally. If the character is in the line of its impact at the time of the shot \textbf{(at the end of the second)}, he dies.
Since Tema looked at the game's source code, he knows complete information about each shot — the time, the penetrated coordinate, and the direction of the shot.
What is the \textbf{minimum} time for the character to reach the desired point? If he is doomed to die and cannot reach the point with coordinates $(n, m)$, output $-1$.
|
Let's first solve it in $\mathcal{O}(nmt)$. This can be done using dynamic programming. $dp[i][j][k] = true$ if the character can be at coordinates $(i, j)$ at time $t$, otherwise $dp[i][j][k] = false$. Such dynamics can be easily recalculated: $dp[i][j][k] = dp[i - 1][j][k - 1] | dp[i][j - 1][k - 1] | dp[i][j][k - 1]$. If the cell is shot by one of the railguns at time $t$, then $dp[i][j][k] = false$. Now let's notice that if the character can reach the final point $(n, m)$, then he will have to stand still no more than $r$ times. To prove this, we can prove another statement: if the character can reach the final point along some trajectory, then for any such trajectory the character can stand still no more than $r$ times. And this statement can already be proven by mathematical induction. Thus, instead of the $dp[n][m][t]$ dynamics, we can calculate the $dp[n][m][r]$ dynamics, where the third parameter is the number of times the character stood still. The transitions here are made similarly.
|
[
"brute force",
"dfs and similar",
"dp",
"graphs"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int q;
cin >> q;
while (q--) {
int n, m;
cin >> n >> m;
int r;
cin >> r;
bool free[n + 1][m + 1][r + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
for (int k = 0; k <= r; ++k) {
free[i][j][k] = true;
}
}
}
for (int i = 0; i < r; ++i) {
int t, d, coord;
cin >> t >> d >> coord;
if (d == 1) {
for (int j = 0; j <= m; ++j) {
if (0 <= t - coord - j && t - coord - j <= r) {
free[coord][j][t - coord - j] = false;
}
}
} else {
for (int j = 0; j <= n; ++j) {
if (0 <= t - coord - j && t - coord - j <= r) {
free[j][coord][t - coord - j] = false;
}
}
}
}
bool dp[n + 1][m + 1][r + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
for (int k = 0; k <= r; ++k) {
dp[i][j][k] = !(i || j || k);
if (free[i][j][k]) {
if (i && dp[i - 1][j][k]) {
dp[i][j][k] = true;
}
if (j && dp[i][j - 1][k]) {
dp[i][j][k] = true;
}
if (k && dp[i][j][k - 1]) {
dp[i][j][k] = true;
}
}
}
}
}
int ans = -1;
for (int t = r; t >= 0; --t) {
if (dp[n][m][t]) {
ans = n + m + t;
}
}
cout << ans << "\n";
}
return 0;
}
|
1840
|
G1
|
In Search of Truth (Easy Version)
|
\textbf{The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $2023$ queries.}
This is an interactive problem.
You are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in the adjacent room and do not know either the number of sectors or their numbers. There is also an arrow that initially points to some sector. Initially, the host tells you the number of the sector to which the arrow points. After that, you can ask the host to move the arrow $k$ sectors counterclockwise or clockwise at most $2023$ times. And each time you are told the number of the sector to which the arrow points.
Your task is to determine the integer $n$ — the number of sectors in at most $2023$ queries.
It is guaranteed that $1 \le n \le 10^6$.
|
Let $a_1, a_2, \dots, a_n$ be the numbers of the sectors in clockwise order, and let the arrow initially point to the sector with number $a_1$. First, let's make $999$ queries of "+ 1", then we will know the numbers of $1000$ consecutive sectors. If $n < 1000$, then the number of the first query that gives the answer $a_1$ is the desired $n$. If we did not find $n$, this means that $n \ge 1000$. Let's save $a_1, a_2, \dots, a_{1000}$. Now we will make queries of "+ 1000" until we get one of the numbers $a_1, a_2, \dots, a_{1000}$ as the answer. Note that we will need no more than $1000$ queries of this type, after which it is easy to determine the number $n$. Thus, we can determine the number $n$ in no more than $999 + 1000 = 1999 \le 2023$ queries.
|
[
"constructive algorithms",
"interactive",
"math",
"meet-in-the-middle",
"probabilities"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MAXN = 1e6 + 7;
int pos[MAXN];
int32_t main() {
int num;
cin >> num;
int ans = 0;
int cur = 1;
pos[num] = 1;
for (int i = 0; i < 1000; ++i) {
cout << '+' << " " << 1 << endl;
++cur;
cin >> num;
if (pos[num]) {
cout << '!' << " " << cur - pos[num] << endl;
return 0;
}
pos[num] = cur;
}
while (true) {
cout << '+' << " " << 1000 << endl;
cur += 1000;
cin >> num;
if (pos[num]) {
cout << '!' << " " << cur - pos[num] << endl;
return 0;
}
pos[num] = cur;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.