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
⌀ |
|---|---|---|---|---|---|---|---|
1696
|
H
|
Maximum Product?
|
You are given a positive integer $k$. For a multiset of integers $S$, define $f(S)$ as the following.
- If the number of elements in $S$ is less than $k$, $f(S)=0$.
- Otherwise, define $f(S)$ as the maximum product you can get by choosing exactly $k$ integers from $S$.
More formally, let $|S|$ denote the number of elements in $S$. Then,
- If $|S|<k$, $f(S)=0$.
- Otherwise, $f(S)=\max\limits_{T\subseteq S,|T|=k}\left(\prod\limits_{i\in T}i\right)$.
You are given a multiset of integers, $A$. Compute $\sum\limits_{B\subseteq A} f(B)$ modulo $10^9+7$.
Note that in this problem, \textbf{we distinguish the elements by indices instead of values}. That is, a multiset consisting of $n$ elements always has $2^n$ distinct subsets regardless of whether some of its elements are equal.
|
Find a way to calculate the maximum product that can be turned into counting. Use monotonicity to reduce the complexity. First, we describe a strategy to find the answer for a single subset. If the whole subset is negative, the answer is the product of the $K$ maximum numbers in it. Otherwise, take $K$ numbers with the maximum absolute value. If there is an even number of negative numbers in those numbers, we're done. Otherwise, find the smallest positive element and change it to the absolute-value-maximum negative element unchosen, or find the largest negative element and change it to the maximum positive element unchosen. We either do the first change or do the second change. This gives a direct dp solution. Take all $a_i$ and sort them into two arrays consisting of positive and negative ones (0 goes to arbitary one), $pos$ and $neg$, sorted by absolute values. By calculating $fpos(i,k)$: the sum of the product of the largest $K$ numbers of all subsets of $pos[1\dots i]$ that contain $pos_i$, and $fneg(i,k)$ similarly, and $gneg(i,k)$, the sum of the product of the absolute value smallest $K$ numbers of all subsets of $neg[i\dots |neg|]$ that contain $neg_i$, and enumerating the following, we can solve the original problem in $O(n^5)$: the number of positive elements in the $K$ numbers with the maximum absolute value in our calculating subset, $p$. the smallest positive element in the $K$ numbers with the maximum absolute value, $pos_i$. the greatest negative element in the $K$ numbers with the maximum absolute value, $neg_j$. (if $p$ is odd) the greatest positive element not in the $K$ numbers with the maximum absolute value, $pos_k$. (if $p$ is odd) the smallest negative element not in the $K$ numbers with the maximum absolute value, $pos_l$. The contribution to the answer can be represented as the sum of product of $fpos,fneg$, and powers of two. I left the details as an exercise. However, notice that the "enumerating $k,l$" part has nothing to do with $p$, so we can pre-calculate the contribution of $k,l$ for every pair $(i,j)$, giving an $O(n^4)$ algorithm. What's more, for fixed $i,j,k$, the $l$-s that we do the first change is a prefix/suffix of all $l$, and $l$-s that we do the second change is a prefix/suffix of all $l$. So with two pointers and prefix sums, we can pre-calculate the contribution of every $(i,j)$ in $O(n^3)$, which is fast enough. You might be afraid that $600^3$ is too slow for 1.5 seconds. However, the two $O(n^3)$ parts of the algorithm actually run in $O(n\times cntpos\times cntneg)$ ($cntpos,cntneg$ are the number of positive/negative integers in the array), leading to an at most $1/4$ constant factor. Thus, the algorithm actually runs very fast (less than 0.25 seconds). However for similar constant factor reasons, the $O(n^4)$ solution only takes about 6.5 seconds on Codeforces, so we had to set a seemingly-tight limit.
|
[
"brute force",
"combinatorics",
"dp",
"greedy",
"implementation",
"math",
"two pointers"
] | 3,500
| null |
1697
|
A
|
Parkway Walk
|
You are walking through a parkway near your house. The parkway has $n+1$ benches in a row numbered from $1$ to $n+1$ from left to right. The distance between the bench $i$ and $i+1$ is $a_i$ meters.
Initially, you have $m$ units of energy. To walk $1$ meter of distance, you spend $1$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by \textbf{sitting on benches} (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy \textbf{can exceed} $m$.
Your task is to find the \textbf{minimum} amount of energy you have to \textbf{restore} (by sitting on benches) to reach the bench $n+1$ from the bench $1$ (and end your walk).
You have to answer $t$ independent test cases.
|
If you have at least $sum(a_i)$ units of energy, then the answer is $0$, because you can just walk to the end. Otherwise, the answer is $sum(a_i) - m$, because you can just sit on the first bench and then just go. Time complexity: $O(n)$.
|
[
"greedy",
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", H"r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int tc;
cin >> tc;
while (tc--) {
int n, m;
cin >> n >> m;
int sum = 0;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
sum += x;
}
cout << max(0, sum - m) << endl;
}
return 0;
}
|
1697
|
B
|
Promo
|
The store sells $n$ items, the price of the $i$-th item is $p_i$. The store's management is going to hold a promotion: if a customer purchases at least $x$ items, $y$ cheapest of them are free.
The management has not yet decided on the exact values of $x$ and $y$. Therefore, they ask you to process $q$ queries: for the given values of $x$ and $y$, determine the maximum total value of items received for free, if a customer makes \textbf{one purchase}.
Note that all queries are independent; they don't affect the store's stock.
|
First of all, there is an answer with exactly $x$ items bought. Suppose items worth $p_1 \le p_2 \le\dots \le p_m$ ($x < m$) were purchased. Then by removing $p_1$ from this set, the sum of $y$ the cheapest items in the set will change by $p_{y+1}-p_1\ge 0$, which means the answer will not decrease. The second fact that is necessary to solve the problem - $x$ of the most expensive items should be chosen. Otherwise, one can remove the minimum price item from the set and add an item with a higher price (it can always be found), which means the answer will not decrease. Using these two facts, it is enough to sort the array and use prefix sums.
|
[
"greedy",
"sortings"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int n, q;
cin >> n >> q;
vector<long long> p(n), s(n + 1);
for (auto& x : p) cin >> x;
sort(p.begin(), p.end());
for (int i = 0; i < n; ++i) s[i + 1] = s[i] + p[i];
while (q--) {
int x, y;
cin >> x >> y;
cout << s[n - x + y] - s[n - x] << '\n';
}
}
|
1697
|
C
|
awoo's Favorite Problem
|
You are given two strings $s$ and $t$, both of length $n$. Each character in both string is 'a', 'b' or 'c'.
In one move, you can perform one of the following actions:
- choose an occurrence of "ab" in $s$ and replace it with "ba";
- choose an occurrence of "bc" in $s$ and replace it with "cb".
You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $s$ to make it equal to string $t$?
|
First, check that the counts of all letters are the same in both strings. Then consider the following restatement of the moves. The letters 'b' in the string $s$ are stationary. Letters 'a' and 'c', however, move around the string. The move of the first type moves a letter 'a' to the right. The move of the second type moves a letter 'c' to the left. Notice that letters 'a' and 'c' can never swap with each other. Thus, if you remove all letters 'b' from both strings, the remaining strings should be the same. Again, since letters 'a' and 'c' can never swap with each other, you can deduce where each of these letters should end up after the swaps. The first letter '{a}' in $s$ should be on the position of the first letter 'a' in $t$ and so on. After that, we recall that 'a's can only move to the right and 'c's can only move to the left. Thus, we check that the $i$-th occurrence of 'a' in $s$ is to the left or equal to the $i$-th occurrences of 'a' in $t$ and vice versa for 'c's. Finally, we can see that this is a sufficient condition. Easy to show by construction: you can just fix the positions one after another left to right. Overall complexity: $O(n)$ per testcase.
|
[
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"strings",
"two pointers"
] | 1,400
|
for _ in range(int(input())):
n = int(input())
s = input()
t = input()
if s.count('b') != t.count('b'):
print("NO")
continue
j = 0
for i in range(n):
if s[i] == 'b':
continue
while t[j] == 'b':
j += 1
if s[i] != t[j] or (s[i] == 'a' and i > j) or (s[i] == 'c' and i < j):
print("NO")
break
j += 1
else:
print("YES")
|
1697
|
D
|
Guess The String
|
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.
The jury has chosen a string $s$ consisting of $n$ characters; each character of $s$ is a lowercase Latin letter. Your task is to guess this string; initially, you know only its length.
You may ask queries of two types:
- $1$ $i$ — the query of the first type, where $i$ is an integer from $1$ to $n$. In response to this query, the jury will tell you the character $s_i$;
- $2$ $l$ $r$ — the query of the second type, where $l$ and $r$ are integers such that $1 \le l \le r \le n$. In response to this query, the jury will tell you the number of different characters among $s_l, s_{l+1}, \dots, s_r$.
You are allowed to ask no more than $26$ queries of the first type, and no more than $6000$ queries of the second type. Your task is to restore the string $s$.
For each test in this problem, the string $s$ is fixed beforehand, and will be the same for every submission.
|
There are several ways to solve this problem. The model solution does it as follows: Restore the characters of $s$ from left to right. The first character is restored by query ? 1 1. For each of the next characters, let's ask if this character is new (by querying ? 2 1 i and comparing the result with the number of different characters on the segment $[1, i-1]$). If it's new, ask ? 1 i to obtain the $i$-th character (there will be at most $26$ such queries). Otherwise, we can find the previous occurrence of the $i$-th character with binary search. Let $f(x,y)$ be the number of different characters from position $x$ to position $y$. If we want to find the previous occurrence of the $i$-th character, we need to find the last index $j$ such that $f(j,i) = f(j,i-1)$. Since the value $f(j,i) - f(j,i-1)$ does not decrease when we increase $j$, we can find the last $j$ such that $f(j,i) - f(j,i-1) = 0$, with binary search. Unfortunately, the number of queries of type $2$ will be too large if we just use binary search over the whole segment $[1,i-1]$. To decrease the number of queries, we can use the fact that the value of $j$ we are interested in is the last occurrence of some character we already met; there are at most $26$ such values, and binary search among them will need only $5$ iterations.
|
[
"binary search",
"constructive algorithms",
"interactive"
] | 1,900
|
#include<bits/stdc++.h>
using namespace std;
char ask_character(int i)
{
cout << "? 1 " << i << endl;
cout.flush();
string s;
cin >> s;
return s[0];
}
int ask_cnt(int l, int r)
{
cout << "? 2 " << l << " " << r << endl;
cout.flush();
int x;
cin >> x;
return x;
}
int main()
{
int n;
cin >> n;
string s = "";
vector<vector<int>> cnt(n + 1);
for(int i = 0; i < n; i++)
{
if(i == 0)
{
s.push_back(ask_character(1));
cnt[0] = {1};
}
else
{
int cur = ask_cnt(1, i + 1);
if(cur > cnt[i - 1][0])
s.push_back(ask_character(i + 1));
else
{
map<char, int> last;
for(int j = 0; j < s.size(); j++)
last[s[j]] = j;
vector<int> lasts;
for(auto x : last) lasts.push_back(x.second);
sort(lasts.begin(), lasts.end());
int l = 0;
int r = lasts.size();
// there is always an occurrence in [lasts[l], i)
// there is no occurrence in [lasts[r], i)
while(r - l > 1)
{
int m = (l + r) / 2;
int c = ask_cnt(lasts[m] + 1, i + 1);
if (c == cnt[i - 1][lasts[m]])
l = m;
else
r = m;
}
s.push_back(s[lasts[l]]);
}
cnt[i].resize(i + 1);
set<char> q;
for(int j = i; j >= 0; j--)
{
q.insert(s[j]);
cnt[i][j] = q.size();
}
}
}
cout << "! " << s << endl;
cout.flush();
return 0;
}
|
1697
|
E
|
Coloring
|
You are given $n$ points on the plane, the coordinates of the $i$-th point are $(x_i, y_i)$. No two points have the same coordinates.
The distance between points $i$ and $j$ is defined as $d(i,j) = |x_i - x_j| + |y_i - y_j|$.
For each point, you have to choose a color, represented by an integer from $1$ to $n$. For every ordered triple of different points $(a,b,c)$, the following constraints should be met:
- if $a$, $b$ and $c$ have the same color, then $d(a,b) = d(a,c) = d(b,c)$;
- if $a$ and $b$ have the same color, and the color of $c$ is different from the color of $a$, then $d(a,b) < d(a,c)$ and $d(a,b) < d(b,c)$.
Calculate the number of different ways to choose the colors that meet these constraints.
|
Let's call a point $i$ isolated if its color does not match the color of any other point. If a point is not isolated, then it has the same color as the points with minimum distance to it (and only these points should have this color). Let's build a directed graph where the arc $i \rightarrow j$ means that the point $j$ is one of the closest to the point $i$ (i. e. $d(i, j) = \min\limits_{k = 1, k \ne i}^{n} d(i,k)$). If there is a path from the vertex $i$ to the vertex $j$, it means that if the vertex $i$ is not isolated, the vertex $j$ should have the same color as vertex $i$. Suppose the set of vertices reachable from $i$ (including $i$ itself) is $S(i)$. Finding $S(i)$ is easy - just run DFS from the vertex $i$. Let's analyze two cases: there exists a pair of vertices $(j, k)$ such that $j \in S(i)$, $k \in S(i)$, and there is no arc from $j$ to $k$; for every pair of vertices $(j, k)$ such that $j \in S(i)$ and $k \in S(i)$, there is an arc $j \rightarrow k$. Why do we need to analyze these two cases? In the first case, the vertex $i$ must be isolated, because painting it and some other vertex into the same color means that every vertex from $S(i)$ will have this color, and it will break the condition in the statement. In the second case, the vertex $i$ may be isolated, or it may have the same color as all vertices in $S(i)$ - and if it is isolated, then the whole set $S(i)$ should consist of isolated vertices. Let's find all such set of vertices that meet the second case. Each vertex will belong to at most one of these sets; if it doesn't belong to any, it must be isolated, otherwise either the whole its set consists of isolated vertices, or the whole set has the same color. So, for each set, we either use $1$ color or $|S(i)|$ colors. This allows us to implement a knapsack-like dynamic programming: let $dp_{i,j}$ be the number of ways to paint $i$ first sets into $j$ colors, such that the colors are not ordered. After running this dynamic programming, we can get the answer by simple combinatorics: iterate on the number of colors we use in these sets in total, multiply the dynamic programming for it by the (ordered) number of ways to choose these colors from $n$, and then by the number of ways to choose the colors for points that must be isolated. This dynamic programming can even be implemented a bit easier if we treat every vertex that must be isolated as a set of size $1$, and this is the way it's written in the model solution.
|
[
"brute force",
"combinatorics",
"constructive algorithms",
"dp",
"geometry",
"graphs",
"greedy",
"implementation",
"math"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
const int N = 143;
const int K = 5;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int binpow(int x, int y)
{
int z = 1;
while(y > 0)
{
if(y % 2 == 1) z = mul(z, x);
x = mul(x, x);
y /= 2;
}
return z;
}
int fact[N];
int rfact[N];
int A(int n, int k)
{
return mul(fact[n], rfact[n - k]);
}
int n;
vector<int> g[N];
int x[N];
int y[N];
int dist[N][N];
int color[N];
int dp[N][N];
int cc = 0;
set<int> pts;
vector<int> compsize;
void dfs1(int i)
{
//cerr << i << endl;
if(pts.count(i) == 1) return;
pts.insert(i);
for(auto v : g[i])
{
dfs1(v);
}
}
void dfs2(int i, int c)
{
if(color[i] == c) return;
color[i] = c;
for(auto v : g[i])
dfs2(v, c);
}
int main()
{
fact[0] = 1;
for(int i = 1; i < N; i++)
fact[i] = mul(i, fact[i - 1]);
for(int i = 0; i < N; i++)
rfact[i] = binpow(fact[i], MOD - 2);
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%d %d", &x[i], &y[i]);
}
for(int i = 0; i < n; i++)
{
dist[i][i] = int(1e9);
for(int j = 0; j < n; j++)
if(i != j)
dist[i][j] = abs(x[i] - x[j]) + abs(y[i] - y[j]);
}
for(int i = 0; i < n; i++)
{
int d = *min_element(dist[i], dist[i] + n);
for(int j = 0; j < n; j++)
if(dist[i][j] == d) g[i].push_back(j);
}
for(int i = 0; i < n; i++)
{
if(color[i] != 0) continue;
cc++;
pts.clear();
dfs1(i);
//cerr << "!" << endl;
int d = *min_element(dist[i], dist[i] + n);
set<int> pts2 = pts;
bool bad = false;
for(auto x : pts)
for(auto y : pts2)
if(x != y && dist[x][y] != d)
bad = true;
if(bad)
{
color[i] = cc;
compsize.push_back(1);
}
else
{
dfs2(i, cc);
compsize.push_back(pts.size());
}
}
dp[0][0] = 1;
int m = compsize.size();
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
{
if(dp[i][j] == 0) continue;
dp[i + 1][j + 1] = add(dp[i + 1][j + 1], dp[i][j]);
if(compsize[i] != 1)
{
dp[i + 1][j + compsize[i]] = add(dp[i + 1][j + compsize[i]], dp[i][j]);
}
}
int ans = 0;
for(int i = 1; i <= n; i++)
ans = add(ans, mul(dp[m][i], A(n, i)));
cout << ans << endl;
}
|
1697
|
F
|
Too Many Constraints
|
You are asked to build an array $a$, consisting of $n$ integers, each element should be from $1$ to $k$.
The array should be non-decreasing ($a_i \le a_{i+1}$ for all $i$ from $1$ to $n-1$).
You are also given additional constraints on it. Each constraint is of one of three following types:
- $1~i~x$: $a_i$ \textbf{should not} be equal to $x$;
- $2~i~j~x$: $a_i + a_j$ should be less than or equal to $x$;
- $3~i~j~x$: $a_i + a_j$ should be greater than or equal to $x$.
Build any non-decreasing array that satisfies all constraints or report that no such array exists.
|
Imagine there were no constraints of the second or the third types. Then it would be possible to solve the problem with some greedy algorithm. Unfortunately, when both these constraints are present, it's not immediately clear how to adapt the greedy. Dynamic programming is probably also out of question, because you can't maintain all possible cuts between equal values on each prefix. Thus, let's try to make a graph problem out of this. Who knows, maybe a flow or something else could work. Create $k$ nodes for each position. Let the $x$-th of them on the $i$-th position represent the condition of kind "is $a_i$ equal to $x$?". Then all constraints can be described as edges on this graph. Binary variables, restrictive edges. Surely, this is 2-SAT. Connect the pairs of values that satisfy each constraint. Add the edges between the adjacent positions to enforce the restriction on the non-decreasing order. Prohibit each position to be assigned to multiple values. Force each position to be assigned at least one value. Huh, it's not that easy. That's where the 2-SAT idea fails. We want the conditions of form $(a_i = 1 \vee a_i = 2 \vee \dots \vee a_i = k)$. But that is not allowed, since 2-SAT has to have two variables in a clause. That's where the main idea of the problem comes up. Instead of making our nodes $(i, x)$ represent $a_i = x$, let's make them $a_i \ge x$ and try building the graph again. If $a_i = x$, then all nodes $(i, y)$ for $y \le x$ will be true, and the rest will be false. So if $(i, x)$ is false, then $(i, x + 1)$ is false. That will enforce the validity of the nodes themselves. First, the order. If $(i, x)$ is true, then $(i + 1, x)$ is true. The first type of constraints. $a_i \neq x$ is basically the same as ($a_i < x$ or $a_i > x$). For our conditions, it's rather ((not $a_i \ge x$) or $a_i \ge x + 1$). The second type of constraints. $a_i + a_j \le x$. Let $a_i$ be greater than or equal to some $y$. Then, for this constraint to hold, $a_j$ should be no greater than $x - y$. Thus, if $(a_i \ge y)$ is true, then $(a_j \ge x - y + 1)$ should be false. Same for $i$ and $j$ swapped. The third type of constraints is similar. $a_i + a_j \ge x$. Let $a_i$ be less than or equal to some $y$. Then, for this constraint to hold, $a_j$ should be greater than or equal to $x - y$. Thus, if $(a_i \ge y + 1)$ is false, then $(a_j \ge x - y)$ should be true. Same for $i$ and $j$ swapped. And that's it. Solve the 2-SAT and restore the answer. I can advise making not $k$ but actually $k + 2$ nodes for $a_i \ge 0, 1, \dots, k+1$ and force the values to be between $1$ and $k$. That will simplify the checks while adding the constraints. Overall complexity: $O((n+m)k)$.
|
[
"2-sat",
"constructive algorithms",
"graphs",
"implementation"
] | 2,800
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct constraint{
int tp, i, j, x;
};
vector<vector<int>> g, tg;
vector<char> used;
vector<int> clr, ord;
void ts(int v){
used[v] = true;
for (int u : g[v]) if (!used[u])
ts(u);
ord.push_back(v);
}
void dfs(int v, int k){
clr[v] = k;
for (int u : tg[v]) if (clr[u] == -1)
dfs(u, k);
}
void either(int x, int y){
g[x ^ 1].push_back(y);
g[y ^ 1].push_back(x);
tg[y].push_back(x ^ 1);
tg[x].push_back(y ^ 1);
}
void implies(int x, int y){
either(x ^ 1, y);
}
void must(int x){
either(x, x);
}
int main() {
int t;
scanf("%d", &t);
forn(_, t){
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
vector<constraint> c(m);
forn(i, m){
scanf("%d%d", &c[i].tp, &c[i].i);
if (c[i].tp != 1) scanf("%d", &c[i].j);
scanf("%d", &c[i].x);
--c[i].i, --c[i].j;
}
int vts = n * (k + 2);
g.assign(2 * vts, vector<int>());
tg.assign(2 * vts, vector<int>());
forn(i, n){
forn(j, (k + 2) - 1)
implies(2 * (i * (k + 2) + j + 1) + 1, 2 * (i * (k + 2) + j) + 1);
must(2 * (i * (k + 2) + 1) + 1);
must(2 * (i * (k + 2) + k + 1));
}
forn(i, n - 1) forn(j, k + 2){
implies(2 * (i * (k + 2) + j) + 1, 2 * ((i + 1) * (k + 2) + j) + 1);
}
forn(i, m){
if (c[i].tp == 1)
either(2 * (c[i].i * (k + 2) + c[i].x + 1) + 1, 2 * (c[i].i * (k + 2) + c[i].x));
else if (c[i].tp == 2){
for (int a = max(1, c[i].x - k); a <= min(k, c[i].x - 1); ++a){
implies(2 * (c[i].i * (k + 2) + a) + 1, 2 * (c[i].j * (k + 2) + (c[i].x - a) + 1));
implies(2 * (c[i].j * (k + 2) + a) + 1, 2 * (c[i].i * (k + 2) + (c[i].x - a) + 1));
}
}
else{
for (int a = max(1, c[i].x - k); a <= min(k, c[i].x - 1); ++a){
implies(2 * (c[i].i * (k + 2) + a + 1), 2 * (c[i].j * (k + 2) + (c[i].x - a)) + 1);
implies(2 * (c[i].j * (k + 2) + a + 1), 2 * (c[i].i * (k + 2) + (c[i].x - a)) + 1);
}
}
}
used.assign(2 * vts, 0);
ord.clear();
forn(i, used.size()) if (!used[i]) ts(i);
reverse(ord.begin(), ord.end());
clr.assign(2 * vts, -1);
int cc = 0;
for (int v : ord) if (clr[v] == -1){
dfs(v, cc);
++cc;
}
vector<int> vals(vts);
bool ans = true;
forn(i, vts){
if (clr[2 * i] == clr[2 * i + 1]){
ans = false;
break;
}
vals[i] = (clr[2 * i] < clr[2 * i + 1]);
}
if (!ans){
puts("-1");
continue;
}
forn(i, n){
int lst = 0;
forn(j, k + 2) if (vals[i * (k + 2) + j])
lst = j;
printf("%d ", lst);
}
puts("");
}
return 0;
}
|
1698
|
A
|
XOR Mixup
|
There is an array $a$ with $n-1$ integers. Let $x$ be the bitwise XOR of all elements of the array. The number $x$ is added to the end of the array $a$ (now it has length $n$), and then the elements are shuffled.
You are given the newly formed array $a$. What is $x$? If there are multiple possible values of $x$, you can output any of them.
|
Any element of the array works. Let's use $\oplus$ for $\mathsf{XOR}$. Suppose that the original array is $[a_1, \dots, a_{n-1}]$. Then $x=a_1 \oplus \dots \oplus a_{n-1}$. Let's show that $a_1$ is the $\mathsf{XOR}$ of all other elements of the array; that is, $a_1 = a_2 \oplus \dots \oplus a_{n-1} \oplus x$. Substituting $x=a_1 \oplus \dots \oplus a_{n-1}$, we have $a_1 = a_2 \oplus \dots \oplus a_{n-1} \oplus a_2 \oplus \dots \oplus a_{n-1}.$ More formally, we can write the following. $\begin{align*} a_1 &\stackrel{?}{=} a_2 \oplus \dots \oplus a_{n-1} \oplus x \\ &= a_2 \oplus \dots \oplus a_{n-1} \oplus (a_1 \oplus \dots \oplus a_{n-1}) \\ &= a_2 \oplus \dots \oplus a_{n-1} \oplus (a_1 \oplus a_2 \oplus \dots \oplus a_{n-1}) \\ &= (a_2 \oplus \dots \oplus a_{n-1}) \oplus a_1 \oplus (a_2 \oplus \dots \oplus a_{n-1}) \\ &= a_1 \oplus (a_2 \oplus \dots \oplus a_{n-1}) \oplus (a_2 \oplus \dots \oplus a_{n-1}) \\ &= a_1. \end{align*}$ The same proof follows for any $a_i$. Hence you can output any element of the array. The time complexity is $\mathcal{O}(n)$.
|
[
"bitmasks",
"brute force"
] | 800
|
for t in range(int(input())):
n = int(input())
print([int(x) for x in input().split()][0])
|
1698
|
B
|
Rising Sand
|
There are $n$ piles of sand where the $i$-th pile has $a_i$ blocks of sand. The $i$-th pile is called too tall if $1 < i < n$ and $a_i > a_{i-1} + a_{i+1}$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)
You are given an integer $k$. An operation consists of picking $k$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $1 \leq l,r \leq n$ such that $r-l+1=k$. Then for all $l \leq i \leq r$, update $a_i \gets a_i+1$.
What is the \textbf{maximum} number of piles that can simultaneously be too tall after some (possibly zero) operations?
|
Note that two piles in a row can't be too tall, since a pile that is too tall has strictly more sand than its neighbours. If $k=1$ then we can make every other pile too tall, excluding the ends of the array. For example, if $a=[1,2,3,4,5,6]$, we can make piles $2$ and $4$ too tall by performing some large number of operations on them (say, by making it into $[1, 10^{100}, 3, 10^{100}, 5, 6]$.) The answer is $\left\lfloor\frac{n-1}{2}\right\rfloor$. If $k \geq 2$, then note that for any pile, if we perform the operation on it then we perform on one of its neighbours as well. Therefore, if the pile is not too tall initially, then it will never become too tall as a result of these operations, since both a pile and at least one of its neighbours will gain sand. So in this case, doing operations never improves the answer, and so the answer is the number of too tall piles initially. The time complexity is $\mathcal{O}(n)$.
|
[
"constructive algorithms",
"greedy",
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n, k;
cin >> n >> k;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
if (k > 1) {
int res = 0;
for (int i = 1; i < n - 1; i++) {
res += (a[i] > a[i - 1] + a[i + 1]);
}
cout << res << '\n';
}
else {
cout << (n - 1) / 2 << '\n';
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1698
|
C
|
3SUM Closure
|
You are given an array $a$ of length $n$. The array is called 3SUM-closed if for all distinct indices $i$, $j$, $k$, the sum $a_i + a_j + a_k$ is an element of the array. More formally, $a$ is 3SUM-closed if for all integers $1 \leq i < j < k \leq n$, there exists some integer $1 \leq l \leq n$ such that $a_i + a_j + a_k = a_l$.
Determine if $a$ is 3SUM-closed.
|
Let's consider some array which is 3SUM-closed. If the array has at least three positive elements, consider the largest three $x$, $y$, and $z$. Notice that $x+y+z$ is strictly larger than $x$, $y$, and $z$, which means that $x+y+z$ is not an element of the array (since $x$, $y$, $z$ were the largest elements). Therefore the array has $\leq 2$ positive elements. Similarly, if the array has at least three negative elements, consider the smallest three $x$, $y$, and $z$. Notice that $x+y+z$ is strictly smaller than $x$, $y$, and $z$, which means that $x+y+z$ is not an element of the array (since $x$, $y$, $z$ were the smallest elements). Therefore the array has $\leq 2$ negative elements. Finally, note that there is no point in having more than $2$ zeroes in the array, since any additional zeroes won't change the sums that can be formed. So if there are more than $2$ zeroes, we can remove them until there are exactly $2$. It follows that the resulting array has at most $2 + 2 + 2 = 6$ elements. This is small, so we can brute force the condition in the problem in $\mathcal{O}(6^4)$ or $\mathcal{O}(6^3)$ time. The time complexity is $\mathcal{O}(n + 6^4)$ or $\mathcal{O}(n + 6^3)$, depending on the implementation.
|
[
"brute force",
"data structures"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
vector<int> pos, neg, a;
for (int i = 0; i < n; i++) {
int x; cin >> x;
if (x > 0) {pos.push_back(x);}
else if (x < 0) {neg.push_back(x);}
else {
if (a.size() < 2) {a.push_back(x);}
}
}
if (pos.size() > 2 || neg.size() > 2) {cout << "NO\n"; return;}
for (int i : pos) {a.push_back(i);}
for (int i : neg) {a.push_back(i);}
for (int i = 0; i < a.size(); i++) {
for (int j = i + 1; j < a.size(); j++) {
for (int k = j + 1; k < a.size(); k++) {
bool ok = false;
for (int l = 0; l < a.size(); l++) {
if (a[i] + a[j] + a[k] == a[l]) {ok = true;}
}
if (!ok) {cout << "NO\n"; return;}
}
}
}
cout << "YES\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1698
|
D
|
Fixed Point Guessing
|
This is an interactive problem.
Initially, there is an array $a = [1, 2, \ldots, n]$, where $n$ is an odd positive integer. The jury has selected $\frac{n-1}{2}$ \textbf{disjoint} pairs of elements, and then the elements in those pairs are swapped. For example, if $a=[1,2,3,4,5]$, and the pairs $1 \leftrightarrow 4$ and $3 \leftrightarrow 5$ are swapped, then the resulting array is $[4, 2, 5, 1, 3]$.
As a result of these swaps, exactly one element will not change position. You need to find this element.
To do this, you can ask several queries. In each query, you can pick two integers $l$ and $r$ ($1 \leq l \leq r \leq n$). In return, you will be given the elements of the subarray $[a_l, a_{l + 1}, \dots, a_r]$ \textbf{sorted in increasing order}.
Find the element which did not change position. You can make at most $\mathbf{15}$ queries.
The array $a$ is fixed before the interaction and does not change after your queries.
Recall that an array $b$ is a subarray of the array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
Note that $\left\lceil\log_2 10^4\right\rceil = 14$, which is less than the number of queries. If we can answer a question of the form "given a subarray, does it contain the fixed point?", then we can binary search on this subarray until we find the fixed point. Given a subarray $[a_l, \dots, a_r]$, let's count the number of $a_i$ such that $l \leq a_i \leq r$. We claim that if this count is odd, then the subarray contains the fixed point; otherwise, it does not. First, let's show that each swapped pair either increases the count by $0$ or by $2$. Suppose that $x \leftrightarrow y$ are swapped (that is, $a_x = y$ and $a_y = x$). If $a_x$ is in the range from $l$ to $r$, then $l \leq y \leq r$ (since $a_x = y$), so $a_y$ is also in the range from $l$ to $r$. Similarly, if $a_x$ is not in the range, then neither is $a_y$. So this pair either increases the count by $0$ or $2$. Contrarily, the fixed point increases the count by $0$ if it is not in the range and $1$ if it is. So we can simply look at the parity of the number of elements satisfying the condition, and run our binary search. The time complexity is $\mathcal{O}(n)$.
|
[
"binary search",
"constructive algorithms",
"interactive"
] | 1,600
|
for t in range(int(input())):
n = int(input())
l = 1
r = n
while l < r:
m = l + (r - l) // 2
print("?", l, m, flush=True)
if (sum(l <= i <= m for i in [int(x) for x in input().split()]) % 2):
r = m
else:
l = m + 1
print("!", l, flush=True)
|
1698
|
E
|
PermutationForces II
|
You are given a permutation $a$ of length $n$. Recall that permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order.
You have a strength of $s$ and perform $n$ moves on the permutation $a$. The $i$-th move consists of the following:
- Pick two integers $x$ and $y$ such that $i \leq x \leq y \leq \min(i+s,n)$, and swap the positions of the integers $x$ and $y$ in the permutation $a$. Note that you \textbf{can} select $x=y$ in the operation, in which case no swap will occur.
You want to turn $a$ into another permutation $b$ after $n$ moves. However, some elements of $b$ are missing and are replaced with $-1$ instead. Count the number of ways to replace each $-1$ in $b$ with some integer from $1$ to $n$ so that $b$ is a permutation and it is possible to turn $a$ into $b$ with a strength of $s$.
Since the answer can be large, output it modulo $998\,244\,353$.
|
Suppose that we know the elements of $b$. We claim that the minimum strength needed is $\max_{i=1}^n a_i - b_i$. Let's prove it. Proof. For simplicity let's sort the elements of $b$ from $1$ to $n$, and rearrange the corresponding elements of $a$ in the same way. In other words, we only need to turn this new array $a$ into the identity $[1, 2, \dots, n]$. First note that on the $i$-th operation, we need to move the number $i$ to the correct position. This is because of the format of the operations; in any future operation, $i$ will not be in the given range, so it is required to move $i$ in the current operation. Let's look at the number $1$. If $a_1 = 1$, then we don't need any strength. Otherwise, we need $a_i - 1$ strength to swap $1$ and $a_i$. Afterwards, we can essentially ignore $1$ for the rest of the operations, since there is no need to move it again. In general, there are two cases for when we need to move $i$ to its correct place: $a_i \geq i$. In this case, we'll never move $a_i$ until the $i$-th operation, where we swap $i$ and $a_i$. We need a strength of $a_i - i$ for that. This is necessary. $a_i < i$. In this case, we will swap $a_i$ in an earlier operation (since $a_i < i$, so we must swap it to its correct place in the $a_i$-th operation). If we again end up with some smaller number, we will need to swap that before $i$, and so on. Suppose that after some time, the current element $a_i$ in the $i$-th position is at least $i$. Then this element must have been swapped with some other element smaller than $i$ (since we only perform swaps with elements smaller than $i$ before the $i$-th operation). In particular, this element originally started somewhere to the left of $i$, say at position $j < i$. Then in the strength calculation, we counted $a_i - j$, which is more than $a_i - i$, i.e. more than we actually need to swap $i$ and $a_i$. This is sufficient. Suppose that after some time, the current element $a_i$ in the $i$-th position is at least $i$. Then this element must have been swapped with some other element smaller than $i$ (since we only perform swaps with elements smaller than $i$ before the $i$-th operation). In particular, this element originally started somewhere to the left of $i$, say at position $j < i$. Then in the strength calculation, we counted $a_i - j$, which is more than $a_i - i$, i.e. more than we actually need to swap $i$ and $a_i$. This is sufficient. Hence we only need to check the inequality $s \geq a_i - b_i$ for all $i$. Now we proceed to the counting part. Rewrite this as $a_i - s \leq b_i$. Suppose that $k$ values of $b_i$ are missing. Call them $[m_1, \dots, m_k]$ in increasing order. Then note that if some element of $m$ satisfies this inequality, all larger elements of $m$ will. In other words, for each $a_i$ whose corresponding element of $b$ is missing, some suffix of $[m_1, \dots, m_k]$ will work. We can simply binary search to find this suffix for each $a_i$. Let $l_i$ denote the length of this suffix. Afterwards, we need to count the number of ways to assign each missing element to an $a_i$. Process the elements greedily, from the $a_i$ with the fewest choices to the one with the most (that is, the largest $a_i$ to the smallest). The first $a_i$ has $l_i$ choices, the second $l_i - 1$ (one element of $m$ was already taken), the third $l_i - 2$, and so on. We can compute this product straightforwardly. The time complexity is $\mathcal{O}(n \log n)$.
|
[
"brute force",
"combinatorics",
"greedy",
"sortings",
"trees",
"two pointers"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 998244353;
bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
return (a.second < b.second);
}
void solve() {
int n, s;
cin >> n >> s;
pair<int, int> a[n + 1];
bool vis[n + 1];
for (int i = 1; i <= n; i++) {
cin >> a[i].first;
vis[i] = false;
}
for (int i = 1; i <= n; i++) {
cin >> a[i].second;
if (a[i].second != -1) {
vis[a[i].second] = true;
}
}
vector<int> missing;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {missing.push_back(i);}
}
sort(a + 1, a + n + 1, cmp);
int mx = 0;
for (int i = 1; i <= n; i++) {
if (a[i].second != -1) {
mx = max(mx, a[i].first - a[i].second);
}
}
if (mx > s) {cout << 0 << '\n'; return;}
vector<int> cnts;
for (int i = 1; i <= n; i++) {
if (a[i].second == -1) {
cnts.push_back(missing.end() - lower_bound(missing.begin(), missing.end(), a[i].first - s));
}
}
sort(cnts.begin(), cnts.end());
long long res = 1;
for (int i = 0; i < cnts.size(); i++) {
res = (res * (cnts[i] - i)) % MOD;
}
cout << res << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1698
|
F
|
Equal Reversal
|
There is an array $a$ of length $n$. You may perform the following operation on it:
- Choose two indices $l$ and $r$ where $1 \le l \le r \le n$ and $a_l = a_r$. Then, reverse the subsegment from the $l$-th to the $r$-th element, i. e. set $[a_l, a_{l + 1}, \ldots, a_{r - 1}, a_r]$ to $[a_r, a_{r-1}, \ldots, a_{l+1}, a_l]$.
You are also given another array $b$ of length $n$ which is a permutation of $a$. Find a sequence of at most $n^2$ operations that transforms array $a$ into $b$, or report that no such sequence exists.
|
Consider the following invariants of the array: $a_1$ and $a_n$ don't change as a result of the operations. The set of unordered pairs of adjacent elements doesn't change as a result of the operations. In other words, if you build a graph $\mathcal{G}$ whose vertices are labelled $1$ to $n$, and make an edge connecting $a_i$ and $a_{i+1}$ for all $1 \leq i < n$, the graph does not change after operations. This is because the operation can be seen as reversing the order we traverse a cycle in $\mathcal{G}$, which doesn't change the undirected graph. The first element of $a$ already has to match. Suppose the second element does not match; that is, $a_1 = b_1$ but $a_2 \neq b_2$. Then there has to be some other copy of $b_1$ later in $a$ next to the element in $a$ equal to $b_2$, by the graph condition mentioned above. If the copy of $b_1$ appears after the element equal to $b_2$, we can reverse the subarray whose endpoints are the two copies of $b_1$. Otherwise, it can be shown that there must exist some subarray with equal endpoints that contains $b_1$ followed by $b_2$, so we can reverse it. This takes $2n$ operations, but it requires $\mathcal{O}(n^2)$ time to construct. So the overall complexity is $\mathcal{O}(n^3)$.
|
[
"constructive algorithms",
"graphs",
"implementation",
"math"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
int a[n], b[n];
vector<pair<int, int>> ax, bx;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (i > 0) {ax.emplace_back(min(a[i - 1], a[i]), max(a[i - 1], a[i]));}
}
for (int i = 0; i < n; i++) {
cin >> b[i];
if (i > 0) {bx.emplace_back(min(b[i - 1], b[i]), max(b[i - 1], b[i]));}
}
sort(ax.begin(), ax.end());
sort(bx.begin(), bx.end());
if (!(a[0] == b[0] && a[n - 1] == b[n - 1] && equal(ax.begin(), ax.end(), bx.begin()))) {
cout << "NO\n"; return;
}
cout << "YES\n";
vector<pair<int, int>> ans;
for (int i = 0; i < n - 1; i++) {
if (a[i] == b[i] && a[i + 1] == b[i + 1]) {continue;}
int pos = -1;
for (int j = i; j < n - 1; j++) {
if (a[j + 1] == b[i] && a[j] == b[i + 1]) {pos = j; break;}
}
if (pos != -1) {ans.emplace_back(i + 1, pos + 2); reverse(a + i, a + pos + 2); continue;}
for (int j = i; j < n - 1; j++) {
if (a[j] == b[i] && a[j + 1] == b[i + 1]) {pos = j; break;}
}
set<pair<int, int>> seen;
for (int j = i; j < pos; j++) {
seen.insert(make_pair(min(a[j], a[j + 1]), max(a[j], a[j + 1])));
}
int val = -1;
for (int j = i + 1; j < n - 1; j++) {
if (seen.find(make_pair(min(b[j], b[j + 1]), max(b[j], b[j + 1]))) != seen.end()) {
val = j; break;
}
}
int posr = -1, posl = -1;
for (int j = i; j <= pos; j++) {
if (min(a[j], a[j + 1]) == min(b[val], b[val + 1]) && max(a[j], a[j + 1]) == max(b[val], b[val + 1])) {posr = j; break;}
}
for (int j = n - 2; j >= pos; j--) {
if (min(a[j], a[j + 1]) == min(b[val - 1], b[val]) && max(a[j], a[j + 1]) == max(b[val - 1], b[val])) {posl = j; break;}
}
if (posr < n - 1 && a[posr + 1] == a[posl]) {posr++;}
else if (posl < n - 1 && a[posr] == a[posl + 1]) {posl++;}
else if (posr < n - 1 && posl < n - 1 && a[posr + 1] == a[posl + 1]) {posr++; posl++;}
ans.emplace_back(posr + 1, posl + 1); reverse(a + posr, a + posl + 1);
pos = -1;
for (int j = i; j < n - 1; j++) {
if (a[j + 1] == b[i] && a[j] == b[i + 1]) {pos = j; break;}
}
ans.emplace_back(i + 1, pos + 2); reverse(a + i, a + pos + 2);
}
cout << ans.size() << '\n';
for (auto p : ans) {
cout << p.first << ' ' << p.second << '\n';
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1698
|
G
|
Long Binary String
|
There is a binary string $t$ of length $10^{100}$, and initally all of its bits are $0$. You are given a binary string $s$, and perform the following operation some times:
- Select some substring of $t$, and replace it with its XOR with $s$.$^\dagger$
After several operations, the string $t$ has exactly two bits $1$; that is, there are exactly two distinct indices $p$ and $q$ such that the $p$-th and $q$-th bits of $t$ are $1$, and the rest of the bits are $0$. Find the lexicographically largest$^\ddagger$ string $t$ satisfying these constraints, or report that no such string exists.
$^\dagger$ Formally, choose an index $i$ such that $0 \leq i \leq 10^{100}-|s|$. For all $1 \leq j \leq |s|$, if $s_j = 1$, then toggle $t_{i+j}$. That is, if $t_{i+j}=0$, set $t_{i+j}=1$. Otherwise if $t_{i+j}=1$, set $t_{i+j}=0$.
$^\ddagger$ A binary string $a$ is lexicographically larger than a binary string $b$ of the same length if in the first position where $a$ and $b$ differ, the string $a$ has a bit $1$ and the corresponding bit in $b$ is $0$.
|
Ignore leading zeroes of $s$. We can add them back at the end. Let's view the string as a polynomial $P(x)$ in $\mathrm{GF}(2)$. Then in an operation we can multiply $P(x)$ by any monomial $x^k$ for some $k$, so after some number of operations we can multiply $P(x)$ by some other polynomial $Q(x)$. At the end, we have a string with two flipped bits. We can in fact make the first character equal to $1$ by finding the smallest $k$ such that $P(x)Q(x) = x^k + 1$. Such a $k$ exists, because the constant term of $P$ is $1$ and $Q$ is arbitrary. Rewrite this as $x^k \equiv 1 \pmod{P(x)}$. Now it's clear that the answer is a divisor of the order of $x$ in $P(x)$. We can use polynomial factoring algorithms or baby-step-giant-step and meet in the middle. The time complexity is $\mathcal{O}(2^{|s|/2} |s|^2)$ or $\mathcal{O}(2^{|s|/2} |s|)$.
|
[
"bitmasks",
"math",
"matrices",
"meet-in-the-middle",
"number theory"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define endl '\n'
#define rep(x, start, end) \
for (auto 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()
int n;
string s;
int mod;
int mul(int i, int j) {
int res = 0;
rep(x, 0, n - 1) {
if (i & (1LL << x)) res ^= j;
j <<= 1;
if (j & (1LL << (n - 1))) j ^= mod;
}
return res;
}
int pow(int i) {
int res = 1;
int b = 2;
while (i) {
if (i & 1) res = mul(res, b);
b = mul(b, b);
i >>= 1;
}
return res;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin.exceptions(ios::badbit | ios::failbit);
mod = 0;
cin >> s;
vector<int> pos;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '1') {
pos.push_back(i);
}
}
s.erase(s.find_last_not_of("0") + 1);
int offset = s.find_first_not_of("0");
s.erase(0, offset);
n = s.length();
if (pos.size() == 0) {
cout << -1 << endl;
return 0;
}
if (pos.size() == 1) {
cout << n + offset << ' ' << n + offset + 1 << endl;
return 0;
}
if (pos.size() == 2) {
cout << pos[0] + 1 << ' ' << pos[1] + 1 << endl;
return 0;
}
rep(x, 0, sz(s)) if (s[x] == '1') mod |= (1LL << x);
int h = (n + 1) / 2;
int val = mod;
int prod = 1;
rep(x, 3LL, 1 << h) if (x & 1) {
int num = 0;
while (true) {
int curr = val;
int other = 0;
rep(bit, 0, n) if (curr & (1LL << bit)) {
curr ^= x << bit;
other ^= 1LL << bit;
}
if (curr == 0) {
val = other;
num++;
} else
break;
}
if (num) {
prod *= (1LL << (63 - __builtin_clzll(x))) - 1;
rep(y, 1, num) prod *= 1LL << (63 - __builtin_clzll(x));
}
}
if (val > 1) prod *= (1LL << (63 - __builtin_clzll(val))) - 1;
int ans = 1LL << 60;
for (int x = 1; x * x <= prod; x++) {
if (prod % x == 0) {
if (pow(x) == 1) ans = min(ans, x);
if (pow(prod / x) == 1) ans = min(ans, prod / x);
}
}
cout << 1 + offset << ' ' << ans + 1 + offset << endl;
}
|
1699
|
A
|
The Third Three Number Problem
|
You are given a positive integer $n$. Your task is to find \textbf{any} three integers $a$, $b$ and $c$ ($0 \le a, b, c \le 10^9$) for which $(a\oplus b)+(b\oplus c)+(a\oplus c)=n$, or determine that there are no such integers.
Here $a \oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \oplus 4 = 6$ and $3 \oplus 1=2$.
|
An answer exists only when $n$ is even. $a \oplus a = 0$ $a \oplus 0 = a$ First and foremost, it can be proven that $(a \oplus b) + (b \oplus c) + (a \oplus c)$ is always even, for all possible non-negative values of $a$, $b$ and $c$. Firstly, $a \oplus b$ and $a+b$ have the same parity, since $a + b = a \oplus b + 2 \cdot (a \text{&} b)$. Therefore, $(a \oplus b) + (b \oplus c) + (a \oplus c)$ has the same parity as $(a+b)+(b+c)+(a+c)=2 \cdot (a+b+c)$. Therefore, if $n$ is even, one possible solution is $a=0$, $b=0$ and $c=\frac{n}{2}$. In this case, $(a \oplus b) + (b \oplus c) + (a \oplus c)= 0+\frac{n}{2}+\frac{n}{2}=n$. Otherwise, there are no solutions. Time complexity per testcase: $O(1)$.
|
[
"constructive algorithms",
"math"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
void testcase(){
int n;
cin>>n;
if(n%2==0)
cout<<"0 "<<n/2<<' '<<n/2<<'\n';
else
cout<<"-1\n";
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
int t;
cin>>t;
while(t--)
testcase();
return 0;
}
|
1699
|
B
|
Almost Ternary Matrix
|
You are given two \textbf{even} integers $n$ and $m$. Your task is to find \textbf{any} binary matrix $a$ with $n$ rows and $m$ columns where every cell $(i,j)$ has \textbf{exactly} two neighbours with a different value than $a_{i,j}$.
Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $(x,y)$ are: $(x-1,y)$, $(x,y+1)$, $(x+1,y)$ and $(x,y-1)$.
It can be proven that under the given constraints, an answer always exists.
|
The general construction consists of a $2 \times 2$ checkerboard with a $1$-thick border. Here is the intended solution for $n=6$ and $m=8$: Time complexity per testcase: $O(nm)$.
|
[
"bitmasks",
"constructive algorithms",
"matrices"
] | 900
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void testcase(){
ll n,m;
cin>>n>>m;
for(ll i=1;i<=n;i++){
for(ll j=1;j<=m;j++){
cout<<((i%4<=1)!=(j%4<=1))<<" \n"[j==m];
}
}
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
int t;
cin>>t;
while(t--)
testcase();
return 0;
}
|
1699
|
C
|
The Third Problem
|
You are given a permutation $a_1,a_2,\ldots,a_n$ of integers from $0$ to $n - 1$. Your task is to find how many permutations $b_1,b_2,\ldots,b_n$ are similar to permutation $a$.
Two permutations $a$ and $b$ of size $n$ are considered similar if for all intervals $[l,r]$ ($1 \le l \le r \le n$), the following condition is satisfied: $$\operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]),$$ where the $\operatorname{MEX}$ of a collection of integers $c_1,c_2,\ldots,c_k$ is defined as the smallest non-negative integer $x$ which does not occur in collection $c$. For example, $\operatorname{MEX}([1,2,3,4,5])=0$, and $\operatorname{MEX}([0,1,2,4,5])=3$.
Since the total number of such permutations can be very large, you will have to print its remainder modulo $10^9+7$.
In this problem, a permutation of size $n$ is an array consisting of $n$ distinct integers from $0$ to $n-1$ in arbitrary order. For example, $[1,0,2,4,3]$ is a permutation, while $[0,1,1]$ is not, since $1$ appears twice in the array. $[0,1,3]$ is also not a permutation, since $n=3$ and there is a $3$ in the array.
|
Let $p[x]$ be the position of $x$ in permutation $a$. Since $MEX([a_{p[0]}])=1$, the only possible position of $0$ in permutation $b$ is exactly $p[0]$. Continuing this line of thought, where can $1$ be placed in permutation $b$? Without loss of generality, we will assume that $p[0] \lt p[1]$. If $p[2] \lt p[0]$, then how many possible positions can $2$ have in permutation $b$? If $p[0] \lt p[2] \lt p[1]$, then how many possible positions can $2$ have in permutation $b$? If $p[2] \gt p[1]$, then how many possible positions can $2$ have in permutation $b$? Let $p[x]$ be the position of $x$ in permutation $a$. Since $MEX([a_{p[0]}])=1$, the only possible position of $0$ in permutation $b$ is exactly $p[0]$. Without loss of generality, we will assume that $p[0] \lt p[1]$. For every interval $[l,r]$ ($l \le p[0] \lt p[1]\le r$), $MEX([b_l,\ldots,b_r])$ must be at least $2$. For every other interval, $MEX([b_l,\ldots,b_r])$ cannot exceed $2$. The only position for $1$ which satisfies both of these constraints is exactly $p[1]$. Let's consider the current interval $[l,r]$ as being $[p[0],p[1]]$. If $p[2] \in [l,r]$, we can say that, for every interval $[x,y]$ ($x \le l \lt r \le y$), $MEX([b_x,\ldots,b_y])$ must be at least $3$. Similarly, for every other interval, $MEX([b_x,\ldots,b_y])$ cannot exceed $3$. Both of these constraints are only met if $2$ occurs in permutation $b$ on some position $p \in [l,r]$. Since only $2$ positions are currently occupied in $[l,r]$, the total number of similar permutations will be multiplied by $(r-l+1)-2$. Otherwise, $2$ can be placed in permutation $b$ only on $p[2]$. Additionally, the current interval will be "extended" to include $p[2]$, resuting in either $[p[2],r]$ or $[l,p[2]]$. After processing $0,1, \ldots, k-2$ and $k-1$, the algorithm for processing $k$ is very similar to the one presented earlier. If $p[k] \in [l,r]$, the answer gets multiplied by $(r-l+1)-k$. Otherwise, the current interval is extended to include $p[k]$. Time complexity per testcase: $O(n)$
|
[
"combinatorics",
"constructive algorithms",
"math"
] | 1,700
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll NMAX=1e5+5,MOD=1e9+7;
ll v[NMAX],pos[NMAX];
void tc(){
ll n,l,r,ans=1;
cin>>n;
for(ll i=0;i<n;i++){
cin>>v[i];
pos[v[i]]=i;
}
l=r=pos[0];
for(ll i=1;i<n;i++){
if(pos[i]<l) l=pos[i];
else if(pos[i]>r) r=pos[i];
else ans=ans*(r-l+1-i)%MOD;
}
cout<<ans<<'\n';
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
ll t;
cin>>t;
while(t--)
tc();
return 0;
}
|
1699
|
D
|
Almost Triple Deletions
|
You are given an integer $n$ and an array $a_1,a_2,\ldots,a_n$.
In one operation, you can choose an index $i$ ($1 \le i \lt n$) for which $a_i \neq a_{i+1}$ and delete both $a_i$ and $a_{i+1}$ from the array. After deleting $a_i$ and $a_{i+1}$, the remaining parts of the array are concatenated.
For example, if $a=[1,4,3,3,6,2]$, then after performing an operation with $i=2$, the resulting array will be $[1,3,6,2]$.
What is the maximum possible length of an array of \textbf{equal} elements obtainable from $a$ by performing several (perhaps none) of the aforementioned operations?
|
Consider the opposite problem: What is the smallest possible length of a final array? For which arrays is the smallest possible final length equal to $0$? Considering the second hint, it is possible to completely remove some subarrays from the array. Lemma: An array $a_1,a_2,\ldots, a_n$ can be fully deleted via a sequence of operations if and only if it satisfies both of the following constraints: $n$ is even $n$ is even The maximum frequency of any element in the array is at most $\frac n2$. The maximum frequency of any element in the array is at most $\frac n2$. If $n$ is odd, then any final array will also have an odd length, which can't be $0$. An optimal strategy is to always delete one of the most frequent elements and any one of its neighbours. If the most frequent element occurs $k \gt \frac n2$ times, then the final array will have at least $n-2 \cdot (n-k)=2\cdot k - n \gt 0$ elements. Otherwise, this strategy ensures the full deletion of the array, since, after performing an operation, it is impossible for an element to occur more than $\frac {n-2}{2}$ times in the array. Since the maximum frequency of a value for every subarray $[a_l,a_{l+1},\ldots,a_r]$ can be computed in $O(n^2)$, it is possible to precompute all subarrays which can be deleted via a sequence of operations. Let $dp[i]$ be the maximum length of a final array consisting of $a_i$ and some subsequence from the first $i-1$ elements. Initially, $dp[i]$ is set to $1$ if the prefix $[a_1,a_2,\ldots, a_{i-1}]$ can be fully deleted. Otherwise, $dp[i]=0$. For every pair of indices $i$ and $j$ ($1 \le j \lt i \le n, a_i=a_j$), if we can fully delete the subarray $[a_{j+1},a_{j+2},\ldots a_{i-1}]$, then we can append $a_i$ to any final array ending in $a_j$. Naturally, $dp[i]$ will be strictly greater than $dp[j]$. This gives us the following recurrence: $dp[i]=\max_{j=1}^{i-1}(dp[j]>0 \text{ and } a_i=a_j \text{ and } [a_{j+1},a_{j+2},\ldots,a_{i-1}] \text{ is deletable}) \cdot (dp[j]+1)$ If we define a final array as a subsequence of equal elements from the array $a$, to which $a_{n+1}$ is forcefully appended, then the final answer can be written as $dp[n+1]-1$. Note that, when computing $dp[n+1]$, $a_j$ should not be compared to $a_{n+1}$. Total time complexity per testcase: $O(n^2)$.
|
[
"data structures",
"dp",
"greedy"
] | 2,300
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll NMAX=5e3+5;
ll dp[NMAX],v[NMAX],fr[NMAX];
void testcase(){
ll n,ans=0;
cin>>n;
for(ll i=1;i<=n;i++){
cin>>v[i];
dp[i]=0;
}
for(ll i=0;i<=n;i++){
if(i && dp[i]==0) continue;
ll frmax=0;
for(int j=1;j<=n;j++) fr[j]=0;
for(int j=i+1;j<=n;j++){
if((j-i)%2 && frmax<=(j-i)/2 && (i==0 || v[i]==v[j]))
dp[j]=max(dp[j],dp[i]+1);
frmax=max(frmax,++fr[v[j]]);
}
}
ll frmax=0;
for(int j=1;j<=n;j++) fr[j]=0;
for(int i=n;i>=0;i--){
if((n-i)%2==0 && frmax<=(n-i)/2) ans=max(ans,dp[i]);
frmax=max(frmax,++fr[v[i]]);
}
cout<<ans<<'\n';
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
int t;
cin>>t;
while(t--)
testcase();
return 0;
}
|
1699
|
E
|
Three Days Grace
|
Ibti was thinking about a good title for this problem that would fit the round theme (numerus ternarium). He immediately thought about the third derivative, but that was pretty lame so he decided to include the best band in the world — Three Days Grace.
You are given a multiset $A$ with initial size $n$, whose elements are integers between $1$ and $m$. In one operation, do the following:
- select a value $x$ from the multiset $A$, then
- select two integers $p$ and $q$ such that $p, q > 1$ and $p \cdot q = x$. Insert $p$ and $q$ to $A$, delete $x$ from $A$.
Note that the size of the multiset $A$ increases by $1$ after each operation.
We define the balance of the multiset $A$ as $\max(a_i) - \min(a_i)$. Find the minimum possible balance after performing any number (possible zero) of operations.
|
We can see that in the final multiset, each number $A_i$ from the initial multiset will be assigned to a subset of values $x_1, x_2,....,x_k$ such that their product is $A_i$. Every such multiset can be created. Also let $vmax$ be the maximum value in the initial multiset. Consider iterating through the minimum value. To get the best maximum value that has this minimum we fixed, one can use dynamic programming $dp[i][j] =$the best possible maximum if we had number $i$ and the minimum value in the product is $j$, $j$ is a divisor of $i$. This dp can be calculated in $O(vmax \cdot log^2(vmax))$ for all values. We can also process all updates when incrementing the minimum and keeping the result with a total effort of $O(vmax \cdot log^2(vmax))$. Thus we have a total time complexity of $O(vmax \cdot log^2(vmax))$. However, this ( we hope ) won't pass. Here is a way more elegant solution ( thanks to ntherner ): To get things straight, we observe that when we decompose a number, we just actually write it as a product of numbers. We still consider fixing the minimum value used in our multiset, call it $L$. We will further consider that we iterate $L$ from the greatest possible value (i.e. $vmax$) to $1$, and as such, we try at each iteration to calculate the minimum possible value which will appear in any decomposition as the maximum value in said decomposition. We shall now retain for each element the minimal maximum value in a decomposition where the minimum of that decomposition is $L$, let's say for element $i$, this value will be stored in $dp[i]$. Naturally, after calculating this value for every number, we now try to tweak the calculated values as to match the fact that, after this iteration concluded, we will decrease $L$. For further simplicity, we denote $L' = L - 1$. So, we changed the minimum value allowed. What changes now? Well, it is easy to see that any element that is not divisible by $L'$ won't be affected by this modification, as much as it is impossible to include $L'$ in any decomposition of said number. So it remains to modify the multiples of $L'$. Let's take a such number, $M$. How can we modify $dp[M]$? Well, we can include $L'$ in the decomposition as many times as we want, and then when we decide to stop including it, we remain with a number which needs to be further decomposed. The attributed maximum of this value should already be calculated, so we can consider it as a new candidate for the update of $dp[M]$. This idea could be implemented simpler by going through multiples of $L'$, and for an element, updating $dp[i]$ with $dp[i / L']$ (by taking the minimum of either) We now need for each iteration to keep track of the attributed maximums of each element that actually appears in our initial list. This can be done by keeping a frequency of all these elements, and after all updates, taking the (already known) maximum of the previous iteration and decreasing it until we find another element that actually appears in our set (this can be verified by simply checking the frequency). This is correct, as much as all the values gradually decrease as $L$ decreases, so their maximum would have to decrease as well. Final time complexity: $O(vmax * log(vmax))$
|
[
"data structures",
"dp",
"greedy",
"math",
"number theory",
"two pointers"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int nmax = 5e6 + 5;
int appear[nmax];
int mxval[nmax];
int toggle[nmax];
int main()
{
cin.tie(nullptr)->sync_with_stdio(false);
int t;
cin >> t;
while (t--)
{
int n, m, mn = nmax, mx = 0;
cin >> n >> m;
for (int i = 0; i <= m; ++i)
{
appear[i] = toggle[i] = mxval[i] = 0;
}
for (int i = 0, x; i < n; i++)
{
cin >> x;
appear[x] = 1;
toggle[x] = 1;
mn = min(mn, x);
mx = max(mx, x);
}
for (int i = 0; i <= mx; i++)
{
mxval[i] = i;
}
int ptr = mx, smax = mx - mn;
for (int i = mx; i >= 1; i--)
{
for (ll j = (ll)i * i; j <= mx; j += i)
{
if (appear[j])
toggle[mxval[j]]--;
mxval[j] = min(mxval[j], mxval[j / i]);
if (appear[j])
toggle[mxval[j]]++;
}
while (toggle[ptr] == 0)
ptr--;
if (i <= mn)
smax = min(smax, ptr - i);
}
cout << smax << '\n';
}
}
|
1700
|
A
|
Optimal Path
|
You are given a table $a$ of size $n \times m$. We will consider the table rows numbered from top to bottom from $1$ to $n$, and the columns numbered from left to right from $1$ to $m$. We will denote a cell that is in the $i$-th row and in the $j$-th column as $(i, j)$. In the cell $(i, j)$ there is written a number $(i - 1) \cdot m + j$, that is $a_{ij} = (i - 1) \cdot m + j$.
A turtle initially stands in the cell $(1, 1)$ and it wants to come to the cell $(n, m)$. From the cell $(i, j)$ it can in one step go to one of the cells $(i + 1, j)$ or $(i, j + 1)$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.
For example, with $n = 2$ and $m = 3$ the table will look as shown above. The turtle can take the following path: $(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$. The cost of such way is equal to $a_{11} + a_{12} + a_{13} + a_{23} = 12$. On the other hand, the paths $(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$ and $(1, 1) \rightarrow (1, 3)$ are incorrect, because in the first path the turtle can't make a step $(2, 2) \rightarrow (2, 1)$, and in the second path it can't make a step $(1, 1) \rightarrow (1, 3)$.
You are asked to tell the turtle a minimal possible cost of a path from the cell $(1, 1)$ to the cell $(n, m)$. Please note that the cells $(1, 1)$ and $(n, m)$ are a part of the way.
|
Let's notice that the optimal path looks like the following: $(1, 1) \rightarrow (1, 2) \rightarrow \ldots \rightarrow (1, m) \rightarrow (2, m) \rightarrow \ldots \rightarrow (n, m)$. The proof is relatively easy - all paths from $(1, 1)$ to $(n, m)$ consist of $n + m - 1$ cells and in the optimal path we have minimized all numbers in the path. The cost of such path is equal to $1 + 2 + \ldots + m + 2 \cdot m + \ldots + n \cdot m = \sum\limits_{i=1}^{m - 1} i + m \cdot \sum\limits_{i=1}^n i$. This sum can be found in $O(n + m)$ by just summarizing all numbers, or it can be found in $O(1)$ if you remember that $\sum\limits_{i=1}^n = \frac{n \cdot (n + 1)}{2}$.
|
[
"constructive algorithms",
"greedy",
"math"
] | 800
| null |
1700
|
B
|
Palindromic Numbers
|
During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome.
Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $121, 66, 98989$ are palindromes, and $103, 239, 1241$ are not palindromes.
Alina understands that a valid number always exist. Help her find one!
|
Let X be the number in input. Consider two cases: first digit of X is 9 and not 9. If the first digit of input number is not 9, we can simply output 9999...999 ($n$ digits) - X. If the first digit is 9, we can output 111...1111 ($n + 1$ digits) - X. It is easy to show that this number will be exactly $n$-digit. To simplify implementation, we can first find 9999...999 - X by subtracting all digits of X from 9, and than if this number is not $n$-digit, add 111...1111 - 9999...999 = 11111...1112 to it. Overall complexity will be $\mathcal{O}(n)$.
|
[
"constructive algorithms",
"implementation",
"math"
] | 1,100
| null |
1700
|
C
|
Helping the Nature
|
Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.
There are $n$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $a_1, a_2, \dots, a_n$. Leon has learned three abilities which will help him to dry and water the soil.
- Choose a position $i$ and decrease the level of moisture of the trees $1, 2, \dots, i$ by $1$.
- Choose a position $i$ and decrease the level of moisture of the trees $i, i + 1, \dots, n$ by $1$.
- Increase the level of moisture of all trees by $1$.
Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $0$.
|
Consider the difference array $d_i = a_{i + 1} - a_{i}$. Note that for $d_i > 0$ it is necessary to make $d_i$ subtractions on the suffix. For $d_i < 0$, you need to make $-d_i$ subtractions on the prefix. Let's add them to the answer. Let's calculate the final array using prefix and suffix sums for $O(n)$. Note that it will consist of the same numbers. Add $|x|$ to the answer, where $x$ is the resulting number.
|
[
"constructive algorithms",
"data structures",
"greedy"
] | 1,700
| null |
1700
|
D
|
River Locks
|
Recently in Divanovo, a huge river locks system was built. There are now $n$ locks, the $i$-th of them has the volume of $v_i$ liters, so that it can contain any amount of water between $0$ and $v_i$ liters. Each lock has a pipe attached to it. When the pipe is open, $1$ liter of water enters the lock every second.
The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $i$ to the lock $i + 1$. If the lock $i + 1$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river.
\begin{center}
{\small The picture illustrates $5$ locks with two open pipes at locks $1$ and $3$. Because locks $1$, $3$, and $4$ are already filled, effectively the water goes to locks $2$ and $5$.}
\end{center}
Note that the volume of the $i$-th lock may be greater than the volume of the $i + 1$-th lock.
To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $q$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $j$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $t_j$ seconds.
Please help the mayor to solve this tricky problem and answer his queries.
|
To begin with, we note that it makes sense to open only some pipe prefix, because we need to fill all the locks, and more left pipes affect the total volume of the baths, which is obviously beneficial. Let's enumerate how many pipes we will open, namely which prefix of pipes we will open and calculate $dp_i$ - how long it will take to fill the first $i$ locks if the first $i$ pipes are open. Let's introduce an auxiliary array $pref_i$ - the sum of the capacities of the gateways on the prefix $i$. Then $dp_i = max(dp_{i - 1},\ \lceil pref_i / i \rceil)$. Let's see why this is so. We need all gateways on prefix $i - 1$ to be filled, and also that the $i$-th gateway be filled. Note that if the $i$-th gateway does not have time to fill up in the time $dp_{i - 1}$, then it will fill up in the time $\lceil pref_i / i \rceil$ (filling will occur at the time $pref_i / i$, but since in the condition we are asked about integer times, we can round up and not use real arithmetic), it turns out when the required amount of water is poured into all the locks in total from all pipes. Now knowing $dp_i$ for all $i$ open we can similarly calculate when all n gateways are full. For $i$ this will be $max(dp_i,\ \lceil pref_n / i \rceil)$. It is also obvious that when an additional pipe is opened, the time will not increase, therefore we can do a bin search by time and find out the answer for the desired request. If the request $t$ is less than the minimum filling time for the locks (when all pipes are open), then you need to print $-1$. Total running time O($n + q log(n)$).
|
[
"binary search",
"dp",
"greedy",
"math"
] | 1,900
| null |
1700
|
E
|
Serega the Pirate
|
Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.
A puzzle is a table of $n$ rows and $m$ columns, whose cells contain each number from $1$ to $n \cdot m$ exactly once.
To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $i$, denote the position of the first occurrence of this cell in the sequence as $t_i$. The sequence solves the puzzle, if $t_1 < t_2 < \dots < t_{nm}$. In other words, the cell with number $x$ should be first visited before the cell with number $x + 1$ for each $x$.
Let's call a puzzle solvable, if there exists at least one suitable sequence.
In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $0$, $1$, or at least $2$. In the case, where $1$ move is required, please also find the number of suitable cell pairs to swap.
|
We need to find a simple criteria of a solvable puzzle. It can be shown that for every cell, except cell with value $1$, it should have a neighbour with a smaller value. Indeed, if the puzzle is solvable, a cell going before the first occurence of our cell always has the smaller value. Conversely, if each cell has a smaller neighbor, one can list cells one at a time, and there will always be a path to the next cell along already visited cells with lower numbers. Let's call a cell bad, if it's value is not $1$ and it doesn't have a neighbour with a smaller value. Consider any bad cell. Let's notice, that the pair that we swap should contain either the bad cell itself, or its neighbour, otherwise that bad cell will stay bad. That way we have $5nm$ pairs of candidates, for each of which we'll run a check if the resulting puzzle is solvable. Now we'll learn how to quickly understand, if the puzzle became solvable after a swap. For this we'll keep the amount of bad cells. After the swap, the state can be changed only for these cells and their neighbours. Let's recalc the amount of bad cells and check if it's zero. The resulting complexity is $O(nm)$
|
[
"brute force",
"constructive algorithms"
] | 2,600
| null |
1700
|
F
|
Puzzle
|
Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $2$ rows and $n$ columns, every element of which is either $0$ or $1$. In one move you can swap two values in neighboring cells.
More formally, let's number rows $1$ to $2$ from top to bottom, and columns $1$ to $n$ from left to right. Also, let's denote a cell in row $x$ and column $y$ as $(x, y)$. We consider cells $(x_1, y_1)$ and $(x_2, y_2)$ neighboring if $|x_1 - x_2| + |y_1 - y_2| = 1$.
Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.
|
We are asked to find a minimum cost perfect matching between $1$'s in the matrices, where the cost between $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$. Notice that the answer exists only if the number of $1$'s is equal in both matrices. Consider that this is the case. Notice that every $1$ either stays in its original row or changes it in a single operation. For simplicity let's assume that all operations of that kind are performed in the beginning. Let's denote $\Delta_{i,j}$ as the difference between the $j$-th prefix sum in $i$-th row of the matrices. If the final row for each $1$ is fixed, then the answer is equal to $S + \sum_{i=1}^n (|\Delta_{1,i}| + |\Delta_{2,i}|)$, where $S$ in the number of $1$'s that changed its row. Now let's look at what happens when we change the row of a $1$. For simplicity let's assume that it was in a cell $(1, j)$. Then after the swap we have to increment $S$ by $1$, decrement all $\Delta_{1,j}, \dots \Delta_{1,n}$ by $1$, and increment all $\Delta_{2,j}, \dots \Delta_{2,n}$ by $1$. Now let's solve the following problem: we are given $\Delta_{1,i}$ and $\Delta_{2,i}$ and in one operation we can increment some suffix by $1$ and decrement the same suffix in the other array by $1$. The goal is to minimize $S + \sum_{i=1}^n (|\Delta_{1,i}| + |\Delta_{2,i}|)$. Notice that the following greedy algorithm works: iterate through columns from left to right and while $\Delta_{1,i}$ and $\Delta_{2,i}$ have different signs, decrement the suffix of one that's greater and increment suffix of one that's lower. Now let's prove that this algorithm minimizes the target sum. For this consider some optimal sequence of operations. It doesn't matter in which order operations are performed, so let's assume they are performed from left to right, and are accumulated in a single element for the same suffix. If the sequences differ, denote $i$ as the first such position. Note that before that all $\Delta_{1,i}$ and $\Delta_{2,i}$ are the same in both our answer and the optimal one. Suppose that in the optimal answer we incremented $i$-th suffix of $\Delta_1$ by $k$ and decremented $i$-th suffix of $\Delta_2$ by $k$. Then the target sum will increase by $|k| + |\Delta_{1,i} + k| + |\Delta_{1,i} - k|$. Consider the following cases: $\Delta_{1,i} \ge 0$ and $\Delta_{2,i} \ge 0$ or $\Delta_{1,i} \le 0$ and $\Delta_{2,i} \le 0$. By triangle inequality $|\Delta_{1,i} + k| + |\Delta_{2,i} - k| \ge |\Delta_{1,i} + \Delta_{2,i}| = |\Delta_{1,i}| + |\Delta_{2,i}|$, which means that those $k$ operations could be performed on the $i+1$-st suffix and that wouldn't increase the answer. $\Delta_{1,i} < 0$ and $\Delta_{2,i} > 0$. Here if $k < 0$, $|\Delta_{1,i} + k| + |\Delta_{2,i} - k| = 2|k| + |\Delta_{1,i}| + |\Delta_{2,i}|$, which means that those $k$ operations could be performed on the $i+1$-st suffix and that wouldn't increase the answer. Now if $k \ge 0$. We can assume that $k \le \min(-\Delta_{1,i}, \Delta_{2,i})$, otherwise we will perform an operation on values with the same sign, which we already shown can be done later on. Then $|k| + |\Delta_{1,i} + k| + |\Delta_{2,i} - k| = k + (-k - \Delta_{1,i}) + (\Delta_{2,i} - k) = -k - \Delta_{1,i} + \Delta_{2,i}$. Greedy algorithm suggests doing exactly $t = \min(-\Delta_{1,i}, \Delta_{2,i})$ operations. Note that if we perform $t$ operations on suffix $i$ and $t-k$ operations on suffix $i+1$, we will add $(-t - \Delta_{1,i} + \Delta_{2,i}) + (t - k) = -k - \Delta_{1,i} + \Delta_{2,i}$ to the answer and get the same state as the optimal answer. This means that we can do $t$ operations and not increase the answer. $\Delta_{1,i} > 0$ and $\Delta_{2,i} < 0$. This case can be analyzed in the same way. Let's come back to the original problem. Described greedy algorithm finds a lower bound on the answer. Let's show that it is always possible to achieve it when the operations are allowed only for moving $1$'s between rows and the number of $1$s in each row at the end should be the same. For this note that we can "perform" operations on $1$'s from the second matrix, if we reverse their order and append to the end of the sequence for the first matrix. Now note that if on some prefix $i$ $\Delta_{1,i}$ and $\Delta_{2,i}$ have the same sign, but on prefix $i+1$ the signs differ, there has to be at least a single $1$ in column $i+1$, and we can perform the operation suggested by the greedy algorithm. Finally, if the answer exists it is true that $\Delta_{1,n} + \Delta_{2,n} = 0$, and if $\Delta_{1,n}$ and $\Delta_{2,n}$ have the same sign at the end this means that they are both $0$, which means that the constructed answer is correct. This solution works in $O(n)$ time.
|
[
"constructive algorithms",
"dp",
"greedy"
] | 2,600
| null |
1701
|
A
|
Grass Field
|
There is a field of size $2 \times 2$. Each cell of this field can either contain grass or be empty. The value $a_{i, j}$ is $1$ if the cell $(i, j)$ contains grass, or $0$ otherwise.
In one move, you can choose \textbf{one row} and \textbf{one column} and cut all the grass in this row and this column. In other words, you choose the row $x$ and the column $y$, then you cut the grass in all cells $a_{x, i}$ and all cells $a_{i, y}$ for all $i$ from $1$ to $2$. After you cut the grass from a cell, it becomes empty (i. e. its value is replaced by $0$).
Your task is to find the minimum number of moves required to cut the grass in all non-empty cells of the field (i. e. make all $a_{i, j}$ zeros).
You have to answer $t$ independent test cases.
|
If there is no grass on the field, the answer is $0$. If the whole field is filled with grass, the answer is $2$, because there always will be one cell that we can't clear with one move. Otherwise, the answer is $1$. This is because if the cell $(i, j)$ is empty, we can just choose other row than $i$ and other column than $j$ and clear three other cells in one move.
|
[
"implementation"
] | 800
|
for _ in range(int(input())):
a = [list(map(int, input().split())) for i in range(2)]
cnt = sum([sum(a[i]) for i in range(2)])
if cnt == 0:
print(0)
elif cnt == 4:
print(2)
else:
print(1)
|
1701
|
B
|
Permutation
|
Recall that a permutation of length $n$ is an array where each element from $1$ to $n$ occurs exactly once.
For a fixed positive integer $d$, let's define the cost of the permutation $p$ of length $n$ as the number of indices $i$ $(1 \le i < n)$ such that $p_i \cdot d = p_{i + 1}$.
For example, if $d = 3$ and $p = [5, 2, 6, 7, 1, 3, 4]$, then the cost of such a permutation is $2$, because $p_2 \cdot 3 = p_3$ and $p_5 \cdot 3 = p_6$.
Your task is the following one: for a given value $n$, find the permutation of length $n$ and the value $d$ with maximum possible cost (over all ways to choose the permutation and $d$). If there are multiple answers, then print any of them.
|
Let's notice that for a fixed value of $d$, the answer (the cost of permutation) does not exceed $\frac{n}{d}$, because only numbers from $1$ to $\frac{n}{d}$ can have a pair. It turns out that it is always possible to construct a permutation with the cost of exactly $\frac{n}{d}$. It is enough to consider the number "chains" of the form: $x, x \cdot d, x \cdot d^2, \dots, x \cdot d^k$, where $x \neq 0 \pmod d$. It is not difficult to understand that each number is included in exactly one such chain. Therefore, if we append the chains one after another, then in such a permutation the answer will be equal to $n - \mathrm{the\_number\_of\_ chains}$ (because all numbers will have a pair except the last element in the chain). The number of chains is equal to $n - \frac{n}{d}$, which means the cost of the permutation is equal to $n - (n - \frac{n}{d}) = \frac{n}{d}$. By choosing $d = 2$ the permutation will have the maximum possible cost.
|
[
"greedy"
] | 800
|
#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;
cout << 2 << '\n';
for (int i = 1; i <= n; ++i) if (i % 2 != 0)
for (int j = i; j <= n; j *= 2)
cout << j << ' ';
cout << '\n';
}
}
|
1701
|
C
|
Schedule Management
|
There are $n$ workers and $m$ tasks. The workers are numbered from $1$ to $n$. Each task $i$ has a value $a_i$ — the index of worker who is proficient in this task.
Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in $1$ hour. Otherwise, it takes them $2$ hours.
The workers work in parallel, independently of each other. Each worker can only work on one task at once.
Assign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time $0$. What's the minimum time all tasks can be completed by?
|
The statement should instantly scream binary search at you. Clearly, if you can assign the workers in such a way that the tasks are completed by time $t$, you can complete them all by $t+1$ or more as well. How to check if the tasks can be completed by some time $t$? What that means is that all workers have $t$ hours to work on some tasks. If all tasks took $2$ hours to complete, then each of them could complete $\lfloor \frac t 2 \rfloor$ of them. Thus, together they would be able to complete $\lfloor \frac t 2 \rfloor \cdot n$ tasks. How to incorporate the $1$-hour tasks into that? Well, we can redistribute the tasks in such a way that each worker first completes the tasks they are proficient in, then some other tasks if they have more time. So the general idea is the following. Let each worker $i$ complete $min(t, \mathit{cnt}_i)$ $1$-hour tasks, where $\mathit{cnt}_i$ is the number of tasks the $i$-th worker is proficient in. Then remember how many $2$-hour tasks they can complete, which is $\lfloor \frac{t - min(t, \mathit{cnt}_i)}{2} \rfloor$. Finally, remember how many tasks that they are proficient in they didn't have time to complete, which is $\mathit{cnt}_i - min(t, \mathit{cnt}_i)$. If the sum of the number of incomplete tasks doesn't exceed the sum of the number of tasks they have time to complete, then everything can be completed in time $t$. Worst case, it can take up to $2m$ hours to complete everything - if you assign all tasks to a single worker, and they are not proficient in any of them. Overall complexity: $O(n \log m)$ per testcase.
|
[
"binary search",
"greedy",
"implementation",
"two pointers"
] | 1,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, m;
scanf("%d%d", &n, &m);
vector<int> a(m);
forn(i, m){
scanf("%d", &a[i]);
--a[i];
}
vector<int> cnt(n);
forn(i, m) ++cnt[a[i]];
auto check = [&](int t){
long long fr = 0, need = 0;
forn(i, n){
if (t >= cnt[i])
fr += (t - cnt[i]) / 2;
else
need += cnt[i] - t;
}
return need <= fr;
};
int l = 0, r = 2 * m;
int res = -1;
while (l <= r){
int m = (l + r) / 2;
if (check(m)){
res = m;
r = m - 1;
}
else{
l = m + 1;
}
}
printf("%d\n", res);
}
return 0;
}
|
1701
|
D
|
Permutation Restoration
|
Monocarp had a permutation $a$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).
Then Monocarp calculated an array of integers $b$ of size $n$, where $b_i = \left\lfloor \frac{i}{a_i} \right\rfloor$. For example, if the permutation $a$ is $[2, 1, 4, 3]$, then the array $b$ is equal to $\left[ \left\lfloor \frac{1}{2} \right\rfloor, \left\lfloor \frac{2}{1} \right\rfloor, \left\lfloor \frac{3}{4} \right\rfloor, \left\lfloor \frac{4}{3} \right\rfloor \right] = [0, 2, 0, 1]$.
Unfortunately, the Monocarp has lost his permutation, so he wants to restore it. Your task is to find a permutation $a$ that corresponds to the given array $b$. If there are multiple possible permutations, then print any of them. The tests are constructed in such a way that least one suitable permutation exists.
|
We have $b_i = \left\lfloor \frac{i}{a_i} \right\rfloor$ for each $i$, we can rewrite this as follows: $a_i \cdot b_i \le i < a_i \cdot (b_i+1)$, or $\frac{i}{b_i + 1} < a_i \le \frac{i}{b_i}$. From here we can see that for each $i$ there is a segment of values that can be assigned to $a_i$. So we have to match each number from $1$ to $n$ with one of these segments. To solve this problem, we can iterate from $1$ to $n$. Let the current number be $x$, then it can be paired with a segment $i$ without a pair such that $\frac{i}{b_i + 1} < x \le \frac{i}{b_i}$ and the right bound is minimum among all such segments (because it will be the first to end among these segments). To do this, it is enough to maintain a set with open segments that have not yet been assigned a pair and choose from it a segment with the minimum right bound. Before running this method, you can sort the segments by their left border so they can be easily added to this set when we go from $x$ to $x+1$ (we will need to insert all segments that begin with $x+1$, that's why it's convenient to have them sorted by their left border beforehand).
|
[
"binary search",
"data structures",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,900
|
#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), b(n);
for (int& x : b) cin >> x;
vector<pair<int, int>> ev(n);
for (int i = 0; i < n; ++i)
ev[i] = {(i + 1) / (b[i] + 1) + 1, i};
sort(ev.begin(), ev.end());
set<pair<int, int>> s;
int j = 0;
for (int i = 1; i <= n; ++i) {
while (j < n && ev[j].first == i) {
int id = ev[j++].second;
s.insert({b[id] ? (id + 1) / b[id] : n, id});
}
a[s.begin()->second] = i;
s.erase(s.begin());
}
for (int& x : a) cout << x << ' ';
cout << '\n';
}
}
|
1701
|
E
|
Text Editor
|
You wanted to write a text $t$ consisting of $m$ lowercase Latin letters. But instead, you have written a text $s$ consisting of $n$ lowercase Latin letters, and now you want to fix it by obtaining the text $t$ from the text $s$.
Initially, the cursor of your text editor is at the end of the text $s$ (after its last character). In one move, you can do one of the following actions:
- press the "left" button, so the cursor is moved to the left by one position (or does nothing if it is pointing at the beginning of the text, i. e. before its first character);
- press the "right" button, so the cursor is moved to the right by one position (or does nothing if it is pointing at the end of the text, i. e. after its last character);
- press the "home" button, so the cursor is moved to the beginning of the text (before the first character of the text);
- press the "end" button, so the cursor is moved to the end of the text (after the last character of the text);
- press the "backspace" button, so the character before the cursor is removed from the text (if there is no such character, nothing happens).
Your task is to calculate the minimum number of moves required to obtain the text $t$ from the text $s$ using the given set of actions, or determine it is impossible to obtain the text $t$ from the text $s$.
You have to answer $T$ independent test cases.
|
Of course, there is no need to press "home" more than once (and no need to press "end" at all), because suppose we did something on suffix, then pressed "home", did something on prefix and then pressed "end" and continue doing something on suffix. Then we can merge these two sequences of moves on suffix and press "home" after we did anything we wanted on suffix, and the answer will not get worse. Now, let's iterate over the position $pos$ at which we will press "home" (in range from $0$ to $n$). In other words, we iterate over the position till which we press only "left" and "backspace" to fix the suffix. So now we have the string $s[pos; n)$ and we want to get some suffix of $t$ from this string, but we actually don't know which suffix of $t$ we want. So let's iterate over the length of this suffix $suf$ in a range from $0$ to $m$. Now we have the string $s[pos; n)$ and the string $t[m - suf; m)$ and we have to check if we can obtain this suffix of $t$ from this suffix of $s$. This part can be precalculated in $O(n)$ greedily (we just can store for each suffix of $t$ the rightmost position in $s$ in which this suffix is obtainable). If we can obtain the current suffix, then we obviously can say the number of moves to do that - it is $n - pos$ and actually do not depend on the suffix length (because if we meet the character we need, we just press "left" and move to the next character, otherwise we press "backspace" and move to the next character deleting the one we don't need). After that, we press "home" and now we have to check if we can obtain $t[0; m - suf)$ from $s[0; pos)$. This part can also be precalculated greedily in $O(n)$ like the part with rightmost positions for suffixes. But the minimum number of moves required to obtain the prefix is tricky. Actually, if we consider these prefixes from right to left, we want to match as many characters from the beginning as possible. In other words, if we reverse $s[0; pos)$ and $t[0; m - suf)$, we want to find their longest common prefix, and this will be the number of characters we don't want to touch at all (and if it is the longest common prefix, it means that the next character is bad, and we want to remove it anyway, so the length of LCP of these two reversed prefixes is the only thing affecting the number of moves on the prefix). This part can be precalculated in $O(n^2)$ with simple dynamic programming (using $O(n^2)$ memory) or with z-function in $O(n^2)$ time and $O(n)$ memory - we just need to build a z-function on a string $s[0; pos)^{-1} + \# + t^{-1}$, where $+$ is the concatenation of strings and $-1$ is the reverse operation. The required value of the z-function for the fixed values $pos$ and $suf$ will be in the position $pos + 1 + m - suf$. And the answer for the prefix will be $pos - suf$ (this is the number of extra characters on the prefix we have to delete) plus $pos - z_{pos + 1 + m - suf}$ plus $1$ because we have to press "home". But there is a corner case. If the prefix is empty, then we don't need to do all of this and the answer for prefix will be $0$. Complexity: $O(n^2)$ time and $O(n)$ memory.
|
[
"brute force",
"dp",
"greedy",
"strings"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
vector<int> zf(const string &s) {
int n = s.size();
vector<int> z(n);
int l = 0, r = 0;
for (int i = 1; i < n; ++i) {
if (i <= r) {
z[i] = min(r - i + 1, z[i - l]);
}
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
++z[i];
}
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int T;
cin >> T;
while (T--) {
int n, m;
string s, t;
cin >> n >> m >> s >> t;
int ans = 1e9;
bool bad = false;
vector<int> lpos(m), rpos(m);
for (int i = 0; i < m; ++i) {
if (i > 0) {
lpos[i] = lpos[i - 1] + 1;
} else {
lpos[i] = 0;
}
while (lpos[i] < n && s[lpos[i]] != t[i]) {
++lpos[i];
}
if (lpos[i] >= n) {
bad = true;
break;
}
}
for (int i = m - 1; i >= 0; --i) {
if (i + 1 < m) {
rpos[i] = rpos[i + 1] - 1;
} else {
rpos[i] = n - 1;
}
while (rpos[i] >= 0 && s[rpos[i]] != t[i]) {
--rpos[i];
}
if (rpos[i] < 0) {
bad = true;
break;
}
}
if (bad) {
cout << -1 << endl;
continue;
}
for (int pos = 0; pos <= n; ++pos) {
string tmp = s.substr(0, pos);
reverse(tmp.begin(), tmp.end());
tmp += "#" + t;
reverse(tmp.begin() + pos + 1, tmp.end());
vector<int> z = zf(tmp);
for (int suf = 0; suf <= m; ++suf) {
if (pos - suf < 0) {
continue;
}
if (suf < m && rpos[suf] < pos) {
continue;
}
if (suf - 1 >= 0 && lpos[suf - 1] > pos) {
continue;
}
int rg = 0;
if (suf != 0) {
int sum = (pos - z[pos + 1 + m - suf]) + (pos - suf);
rg = (sum != 0) + sum;
} else {
rg = pos;
}
ans = min(ans, (n - pos) + rg);
}
}
cout << ans << endl;
}
return 0;
}
|
1701
|
F
|
Points
|
A triple of points $i$, $j$ and $k$ on a coordinate line is called \textbf{beautiful} if $i < j < k$ and $k - i \le d$.
You are given a set of points on a coordinate line, initially empty. You have to process queries of three types:
- add a point;
- remove a point;
- calculate the number of beautiful triples consisting of points belonging to the set.
|
We are going to calculate the answer as follows: for every point $i$, let $f(i)$ be the number of points $j$ such that $1 \le j - i \le d$ (i. e. the number of points that are to the right of $i$ and have distance at most $d$ from it). Then, the number of beautiful triples where $i$ is the leftmost point is $\dfrac{f(i)(f(i) - 1)}{2}$. We can sum these values over all points to get the answer; so, the solution should somehow maintain and update the sum of these values efficiently. Let's see what happens when we add a new point or remove an existing point. For all points to the left of it with distance no more than $d$, the value of $f(i)$ increases or decreases by $1$. So, we need some sort of data structure that allows adding/subtracting $1$ on segment and maintains the sum of $\dfrac{f(i)(f(i) - 1)}{2}$. This looks like a lazy segment tree, but updating the sum of $\dfrac{f(i)(f(i) - 1)}{2}$ can be tricky. One way to do this is to notice that $\dfrac{f(i)(f(i) - 1)}{2} = \dfrac{f(i)^2}{2} - \dfrac{f(i)}{2}$. So maybe we can maintain the sum of $f(i)^2$ and the sum of $f(i)$ on the segment? It turns out we can. The model solution does this as follows: the leaf of the segment tree corresponding to the position $i$ stores a vector with three values: $(f(i)^0, f(i)^1, f(i)^2)$. The inner nodes store the sums of these vectors in the subtree. We can find a matrix which, when multiplied by $(x^0, x^1, x^2)$, gets the vector $((x+1)^0, (x+1)^1, (x+1)^2)$, and the inverse matrix to it. Then adding $1$ to $f(i)$ on segment means multiplying all vectors on segment by that matrix, and subtracting $1$ means multiplying by the inverse matrix; and since matrix multiplication is both associative and distributive, the segment tree can handle these queries. Side note: this method with matrices is asymptotically fine, but the constant factor in it is fairly large. You can speed this up by getting rid of the matrices and instead storing the sum of $f(i)$ and the sum of $f(i)^2$ in each node, and coding the formulas that allow you to add/subtract $1$ on segment by hand, without any matrix operations. This can make a noticeable improvement in terms of actual time consumption, although it wasn't needed in this problem since the time limit was pretty generous. Okay, there's only one small issue left: right now our structure can store the sum of $f(i)$ and $f(i)^2$ over all possible points (we build it on segment $[0, 200000]$, for example), but we only need the sum over existing points. One way to handle it is to use a flag for each leaf of the segment tree, and pull the value up from the leaf only if this flag is true. We will need a function that changes the value of this flag for a single leaf, but it's not very different from a function that changes one value in a lazy segment tree. Time complexity of the solution is $O(A + q \log A)$, where $A$ is the maximum coordinate of the point, although the constant factor of the described approach is fairly large since it involves $3 \times 3$ matrix multiplications. You can improve the constant factor by getting rid of the matrices, as mentioned earlier.
|
[
"combinatorics",
"data structures",
"implementation",
"math",
"matrices"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
const int N = 200043;
const int M = 200001;
typedef array<long long, 3> vec;
typedef array<vec, 3> mat;
vec operator+(const vec& a, const vec& b)
{
vec c;
for(int i = 0; i < 3; i++) c[i] = a[i] + b[i];
return c;
}
vec operator-(const vec& a, const vec& b)
{
vec c;
for(int i = 0; i < 3; i++) c[i] = a[i] - b[i];
return c;
}
vec operator*(const mat& a, const vec& b)
{
vec c;
for(int i = 0; i < 3; i++) c[i] = 0;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
c[i] += a[i][j] * b[j];
return c;
}
mat operator*(const mat& a, const mat& b)
{
mat c;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
c[i][j] = 0;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++)
c[i][k] += a[i][j] * b[j][k];
return c;
}
mat F = {vec({1, 0, 0}), vec({1, 1, 0}), vec({1, 2, 1})};
mat B = {vec({1, 0, 0}), vec({-1, 1, 0}), vec({1, -2, 1})};
mat E = {vec({1, 0, 0}), vec({0, 1, 0}), vec({0, 0, 1})};
vec S = {1, 0, 0};
vec Z = {0, 0, 0};
vec t[4 * N];
mat f[4 * N];
bool active[4 * N];
bool has[N];
int d, q;
vec getVal(int v)
{
if(!active[v]) return Z;
return f[v] * t[v];
}
void recalc(int v)
{
t[v] = getVal(v * 2 + 1) + getVal(v * 2 + 2);
}
void build(int v, int l, int r)
{
if(l == r - 1)
{
f[v] = E;
t[v] = S;
active[v] = false;
}
else
{
int m = (l + r) / 2;
build(v * 2 + 1, l, m);
build(v * 2 + 2, m, r);
f[v] = E;
recalc(v);
active[v] = true;
}
}
void push(int v)
{
if(f[v] == E) return;
t[v] = f[v] * t[v];
f[v * 2 + 1] = f[v] * f[v * 2 + 1];
f[v * 2 + 2] = f[v] * f[v * 2 + 2];
f[v] = E;
}
void updSegment(int v, int l, int r, int L, int R, bool adv)
{
if(L >= R) return;
if(l == L && r == R)
{
if(adv) f[v] = F * f[v];
else f[v] = B * f[v];
return;
}
push(v);
int m = (l + r) / 2;
updSegment(v * 2 + 1, l, m, L, min(m, R), adv);
updSegment(v * 2 + 2, m, r, max(m, L), R, adv);
recalc(v);
}
void setState(int v, int l, int r, int pos, bool val)
{
if(l == r - 1)
{
active[v] = val;
return;
}
push(v);
int m = (l + r) / 2;
if(pos < m)
setState(v * 2 + 1, l, m, pos, val);
else
setState(v * 2 + 2, m, r, pos, val);
recalc(v);
}
void addPoint(int x)
{
int lf = max(0, x - d);
int rg = x;
if(lf < rg)
updSegment(0, 0, M, lf, rg, true);
setState(0, 0, M, x, true);
}
void delPoint(int x)
{
int lf = max(0, x - d);
int rg = x;
if(lf < rg)
updSegment(0, 0, M, lf, rg, false);
setState(0, 0, M, x, false);
}
void query(int x)
{
if(has[x])
{
has[x] = false;
delPoint(x);
}
else
{
has[x] = true;
addPoint(x);
}
vec res = getVal(0);
printf("%lld\n", (res[2] - res[1]) / 2);
}
int main()
{
scanf("%d %d", &q, &d);
build(0, 0, M);
for(int i = 0; i < q; i++)
{
int x;
scanf("%d", &x);
query(x);
}
}
|
1702
|
A
|
Round Down the Price
|
At the store, the salespeople want to make all prices round.
In this problem, a number that is a power of $10$ is called a round number. For example, the numbers $10^0 = 1$, $10^1 = 10$, $10^2 = 100$ are round numbers, but $20$, $110$ and $256$ are not round numbers.
So, if an item is worth $m$ bourles (the value of the item is not greater than $10^9$), the sellers want to change its value to the nearest round number that is not greater than $m$. They ask you: by how many bourles should you \textbf{decrease} the value of the item to make it worth exactly $10^k$ bourles, where the value of $k$ — is the maximum possible ($k$ — any non-negative integer).
For example, let the item have a value of $178$-bourles. Then the new price of the item will be $100$, and the answer will be $178-100=78$.
|
Note that the number $m$ and the nearest round number not exceeding $m$ have the same size (consist of the same number of digits in the record). Denote the size of $m$ by $len$. Then we can construct the nearest round number. It will consist of one and $len - 1$ zeros.
|
[
"constructive algorithms"
] | 800
|
#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 m; cin >> m;
string t = to_string(m);
string s = "1";
for (int i = 1; i < sz(t); i++) {
s += '0';
}
int k = stoi(s);
cout << m - k << '\n';
}
int main() {
int t;
cin >> t;
forn(tt, t) {
solve();
}
}
|
1702
|
B
|
Polycarp Writes a String from Memory
|
Polycarp has a poor memory. Each day he can remember no more than $3$ of different letters.
Polycarp wants to write a non-empty string of $s$ consisting of lowercase Latin letters, taking \textbf{minimum} number of days. In how many days will he be able to do it?
Polycarp initially has an empty string and can only add characters to the end of that string.
For example, if Polycarp wants to write the string lollipops, he will do it in $2$ days:
- on the first day Polycarp will memorize the letters l, o, i and write lolli;
- On the second day Polycarp will remember the letters p, o, s, add pops to the resulting line and get the line lollipops.
If Polycarp wants to write the string stringology, he will do it in $4$ days:
- in the first day will be written part str;
- on day two will be written part ing;
- on the third day, part of olog will be written;
- on the fourth day, part of y will be written.
For a given string $s$, print the minimum number of days it will take Polycarp to write it.
|
Let us simulate the process. We store a set $v$ consisting of letters that Polycarp memorizes on one day. Gradually dial the set $s$. If the size of $v$ exceeds $3$, we add $1$ to the day counter $ans$ and clear $v$.
|
[
"greedy"
] | 800
|
#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() {
string s; cin >> s;
set<char> v;
int ans = 0;
for (int i = 0; i < sz(s); i++) {
v.insert(s[i]);
if (sz(v) > 3) {
ans++;
v.clear();
v.insert(s[i]);
}
}
if (!v.empty()) ans++;
cout << ans << endl;
}
int main() {
int t;
cin >> t;
forn(tt, t) {
solve();
}
}
|
1702
|
C
|
Train and Queries
|
Along the railroad there are stations indexed from $1$ to $10^9$. An express train always travels along a route consisting of $n$ stations with indices $u_1, u_2, \dots, u_n$, where ($1 \le u_i \le 10^9$). The train travels along the route from left to right. It starts at station $u_1$, then stops at station $u_2$, then at $u_3$, and so on. Station $u_n$ — the terminus.
It is possible that the train will visit the same station more than once. That is, there may be duplicates among the values $u_1, u_2, \dots, u_n$.
You are given $k$ queries, each containing two different integers $a_j$ and $b_j$ ($1 \le a_j, b_j \le 10^9$). For each query, determine whether it is possible to travel by train from the station with index $a_j$ to the station with index $b_j$.
For example, let the train route consist of $6$ of stations with indices [$3, 7, 1, 5, 1, 4$] and give $3$ of the following queries:
- $a_1 = 3$, $b_1 = 5$It is possible to travel from station $3$ to station $5$ by taking a section of the route consisting of stations [$3, 7, 1, 5$]. Answer: YES.
- $a_2 = 1$, $b_2 = 7$You cannot travel from station $1$ to station $7$ because the train cannot travel in the opposite direction. Answer: NO.
- $a_3 = 3$, $b_3 = 10$It is not possible to travel from station $3$ to station $10$ because station $10$ is not part of the train's route. Answer: NO.
|
To solve the problem, we will use the dictionary. Each station will be matched with a pair of integers - the indices of its first and last entries in the route. Then we will sequentially process queries. If at least one of the stations $a_j$ or $b_j$ is missing in the dictionary - the answer is NO. Otherwise, check: If the index of the first entry of station $a_j$ in the route is strictly less than the index of the last entry of station $b_j$ in the route - the answer is YES. Otherwise, the answer is NO.
|
[
"data structures",
"greedy"
] | 1,100
|
#include<bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
void solve(){
int n, k;
cin >> n >> k;
map<int, pair<int, int>>m;
forn(i, n){
int u;
cin >> u;
if(!m.count(u)) {
m[u].first = i;
m[u].second = i;
}
else m[u].second = i;
}
forn(i, k){
int a, b;
cin >> a >> b;
if(!m.count(a) or !m.count(b) or m[a].first > m[b].second) {
cout << "NO\n"; //equals = 0 = wrong
}
else cout << "YES\n";
}
}
int main(){
int t;
cin >> t;
while(t--){
solve();
}
}
|
1702
|
D
|
Not a Cheap String
|
Let $s$ be a string of lowercase Latin letters. Its price is the sum of the indices of letters (an integer between 1 and 26) that are included in it. For example, the price of the string abca is $1+2+3+1=7$.
The string $w$ and the integer $p$ are given. Remove the minimal number of letters from $w$ so that its price becomes less than or equal to $p$ and print the resulting string. Note that the resulting string may be empty. You can delete arbitrary letters, they do not have to go in a row. If the price of a given string $w$ is less than or equal to $p$, then nothing needs to be deleted and $w$ must be output.
Note that when you delete a letter from $w$, the order of the remaining letters is preserved. For example, if you delete the letter e from the string test, you get tst.
|
The main idea is that it is always better to remove the most expensive symbol. To do this quickly, we will count all the symbols and remove them from the most expensive to the cheapest, counting how many times we have removed each. During the output, we will skip the characters the number of times that we deleted.
|
[
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
string s;
cin >> s;
int p;
cin >> p;
string w(s);
sort(w.rbegin(), w.rend());
int cost = 0;
forn(i, s.length())
cost += s[i] - 'a' + 1;
map<char,int> del;
forn(i, w.length())
if (cost > p) {
del[w[i]]++;
cost -= w[i] - 'a' + 1;
}
forn(i, s.length()) {
if (del[s[i]] > 0) {
del[s[i]]--;
continue;
}
cout << s[i];
}
cout << endl;
}
}
|
1702
|
E
|
Split Into Two Sets
|
Polycarp was recently given a set of $n$ (number $n$ — even) dominoes. Each domino contains two integers from $1$ to $n$.
Can he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets.
For example, if he has $4$ dominoes: $\{1, 4\}$, $\{1, 3\}$, $\{3, 2\}$ and $\{4, 2\}$, then Polycarp will be able to divide them into two sets in the required way. The first set can include the first and third dominoes ($\{1, 4\}$ and $\{3, 2\}$), and the second set — the second and fourth ones ($\{1, 3\}$ and $\{4, 2\}$).
|
Polycarp has $n$ dominoes, on each domino there are $2$ numbers - it turns out, there will be $2n$ numbers in total. We need to divide $2n$ numbers (each number from $1$ to $n$) into two sets so that all numbers in each set are different - each set will consist of $n$ numbers. It turns out that all numbers from $1$ to $n$ must occur exactly $2$ times, no more and no less. Let's imagine it all as a bipartite graph, where there are vertices from $1$ to $n$, and dominoes are edges. Since each number occurs exactly $2$ times, then we have a lot of cycles. In which the edges of each number must be included in different sets, in other words, the cycles must be of even length. This can be checked in $O(n)$ by a simple enumeration.
|
[
"dfs and similar",
"dsu",
"graphs"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define forn(i, n) for (int i = 0; i < int(n); i++)
map<int, vector<int>> m;
vector<bool> used;
int go(int v) {
used[v] = true;
for (auto now : m[v]) {
if (!used[now]) {
return go(now) + 1;
}
}
return 1;
}
void solve() {
int n, x, y;
cin >> n;
m.clear();
used.clear();
used.resize(n + 1, false);
bool fault = false;
forn(i, n) {
cin >> x >> y;
m[x].push_back(y);
m[y].push_back(x);
if (x == y || m[x].size() > 2 || m[y].size() > 2) fault = true;
}
if (fault) {
cout << "NO\n";
return;
}
forn(i, n) {
if (!used[i + 1]) {
if (go(i + 1) % 2) {
cout << "NO\n";
return;
}
}
}
cout << "YES\n";
}
int main() {
int tests;
cin >> tests;
forn(tt, tests) {
solve();
}
}
|
1702
|
F
|
Equate Multisets
|
Multiset —is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. Two multisets are equal when each value occurs the same number of times. For example, the multisets $\{2,2,4\}$ and $\{2,4,2\}$ are equal, but the multisets $\{1,2,2\}$ and $\{1,1,2\}$ — are not.
You are given two multisets $a$ and $b$, each consisting of $n$ integers.
In a single operation, any element of the $b$ multiset can be doubled or halved (rounded down). In other words, you have one of the following operations available for an element $x$ of the $b$ multiset:
- replace $x$ with $x \cdot 2$,
- or replace $x$ with $\lfloor \frac{x}{2} \rfloor$ (round down).
Note that you cannot change the elements of the $a$ multiset.
See if you can make the multiset $b$ become equal to the multiset $a$ in an arbitrary number of operations (maybe $0$).
For example, if $n = 4$, $a = \{4, 24, 5, 2\}$, $b = \{4, 1, 6, 11\}$, then the answer is yes. We can proceed as follows:
- Replace $1$ with $1 \cdot 2 = 2$. We get $b = \{4, 2, 6, 11\}$.
- Replace $11$ with $\lfloor \frac{11}{2} \rfloor = 5$. We get $b = \{4, 2, 6, 5\}$.
- Replace $6$ with $6 \cdot 2 = 12$. We get $b = \{4, 2, 12, 5\}$.
- Replace $12$ with $12 \cdot 2 = 24$. We get $b = \{4, 2, 24, 5\}$.
- Got equal multisets $a = \{4, 24, 5, 2\}$ and $b = \{4, 2, 24, 5\}$.
|
We divide each number from the multiset $a$ by $2$ as long as it is divisible without a remainder. Because if we can get a new number from the multiset $a$, we can also increase it to the original number by multiplication by $2$. Now notice that it does not make sense to use the first operation (multiplication by $2$), because we get an even number, and only odd numbers remain in the multiset $a$. Then we take the largest number from $b$ and if it is in $a$, we remove this number from both multisets. Otherwise, we use the second operation, if the number is greater than $1$. If it is equal to $1$, then it is impossible to equalize the multisets $a$ and $b$.
|
[
"constructive algorithms",
"data structures",
"greedy",
"math",
"number theory"
] | 1,700
|
#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
const int INF = 1e9;
void solve() {
int n; cin >> n;
multiset<int> a, b;
forn(i, n) {
int x; cin >> x;
while (x % 2 == 0) {
x /= 2;
}
a.insert(x);
}
forn(i, n) {
int x; cin >> x;
b.insert(x);
}
n = sz(a);
while (!b.empty()) {
int x = *b.rbegin();
// cout << x << endl;
if (!a.count(x)) {
if (x == 1) break;
b.erase(b.find(x));
b.insert(x / 2);
} else {
b.erase(b.find(x));
a.erase(a.find(x));
}
}
cout << (b.empty() ? "YES" : "NO") << endl;
}
int main() {
int t;
cin >> t;
forn(tt, t) {
solve();
}
}
|
1702
|
G1
|
Passable Paths (easy version)
|
\textbf{This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.}
Polycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles.
He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).
In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).
For example, for a tree below sets $\{3, 2, 5\}$, $\{1, 5, 4\}$, $\{1, 4\}$ are passable, and $\{1, 3, 5\}$, $\{1, 2, 3, 4, 5\}$ are not.
Polycarp asks you to answer $q$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is \textbf{passable}.
|
If the answer is YES, then we can choose a subset of the tree vertices forming a simple path and containing all the vertices of our set. Let's choose the minimum possible path, its ends - vertices from the set. The constraints allow us to answer the query in $\mathcal{O}(n)$, hang the tree by one of the ends and check if it is true that there is only one selected vertex that does not have any selected ones in the subtree, if there is one such vertex, then it is - the second end. To make it easier to search for one of the ends, we will hang the tree by any vertex before the queries, calculate their depths and take the deepest of the set.
|
[
"dfs and similar",
"trees"
] | 1,900
|
#include <bits/stdc++.h>
#define int long long
#define pb emplace_back
#define mp make_pair
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(143);
const int inf = 1e15;
const int M = 1e9 + 7;
const ld pi = atan2(0, -1);
const ld eps = 1e-6;
void depth(int v, int p, vector<vector<int>> &sl, vector<int> &d){
if(p >= 0) d[v] = d[p] + 1;
for(int u: sl[v]){
if(u == p) continue;
depth(u, v, sl, d);
}
}
int dfs(int v, int p, vector<vector<int>> &sl, vector<bool> &chosen){
int res = 0;
bool lower = false;
for(int u: sl[v]){
if(u == p) continue;
res += dfs(u, v, sl, chosen);
lower = lower || chosen[u];
}
chosen[v] = chosen[v] || lower;
if(chosen[v] && !lower) res = 1;
return res;
}
void solve(){
int n;
cin >> n;
vector<vector<int>> sl(n);
for(int i = 1; i < n; ++i){
int u, v;
cin >> u >> v;
sl[--u].push_back(--v);
sl[v].push_back(u);
}
vector<int> d(n);
depth(0, -1, sl, d);
int q;
cin >> q;
for(; q; --q){
int k;
cin >> k;
vector<bool> chosen(n);
int mx = 0;
for(int i = 0; i < k; ++i){
int p;
cin >> p;
--p;
if(d[p] > d[mx]) mx = p;
chosen[p] = true;
}
int leaves = dfs(mx, -1, sl, chosen);
if(leaves == 1) cout << "YES\n";
else cout << "NO\n";
}
}
bool multi = false;
signed main() {
int t = 1;
if (multi)cin >> t;
for (; t; --t) {
solve();
//cout << endl;
}
return 0;
}
|
1702
|
G2
|
Passable Paths (hard version)
|
\textbf{This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.}
Polycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles.
He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).
In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).
For example, for a tree below sets $\{3, 2, 5\}$, $\{1, 5, 4\}$, $\{1, 4\}$ are passable, and $\{1, 3, 5\}$, $\{1, 2, 3, 4, 5\}$ are not.
Polycarp asks you to answer $q$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is \textbf{passable}.
|
Recall that the path in the rooted tree - ascends from one end to the least common ancestor ($lca$) of the ends and descends to the other end (possibly by 0). Then our set is divided into two simple ways. To check this, you only need to count $lca$. We will first calculate the depths, as for solving an easy version of the problem. We will go along the vertices according to the non-growth of the depths, if $lca$ of the deepest vertex and the current one is equal to the current one, then it is the ancestor of the deepest one, we will mark it. Next, we will find the deepest unmarked vertex and do the same, if there is no such vertex, then the whole path goes down and the answer is YES. If there are unmarked vertices, then there are vertices outside of those two ascents and the answer is NO. Now we need to check that the two ascents do not intersect or intersect only at the $lca$ of ends, for this we just make sure that $lca$ is not deeper than the shallowest vertex of the set.
|
[
"data structures",
"dfs and similar",
"trees"
] | 2,000
|
#include <bits/stdc++.h>
#define int long long
#define pb emplace_back
#define mp make_pair
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(143);
const int inf = 1e15;
const int M = 1e9 + 7;
const ld pi = atan2(0, -1);
const ld eps = 1e-6;
int n, sz;
vector<vector<int>> sl, up;
vector<int> d;
void precalc(int v, int p){
d[v] = d[p] + 1;
up[v][0] = p;
for(int i = 1; i <= sz; ++i){
up[v][i] = up[up[v][i - 1]][i - 1];
}
for(int u: sl[v]){
if(u == p) continue;
precalc(u, v);
}
}
int lca(int u, int v){
if(d[u] < d[v]){
swap(u, v);
}
for(int cur = sz; cur >= 0; --cur){
if (d[u] - (1 << cur) >= d[v]) {
u = up[u][cur];
}
}
for(int cur = sz; cur >= 0; --cur){
if (up[u][cur] != up[v][cur]) {
u = up[u][cur];
v = up[v][cur];
}
}
return u == v ? u : up[u][0];
}
void solve(){
cin >> n;
sz = 0;
while ((1 << sz) < n) sz++;
d.assign(n, -1);
up.assign(n, vector<int>(sz + 1));
sl.assign(n, vector<int>(0));
for(int i = 1; i < n; ++i){
int u, v;
cin >> u >> v;
sl[--u].push_back(--v);
sl[v].push_back(u);
}
precalc(0, 0);
int q;
cin >> q;
for(; q; --q){
int k;
cin >> k;
vector<int> p(k);
for(int &e: p) {
cin >> e;
--e;
}
sort(all(p), [](int a, int b) {
return d[a] > d[b];
});
vector<bool> used(k);
for(int i = 0; i < k; ++i){
if(lca(p[0], p[i]) == p[i]) used[i] = true;
}
int f = 0;
while (f < k && used[f]) f++;
if(f == k){
cout << "YES\n";
continue;
}
bool ans = true;
for(int i = f; i < k; ++i){
if(lca(p[f], p[i]) == p[i]) used[i] = true;
}
for(bool e: used){
ans &= e;
}
ans &= d[lca(p[0], p[f])] <= d[p.back()];
if(ans) cout << "YES\n";
else cout << "NO\n";
}
}
bool multi = false;
signed main() {
int t = 1;
if (multi)cin >> t;
for (; t; --t) {
solve();
//cout << endl;
}
return 0;
}
|
1703
|
A
|
YES or YES?
|
There is a string $s$ of length $3$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.
|
You should implement what is written in the statement. Here are three ways to do it: Check that the first character is $\texttt{Y}$ or $\texttt{y}$, check that the second character is $\texttt{E}$ or $\texttt{e}$, and check the third character is $\texttt{S}$ or $\texttt{s}$. Make an array storing all acceptable strings (there are only $8$), and loop and see if any of the strings match the input. Use some built-in function like tolower() in C++ to make the string all lowercase, and check if $s$ is equal to $\texttt{yes}$.
|
[
"brute force",
"implementation",
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
string s;
cin >> s;
if (s[0] != 'y' && s[0] != 'Y') {cout << "NO\n";}
else if (s[1] != 'e' && s[1] != 'E') {cout << "NO\n";}
else if (s[2] != 's' && s[2] != 'S') {cout << "NO\n";}
else {cout << "YES\n";}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1703
|
B
|
ICPC Balloons
|
In an ICPC contest, balloons are distributed as follows:
- Whenever a team solves a problem, that team gets a balloon.
- The first team to solve a problem gets an additional balloon.
A contest has 26 problems, labelled $\textsf{A}$, $\textsf{B}$, $\textsf{C}$, ..., $\textsf{Z}$. You are given the order of solved problems in the contest, denoted as a string $s$, where the $i$-th character indicates that the problem $s_i$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.
|
Let's keep an array $a$ of booleans, $a_i$ denoting whether or not some team has solved the $i$th problem already. Now we can iterate through the string from left to right and keep a running total $\mathrm{tot}$. If $a_i$ is true (the $i$-th problem has already been solved), increase $\mathrm{tot}$ by $1$; otherwise, increase $\mathrm{tot}$ by $2$ and set $a_i$ to true. The time complexity is $\mathcal{O}(n)$. Bonus: the answer is always $n + \text{number of distinct characters in }s$. Can you see why?
|
[
"data structures",
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
string s;
cin >> s;
bool vis[26] = {};
int res = 0;
for (char c : s) {
if (!vis[c - 'A']) {res += 2; vis[c - 'A'] = true;}
else {res++;}
}
cout << res << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1703
|
C
|
Cypher
|
Luca has a cypher made up of a sequence of $n$ wheels, each with a digit $a_i$ written on it. On the $i$-th wheel, he made $b_i$ moves. Each move is one of two types:
- up move (denoted by $U$): it increases the $i$-th digit by $1$. After applying the up move on $9$, it becomes $0$.
- down move (denoted by $D$): it decreases the $i$-th digit by $1$. After applying the down move on $0$, it becomes $9$.
\begin{center}
{\small Example for $n=4$. The current sequence is 0 0 0 0.}
\end{center}
Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.
|
We will perform each move in reverse from the final sequence of the cypher. down move: it increases the $i$-th digit by $1$. After applying the up move on $9$, it becomes $0$. up move (denoted by $\texttt{D}$): it decreases the $i$-th digit by $1$. After applying the down move on $0$, it becomes $9$.
|
[
"brute force",
"implementation",
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
for(int i = 0; i < n; i++)
{
int b;
cin >> b;
if(b == 0)
{
continue;
}
string now;
cin >> now;
for(int j = 0; j < b; j++)
{
if(now[j] == 'U'){a[i]--;}
else if(now[j] == 'D'){a[i]++;}
if(a[i] < 0){a[i]+=10;}
if(a[i] > 9){a[i]-=10;}
}
}
for(int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main(){
int t;
cin>> t;
while(t--)
{
solve();
}
return 0;
}
|
1703
|
D
|
Double Strings
|
You are given $n$ strings $s_1, s_2, \dots, s_n$ of length at most $\mathbf{8}$.
For each string $s_i$, determine if there exist two strings $s_j$ and $s_k$ such that $s_i = s_j + s_k$. That is, $s_i$ is the concatenation of $s_j$ and $s_k$. Note that $j$ \textbf{can} be equal to $k$.
Recall that the concatenation of strings $s$ and $t$ is $s + t = s_1 s_2 \dots s_p t_1 t_2 \dots t_q$, where $p$ and $q$ are the lengths of strings $s$ and $t$ respectively. For example, concatenation of "code" and "forces" is "codeforces".
|
Use some data structure that allows you to answer queries of the form: "does the string $t$ appear in the array $s_1, \dots, s_n$?" For example, in C++ you can use a map<string, bool>, while in Python you can use a dictionary dict. Afterwards, for each string $s$, brute force all strings $x$ and $y$ such that $s = x + y$. There are at most $7$ such strings, because $s$ has length at most $8$. Then check if both $x$ and $y$ appear in the array using your data structure. The time complexity is $\mathcal{O}(\ell n \log n)$ per test case, where $\ell$ is the maximum length of an input string.
|
[
"brute force",
"data structures",
"strings"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
string s[n];
map<string, bool> mp;
for (int i = 0; i < n; i++) {
cin >> s[i];
mp[s[i]] = true;
}
for (int i = 0; i < n; i++) {
bool ok = false;
for (int j = 1; j < s[i].length(); j++) {
string pref = s[i].substr(0, j), suff = s[i].substr(j, s[i].length() - j);
if (mp[pref] && mp[suff]) {ok = true;}
}
cout << ok;
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1703
|
E
|
Mirror Grid
|
You are given a square grid with $n$ rows and $n$ columns. Each cell contains either $0$ or $1$.
In an operation, you can select a cell of the grid and flip it (from $0 \to 1$ or $1 \to 0$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $0^{\circ}$, $90^{\circ}$, $180^{\circ}$ and $270^{\circ}$.
The picture below shows an example of all rotations of a grid.
|
Let's rotate the grid by $0^{\circ}$, $90^{\circ}$, $180^{\circ}$, and $270^{\circ}$, and mark all cells that map to each other under these rotations. For example, for $4 \times 4$ and $5 \times 5$ grids, mirror grid must have the following patterns, the same letters denoting equal values: $\begin{matrix} a & b & c & a\\ c & d & d & b\\ b & d & d & c\\ a & c & b & a \end{matrix} \qquad \qquad \begin{matrix} a & b & c & d & a\\ d & e & f & e & b\\ c & f & g & f & c\\ b & e & f & e & d\\ a & d & c & b & a \end{matrix}$ In general, we can rotate the grid by $0^{\circ}$, $90^{\circ}$, $180^{\circ}$, and $270^{\circ}$ and see which cells need to have equal values by seeing the positions which each cell maps to. Now to solve the problem, we consider each equal value (each of the letters $a$, $b$, $c$, ... in the above figures) independently, and consider the minimum number of moves to make them all $0$ or all $1$. The answer is the total across all values. See the implementation for better understanding. The time complexity is $\mathcal{O}(n^2)$ per testcase.
|
[
"implementation"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
int a[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
char c;
cin >> c;
a[i][j] = c-'0';
}
}
int ans = 0;
for(int i = 0; i < (n+1)/2; i++)
{
for(int j = 0; j < n/2; j++)
{
int nowi = i, nowj = j;
int oldnowj = nowj;
int sum = a[nowi][nowj];
nowj = n-nowi-1;
nowi = oldnowj;
sum+=a[nowi][nowj];
oldnowj = nowj;
nowj = n-nowi-1;
nowi = oldnowj;
sum+=a[nowi][nowj];
oldnowj = nowj;
nowj = n-nowi-1;
nowi = oldnowj;
sum+=a[nowi][nowj];
ans+=min(sum, 4-sum);
}
}
cout << ans << endl;
}
int main(){
int t;
cin>> t;
while(t--)
{
solve();
}
return 0;
}
|
1703
|
F
|
Yet Another Problem About Pairs Satisfying an Inequality
|
You are given an array $a_1, a_2, \dots a_n$. Count the number of pairs of indices $1 \leq i, j \leq n$ such that $a_i < i < a_j < j$.
|
Call a pair good if it satisfies the condition. Let's split the inequality into three parts: $a_i < i$, $i < a_j$, $a_j < j$. Note that if $a_i \geq i$ for any $i$, then it can't be an element of a good pair, because it fails the first and third conditions. So we can throw out all elements of the array satisfying $a_i \geq i$. For the remaining elements, the first and third inequalities are already satisfied, so we only have to count the number of pairs $(i,j)$ with $i < a_j$. Let's iterate $j$ through the array from the left to the right, and make a list storing all $i$ that appear before $j$. Then for each $j$, count the number of $i$ less than $a_j$ by binary searching on the number of elements in the list less than $a_j$. Afterwards, add $j$ to the end of the list. Since we iterate from left to right, the list will always remain sorted (we insert the indices of elements, which are increasing from left to right), so the binary search will always work. The time complexity is $\mathcal{O}(n \log n)$.
|
[
"binary search",
"data structures",
"dp",
"greedy",
"sortings"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
int a[n + 1];
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
long long res = 0;
vector<int> v;
for (int i = 1; i <= n; i++) {
if (a[i] >= i) {continue;}
res += (long long)(lower_bound(v.begin(), v.end(), a[i]) - v.begin());
v.push_back(i);
}
cout << res << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1703
|
G
|
Good Key, Bad Key
|
There are $n$ chests. The $i$-th chest contains $a_i$ coins. You need to open all $n$ chests \textbf{in order from chest}$1$\textbf{to chest}$n$.
There are two types of keys you can use to open a chest:
- a good key, which costs $k$ coins to use;
- a bad key, which does not cost any coins, but will halve all the coins in each unopened chest, \textbf{including the chest it is about to open}. The halving operation \textbf{will round down} to the nearest integer for each chest halved. In other words using a bad key to open chest $i$ will do $a_i = \lfloor{\frac{a_i}{2}\rfloor}$, $a_{i+1} = \lfloor\frac{a_{i+1}}{2}\rfloor, \dots, a_n = \lfloor \frac{a_n}{2}\rfloor$;
- any key (both good and bad) breaks after a usage, that is, it is a one-time use.
You need to use in total $n$ keys, one for each chest. Initially, you have no coins and no keys. If you want to use a good key, then you need to buy it.
During the process, you are allowed to go into debt; for example, if you have $1$ coin, you are allowed to buy a good key worth $k=3$ coins, and your balance will become $-2$ coins.
Find the maximum number of coins you can have after opening all $n$ chests in order from chest $1$ to chest $n$.
|
We will prove it is always optimal to use good keys for a prefix then only use bad keys. Consider we have used a bad key then a good key, by doing this we obtain $\lfloor\frac{a_i}{2}\rfloor + \lfloor\frac{a_{i+1}}{2}\rfloor - k$ coins. If we switch and use a good key first, the a bad key then we obtain $a_i + \lfloor\frac{a_{i+1}}{2}\rfloor - k$, this number is clearly bigger so we will never encounter a bad key before a good key in an optimal solution, thus we will use a prefix of good keys then move on to using bad keys. For every possible prefix of good keys we will calculate the coins we get at the end. We do this by maintaining a variable with the prefix sum where we use the good keys and then calculate what we will get from the chests where we use bad keys. Notice that because we halve all the chests when we use a bad key we only need to verify the next $\log_2(10^9) \approx 30$ chests, all chests after it will go to $0$ coins. Final complexity: $\mathcal{O}(n\log a_i)$.
|
[
"bitmasks",
"brute force",
"dp",
"greedy",
"math"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n, k;
cin >> n >> k;
int a[n];
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
long long ans = 0;
long long sum = 0;
for(int i = -1; i < n; i++)
{
long long now = sum;
for(int j = i+1; j < min(n, i+32); j++)
{
int copy = a[j];
copy>>=j-i;
now+=copy;
}
ans = max(ans, now);
if(i+1 != n)
{
sum+=a[i+1]-k;
}
}
cout << ans << endl;
}
int main(){
int t;
cin >> t;
while(t--)
{
solve();
}
return 0;
}
|
1704
|
A
|
Two 0-1 Sequences
|
AquaMoon has two binary sequences $a$ and $b$, which contain only $0$ and $1$. AquaMoon can perform the following two operations any number of times ($a_1$ is the first element of $a$, $a_2$ is the second element of $a$, and so on):
- Operation 1: if $a$ contains at least two elements, change $a_2$ to $\operatorname{min}(a_1,a_2)$, and remove the first element of $a$.
- Operation 2: if $a$ contains at least two elements, change $a_2$ to $\operatorname{max}(a_1,a_2)$, and remove the first element of $a$.
Note that after a removal of the first element of $a$, the former $a_2$ becomes the first element of $a$, the former $a_3$ becomes the second element of $a$ and so on, and the length of $a$ reduces by one.
Determine if AquaMoon can make $a$ equal to $b$ by using these operations.
|
Considering that whichever the operation you use, the length of $a$ would decrease $1$. So you can only modify the first $n-m+1$ elements of $a$, otherwise the length of $a$ can't be equal to the length of $b$. That means $\{a_{n-m+2},\dots,a_n\}$ must equals to $\{b_2,\dots,b_m\}$. And about the first element of $b$: if $b_1$ is $0$, you can use Operation 1 to make $0$ and remove elements. if $b_1$ is $1$, you can use Operation 2 to make $1$ and remove elements. if $b_1$ is $1$, you can use Operation 2 to make $1$ and remove elements. So just check the first $n-m+1$ elements in $a$ to find if there is anyone that equals to $b_1$.
|
[
"constructive algorithms",
"greedy"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5;
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T;
cin >> T;
while (T--) {
int n, m;
cin >> n >> m;
string a, b;
cin >> a >> b;
if (n < m) {
cout << "NO\n";
continue;
}
bool same = true;
for (int i = 1; i < b.size(); ++i) {
if (a[i + n - m] != b[i]) {
same = false;
break;
}
}
if (!same) {
cout << "NO\n";
continue;
}
for (int i = 0; i < n - m + 1; ++i) {
if (a[i] == b[0]) {
same = false;
}
}
if (same) {
cout << "NO\n";
}
else {
cout << "YES\n";
}
}
}
|
1704
|
B
|
Luke is a Foodie
|
Luke likes to eat. There are $n$ piles of food aligned in a straight line in front of him. The $i$-th pile contains $a_i$ units of food.
Luke will walk from the $1$-st pile towards the $n$-th pile, and he wants to eat every pile of food without walking back. When Luke reaches the $i$-th pile, he can eat that pile if and only if $|v - a_i| \leq x$, where $x$ is a fixed integer, and $v$ is Luke's food affinity.
Before Luke starts to walk, he can set $v$ to any integer. Also, for each $i$ ($1 \leq i \leq n$), Luke can change his food affinity to any integer \textbf{before} he eats the $i$-th pile.
Find the minimum number of changes needed to eat every pile of food.
Note that the initial choice for $v$ is \textbf{not} considered as a change.
|
For $a_i$, if $|v-a_i| \leq x$, then $a_i-x \leq v \leq a_i+x$. Then consider using the greedy strategy. We will only change $v$ when we cannot find any possible $v$ to satisfy the current conditions. Therefore, we can determine the range of $v$. Initially, set $l=a_1-x,r=a_1+x$, then $v \in [l,r]$. For $a_i$, change $l=\max(l,a_i-x),r=\min(r,a_i+x)$. Once $l>r$, which means from the last time that we changed $v$ to the current $a_i$ we cannot find any possible $v$ to satisfy the all the conditions between the two positions, we should change $l=a_i-x,r=a_i+x$, and add $1$ to answer.
|
[
"brute force",
"greedy",
"implementation"
] | 1,000
|
#include <stdio.h>
#include <string.h>
#include <vector>
#include <set>
#include <queue>
#include <string>
#include <map>
#include <chrono>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <iostream>
#include <memory>
#include <cstdio>
#include <assert.h>
#include <iostream>
const int MAXN = 300005;
int numbers[MAXN];
int main() {
int t;
int n, x;
scanf("%d", &t);
while (t--)
{
scanf("%d %d", &n, &x);
for (int i = 1; i <= n; i++) {
scanf("%d", &numbers[i]);
}
int num_min = numbers[1];
int num_max = numbers[1];
int res = 0;
for (int i = 2; i <= n; i++) {
if (numbers[i] > num_max) {
num_max = numbers[i];
}
if (numbers[i] < num_min) {
num_min = numbers[i];
}
if (num_max - num_min > 2 * x) {
res++;
num_min = num_max = numbers[i];
}
}
printf("%d\n", res);
}
return 0;
}
|
1704
|
C
|
Virus
|
There are $n$ houses numbered from $1$ to $n$ on a circle. For each $1 \leq i \leq n - 1$, house $i$ and house $i + 1$ are neighbours; additionally, house $n$ and house $1$ are also neighbours.
Initially, $m$ of these $n$ houses are infected by a deadly virus. Each \textbf{morning}, Cirno can choose a house which is uninfected and protect the house from being infected permanently.
Every day, the following things happen in order:
- Cirno chooses an uninfected house, and protect it permanently.
- All uninfected, unprotected houses which have at least one \textbf{infected} neighbor become infected.
Cirno wants to stop the virus from spreading. Find the minimum number of houses that will be infected in the end, if she optimally choose the houses to protect.
Note that every day Cirno always chooses a house to protect \textbf{before} the virus spreads. Also, a protected house will not be infected forever.
|
First, considering it is easier to calculate the number of houses which are not infected, so we focus on it firstly. Conspicuously, if between $a_i$ and $a_{i+1}$ there are $x$ houses (Array $a$ has been sorted.), and the infection will last $y$ days, there will remain $x-2 \times y$ houses on the end. Simultaneously, every day we can protect at least one house permanently, which indicates that for every distance between $a_i$ and $a_{i+1}$, if $x- 2\times y > 0$, we have an opportunity to get one house protected. Moreover, the longer uninfected segments have priorities, because we can set two houses to stop the spread of inflection and the loss per day will be prevented. By contrast, for shorter segments, when all the houses in this segment are infected, then there won't be any loss afterwards. In other words, the loss of longer segments will last for longer time if we do not take actions in time. As a result, if we operate the longer segments as early as possible, we can protect more houses. In conclusion, our final strategy can be decribed as following: Sort the uninfected segments of houses according to their length, then the longer the segment is, the earlier we will deal with the houses lying on the side of the segment.
|
[
"greedy",
"implementation",
"sortings"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
const int N = 500005, inf = 2147483647, M = 1004535809;
int n, m, a[N], T, k;
struct str {
int x, y;
}t[N];
int main() {
scanf("%d", &T);
while (T--) {
k = 0;
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; ++i)
scanf("%d", &a[i]);
sort(a + 1, a + 1 + m);
for (int i = 2; i <= m; ++i)
t[++k] = { a[i] - a[i - 1] - 1,2 };
int num_tmp = a[1] + n - a[m] - 1;
if (num_tmp > 0) {
t[++k] = { num_tmp, 2 };
}
sort(t + 1, t + 1 + k, [](str a, str b) {return a.x > b.x; });
long long ans = 0, cnt = 0;
for (int i = 1; i <= k; ++i) {
if (t[i].x - cnt * 2 > 0) {
int num_tmp = max(1ll, t[i].x - cnt * 2 - 1);
ans += num_tmp;
}
cnt += 2;
}
printf("%lld\n", n - ans);
}
}
|
1704
|
D
|
Magical Array
|
Eric has an array $b$ of length $m$, then he generates $n$ additional arrays $c_1, c_2, \dots, c_n$, each of length $m$, from the array $b$, by the following way:
Initially, $c_i = b$ for every $1 \le i \le n$. Eric secretly chooses an integer $k$ $(1 \le k \le n)$ and chooses $c_k$ to be the special array.
There are two operations that Eric can perform on an array $c_t$:
- Operation 1: Choose two integers $i$ and $j$ ($2 \leq i < j \leq m-1$), subtract $1$ from both $c_t[i]$ and $c_t[j]$, and add $1$ to both $c_t[i-1]$ and $c_t[j+1]$. \textbf{That operation can only be used on a non-special array, that is when $t \neq k$.};
- Operation 2: Choose two integers $i$ and $j$ ($2 \leq i < j \leq m-2$), subtract $1$ from both $c_t[i]$ and $c_t[j]$, and add $1$ to both $c_t[i-1]$ and $c_t[j+2]$. \textbf{That operation can only be used on a special array, that is when $t = k$.}Note that Eric can't perform an operation if any element of the array will become less than $0$ after that operation.
Now, Eric does the following:
- For every \textbf{non-special} array $c_i$ ($i \neq k$), Eric uses \textbf{only operation 1} on it \textbf{at least once}.
- For the \textbf{special} array $c_k$, Eric uses \textbf{only operation 2} on it \textbf{at least once}.
Lastly, Eric discards the array $b$.
For given arrays $c_1, c_2, \dots, c_n$, your task is to find out the special array, i.e. the value $k$. Also, you need to find the number of times of operation $2$ was used on it.
|
First, let's focus on $\textbf{operation 1}$ and do some calculations: 1. $a_{i-1} \times (i-1) + a_i \times i + a_j \times j + a_{j+1} \times (j+1) = i \times (a_{i-1}+a_i) + j \times (a_j+a_{j+1}) -a_{i-1} + a_{j+1}$ 2. $(a_{i-1}+1) \times (i-1) + (a_i-1) \times i + (a_j-1) \times j + (a_{j+1}+1) \times (j+1)$ $\ \ \ = i \times (a_{i-1}+a_i) + j \times (a_j+a_{j+1}) -a_{i-1} + a_{j+1}$ See what? Yes, even if you give lots of $\textbf{operation 1}$ to array $a$, the sum of $(a_{i} \times i)$ remains. Thus, you can easily find $c_k$. And how to find the number of $\textbf{operation 2}$ ? Let's do some calculations again: 1. $a_{i-1} \times (i-1) + a_i \times i + a_j \times j + a_{j+1} \times (j+1) +a_{j+2} \times (j+2)$ $\ \ \ = i \times (a_{i-1}+a_i) + j \times (a_j+a_{j+1}+a_{j+2}) -a_{i-1} + a_{j+1}+2 \times a_{j+2}$ 2. $(a_{i-1}+1) \times (i-1) + (a_i-1) \times i + (a_j-1) \times j + a_{j+1} \times (j+1) + (a_{j+2}+1) \times (j+2)$ $\ \ \ = i \times (a_{i-1}+a_i) + j \times (a_j+a_{j+1}+a_{j+2}) -a_{i-1} + a_{j+1}+ 2 \times a_{j+2} +1$ This operation will add $1$ to the result of $\sum a_i\times i$. Just minus the initial $\sum a_i\times i$ and you will get the number of operations applied.
|
[
"constructive algorithms",
"hashing",
"implementation",
"math"
] | 1,900
|
#include <stdio.h>
#include <string.h>
#include <vector>
#include <map>
#include <cassert>
const int MAXN = 500005;
std::vector<long long> numbers[MAXN];
std::map<long long, long long> val_to_index;
int main()
{
int t;
int n, m;
scanf("%d ", &t);
while (t--)
{
val_to_index.clear();
scanf("%d %d", &n, &m);
long long num_tmp;
for (int i = 1; i <= n; i++) {
numbers[i].clear();
numbers[i].push_back(0);
for (int j = 1; j <= m; j++) {
scanf("%lld", &num_tmp);
numbers[i].push_back(num_tmp);
}
}
long long res_tmp = -1;
for (long long i = 1; i <= n; i++) {
long long val = 0;
for (long long j = 1; j <= m; j++) {
val += (j * numbers[i][j]);
}
if (val_to_index.find(val) != val_to_index.end()) {
res_tmp = val;
val_to_index[val] = -1;
}
else {
val_to_index[val] = i;
}
}
assert(val_to_index.size() == 2);
for (auto &item : val_to_index) {
if (item.second != -1ll) {
printf("%lld %lld\n", item.second, std::abs(res_tmp - item.first));
break;
}
}
}
return 0;
}
|
1704
|
E
|
Count Seconds
|
Cirno has a DAG (Directed Acyclic Graph) with $n$ nodes and $m$ edges. The graph has exactly one node that has no out edges. The $i$-th node has an integer $a_i$ on it.
Every second the following happens:
- Let $S$ be the set of nodes $x$ that have $a_x > 0$.
- For all $x \in S$, $1$ is subtracted from $a_x$, and then for each node $y$, such that there is an edge from $x$ to $y$, $1$ is added to $a_y$.
Find the first moment of time when all $a_i$ become $0$. Since the answer can be very large, output it modulo $998\,244\,353$.
|
For the sink point, We can find that it may be zero at some time $t$ and $t \leq n$, then it will be full for some continous time, and then will be zero forever. That's because for time $t\ge n$, for some certain $a_x>0$, all roads from $x$ to the sink point must be greater than $0$ since $n$ rounds are enough for such $a_x$ to spread along these roads. Meanwhile, when some $a_y$ is decreased, it will also receive the numbers from upper nodes $x$. As a result, after $n$ turns, $a_y$ will be greater than $0$ until all $a_x$ turns to $0$ for all $x$ that there's an edge from $x$ to $y$. Simulate the first $n$ rounds, then we just need to calculate what's the final number on the sink node if the the number on the sink point is never decreased. That's exactly the rounds it will take the sink point to be decreased to $0$. Let $dp_i$ be the total number of $1$s the i-th node will add to some sink point finally if there is an $1$ on the i-th node. We can easily get the $dp_i$ in O(n) time for every sink point. Do a topological sort, and add the $sum_i$ of the current node $i$ to the $sum_j$ of the newly queued point $j$ during the sorting process. Calculate the sum of $s_i \times dp_i$ and you can get the answer. The total time complexity will be $O(n^2)$. Note that the numbers on the nodes may be a multiple of $998244353$, so pay attention to them when simulating in the first $n$ turns.
|
[
"brute force",
"constructive algorithms",
"dp",
"graphs",
"implementation",
"math"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
const int N = 500005, inf = 2147483647, M = 998244353;
int n, m, a[N], u, v, i, d[N], q[N], r, mx;
int b[N], tmp[N];
vector<int> g[N], z[N];
long long s[N];
int p[15];
void NEX(int M) {
for (int i = 1; i <= n; ++i)
if (b[i]) {
tmp[i] += b[i] - 1;
for (auto it : g[i])
++tmp[it];
}
for (int i = 1; i <= n; ++i) {
if (tmp[i] >= M)
b[i] = tmp[i] % M + M;
else
b[i] = tmp[i] % M;
tmp[i] = 0;
}
}
int cal(int M) {
for (int i = 1; i <= n; ++i) {
b[i] = a[i];
}
for (int i = 1; i <= n; ++i) {
bool fl = false;
for (int j = 1; j <= n; ++j)
if (b[j])
fl = true;
if (!fl)
return i - 1;
NEX(M);
}
return n;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
g[i].clear();
z[i].clear();
d[i] = 0;
tmp[i] = 0;
s[i] = 0;
}
for (int i = 1; i <= m; ++i) {
scanf("%d %d", &u, &v);
++d[u];
g[u].push_back(v);
z[v].push_back(u);
}
mx = cal(M);
if (mx < n) {
cout << mx << endl;
continue;
}
r = 0;
for (int i = 1; i <= n; ++i)
if (!d[i])
q[++r] = i;
s[q[1]] = 1;
for (int i = 1; i <= r; ++i) {
s[q[i]] %= M;
for (auto it : z[q[i]]) {
--d[it];
s[it] += s[q[i]];
if (!d[it])
q[++r] = it;
}
}
long long ans = n;
for (int i = 1; i <= n; ++i)
ans = (ans + s[i] * b[i]) % M;
cout << ans << endl;
}
}
|
1704
|
F
|
Colouring Game
|
Alice and Bob are playing a game. There are $n$ cells in a row. Initially each cell is either red or blue. Alice goes first.
On each turn, Alice chooses two neighbouring cells which contain at least one red cell, and paints that two cells white. Then, Bob chooses two neighbouring cells which contain at least one blue cell, and paints that two cells white. The player who cannot make a move loses.
Find the winner if both Alice and Bob play optimally.
Note that a chosen cell can be white, as long as the other cell satisfies the constraints.
|
First, when the number red cells and blue cells are not equal, the player who owns a larger numberof his/her corresponding cells will win (Alice owns red and Bob owns blue). His/Her strategy can be: each time paint one segment of RB or BR white until there is none. This operation doesn't change the difference between the number of R and B and will decrease the number of the color of his/her opponent. Then Alice will only paint RW and WR, while Bob will only paint BW or WB. This operation will only decreace his/her own number of color, so the player who owns more cells of color will certainly win. When the number of red cells and blue cells are the same, Alice and Bob will play games first on red-and-blue segments, until there is no RB or BR, and the player who faces this situation will lose. Playing games on red-and-blue segments can be described as the following game: each player can take two neighbouring cells which has not be taken yet in his/her turn. As a result, this game becomes equal, then we can use SG function to forecast the result. This SG function has the following calculating method: $SG(n)=mex_{i=0}^{n-2} SG(i)\oplus SG(n-2-i)$. In order to speed up, we can observe that ${SG(i)}$ has a cyclic section of length $34$ except for the first few elements. It can also be proved by verifying the first $34^2$ elements has this cyclic section, and this demonstrates that for all kinds of xor combination of the cyclic section leads to this cycle. Use Mathematical Induction and we can know this combination will be the the same (just add some repeated numbers to the calculation of $mex$ as the previous $34$-th number) for the subsequent elements. The total time complexity can be reduced to $O(n)$ in calculating the SG function.
|
[
"constructive algorithms",
"dp",
"games"
] | 2,600
|
#include<bits/stdc++.h>
using namespace std;
const int N=500005,inf=2147483647,M=998244353;
int n,i,t,f[N],vis[N];
char c[N];
int main(){
for(int i=1;i<=1000;++i){
for(int j=0;j<=i-2;++j)
vis[f[j]^f[i-2-j]]=1;
int j;
for(j=0;vis[j];++j);
f[i]=j;
for(int j=0;j<=i;++j)
vis[j]=0;
}
for(int i=1001;i<N;++i)
f[i]=f[i-34];
scanf("%d",&t);
while(t--){
scanf("%d",&n);
scanf("%s",c+1);
int s=0;
for(int i=1;i<=n;++i)
if(c[i]=='R')
++s;
else
--s;
if(s>0)
puts("Alice");
if(s<0)
puts("Bob");
if(s==0){
int ans=0;
for(int i=1;i<=n;){
int j=i+1;
for(;j<=n&&c[j]!=c[j-1];++j);
ans^=f[j-i];
i=j;
}
puts(ans?"Alice":"Bob");
}
}
}
|
1704
|
G
|
Mio and Lucky Array
|
Mio has an array $a$ consisting of $n$ integers, and an array $b$ consisting of $m$ integers.
Mio can do the following operation to $a$:
- Choose an integer $i$ ($1 \leq i \leq n$) that has \textbf{not} been chosen before, then add $1$ to $a_i$, subtract $2$ from $a_{i+1}$, add $3$ to $a_{i+2}$ an so on. Formally, the operation is to add $(-1)^{j-i} \cdot (j-i+1) $ to $a_j$ for $i \leq j \leq n$.
Mio wants to transform $a$ so that it will contain $b$ as a \textbf{subarray}. Could you answer her question, and provide a sequence of operations to do so, if it is possible?
An array $b$ is a \textbf{subarray} of an array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
|
Let's define $f_i = a_i + 2 a_{i-1} + a_{i-2}, g_i = b_i + 2b_{i-1} + b_{i-2}$. Cosidering after the operation on some index $i$, for any $j\ne i$, $f_j$ will remain the same; For $j=i$, $f_j$ will be increased by $1$. Then we can find the operation on $a$ is a single point operation on $f$. It can be proved that the following conditions are equivalent to the condition that $b[1,m]$ can match $a[k+1,k+m]$: $\left\{\begin{matrix} b_1=a_{k+1} \\ b_2 + b_1 = a_{k+2} + a_{k+1} \\ g_i = f_{k+i} (i \ge 3) \\ \end{matrix}\right.$ For $i \le k+2$, operation on $i$ will make $a_{k+1}+a_{k+2} \gets a_{k+1} + a_{k+2} + (-1)^{k-i}$. So the second condition restricts the difference of operating times between odd positions and even positions among first $k+2$ positions. When conducting an operation on $i$ it will make $a_{k+1} \gets a_{k+1} + (k+2-i)\times (-1)^{k-i}$. So we can convert the problem to: using $-0,+1,-2,+3,-4,+5\cdots,(-1)^n n$, to make the number of subtractions(operations which make $a_{k+1}$ be decreased) minus the number of additions(operations which make $a_{k+1}$ be increased) is $a$, and the final $a_{k+1}$ should be $b$. Further, suppose I first select all the subtractions($-0,-2,-4,-6,\dots$), i.e. take all the operation on odd/even(depending on the parity of $k$) positions. If I don't want to select it afterwards, it can be regarded as a re-add operation, then the first and second restrictions can be converted to $a \gets a +\lfloor\frac{k+1}{2}\rfloor+1, b\gets b+\sum_{i= 0}^{\lfloor \frac{k+1}{2}\rfloor} 2i$, where $a$ indicates that $a$ numbers need to be selected, and $b$ indicates that the selected sum is $b$. All $b$ which satisfies $\sum_{i=0}^{a-1} i \le b \le \sum_{i=k+1-a}^{k+1} i$ are legal and easy to construct. Next consider the third restriction, the constructor $f(k) = \sum_{i=3}^m (g_i-f_{i+k})(g_i-f_{i+k}-1)$. If $f_{i+k}=g_i$ or $f_{i+k}+1=g_i$, then the above formula is 0. Whether $f_{i+k}=g_i$ respectively represents whether we need to operate on $k+i$, otherwise the above formula must be greater than 0. If $b[1,m]$ matches $a[k+1,k+m]$, then $f(k) = 0$, otherwise it must not match. So consider how to calculate $f$. $f(k) = \sum_{i=3}^m f_{i+k}^2+g_i^2-2f_{i+k}g_i-g_i+f_i$ Considering that $f(k)$ may be quite large, you need to test several different prime numbers if you use NTT, in order to avoid hacking. The total time complexity $O(n\log n)$. Also the available $k$ which satisfies the third restriction can also be found using bitset, the total time complexity $O(\frac{n^2}{\omega})$.
|
[
"constructive algorithms",
"fft",
"math",
"strings"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
const int M1=998244353,M2=1004535809,M3=469762049,E=524288,N=200005;
struct poly{
const int M;
poly(int _M):M(_M){}
int R[N*4];
long long qpow(long long a,long long b){
long long ans=1;
while(b){
if(b&1)
ans=ans*a%M;
a=a*a%M;
b>>=1;
}
return ans;
}
long long wn[N*4],iwn[N*4],inv[N*4],fac[N*4],ifac[N*4];
void init(int E,int g){
int i;
iwn[E/2]=wn[E/2]=1;
long long s1=qpow(g,(M-1)/E);
long long s2=qpow(s1,M-2);
for(i=E/2+1;i<E;++i){
wn[i]=wn[i-1]*s1%M;
iwn[i]=iwn[i-1]*s2%M;
}
for(i=E/2-1;i;--i){
wn[i]=wn[i<<1];
iwn[i]=iwn[i<<1];
}
ifac[0]=fac[0]=inv[1]=1;
for(i=2;i<E;++i)
inv[i]=inv[M%i]*(M-M/i)%M;
for(i=1;i<E;++i){
ifac[i]=inv[i]*ifac[i-1]%M;
fac[i]=fac[i-1]*i%M;
}
}
unsigned long long ccc[N*4];
void NTT(long long *f,int lim,int op){
int i,j,k;
for(i=0;i<lim;++i){
R[i]=(R[i>>1]>>1)|(i&1?lim>>1:0);
if(R[i]<i)
swap(f[R[i]],f[i]);
}
for(i=0;i<lim;++i)
ccc[i]=(f[i]%M+M)%M;
for(i=1;i<lim;i<<=1)
for(j=0;j<lim;j+=(i<<1))
for(k=j;k<j+i;++k){
long long w=(op==1?wn[k-j+i]:iwn[k-j+i]);
unsigned long long p=ccc[k+i]*w%M;
ccc[k+i]=ccc[k]+M-p;
ccc[k]+=p;
}
for(i=0;i<lim;++i)
f[i]=ccc[i]%M;
if(op==-1){
long long inv=qpow(lim,M-2);
for(i=0;i<lim;++i)
f[i]=f[i]*inv%M;
}
}
long long ta[N*4],tb[N*4];
void mult(long long *a,int n,long long *b,int m,long long *c){
int lim=1;
while(lim<n+m)
lim<<=1;
copy(a,a+n,ta);
copy(b,b+m,tb);
for(int i=n;i<lim;++i)
ta[i]=0;
for(int i=m;i<lim;++i)
tb[i]=0;
NTT(ta,lim,1);
NTT(tb,lim,1);
for(int i=0;i<lim;++i)
ta[i]=ta[i]*tb[i]%M;
NTT(ta,lim,-1);
copy(ta,ta+lim,c);
}
}X(M1),Y(M2),Z(M3);
int n,m,o[N],t,tn;
long long a[N],b[N],c[N],d[N*4],e[N],f[N*4],ss[N],td[N],tf[N];
bool fl[N],zz;
vector<int> ans;
long long cal(int l,int r){
return 1ll*(l+r)*(r-l+1)/2;
}
long long cal2(int u,int v){
return 1ll*((v-u)/2+1)*(u+v)/2;
}
bool iok(int n,int p,int q){
long long ss=q+1ll*(n/2)*(n/2+1);
p=p+(n/2+1);
long long mn=cal(0,p-1),mx=cal(n-p+1,n);
if(mn<=ss&&ss<=mx){
for(int i=n;i<n+m-2;++i)
if(td[i]!=tf[i-n+1]&&td[i]!=tf[i-n+1]-1)
return false;
ss-=mn;
for(int i=n;i<n+m-2;++i)
if(td[i]!=tf[i-n+1])
ans.push_back(i+2);
fill(fl,fl+1+n,0);
for(int i=0;i<p;++i)
fl[(ss/p+(i>=p-ss%p)+i)]=1;
for(int i=0;i<=n;++i)
if(fl[i]^(i&1)^1)
if(n+1-i<=tn)
ans.push_back(n+1-i);
zz=true;
return true;
}
return false;
}
void OT(){
if(!zz)
puts("-1");
else{
printf("%d\n",ans.size());
for(auto it:ans)
printf("%d ",it);
printf("\n");
}
}
void judgement(poly &v,long long *c,long long *e){
for(int i=0;i<n-2;++i)
d[i]=(c[i+1]+c[i+2])%v.M;
for(int i=0;i<m-2;++i)
f[i]=(e[i+1]+e[i+2])%v.M;
reverse(f,f+m-2);
long long s=0;
for(int i=0;i<m-2;++i)
s+=(f[i]*f[i]-f[i])%v.M;
for(int i=1;i<=n-2;++i)
ss[i]=(ss[i-1]+d[i-1]*(d[i-1]+1))%v.M;
v.mult(d,n-2,f,m-2,d);
for(int i=m-3;i<n-2;++i)
if((s+ss[i+1]-ss[i-m+3]-2*d[i])%v.M!=0)
o[i-m+4]=0;
}
int main(){
X.init(E,3);
Y.init(E,3);
Z.init(E,3);
scanf("%d",&t);
while(t--){
scanf("%d",&n);
tn=n;
for(int i=1;i<=n;++i)
scanf("%lld",&a[i]);
scanf("%d",&m);
for(int i=1;i<=m;++i)
scanf("%lld",&b[i]);
for(int i=1;i<n;++i)
c[i]=a[i]+a[i+1];
for(int i=1;i<m;++i)
e[i]=b[i]+b[i+1];
fill(o,o+1+n,0);
ans.clear();
for(int i=1;i<=n;++i)
o[i]=1;
if(m>2){
for(int i=0;i<n-2;++i)
td[i+1]=c[i+1]+c[i+2];
for(int i=0;i<m-2;++i)
tf[i+1]=e[i+1]+e[i+2];
judgement(X,c,e);
judgement(Y,c,e);
judgement(Z,c,e);
}
else
for(int i=1;i<=n;++i)
o[i]=1;
int x=-1;
zz=false;
if(m==1){
for(int i=1;i<=n;++i)
if(-cal2(0,i/2*2)<=b[1]-a[i]&&b[1]-a[i]<=cal2(1,(i-1)/2*2+1)){
for(int j=-(i/2+1);j<=(i+1)/2;++j)
if(iok(i,j,b[1]-a[i]))
break;
break;
}
}
else
for(int i=1;i+m-1<=n;++i)
if(o[i]&&iok(i,(a[i]+a[i+1])-(b[1]+b[2]),b[1]-a[i]))
break;
OT();
}
}
|
1704
|
H1
|
Game of AI (easy version)
|
\textbf{This is the easy version of this problem. The difference between easy and hard versions is the constraint on $k$ and the time limit. Also, in this version of the problem, you only need to calculate the answer when $n=k$. You can make hacks only if both versions of the problem are solved.}
Cirno is playing a war simulator game with $n$ towers (numbered from $1$ to $n$) and $n$ bots (numbered from $1$ to $n$). The $i$-th tower is initially occupied by the $i$-th bot for $1 \le i \le n$.
Before the game, Cirno first chooses a permutation $p = [p_1, p_2, \ldots, p_n]$ of length $n$ (A permutation of length $n$ is an array of length $n$ where each integer between $1$ and $n$ appears exactly once). After that, she can choose a sequence $a = [a_1, a_2, \ldots, a_n]$ ($1 \le a_i \le n$ and $a_i \ne i$ for all $1 \le i \le n$).
The game has $n$ rounds of attacks. In the $i$-th round, if the $p_i$-th bot is still in the game, it will begin its attack, and as the result the $a_{p_i}$-th tower becomes occupied by the $p_i$-th bot; the bot that previously occupied the $a_{p_i}$-th tower will no longer occupy it. If the $p_i$-th bot is not in the game, nothing will happen in this round.
After each round, if a bot doesn't occupy any towers, it will be eliminated and leave the game. Please note that no tower can be occupied by more than one bot, but one bot can occupy more than one tower during the game.
At the end of the game, Cirno will record the result as a sequence $b = [b_1, b_2, \ldots, b_n]$, where $b_i$ is the number of the bot that occupies the $i$-th tower at the end of the game.
However, as a mathematics master, she wants you to solve the following counting problem instead of playing games:
Count the number of different pairs of sequences $a$ and $b$ that we can get from all possible choices of sequence $a$ and permutation $p$.
Since this number may be large, output it modulo $M$.
|
Consider calculate the number of possible sequences $a$ for a fixed sequence $b$. We can find that if $b_i\ne i$, that means $i$ is occupied by $b_i$ finally, so we have $a_{b_i}$=i. If $b_i=i$, that means for all $j$ that $a_j=i$, $j$ is occupied before it begins its attack. As a result, we must have $b_j\ne j$. The sequences $a$ which satisfies the above conditions is also possible to match a valid $p$. The attacking order can be arranged easily. Now for how to count, we can build a graph according to the information given by $b_i\ne i$. We can see that the graph will in the form of some chains. Also, we can find that for a graph which consists of some chains, we can find the unique $b$ which satisfies the graph. Then some positions of array $a$ is also fixed, except the top of each chain. As for how to decide the these $a_i$($i$ is the top of some chain), we need to divide into two situations: one is the chain's length is greater than $1$, we can see that this $a_i$ can take any number between $1$ and $n$ except $i$; The other one is the chain's length is one, so $a_i$ cannot be any bottom of each chain. Then we can easily calculate the number of arrays $a$ by product the possible number of values of each $a_i$. In conclusion, we can enumerate the number of chains, and the number of chains with length $1$, then use combination number to calculate. Time complexity is $O(n^2)$.
|
[
"combinatorics",
"constructive algorithms",
"dp",
"fft",
"math"
] | 3,200
|
#include<bits/stdc++.h>
using namespace std;
const int N=200005,E=15000005;
const long long inf=1000000000000000000ll;
int n,M,mi[5005][5005];
long long fac[N],inv[N],ans;
long long C(int n,int m){
return fac[n]*inv[m]%M*inv[n-m]%M;
}
long long qpow(long long a,long long b){
long long s=a,ans=1;
while(b){
if(b&1)
ans=ans*s%M;
s=s*s%M;
b>>=1;
}
return ans;
}
int main(){
cin>>n>>M;
fac[0]=inv[0]=inv[1]=1;
for(int i=2;i<=n;++i)
inv[i]=inv[M%i]*(M-M/i)%M;
for(int i=1;i<=n;++i){
inv[i]=inv[i-1]*inv[i]%M;
fac[i]=fac[i-1]*i%M;
}
long long s1=1;
for(int i=0;i<=n;++i){
mi[i][0]=1;
for(int j=1;j<=n;++j)
mi[i][j]=1ll*mi[i][j-1]*i%M;
}
for(int j=1;2*j<=n;++j){
s1=s1*(n-1)%M;
for(int i=0;i<=n-2*j;++i)
ans=(ans+C(n,i)*fac[n-i]%M*s1%M*mi[n-i-j][i]%M*C(n-i-j-1,j-1)%M*inv[j])%M;
}
cout<<ans<<endl;
}
|
1704
|
H2
|
Game of AI (hard version)
|
\textbf{This is the hard version of this problem. The difference between easy and hard versions is the constraint on $k$ and the time limit. Notice that you need to calculate the answer for all positive integers $n \in [1,k]$ in this version. You can make hacks only if both versions of the problem are solved.}
Cirno is playing a war simulator game with $n$ towers (numbered from $1$ to $n$) and $n$ bots (numbered from $1$ to $n$). The $i$-th tower is initially occupied by the $i$-th bot for $1 \le i \le n$.
Before the game, Cirno first chooses a permutation $p = [p_1, p_2, \ldots, p_n]$ of length $n$ (A permutation of length $n$ is an array of length $n$ where each integer between $1$ and $n$ appears exactly once). After that, she can choose a sequence $a = [a_1, a_2, \ldots, a_n]$ ($1 \le a_i \le n$ and $a_i \ne i$ for all $1 \le i \le n$).
The game has $n$ rounds of attacks. In the $i$-th round, if the $p_i$-th bot is still in the game, it will begin its attack, and as the result the $a_{p_i}$-th tower becomes occupied by the $p_i$-th bot; the bot that previously occupied the $a_{p_i}$-th tower will no longer occupy it. If the $p_i$-th bot is not in the game, nothing will happen in this round.
After each round, if a bot doesn't occupy any towers, it will be eliminated and leave the game. Please note that no tower can be occupied by more than one bot, but one bot can occupy more than one tower during the game.
At the end of the game, Cirno will record the result as a sequence $b = [b_1, b_2, \ldots, b_n]$, where $b_i$ is the number of the bot that occupies the $i$-th tower at the end of the game.
However, as a mathematics master, she wants you to solve the following counting problem instead of playing games:
Count the number of different pairs of sequences $a$, $b$ from all possible choices of sequence $a$ and permutation $p$.
Calculate the answers for all $n$ such that $1 \le n \le k$. Since these numbers may be large, output them modulo $M$.
|
Given $b$, The conclusion of possible array $a$ remains. If we fix array $a$, we will find that for each $i$, $b_i$ will only be $j$ that $a_j=i$ or $j=i$. For any pair $(x,y)$, if $a_x=y$, we will find that $b_x=x$ and $b_y=y$ at the same time is impossible. All arrays $b$ which satisfies the above conditions are valid. So for a fixed array $a$, and we fix the position that $b_i=i$(It can be shown that the chosen nodes form a independent set), then the number of possible $b$ will be product of each in-degree of each $x$ that $b_x\ne x$. Now we can see if we build a graph according to $a$, the answer will be the sume of product over all independent sets. We need to solve the problem of three parts: the nodes form a tree, some trees' roots form a ring, some trees based on rings form a graph. For the tree part, let $P(x)$ be generating function of the sum of pruducts if the root is not included in the independent set, and $Q(x)$ otherwise. Then we have: $P(x)=x(P(x)+Q(x))e^{P(x)+Q(x)}$ $Q(x)=xe^{P(x)}$ We can solve the equation, and use Newton's method to calculate $P(x)$ and $Q(x)$. Consider how to merge trees together. If one root is not in the independent set, It can either be occupied by one of its children or the previous node on the ring, so its generating function can be represented as $A(x)$(compared with $P(x)$, it adds the contribution caused by that it's occupied by the previous node on the ring), which is easy to calculate. For those which are in the independent set, their previous nodes must not be in. So we binding them together and their generating functions can be represented as $B(x)$. The final answer is $\sum_{i=1}^{+\infty} \frac{(A(x)+B(x))^i}{i}-A(x)=-\ln(1-A(x)-B(x))-A(x)$. Note that when every node on the ring is occupied by previous node, it is also impossible. So we need to minus this answer. It can be calculated with similar method. At last, we need to combine these rings into a graph, which can be done with $exp$ operation. Time complexity is $O(n\log n)$.
|
[
"combinatorics",
"fft",
"math"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
const int N=100005,inf=2147483647;
const long long sq5=200717101;
int M;
namespace poly{
int R[N*4];
long long qpow(long long a,long long b){
long long ans=1;
while(b){
if(b&1)
ans=ans*a%M;
a=a*a%M;
b>>=1;
}
return ans;
}
long long wn[N*4],iwn[N*4],inv[N*4],fac[N*4],ifac[N*4],g;
void init(int E){
int i;
iwn[E/2]=wn[E/2]=1;
long long s1=qpow(g,(M-1)/E);
long long s2=qpow(s1,M-2);
for(i=E/2+1;i<E;++i){
wn[i]=wn[i-1]*s1%M;
iwn[i]=iwn[i-1]*s2%M;
}
for(i=E/2-1;i;--i){
wn[i]=wn[i<<1];
iwn[i]=iwn[i<<1];
}
ifac[0]=fac[0]=inv[1]=1;
for(i=2;i<E;++i)
inv[i]=inv[M%i]*(M-M/i)%M;
for(i=1;i<E;++i){
ifac[i]=inv[i]*ifac[i-1]%M;
fac[i]=fac[i-1]*i%M;
}
}
unsigned long long ccc[N*4];
void NTT(long long *f,int lim,int op){
int i,j,k;
for(i=0;i<lim;++i){
R[i]=(R[i>>1]>>1)|(i&1?lim>>1:0);
if(R[i]<i)
swap(f[R[i]],f[i]);
}
for(i=0;i<lim;++i)
ccc[i]=(f[i]%M+M)%M;
for(i=1;i<lim;i<<=1)
for(j=0;j<lim;j+=(i<<1))
for(k=j;k<j+i;++k){
long long w=(op==1?wn[k-j+i]:iwn[k-j+i]);
unsigned long long p=ccc[k+i]*w%M;
ccc[k+i]=ccc[k]+M-p;
ccc[k]+=p;
}
for(i=0;i<lim;++i)
f[i]=ccc[i]%M;
if(op==-1){
long long inv=qpow(lim,M-2);
for(i=0;i<lim;++i)
f[i]=f[i]*inv%M;
}
}
long long ta[N*4],tb[N*4];
void mult(long long *a,int n,long long *b,int m,long long *c){
int lim=1;
while(lim<n+m)
lim<<=1;
copy(a,a+n,ta);
copy(b,b+m,tb);
for(int i=n;i<lim;++i)
ta[i]=0;
for(int i=m;i<lim;++i)
tb[i]=0;
NTT(ta,lim,1);
NTT(tb,lim,1);
for(int i=0;i<lim;++i)
ta[i]=ta[i]*tb[i]%M;
NTT(ta,lim,-1);
copy(ta,ta+lim,c);
}
long long tmp[N*4],tans[N*4];
void Getinv(long long *a,long long *ans,int lim){
ans[0]=qpow(a[0],M-2);
for(int i=1;i<lim;i<<=1){
for(int j=i;j<(i<<2);++j)
ans[j]=tans[j]=tmp[j]=0;
for(int j=0;j<(i<<1);++j)
tmp[j]=a[j];
for(int j=0;j<i;++j)
tans[j]=ans[j];
NTT(tmp,i<<2,1);
NTT(tans,i<<2,1);
for(int j=0;j<(i<<2);++j)
tmp[j]=tmp[j]*tans[j]%M*tans[j]%M;
NTT(tmp,i<<2,-1);
for(int j=0;j<(i<<1);++j)
ans[j]=(2*ans[j]-tmp[j])%M;
}
}
long long tinv[N*4];
void Getln(long long *a,long long *ans,int n){
for(int i=0;i<n-1;++i)
ans[i]=a[i+1]*(i+1)%M;
Getinv(a,tinv,n);
mult(ans,n-1,tinv,n,ans);
for(int i=n;i>=1;--i)
ans[i]=ans[i-1]*inv[i]%M;
ans[0]=0;
}
long long tln[N*4];
void Getexp(long long *a,long long *ans,int n){
ans[0]=1;
for(int i=1;i<n;i<<=1){
for(int j=i;j<(i<<1);++j)
ans[j]=0;
Getln(ans,tln,i<<1);
for(int j=0;j<(i<<1);++j)
tln[j]=-tln[j]+a[j];
++tln[0];
mult(ans,i,tln,i<<1,ans);
}
}
void Getroot(long long *a,long long *ans,int n){
ans[0]=1;
for(int i=1;i<n;i<<=1){
fill(ans+i,ans+(i<<1),0);
Getinv(ans,tinv,i<<1);
mult(tinv,i<<1,a,i<<1,tinv);
for(int j=0;j<(i<<1);++j)
ans[j]=(ans[j]+tinv[j])*inv[2]%M;
}
}
long long ttln[N*4];
void Getpow(long long *a,long long *ans,int n,int m){
Getln(a,ttln,m);
for(int i=0;i<m;++i)
ttln[i]=ttln[i]*n%M;
Getexp(ttln,ans,m);
}
};
int n,m;
long long f[N*4],g[N*4],h[N*4],hd[N*4],tmp[N*4],eh[N*4],tmp2[N*4],inv[N*4];
void Newton(int lim){
f[0]=f[1]=0;
for(int i=2;i<lim;i<<=1){
poly::Getexp(f,g,i<<1);
for(int j=(i<<1)-1;j>=1;--j)
g[j]=g[j-1];
g[0]=0;
for(int j=0;j<(i<<1);++j)
h[j]=(f[j]+g[j])%M;
poly::Getexp(h,eh,i<<1);
poly::mult(eh,i<<1,h,i<<1,tmp);
++h[0];
++g[0];
poly::mult(g,i<<1,h,i<<1,tmp2);
poly::mult(tmp2,i<<1,eh,i<<1,tmp2);
for(int j=(i<<1);j>=1;--j){
tmp2[j]=-tmp2[j-1];
tmp[j]=-tmp[j-1];
}
tmp2[0]=1;
for(int j=0;j<(i<<1);++j)
tmp[j]=(tmp[j]+f[j])%M;
poly::Getinv(tmp2,inv,i<<1);
poly::mult(inv,i<<1,tmp,i<<1,h);
for(int j=0;j<(i<<1);++j)
f[j]=(f[j]-h[j])%M;
}
}
long long rt[N*4],X[N*4],Y[N*4],p1[N*4],p2[N*4],p[N*4],e1[N*4],e2[N*4];
long long fd[N*4],gd[N*4],as[N*4],ans[N*4],as2[N*4];
int lim=1;
int main(){
cin>>n>>M;
int tmpp=M-1;
vector<int> dz;
for(int i=2;i*i<=tmpp;++i)
while(tmpp%i==0){
tmpp/=i;
dz.push_back(i);
}
if(tmpp!=1)
dz.push_back(tmpp);
for(int i=2;i<M;++i){
int z=M-1;
bool fl=true;
for(auto it:dz)
if(poly::qpow(i,z/it)==1){
fl=false;
break;
}
if(fl){
poly::g=i;
break;
}
}
poly::init(262144);
++n;
while(lim<=n*2)
lim<<=1;
Newton(n+1);
memset(inv,0,sizeof(inv));
poly::Getexp(f,g,n+1);
for(int j=n;j>=1;--j)
g[j]=g[j-1];
g[0]=0;
for(int j=0;j<=n;++j)
h[j]=(f[j]+g[j])%M;
poly::Getexp(h,eh,n+1);
for(int j=1;j<=n;++j)
tmp[j]=-eh[j-1];
tmp[0]=1;
poly::Getln(tmp,as2,n+1);
for(int j=1;j<=n;++j)
as2[j]=(as2[j]-f[j])%M;
poly::mult(eh,n+1,h,n+1,X);
for(int i=0;i<=n;++i)
eh[i]=(X[i]+eh[i])%M;
for(int i=n;i>=1;--i){
eh[i]=eh[i-1];
Y[i]=eh[i];
}
eh[0]=0;
poly::mult(eh,n+1,g,n+1,eh);
for(int i=1;i<=n;++i)
h[i]=(-eh[i]-Y[i])%M;
h[0]=1;
poly::Getln(h,as,n+1);
for(int i=0;i<=n;++i)
as[i]=(-as[i]+as2[i])%M;
poly::Getexp(as,ans,n+1);
--n;
for(int i=1;i<=n;++i)
printf("%lld\n",(ans[i]*poly::fac[i]%M+M)%M);
}
|
1705
|
A
|
Mark the Photographer
|
Mark is asked to take a group photo of $2n$ people. The $i$-th person has height $h_i$ units.
To do so, he ordered these people into two rows, the front row and the back row, each consisting of $n$ people. However, to ensure that everyone is seen properly, the $j$-th person of the back row must be at least $x$ units taller than the $j$-th person of the front row for each $j$ between $1$ and $n$, inclusive.
Help Mark determine if this is possible.
|
First, sort $h_1 \leq h_2 \leq \dots \leq h_{2n}$. There is a very explicit description to which $h_i$'s work. What is the optimal arrangement that maximizes the minimum difference across all pairs? We have a very explicit description of whether the arrangement is possible. Sort the heights so that $h_1 \leq h_2 \leq \dots \leq h_{2n}$. Then, there exists such arrangement if and only if all the following conditions hold. $\begin{align*} h_{n+1}-h_1 &\geq x \\ h_{n+2}-h_2 &\geq x \\ &\vdots \\ h_{2n}-h_n &\geq x \end{align*}$ We present two proofs. Proof 1 (Direct Proof). Suppose that the arrangement is possible. We will show that for each $i$, we have $h_{n+i}-h_i\geq x$. To do so, note that $n+1$ people who have height in $[h_i, h_{n+i}]$. It's impossible that these $n+1$ people got assigned to different columns (because there are $n$ columns), so there exist two people that got assigned to the same column. However, because these two people have height in $[h_i, h_{n+i}]$, the difference in heights between these two people is at most $h_{n+i}-h_i$. As the difference is at least $x$ by the arrangement, we must have that $h_{n+i}-h_i\geq x$. $\blacksquare$ Proof 2 (Exchange Argument). First, we look at two pairs. Suppose that the $i$-th person in the first and second row have heights $a < b$, while the $j$-th person in the first and second row have heights $c < d$. $\begin{array}{ccccc} \dots & a & \dots & c & \dots \\ \dots & b & \dots & d & \dots \end{array}$ Assume that $b\geq c$, then we switch $b,c$. The arrangement still works since $a-c \geq a-b \geq x$ and $b-d \geq c-d \geq x$. Similarly, $a\geq d$ yields a switch. Thus, we can keep exchanging until anyone in the first row is at least as tall as anyone in the second row. Thus, the first row must be $h_{n+1}, h_{n+2}, \dots, h_{2n}$, while the second row must be $h_1, h_2, \dots, h_n$ in some order. Now, we look at the same picture again. Assume that $a\geq c$ but $b\leq d$. then, we can switch $b,d$, and it still works because $a-d \geq c-d \geq x$ and $c-b \geq c-d \geq x$. Thus, we can switch the second row until it matches the order of the first row. Therefore, we force the first row to be $h_{n+1}, h_{n+2}, \dots, h_{2n}$, while the second row must be $h_1, h_2, \dots, h_n$ in that order. This implies the conclusion. $\blacksquare$ Time Complexity: $O(n\log n)$ for sorting.
|
[
"greedy",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, x;
cin >> n >> x;
vector<int> a(2 * n);
for (int i = 0; i < 2 * n; ++i)
cin >> a[i];
sort(a.begin(), a.end());
bool ok = true;
for (int i = 0; i < n; ++i)
if (a[n + i] - a[i] < x) ok = false;
cout << (ok ? "YES" : "NO") << "\n";
}
int main() {
int tt; cin >> tt;
while (tt--) solve();
}
|
1705
|
B
|
Mark the Dust Sweeper
|
Mark is cleaning a row of $n$ rooms. The $i$-th room has a nonnegative dust level $a_i$. He has a magical cleaning machine that can do the following three-step operation.
- Select two indices $i<j$ such that the dust levels $a_i$, $a_{i+1}$, $\dots$, $a_{j-1}$ are all strictly greater than $0$.
- Set $a_i$ to $a_i-1$.
- Set $a_j$ to $a_j+1$.
Mark's goal is to make $a_1 = a_2 = \ldots = a_{n-1} = 0$ so that he can nicely sweep the $n$-th room. Determine the minimum number of operations needed to reach his goal.
|
The optimal way is to fill all the zero entries first. Delete the leading zeroes in the array $a$ (i.e., the first $t$ numbers of $a$ that are zero) so that now $a_1\ne 0$. Let $k$ be the number of $0$'s in $a_1,a_2,\dots,a_{n-1}$. The answer is $(a_1+a_2+\dots + a_{n-1}) + k.$ To see why, let Mark keep filling the holes (rooms with dust level $0$) first by subtracting the first nonzero index and changing the first zero index to $1$. This takes $k$ moves to fill all zeroes in $a_1,a_2,\dots,a_{n-1}$. Then, we can start moving, from left to right, all dust to the $n$-th room, taking $a_1+a_2+\dots+a_{n-1}$ moves. Finally, we argue that this is the minimum number of moves. To that end, we prove that each move decreases the answer by at most $1$. We consider two cases. If a move has $j=n$, then it decreases $a_1+a_2+\dots+a_{n-1}$ by $1$ but does not decrease $k$. If $j\ne n$, then the move doesn't decrease $a_1+a_2+\dots+a_{n-1}$ and decreases $k$ by at most $1$. Thus, we are done. The time complexity is $O(n)$.
|
[
"constructive algorithms",
"greedy",
"implementation"
] | 900
|
#include <iostream>
#include <vector>
#define ll long long
using namespace std;
void solve(){
int n; cin >> n;
vector<int> a(n);
for(int i = 0; i < n; ++i)
cin >> a[i];
ll ans = 0;
int ptr = 0;
while(ptr < n && a[ptr] == 0)
ptr++;
for(int i = ptr; i < n-1; ++i){
ans += a[i];
if(a[i] == 0) ans++;
}
cout << ans << "\n";
}
int main(){
int tt; cin >> tt;
while(tt--) solve();
}
|
1705
|
C
|
Mark and His Unfinished Essay
|
One night, Mark realized that there is an essay due tomorrow. He hasn't written anything yet, so Mark decided to randomly copy-paste substrings from the prompt to make the essay.
More formally, the prompt is a string $s$ of initial length $n$. Mark will perform the copy-pasting operation $c$ times. Each operation is described by two integers $l$ and $r$, which means that Mark will append letters $s_l s_{l+1} \ldots s_r$ to the end of string $s$. Note that the length of $s$ increases after this operation.
Of course, Mark needs to be able to see what has been written. After copying, Mark will ask $q$ queries: given an integer $k$, determine the $k$-th letter of the final string $s$.
|
What's in common between all letters that were copied at the same time? The answer is the difference between the current position and the position where it came from. That's what you need to store. By tracking the difference, you can recurse to the previously-copied substring. This is an implementation problem. What you need to do is after the $i$-th copying operation, we need to keep track of the beginning point $a_i$ and the ending point $b_i$ of the appended string. Moreover, we also keep track the subtraction distance $t_i = a_i-l_i$ so that for $k\in [a_i, b_i]$, the $k$-th letter is the same as the $(k-t_i)$-th letter. Thus, we have recursed the position to the smaller position $k-t_i$, so we keep doing that until we reach the initial string. Therefore, to solve this problem, we iterate from $i=c,c-1,\dots,1$. If $k$ is in $[a_i,b_i]$, subtract $k$ by $t_i$. After all operations, $k$ should be at the inital string, and we output the $k$-th letter. The time complexity of this solution is $O(cq)$. However, less efficient solutions of $O((c\log c) q)$ (using binary search each time) or $O(c^2q)$ (by going through all intervals in each iteration) pass as well.
|
[
"brute force",
"implementation"
] | 1,400
|
#include<bits/stdc++.h>
#define ll long long
using namespace std;
void solve(){
int n, c, q; cin >> n >> c >> q;
string s; cin >> s;
vector<ll> left(c+1), right(c+1), diff(c+1);
left[0] = 0;
right[0] = n;
for(int i=1; i<=c; ++i){
ll l, r; cin >> l >> r;
l--; r--;
left[i] = right[i-1];
right[i] = left[i] + (r-l+1);
diff[i] = left[i] - l;
}
while(q--){
ll k; cin >> k;
k--;
for(int i=c; i>=1; --i){
if(k < left[i]) continue;
else k -= diff[i];
}
cout << s[k] << "\n";
}
}
int main(){
int tt; cin >> tt;
while(tt--) solve();
}
|
1705
|
D
|
Mark and Lightbulbs
|
Mark has just purchased a rack of $n$ lightbulbs. The state of the lightbulbs can be described with binary string $s = s_1s_2\dots s_n$, where $s_i=1$ means that the $i$-th lightbulb is turned on, while $s_i=0$ means that the $i$-th lightbulb is turned off.
Unfortunately, the lightbulbs are broken, and the only operation he can perform to change the state of the lightbulbs is the following:
- Select an index $i$ from $2,3,\dots,n-1$ such that $s_{i-1}\ne s_{i+1}$.
- Toggle $s_i$. Namely, if $s_i$ is $0$, set $s_i$ to $1$ or vice versa.
Mark wants the state of the lightbulbs to be another binary string $t$. Help Mark determine the minimum number of operations to do so.
|
Look at all the $01$'s and $10$'s carefully. The sum of the number of $01$'s and $10$'s is constant. Consider all positions of $01$'s and $10$'s. How does it change in each operation? As explained in the sample explanations, the operation cannot change the first or the last bit. Thus, if either $s_1\ne t_1$ or $s_n\ne t_n$, simply return $\texttt{-1}$. Now, the key idea is to consider a binary $\overline{s} = (s_1\oplus s_2)(s_2\oplus s_3) \dots (s_{n-1}\oplus s_n)$ of length $n-1$, where $a\oplus b$ denotes the XOR operation of bits $a$ and $b$. Then, it's easy to verify that the operation acts on $\overline{s}$ by just swapping two different bits. An example is shown below $\begin{array}{cc} s & \overline s \\ \texttt{000101} & \texttt{00111} \\ \downarrow & \downarrow \\ \texttt{001101} & \texttt{01011}\\ \downarrow & \downarrow \\ \texttt{011101} & \texttt{10011} \\ \downarrow & \downarrow \\ \texttt{011001} & \texttt{10101} \\ \downarrow & \downarrow \\ \texttt{011011} & \texttt{10110} \\ \downarrow & \downarrow \\ \texttt{010011} & \texttt{11010} \end{array}$ Thus, the operation is possible if and only if $\overline s$ and $\overline t$ has the same number of $1$'s. Moreover, if $a_1,a_2,\dots,a_k$ are the positions of $1$'s in $\overline s$ and $b_1,b_2,\dots,b_k$ are the positions of $1$'s in $\overline t$. Then, the minimum number of moves is given by $|a_1-b_1| + |a_2-b_2| + \dots + |a_k-b_k|,$ which can be evaluated in $O(n)$. This is a well-known fact, but for completeness, here is the proof. Note that the operation is moving $1$ to left or right by one position. Thus, to achieve that number of moves, simply move the first $1$ from $a_1$ to $b_1$, move the second $1$ from $a_2$ to $b_2$, $\ldots$, and move the $k$-th $1$ from $a_k$ to $b_k$. For the lower bound, notice that the $i$-th $1$ cannot move past the $(i-1)$-th or $(i+1)$-th $1$. Thus, it takes at least $|a_i-b_i|$ moves to move the $i$-th $1$ from $a_i$ to $b_i$. Summing gives the conclusion. Note that another way to think about this problem is to look at the block of $1$'s and $0$'s and notice that the number of blocks remains constant. This is more or less the same as the above solution.
|
[
"combinatorics",
"constructive algorithms",
"greedy",
"math",
"sortings"
] | 1,800
|
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve(){
int n; cin >> n;
string s,t; cin >> s >> t;
vector<ll> pos_s, pos_t;
if(s[0] != t[0] || s[n-1] != t[n-1]){
cout << -1 << "\n";
return;
}
for(int i=0; i<n-1; i++){
if(s[i] != s[i+1]) pos_s.push_back(i);
if(t[i] != t[i+1]) pos_t.push_back(i);
}
if(pos_s.size() != pos_t.size()){
cout << -1 << "\n";
}
else{
int k = pos_s.size();
ll ans = 0;
for(int i=0; i<k; ++i){
ans += abs(pos_s[i] - pos_t[i]);
}
cout << ans << "\n";
}
}
int main(){
int tt; cin >> tt;
while(tt--) solve();
}
|
1705
|
E
|
Mark and Professor Koro
|
After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $n$ positive integers $a_1, a_2,\dots,a_n$ on it.
Then, professor Koro comes in. He can perform the following operation:
- select an integer $x$ that appears at least $2$ times on the board,
- erase those $2$ appearances, and
- write $x+1$ on the board.
Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"
Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $q$ times. Each time, he will choose positive integers $k$ and $l$, then change $a_k$ to $l$. After each update, he will ask Mark the same question again.
Help Mark answer these questions faster than Professor Koro!
Note that the updates are persistent. Changes made to the sequence $a$ will apply when processing future updates.
|
Find a concise description of the answer first. Think about power of two. The sum $2^{a_1}+2^{a_2}+\dots+2^{a_n}$ is constant. Show that the answer must be the most significant bit of that. Use either bitset or lazy segment tree to simulate the addition/subtraction. The key observation is the following. Claim: The answer is $\lfloor\log_2(2^{a_1}+2^{a_2}+\dots+2^{a_n})\rfloor.$ Proof: The upper bound is pretty clear, as the operation doesn't change the $\sum 2^{a_i}$. Moreover, the sum must be at least $2^{\text{ans}}$, giving the result. For the construction, let Mark keep performing the operation until he cannot. At this point, all numbers must be distinct, and the $\sum 2^{a_i}$ is unchanged. Let the current numbers on the board be $b_1<b_2<\dots < b_k$. Then, $\sum_{i=1}^n 2^{a_i} = 2^{b_1}+2^{b_2}+\dots + 2^{b_k} \leq 2^1+2^2+\dots+2^{b_k} < 2^{b_k+1}.$ Thus, Mark can make the final number be $b_k = \lfloor\log_2(2^{a_1}+2^{a_2}+\dots+2^{a_n})\rfloor$ as desired. $\blacksquare$ Finally, we need a data structure to maintain the $\sum 2^{a_i}$ and simulate base 2 addition. There are many ways to proceed, including the following: Using bitsets, partition the bits into many chunks of $w$ bits ($w$ between $50$ and $64$ is fine). This gives $O(n^2/w)$ complexity, but its low constant factor makes it enough to pass comfortably. Using bitsets, partition the bits into many chunks of $w$ bits ($w$ between $50$ and $64$ is fine). This gives $O(n^2/w)$ complexity, but its low constant factor makes it enough to pass comfortably. Use lazy segment augmented with $O(\log n)$ binary search. For each bit added, find where the longest streak of $1$'s to the left of that bit ends, and update accordingly. Similarly, for each bit subtracted, find where the longest streak of $0$'s to the left of that bit ends, and update accordingly. The total complexity is $O(n\log n)$. Use lazy segment augmented with $O(\log n)$ binary search. For each bit added, find where the longest streak of $1$'s to the left of that bit ends, and update accordingly. Similarly, for each bit subtracted, find where the longest streak of $0$'s to the left of that bit ends, and update accordingly. The total complexity is $O(n\log n)$.
|
[
"binary search",
"bitmasks",
"brute force",
"combinatorics",
"data structures",
"greedy"
] | 2,300
|
#include<bits/stdc++.h>
using namespace std;
struct LazySeg {
int l, r;
int val = 0, tag = 0;
bool is_lazy = false;
LazySeg * l_child = NULL, * r_child = NULL;
LazySeg(int _l, int _r) {
l = _l;
r = _r;
if (r - l > 1) {
int m = (l + r) / 2;
l_child = new LazySeg(l, m);
r_child = new LazySeg(m, r);
}
}~LazySeg() {
delete l_child;
delete r_child;
}
void unlazy() {
if (!is_lazy) return;
val = (r - l) * tag;
if (r - l <= 1) return;
l_child -> tag = tag;
l_child -> is_lazy = true;
r_child -> tag = tag;
r_child -> is_lazy = true;
tag = 0;
is_lazy = false;
}
void update(int from, int to, int x) {
unlazy();
if (from >= r || l >= to) return;
if (from <= l && to >= r) {
tag = x;
is_lazy = true;
unlazy();
} else {
l_child -> update(from, to, x);
r_child -> update(from, to, x);
val = l_child -> val + r_child -> val;
}
}
int query(int from, int to) {
if (from >= r || l >= to) return 0;
unlazy();
if (from <= l && to >= r) return val;
else {
if (l_child == NULL) return 0;
return l_child -> query(from, to) + r_child -> query(from, to);
}
}
//pre = prefix in [l,k)
int max_right(int k, int pre, int v) {
unlazy();
if (r - l == 1) {
if (val == v) return l;
else return l - 1;
}
l_child -> unlazy();
int mid = (l + r) / 2;
if (mid <= k) {
return r_child -> max_right(k, pre - l_child -> val, v);
} else if (l_child -> val - pre == v * (mid - k)) {
//left to mid-1 has all 1's => answer must be >= mid-1
return r_child -> max_right(mid, 0, v);
} else {
return l_child -> max_right(k, pre, v);
}
}
//suff = suffix
int get_answer() {
unlazy();
if (r - l == 1) {
if (val == 1) return l;
else return l - 1;
}
r_child -> unlazy();
if (r_child -> val == 0) {
//[mid to end] are all 0
return l_child -> get_answer();
} else {
return r_child -> get_answer();
}
}
};
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int n, q;
cin >> n >> q;
LazySeg tr(0, 200100);
auto add = [ & ](int x) {
int y = tr.max_right(x, tr.query(0, x), 1) + 1;
if (y == x) { //no carry; just change 0 to 1
tr.update(x, x + 1, 1);
} else { //there is a carry; set the whole block of 1's to 0
tr.update(x, y, 0);
tr.update(y, y + 1, 1);
}
};
auto remove = [ & ](int x) {
int y = tr.max_right(x, tr.query(0, x), 0) + 1;
if (y == x) {
tr.update(x, x + 1, 0);
} else {
tr.update(x, y, 1);
tr.update(y, y + 1, 0);
}
};
vector < int > a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
add(a[i]);
}
while (q--) {
int k, l; cin >> k >> l;
k--;
remove(a[k]); add(l);
a[k] = l;
cout << tr.get_answer() << "\n";
}
}
|
1705
|
F
|
Mark and the Online Exam
|
Mark is administering an online exam consisting of $n$ true-false questions. However, he has lost all answer keys. He needs a way to retrieve the answers before his client gets infuriated.
Fortunately, he has access to the grading system. Thus, for each query, you can input the answers to all $n$ questions, and the grading system will output how many of them are correct.
He doesn't have much time, so he can use the grading system at most $675$ times. Help Mark determine the answer keys.
Note that answer keys are fixed in advance and will not change depending on your queries.
|
Unfortunately, a harder version of this problem has appeared in a Chinese contest here and here. You can look at their solution here. We thank many contestants who pointed it out. It's possible to solve this problem without any randomization. See the subsequent hints for how to do so. Observe that we can take differences between two very close queries to get the number of $\texttt{T}$'s in a small subsequence. You can take the difference against a pre-computed query. Applying this with a group of two questions. You have three possibilities: either $\texttt{TT}$, $\texttt{FF}$, and ${\texttt{TF}, \texttt{FT}}$. If the third possibility happens, simultaneously figure out whether is $\texttt{TF}$ or $\texttt{FT}$ and answer one question within one query. You will need to precompute the query $\texttt{TFTF}\dots\texttt{TF}$. There are many possible approaches, including using randomized algorithms. However, I will present the solution that takes about $\tfrac{2n}{3}$ queries deterministically. We pre-query $\texttt{TTT...T}$ and $\texttt{TFTF...TF}$. Then, for $i=1,2,\dots,\left\lfloor\frac n3\right\rfloor$, we take the difference when both the $(2i-1)$-th and the $2i$-th question in $\texttt{TTT...T}$ is changed to $\texttt{F}$. If the difference is $+2$, then both answers must be $\texttt F$. If the difference is $-2$, then both answers must be $\texttt T$. Else, the answers must be $\texttt{TF}$ or $\texttt{FT}$ in some order. Now, here is the key idea: if the last case happens, then we can figure out if it's $\texttt{TF}$ or $\texttt{FT}$ as well as the answer to one more question in one query. To do so, compare the previous $\texttt{TFTF...TF}$ with a new query that has $3$ differences: $\begin{align*} \\ \texttt{TFTF} \dots \texttt{TF} \dots \texttt{T} \dots \texttt{TF} \\ \texttt{TFTF} \dots \color{red}{\texttt{FT}} \dots \color{red}{\texttt F} \dots \texttt{TF} \end{align*}$ (Note: we assume that the third question corresponds to $\texttt T$ in the query. If it's $\texttt F$, just change to $\texttt T$ and proceed analogously.) There are four possible scenarios. If the answers are $\texttt{TF}$ and $\texttt{T}$, then the difference is $-3$. If the answers are $\texttt{TF}$ and $\texttt{F}$, then the difference is $-1$. If the answers are $\texttt{FT}$ and $\texttt{T}$, then the difference is $+1$. If the answers are $\texttt{FT}$ and $\texttt{F}$, then the difference is $+3$. Therefore, we can distinguish these four scenarios in one go. Finally, if the first two cases happen, we can easily figure out the answer to one more question in one query (say, by changing that question to $\texttt F$ and compare with the $\texttt{TT...T}$ query). Either way, we can deduce the answer to $3$ questions in $2$ queries, leading to a solution with $\tfrac{2n}{3}$ queries. Note that this solution can be easily improved to $\frac {3n}{5}$ on average by randomly shuffling the questions.
|
[
"bitmasks",
"constructive algorithms",
"interactive",
"probabilities"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
int n;
int query(string s){
cout << s << endl;
cout.flush();
int x; cin >> x;
if(x==n) exit(0);
return x;
}
int main(){
cin >> n;
//query true count
string all_T(n, 'T'), ans(n, '?');
int cnt_T = query(all_T);
//query TF
string all_TF(n, 'T');
for(int i=1; i<n; i+=2) all_TF[i] = 'F';
int cnt_TF = query(all_TF);
//begin the loop
int l = 0, r = n-1;
while(r >= l){
if(r==l){ //only l is undetermined
string s(all_T);
s[l] = 'F';
int k = query(s);
if(k > cnt_T){
ans[l] = 'F';
}
else{
ans[l] = 'T';
}
l++; r--;
}
else{
string s(all_T);
s[l] = 'F'; s[l+1] = 'F';
int k = query(s) - cnt_T;
if(k == 2){
ans[l] = 'F'; ans[l+1] = 'F';
l += 2;
}
else if(k == -2){
ans[l] = 'T'; ans[l+1] = 'T';
l += 2;
}
else{
if(r == l+1){ //only l and l+1 left; figure out the order
string s(all_T);
s[l] = 'F';
int k = query(s);
if(k > cnt_T){
ans[l] = 'F'; ans[l+1] = 'T';
}
else{
ans[l] = 'T'; ans[l+1] = 'F';
}
l += 2;
}
else{ //determine l, l+1, r
string s(all_TF);
s[l] = 'F'; s[l+1] = 'T';
if(s[r] == 'F') s[r] = 'T';
else s[r] = 'F';
int k = query(s) - cnt_TF;
if(k == 3){
ans[l] = 'F'; ans[l+1] = 'T'; ans[r] = s[r];
}
else if(k == 1){
ans[l] = 'F'; ans[l+1] = 'T'; ans[r] = all_TF[r];
}
else if(k == -1){
ans[l] = 'T'; ans[l+1] = 'F'; ans[r] = s[r];
}
else{
ans[l] = 'T'; ans[l+1] = 'F'; ans[r] = all_TF[r];
}
l += 2; r--;
}
}
}
}
query(ans);
}
|
1706
|
A
|
Another String Minimization Problem
|
You have a sequence $a_1, a_2, \ldots, a_n$ of length $n$, consisting of integers between $1$ and $m$. You also have a string $s$, consisting of $m$ characters B.
You are going to perform the following $n$ operations.
- At the $i$-th ($1 \le i \le n$) operation, you replace either the $a_i$-th \textbf{or} the $(m + 1 - a_i)$-th character of $s$ with A. You can replace the character at any position multiple times through the operations.
Find the lexicographically smallest string you can get after these operations.
A string $x$ is lexicographically smaller than a string $y$ of the same length if and only if in the first position where $x$ and $y$ differ, the string $x$ has a letter that appears earlier in the alphabet than the corresponding letter in $y$.
|
Let's iterate through the elements of $a$. For convenience, we'll make $a_i = \min(a_i, m + 1 - a_i)$. If the $a_i$-th character of $s$ is not currently A, then we should replace it. Otherwise, we replace the $(m+1-a_i)$-th character. This is because if we have the choice between replacing two characters, replacing the one with the smaller index will result in a lexicographically smaller string. Alternatively, we can keep track of how many times either $x$ or $m + 1 - x$ appears in $a$ for each $1 \le x \le \lceil \frac{m}{2} \rceil$. If they appear $0$ times, neither of these indices in $s$ can become A. If they appear $1$ time, it is optimal to set the $x$-th character to A, since this will produce a lexicographically smaller string. Otherwise, they appear at least $2$ times, and it is possible to set both the $x$-th and $(m + 1 - x)$-th character to A.
|
[
"2-sat",
"constructive algorithms",
"greedy",
"string suffix structures",
"strings"
] | 800
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
const int MAXN = 55;
int t, n, m;
int cnt[MAXN];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 0; i < m; i++)
cnt[i] = 0;
for (int i = 0; i < n; i++) {
int x; cin >> x;
x--;
x = min(x, m - 1 - x);
cnt[x]++;
}
string ans(m, 'B');
for (int i = 0; i < m; i++) {
if (!cnt[i]) continue;
ans[i] = 'A';
if (cnt[i] > 1)
ans[m - 1 - i] = 'A';
}
cout << ans << "\n";
}
}
|
1706
|
B
|
Making Towers
|
You have a sequence of $n$ colored blocks. The color of the $i$-th block is $c_i$, an integer between $1$ and $n$.
You will place the blocks down in sequence on an infinite coordinate grid in the following way.
- Initially, you place block $1$ at $(0, 0)$.
- For $2 \le i \le n$, if the $(i - 1)$-th block is placed at position $(x, y)$, then the $i$-th block can be placed at one of positions $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$ (\textbf{but not at position $(x, y - 1)$}), as long no previous block was placed at that position.
A tower is formed by $s$ blocks such that they are placed at positions $(x, y), (x, y + 1), \ldots, (x, y + s - 1)$ for some position $(x, y)$ and integer $s$. The size of the tower is $s$, the number of blocks in it. A tower of color $r$ is a tower such that all blocks in it have the color $r$.
For each color $r$ from $1$ to $n$, solve the following problem \textbf{independently}:
- Find the maximum size of a tower of color $r$ that you can form by placing down the blocks according to the rules.
|
When can two blocks of the same color form two consecutive elements of a tower? Formally, if we have two blocks of the same color at indices $i$ and $j$ such that $i < j$, how can we tell if it is possible to place them at $(x_i, y_i)$ and $(x_i, y_i + 1)$ respectively? As it turns out, they can be placed like this if and only if $i$ and $j$ have different parities. First, if they have the same parity, it is impossible to place them this way. Note that $x_i + y_i$ must have a different parity from $x_{i + 1} + y_{i + 1}$, since these sums must differ by exactly $1$. So, if $i$ and $j$ have the same parity, then $x_i + y_i$ must also have the same parity as $x_j + y_j$. But we want them to be vertically adjacent, which is not possible if their parities must be the same. So, it is impossible to make two blocks with indices of the same parity adjacent to each other. Next, there is a valid construction if you want to put blocks $i$ and $j$ together when they have different parities. Say that block $i$ will go at position $(x_i, y_i)$ and block $j$ goes at position $(x_i, y_{i}+1)$. If $j=i+1$, then we are done. Now, let's say that $j=i+3$. Then, we can place block $i+1$ at $(x_i+1,y_i)$ and block $j-1$ at position $(x_i+1,y_{i}+1)$. What if $j=i+5$? Then we can do the same as the previous case, and then put block $i+2$ at $(x_i+2,y_i)$ and block $j-2$ at $(x_i+2,y_i+1)$. Essentially, we are making the blocks between $i$ and $j$ into a horizontal line extending out for $\frac{j-i-1}{2}$ blocks then coming back in. If there are already blocks to the right of $(x_i, y_i)$, then we can do the same construction but extending out to the left. Note that since we cannot move down, at least one of the right and left side must be open. There are two ways we can go from here: First, there is a DP solution. Let's imagine the naive $\mathcal{O}(n^2)$ dp: We say that $dp[i][c]$ is the maximum size of a tower with color $c$, such that the last block placed was at index $i$. The transitions look like this: $dp[i][c_i] = \max\limits_{j < i, j \not \equiv i \pmod 2}(dp[j][c_i] + 1)$. We check all $j < i$ such that $j$ and $i$ have different parities, then see if adding a block to this tower makes a better solution. To optimize it, we can notice that for the first DP dimension (index), only the parity of the index matters - for each color, we just need to keep track of the maximum $dp[i][c]$ for even and odd $i$. We will iterate through all blocks $a_i$, maintaining $dp[p][c]$, which contains the maximum size of a tower with color $c$, where the last block included in the tower had an index with parity $p$ ($p=0$ indicates an even index, $p=1$ indicates an odd index). If the current index is even, we set $dp[0][c_i] = \max(dp[0][c_i], dp[1][c_i] + 1)$. If it is odd, we set $dp[1][c_i] = \max(dp[1][c_i], dp[0][c_i] + 1)$. The solution runs in linear time. Alternatively, there's a greedy solution. After selecting a block, the next block selected must always have the opposite parity. Therefore, it makes sense to greedily select the first block of the same color with opposite parity, since it will never improve the answer if we select a later block. For each color, we start from the first block and iterate through, adding each block to the sequence if and only if it has a different parity from the last one.
|
[
"dp",
"greedy",
"math"
] | 1,100
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
const int MAXN = 100100;
int t, n;
vector<int> a[MAXN];
int solve(int x) {
if (!a[x].size()) return 0;
int curr = a[x][0];
int ans = 1;
for (int i : a[x]) {
if ((i & 1) != (curr & 1)) {
ans++;
curr = i;
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++)
a[i].clear();
for (int i = 1; i <= n; i++) {
int x; cin >> x;
a[x].push_back(i);
}
for (int i = 1; i <= n; i++)
cout << solve(i) << " \n"[i == n];
}
}
|
1706
|
C
|
Qpwoeirut And The City
|
Qpwoeirut has taken up architecture and ambitiously decided to remodel his city.
Qpwoeirut's city can be described as a row of $n$ buildings, the $i$-th ($1 \le i \le n$) of which is $h_i$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $i$ is taller than the building $j$ if and only if the number of floors $h_i$ in building $i$ is larger than the number of floors $h_j$ in building $j$.
Building $i$ is cool if it is taller than both building $i-1$ and building $i+1$ (and both of them exist). Note that neither the $1$-st nor the $n$-th building can be cool.
To remodel the city, Qpwoeirut needs to maximize the number of cool buildings. To do this, Qpwoeirut can build additional floors on top of any of the buildings to make them taller. Note that he cannot remove already existing floors.
Since building new floors is expensive, Qpwoeirut wants to minimize the number of floors he builds. Find the minimum number of floors Qpwoeirut needs to build in order to maximize the number of cool buildings.
|
The first observation to be made is that no two adjacent building can both be cool at the same time. This means that, for odd $n$, there must be $\frac{n-1}{2}$ cool buildings arranged in the following configuration... 01010...01010(0 - normal (not cool) building, 1 - cool building) For even $n$, there must be $\frac{n-2}{2}$ cool buildings. This means that exactly one pair of adjacent buildings in the city is normal, meaning that the buildings must be arranged in one of the following configurations... 01010...01010001010...01001001010...001010$\vdots$010100...01010010010...01010001010...01010(0 - normal (not cool) building, 1 - cool building) For odd $n$, the solution is relatively simple. Just find the total floors necessary to make each of the alternating buildings (starting from the 2nd building) cool and that is the answer. For even $n$, the solution is more complex. First, find the number of floors necessary to get to the first of the configurations shown above. Then, loop through each of the subsequent configurations, each time using the previous configuration to get the number of floors necessary for the new configuration in $O(1)$ time. This enables a solution in $O(n)$ time. For example, in the 4th test case from the example in the problem statement, the possible configurations of cool buildings are... 4 2 1 3 5 3 6 14 2 1 3 5 3 6 14 2 1 3 5 3 6 14 2 1 3 5 3 6 1(light - normal (not cool) building, bold - cool building) The number of floors necessary to reach each of these configurations are... 1st configuration: (5 - 2) + (6 - 3) + (7 - 3) = 10. 2nd configuration: 10 - (7 - 3) + (6 - 6) = 6. 3rd configuration: 6 - (6 - 3) + (5 - 5) = 3. 4th configuration: 3 - (5 - 2) + (4 - 1) = 3. The answer is the minimum of these values, which is $3$. For even $n$, the floors necessary for every configuration can also be found in $O(n)$ time using an alternating forward prefix sum array and an alternating backward prefix sum array.
|
[
"dp",
"flows",
"greedy",
"implementation"
] | 1,400
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
const int MAXN = 100100;
int t, n;
ll a[MAXN];
ll get(int i) {
return max(0ll, max(a[i - 1], a[i + 1]) - a[i] + 1);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
if (n & 1) {
ll ans = 0;
for (int i = 2; i < n; i += 2)
ans += get(i);
cout << ans << "\n";
continue;
}
ll tot = 0;
for (int i = 2; i < n; i += 2)
tot += get(i);
ll ans = tot;
for (int i = n - 1; i > 1; i -= 2) {
tot -= get(i - 1);
tot += get(i);
ans = min(ans, tot);
}
cout << ans << "\n";
}
}
|
1706
|
D1
|
Chopping Carrots (Easy Version)
|
\url{CDN_BASE_URL/51167bab54119df1f721947703725ebd}
|
Let's iterate over integers $v = 0, 1, \ldots, a_1$. We'll construct an answer assuming that the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$ is at least $v$. For all $1 \le i \le n$, we set $p_i = \min(k, \lfloor \frac{a_i}{v} \rfloor)$: the maximum value $p_i$ such that $1 \le p_i \le k$ and $v \le \lfloor \frac{a_i}{p_i} \rfloor$ (if $v = 0$ we can just set $p_i = k$)). Now, we find the value of $\max\limits_{1 \le i \le n}(\lfloor\frac{a_i}{p_i}\rfloor ) - v$. This gives the answer when the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$ is $v$. Finally, we compute this for all $0 \le v \le a_1$. This gives a $\mathcal{O}(n \cdot a_1)$ time solution per test case.
|
[
"binary search",
"brute force",
"constructive algorithms",
"greedy",
"number theory"
] | 1,700
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
const int MAXN = 3030;
int t, n, k;
int a[MAXN];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> t;
while (t--) {
cin >> n >> k;
for (int i = 0; i < n; i++)
cin >> a[i];
int ans = 1e9;
for (int v = 1; v <= a[0]; v++) {
int cm = v;
for (int i = 0; i < n; i++) {
int p = min(k, (v ? (a[i] / v) : k));
cm = max(cm, a[i] / p);
}
ans = min(ans, cm - v);
}
cout << ans << "\n";
}
}
|
1706
|
D2
|
Chopping Carrots (Hard Version)
|
This is the hard version of the problem. The only difference between the versions is the constraints on $n$, $k$, $a_i$, and the sum of $n$ over all test cases. You can make hacks only if both versions of the problem are solved.
\textbf{Note the unusual memory limit.}
You are given an array of integers $a_1, a_2, \ldots, a_n$ of length $n$, and an integer $k$.
The cost of an array of integers $p_1, p_2, \ldots, p_n$ of length $n$ is $$\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).$$
Here, $\lfloor \frac{x}{y} \rfloor$ denotes the integer part of the division of $x$ by $y$. Find the minimum cost of an array $p$ such that $1 \le p_i \le k$ for all $1 \le i \le n$.
|
Solution 1 Let's fix $v$, the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$. Then, for all $1 \le i \le n$, we find the maximum value $p_i$ such that $p_i \le k$ and $\lfloor \frac{a_i}{p_i} \rfloor \ge v$. For some minimum value $v$, let's call the array described above $P(v)$, and let's define $M(v) = \max\limits_{1 \le i \le n} \lfloor \frac{a_i}{P(v)_i} \rfloor$. We can find the answer by taking the minimum of $M(v) - v$ across all $0 \le v \le a_1$, giving a $O(n \cdot a_i)$ solution. To speed it up, let's consider how some element $a_i$ will affect the values of $M(v)$. First, notice that $\lfloor \frac{a_i}{q} \rfloor$ (where $1 \le q \le k$) can take on at most $O(\min(k,\sqrt{a_i}))$ distinct values. Let's denote these values (in increasing order) $s_1, s_2, s_3, \ldots, s_x$. Consider what happens when $v \le s_1$. Then, $M(v)$ must be at least $s_1$. What about when $s_1 < v \le s_2$? Then, $M(v)$ must be at least $s_2$. And so on, until $s_{x - 1} < v \le s_x$, where $M(v)$ must be at least $s_x$. This way, we can get lower bounds on value of $M(v)$. It is easy to see that the highest of these bounds is achievable. Let's iterate over array $a$. Let $m[v]$ (here, $m = m[0], m[1], m[2], \ldots, m[a_1]$ is an array of length $a_1 + 1$) be the highest of lower bounds on $M(v)$ we already found. Initially, $m[v] = 0$ for all $v$. When we are dealing with $a_i$ we want to do the following: For all $0 \le j \le x - 1$, we want to update $m[y] = \max(m[y], s_{j+1})$ for all $s_{j} + 1 \le y \le s_{j + 1}$ (for convenience we define $s_0 = -1$). Since $s_0 < s_1 < s_2 < \ldots < s_x$, this can be done without any fancy data structures - instead of updating all these ranges directly, we can set $m[s_j + 1] = \max(m[s_j + 1], s_{j+1}])$, so that $M(v)$ will be equal to $\max(m[0], m[1], \ldots, m[v])$. Then, once $m$ is computed, we can sweep through to find all values of $M(v)$ in with prefix maxes. Once we have $m$ computed, we can find $M(v) - v$ for all $0 \le v \le a_1$ in linear time. This gives a $\mathcal{O}(\sum\limits_{1 \le i \le n}\min(k, \sqrt{a_i}) + a_1)$ solution per test case, with total $\mathcal{O}(n + \max_a)$ memory across all tests. Solution 2 (AlperenT) Now, let's fix $v$ as the maximum value of $\lfloor \frac{a_i}{p_i} \rfloor$. We now want to maximize the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$. Let's now consider all elements $a_i$ that satisfy $1 \le a_i \le v$. For these elements, it will be optimal to set $p_i = 1$, since we want to maximize them. How about elements $a_i$ satisfying $v + 1 \le a_i \le 2(v+1) - 1$? We need to have $\lfloor \frac{a_i}{p_i} \rfloor \le v$, so for these elements, we must have $p_i \ge 2$. At the same time, we want to maximize them - so it will be optimal to set all these $p_i = 2$. Continuing this logic, for all integers $u = 1, 2, \ldots, k$, we should check the elements $a_i$ satisfying $(u-1)\cdot (v + 1) \le a_i \le u \cdot (v+1)$, and set all these $p_i = u$. How can we determine the minimum value of $\lfloor \frac{a_i}{p_i} \rfloor$ from this? For a fixed $u$, the minimum $\lfloor \frac{a_i}{u} \rfloor$ will come from the minimum $a_i$. So if we can determine the minimum $a_i$ such that $(u-1)\cdot (v + 1) \le a_i \le u \cdot (v+1)$, and calculate these values across all $u = 1, 2, \ldots, k$, then we will get the answer. To help us, let's precompute an array $next_1, next_2, \ldots, next_{a_n}$. $next_j$ will store the minimum value of $a_i$ such that $a_i \ge j$. Now, for a fixed $u$, we can check $next_{(u-1) \cdot v + 1}$. If this value is less than or equal to $u \cdot v$, it will be the minimum $a_i$ that we divide by $u$. Two important details: If there exists some $a_i \ge (v + 1) \cdot k$, then it is impossible to have the max element as $v$, and we should skip it. For some value $v$, we only need to check $u$ such that $(u-1)\cdot v + 1 \le a_n$. Using this second detail, the solution runs in $\mathcal{O}\left( \sum\limits_{i = 1}^{a_n}\frac{a_n}{i} \right) = \mathcal{O}(a_n \cdot \log(a_n))$ time per test case. The memory usage is $\mathcal{O}(n + \max_a)$ across all tests.
|
[
"brute force",
"constructive algorithms",
"data structures",
"dp",
"greedy",
"math",
"number theory",
"two pointers"
] | 2,400
|
// AUTHOR: AlperenT
#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5, INF = (long long)2e18 + 5;
long long t, n, k, arr[N], closest[N], mn, ans;
vector<pair<long long, long long>> v;
void solve(){
ans = INF;
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> arr[i];
arr[0] = -1;
for(int i = 1; i <= n; i++){
fill(closest + arr[i - 1] + 1, closest + arr[i] + 1, arr[i]);
}
fill(closest + arr[n] + 1, closest + N, INF);
for(int mx = 1; mx <= 100000; mx++){
v.clear();
v.push_back({1, mx});
for(int i = 2; i <= k; i++){
v.push_back({v.back().second + 1, 1ll * (mx + 1) * i - 1});
if(v.back().second > arr[n]) break;
}
if(v.back().second >= arr[n]){
mn = INF;
for(int i = 0; i < v.size(); i++){
int nxt = closest[v[i].first];
if(nxt <= v[i].second) mn = min(mn, nxt / (i + 1ll));
}
assert(mn <= mx);
ans = min(ans, mx - mn);
}
}
cout << ans << "\n";
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);
cin >> t;
while(t--){
solve();
}
}
|
1706
|
E
|
Qpwoeirut and Vertices
|
You are given a connected undirected graph with $n$ vertices and $m$ edges. Vertices of the graph are numbered by integers from $1$ to $n$ and edges of the graph are numbered by integers from $1$ to $m$.
Your task is to answer $q$ queries, each consisting of two integers $l$ and $r$. The answer to each query is the smallest non-negative integer $k$ such that the following condition holds:
- For all pairs of integers $(a, b)$ such that $l\le a\le b\le r$, vertices $a$ and $b$ are reachable from one another using only the first $k$ edges (that is, edges $1, 2, \ldots, k$).
|
If $l = r$, answer is $0$. From now on we assume $l < r$. Say we have a function $f(i)$ that tells us for some $2 \le i \le n$ the answer for the query $[i - 1, i]$. Then for some query $[l, r]$, the answer will be $k = \max(f(l+1), f(l+2), \ldots, f(r-1), f(r))$. This is true because: Since all consecutive nodes are connected, the first $k$ edges will be sufficient to connect all nodes $l, l+1, \ldots, r$. Say that it is possible to connect these nodes using the first $k'$ edges ($k' < k$). We know that there is at least $1$ index $l + 1 \le i \le r$ such that $f(i) = k$. But if the answer for this query is $k'$, then it must be true that $f(i) \le k'$ (because we can reach vertex $i - 1$ from vertex $i$ using only the first $k'$ edges then). Then, we have $f(i) \le k' < k = f(i)$, which is a contradiction. So if we precompute the values of $f(i)$ for all $2 \le i \le n$, we can answer any query efficiently using a range max query structure (for example, a sparse table or segment tree). Here's how to find $f(i)$: Weight the edges, so that the $i$-th edge has a weight $i$. Find the unique minimum spanning tree of this weighted graph. $f(i)$ will be the maximum weight of an edge on the path from $i - 1$ to $i$. This will always give the correct value for $f(i)$ since edges not in the MST are useless. Let's imagine building the MST with Kruskal's: if we don't add the $W$-th edge, that means that the first $W-1$ edges are sufficient to connect $u_W$ and $v_W$, and we can use those instead to get a better answer. On the resulting tree, the optimal way to connect any two nodes is to use the edges on the simple shortest path between them. Finding the max edge weight in a path on a tree can be done, for example, with binary lifting: for each node we store the maximum weight on the path to the root with length $1$, $2$, $4$, $8$, and so on. Then, we can find the max edge weight on the path from any two nodes to their LCA in $\mathcal O(\log(n))$. Instead of using binary lifting, we can also directly represent the MST in the DSU. After successfully merging two components rooted at $u$ and $v$ in the DSU, we add an edge $(u, v)$ with the weight being the edge number from the input. $f(i)$ will then be the maximum edge from $i-1$ to $i$ in the newly constructed tree. We can just walk up the tree since the maximum depth is at most $\mathcal O(\log n)$ assuming the DSU implementation uses small-to-large merging. This gives an $\mathcal O((m+q)\log(n))$ or $\mathcal O(m\log(n) + q)$ solution, depending on the implementation.
|
[
"binary search",
"data structures",
"dfs and similar",
"divide and conquer",
"dsu",
"greedy",
"trees"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
struct dsu {
vector<int> ds, wt;
dsu(int n) {
ds.assign(n, -1);
wt.assign(n, INT_MAX);
}
int find(int i) {
return ds[i] < 0 ? i : find(ds[i]);
}
void merge(int i, int j, int weight) {
i = find(i), j = find(j);
if (i != j) {
if (ds[i] > ds[j])
swap(i, j);
ds[i] += ds[j], ds[j] = i;
wt[j] = weight;
}
}
int weight(int i, int j) {
int w = 0;
while (i != j) {
if (wt[i] < wt[j])
w = wt[i], i = ds[i];
else
w = wt[j], j = ds[j];
}
return w;
}
};
struct segtree {
vector<int> tr; int n;
segtree(vector<int> v) {
n = v.size();
tr.resize(n * 2);
for (int i = 0; i < n; i++)
tr[n + i] = v[i];
for (int i = n - 1; i > 0; i--)
pull(i);
}
void pull(int i) {
tr[i] = max(tr[i * 2], tr[i * 2 + 1]);
}
int query(int l, int r) {
int x = 0;
for (l += n, r += n; l <= r; l /= 2, r /= 2) {
if (l & 1)
x = max(x, tr[l++]);
if (~r & 1)
x = max(x, tr[r--]);
}
return x;
}
};
void run() {
int n, m, q;
scanf("%d%d%d", &n, &m, &q);
dsu ds(n);
for (int w = 1; w <= m; w++) {
int i, j;
scanf("%d%d", &i, &j), i--, j--;
ds.merge(i, j, w);
}
vector<int> weights(n - 1);
for (int i = 0; i < n - 1; i++)
weights[i] = ds.weight(i, i + 1);
segtree st(weights);
while (q--) {
int l, r;
scanf("%d%d", &l, &r), l--, r--;
printf("%d ", l == r ? 0 : st.query(l, r - 1));
}
printf("\n");
}
int main() {
int t = 1;
scanf("%d", &t);
while (t--)
run();
return 0;
}
|
1707
|
A
|
Doremy's IQ
|
Doremy is asked to test $n$ contests. Contest $i$ can only be tested on day $i$. The difficulty of contest $i$ is $a_i$. Initially, Doremy's IQ is $q$. On day $i$ Doremy will choose whether to test contest $i$ or not. She can only test a contest if her current IQ is strictly greater than $0$.
If Doremy chooses to test contest $i$ on day $i$, the following happens:
- if $a_i>q$, Doremy will feel she is not wise enough, so $q$ decreases by $1$;
- otherwise, nothing changes.
If she chooses not to test a contest, nothing changes.Doremy wants to test as many contests as possible. Please give Doremy a solution.
|
Solution 1 We call contests that will decrease Doremy's IQ bad contests and the other good contests. In the best solution(testing the maximum number of contests), there is always an index $x$. Contest $i$ ($i < x$) is tested, if Contest $i$ is good; Contest $i$ ($i \ge x$) is tested, no matter what kind of contest it is. How to prove that this conclusion? For any choice, we can find the last contest $a$ that is not tested and the first bad contest $b$ that is tested. If $b<a$, we can give up contest $b$ and choose to test contest $a$, and the number of contests that is tested does not change. If $b>a$, there is already an valid $x$. When $x$ is smallest, you can get the best solution. And we can find the smallest $x$ by binary search. Time complexity $O(n \log n)$. Solution 2 Consider everything in the reverse order. Assume that Doremy has $Q=0$ IQ in the end. Consider whether a contest should be tested in the reverse order. $a_i\le Q$. Doremy should tested the contest because there is no decrease in her IQ. $a_i > Q$ and $Q < q$. If Doremy tests the contest, her IQ will decrease by $1$, so in the reverse order, her IQ increases by $1$; otherwise she just skipped the contest and nothing happened. Doremy can test at most $q$ contest with the $a_i>Q$ property. But if Doremy gets more IQ, she can participate more previous good contests. So she should test this contest. If $a_i > Q$ and $Q=q$, Doremy cannot test the contest because her IQ is not enough. So you can determine whether every contest should be tested. Time complexity $O(n)$.
|
[
"binary search",
"constructive algorithms",
"greedy",
"implementation"
] | 1,600
|
#include<cstdio>
int a[100005],b[100005];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n,iq;
scanf("%d%d",&n,&iq);
for(int i=1;i<=n;++i)
scanf("%d",&a[i]);
int sum=0,nq=0;
for(int i=n;i>=1;--i){
if(a[i]<=nq)b[i]=1;
else if(nq<iq)++nq,b[i]=1;
else b[i]=0;
}
for(int i=1;i<=n;++i)
printf("%d",b[i]);
puts("");
}
return 0;
}
|
1707
|
B
|
Difference Array
|
You are given an array $a$ consisting of $n$ non-negative integers. It is guaranteed that $a$ is sorted from small to large.
For each operation, we generate a new array $b_i=a_{i+1}-a_{i}$ for $1 \le i < n$. Then we sort $b$ from small to large, replace $a$ with $b$, and decrease $n$ by $1$.
After performing $n-1$ operations, $n$ becomes $1$. You need to output the only integer in array $a$ (that is to say, you need to output $a_1$).
|
Let's prove that the brute-force solution (considering zeros differently) can pass. Define $S=\sum\limits_{i=1}^{n} a_i$ and it changes when an operation is performed. After sorting the array $a$ and ignoring $0$ s, the fact $\begin{aligned} n-1+a_n &\le S & (a_i \ge 1)\\ n-1 &\le S - a_n \end{aligned}$ is always true. And after performing one operation, $S = a_n-a_1\le a_n$. So in each operation, you cost $O(n \log n)$ time to sort the new array and decrease $S$ by at least $n-1$. After the first operation, $S$ is $O(a_n)$. The complexity is $O(A \log A)$, where $A=\max\{n,a_n\}$.
|
[
"brute force",
"data structures",
"implementation",
"sortings"
] | 1,900
|
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;
}
template<typename T>void write(T x){
static char q[65];int cnt=0;
if(x<0)pc('-'),x=-x;
q[++cnt]=x%10,x/=10;
while(x)
q[++cnt]=x%10,x/=10;
while(cnt)pc(q[cnt--]+'0');
}
const int maxn=100005;
int a[maxn];
int main(){
int T;read(T);
while(T--){
int n;read(n);
for(int i=1;i<=n;++i)read(a[i]);
for(int i=n-1;i>=1;--i){
int pre=a[i+1],ok=false;
for(int j=i;j>=1;--j){
ok=(a[j]==0);
pre-=(a[j]=pre-a[j]);
if(ok){
sort(a+j,a+i+1);
break;
}
}
if(!ok)
sort(a+1,a+i+1);
}
write(a[1]),pc('\n');
}
return 0;
}
/*
_|_|_|_| _|_| _| _| _|_|_|_|_| _|_|_|_|_| _|
_| _| _| _| _|_| _| _| _| _|
_| _| _| _| _| _| _| _| _| _|
_| _| _|_|_|_|_| _| _| _| _| _|_|_|_|_| _|
_| _| _| _| _| _| _| _| _| _|
_| _| _| _| _| _|_| _| _| _|
_|_|_|_| _| _| _| _| _|_|_|_|_| _|_|_|_|_| _|_|_|_|_|
_|_|_|_|_| _| _| _|_|_|_| _| _|
_| _| _| _| _| _| _|
_| _| _| _| _| _| _|
_| _|_| _| _| _|_|
_| _| _| _| _| _|
_| _| _| _| _| _|
_| _| _| _|_|_|_| _|
_| _|_|_| _| _| _|_|_|_|_|
_| _| _| _| _| _|
_| _| _| _| _| _|
_| _| _| _| _| _|_|_|_|_|
_| _| _| _| _| _|
_| _| _| _|_| _|
_|_|_|_|_| _|_|_| _| _|_|_|_|_|
_|_|_|_|_| _| _| _|_|_|_|_|
_| _| _| _|
_| _| _| _|
_| _|_| _|
_| _| _|
_| _| _|
_| _| _|
Created by xiaolilsq.
*/
|
1707
|
C
|
DFS Trees
|
You are given a connected undirected graph consisting of $n$ vertices and $m$ edges. The weight of the $i$-th edge is $i$.
Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:
\begin{verbatim}
vis := an array of length n
s := a set of edges
function dfs(u):
vis[u] := true
iterate through each edge (u, v) in the order from smallest to largest edge weight
if vis[v] = false
add edge (u, v) into the set (s)
dfs(v)
function findMST(u):
reset all elements of (vis) to false
reset the edge set (s) to empty
dfs(u)
return the edge set (s)
\end{verbatim}
Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
|
Minimum spanning tree is unique in the given graph. If $\operatorname{findMST}$(x) creates an MST, there is no cross edge in the graph. So if you can determine whether there is a cross edge starting DFS from every node, the problem is solved. Pay attention to every edge that is not in the MST. Let's focus on one single edge $(u,v)$ and see starting DFS from which node, $(u,v)$ is a cross edge. Take the following graph as an example. If we start from nodes $a$, $b$, $c$, $d$, $e$ or $f$, $(u,v)$ is a cross edge. If we start from nodes $t$, $u$, $o$ or $v$, $(u,v)$ is not a cross edge. We can find that when considering $u$ as the root of the tree, $o$ and $v$ are on the subtree of $v$. When considering $v$ as the root of the tree, $t$ and $u$ are on the subtree of $u$. So if an edge $(u,v)$ is not in the MST, only the subtree of $u$($u$ included, when considering $v$ as the root) and the subtree of $v$($v$ included, when considering $u$ as the root) can be answers. We just need to do this process for each edge not in the MST. After that we can get the answers. We can finish the process in $O(n\log n)$ with bin-up on tree and BIT or in $O(n)$ with some case work while dfs.
|
[
"dfs and similar",
"dsu",
"graphs",
"greedy",
"sortings",
"trees"
] | 2,400
|
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;
}
template<typename T>void write(T x){
static char q[65];int cnt=0;
if(x<0)pc('-'),x=-x;
q[++cnt]=x%10,x/=10;
while(x)
q[++cnt]=x%10,x/=10;
while(cnt)pc(q[cnt--]+'0');
}
const int maxn=100005,maxm=200005;
int par[maxn];
int AC(int x){
return par[x]==x?x:par[x]=AC(par[x]);
}
struct Edge{
int v,nt;
Edge(int v=0,int nt=0):
v(v),nt(nt){}
}e[maxn*2],es[maxm];
int hd[maxn],num;
void qwq(int u,int v){
e[++num]=Edge(v,hd[u]),hd[u]=num;
}
int dp[maxn];
int pa[maxn][20];
void dfs(int u,int p){
pa[u][0]=p;
for(int j=1;(1<<j)<=dp[u];++j)
pa[u][j]=pa[pa[u][j-1]][j-1];
for(int i=hd[u];i;i=e[i].nt){
int v=e[i].v;
if(v==p)continue;
dp[v]=dp[u]+1;dfs(v,u);
}
}
int jump(int x,int t){
for(int cn=0;t;t>>=1,++cn)
if(t&1)x=pa[x][cn];
return x;
}
int lca(int x,int y){
if(dp[x]>dp[y])x=jump(x,dp[x]-dp[y]);
if(dp[y]>dp[x])y=jump(y,dp[y]-dp[x]);
if(x==y)return x;
for(int t=19;t>=0;--t)
if(pa[x][t]!=pa[y][t])
x=pa[x][t],y=pa[y][t];
return pa[x][0];
}
int vis[maxn];
char s[maxn];
void pushdown(int u,int p){
if(vis[u]==0)s[u]='1';
else s[u]='0';
for(int i=hd[u];i;i=e[i].nt){
int v=e[i].v;
if(v==p)continue;
vis[v]+=vis[u];
pushdown(v,u);
}
}
int main(){
int n,m;
read(n),read(m);
for(int i=1;i<=n;++i)
par[i]=i;
int tp=0;
for(int i=1;i<=m;++i){
int u,v;
read(u),read(v);
if(AC(u)==AC(v)){
es[++tp]=Edge(u,v);
}
else{
par[AC(u)]=AC(v);
qwq(u,v),qwq(v,u);
}
}
int root=1;
dfs(root,0);
for(int i=1;i<=tp;++i){
int u=es[i].v,v=es[i].nt;
if(dp[u]>dp[v])u^=v^=u^=v;
int w=lca(u,v);
if(u==w){
--vis[v];
++vis[jump(v,dp[v]-dp[u]-1)];
}
else{
++vis[root];
--vis[u];
--vis[v];
}
}
pushdown(root,0);
s[n+1]='\0';
printf("%s\n",s+1);
return 0;
}
|
1707
|
D
|
Partial Virtual Trees
|
Kawashiro Nitori is a girl who loves competitive programming. One day she found a rooted tree consisting of $n$ vertices. The root is vertex $1$. As an advanced problem setter, she quickly thought of a problem.
Kawashiro Nitori has a vertex set $U=\{1,2,\ldots,n\}$. She's going to play a game with the tree and the set. In each operation, she will choose a vertex set $T$, where $T$ is a partial virtual tree of $U$, and change $U$ into $T$.
A vertex set $S_1$ is a partial virtual tree of a vertex set $S_2$, if $S_1$ is a subset of $S_2$, $S_1 \neq S_2$, and for all pairs of vertices $i$ and $j$ in $S_1$, $\operatorname{LCA}(i,j)$ is in $S_1$, where $\operatorname{LCA}(x,y)$ denotes the lowest common ancestor of vertices $x$ and $y$ on the tree. Note that a vertex set can have many different partial virtual trees.
Kawashiro Nitori wants to know for each possible $k$, if she performs the operation \textbf{exactly} $k$ times, in how many ways she can make $U=\{1\}$ in the end? Two ways are considered different if there exists an integer $z$ ($1 \le z \le k$) such that after $z$ operations the sets $U$ are different.
Since the answer could be very large, you need to find it modulo $p$. It's guaranteed that $p$ is a prime number.
|
First ignore the requirement that the virtual tree cannot be the entire tree. Then we count the number of ways without this requirement for all $k$ using DP. $dp_{x,i}$ is the number of ways to delete everything in the subtree of $x$ in exact $i$ operations. Node $x$ must be deleted at some time $j \le i$ and all but at most one child subtree of $x$ must be deleted before time $j$. Let: $C_x$ be the set of $x$'s children. $S_{x,i}=\sum_{j\le i} dp_{x,i}$ $D_{x,j}=\prod_{u\in C(x)}S_{u,j}$ Then $\begin{aligned} dp_{x,i} &=\sum_{j < i}\sum_{u\in C_x}\dfrac{dp_{u,i}D_{x,j}}{S_{u,j}} + \prod_{u\in C_x} S_{u,i}\\ &=\sum_{u \in C_x}dp_{u,i} \sum_{j < i} \dfrac{D_{x,j}}{S_{u,j}}+\prod_{u \in C_x}S_{u,i} \end{aligned}$ Specially, when $x$ is root ($x=1$), $x$ is the last one to be deleted. So $dp_{x,i}=\prod_{u\in C_x} S_{u,i}$ in this case. It's not hard to computer this with prefix sums in $O(n^2)$ time. Then consider the requirement that the virtual tree cannot be the entire tree. Let the real answer be $Ans_k$. Then $\begin{aligned} dp_{1,i} &= \sum_{j=0}^{i} \binom{i}{j}Ans_j \\ Ans_i &= dp_{1,i} - \sum_{j=0}^{i-1} \binom{i}{j} Ans_j \end{aligned}$ So we can figure out the real answer in $O(n^2)$ time.
|
[
"combinatorics",
"dfs and similar",
"dp",
"math",
"trees"
] | 3,000
|
#include <bits/stdc++.h>
#define debug(...) fprintf(stderr ,__VA_ARGS__)
#define __FILE(x)\
freopen(#x".in" ,"r" ,stdin);\
freopen(#x".out" ,"w" ,stdout)
#define LL long long
const int MX = 2000 + 23;
LL MOD;
using namespace std;
int read(){
char k = getchar(); int x = 0;
while(k < '0' || k > '9') k = getchar();
while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();
return x;
}
int head[MX] ,tot = 1;
struct edge{
int node ,next;
}h[MX << 1];
void addedge(int u ,int v ,int flg = 1){
// if(flg) debug("%d %d\n" ,u ,v);
h[++tot] = (edge){v ,head[u]} ,head[u] = tot;
if(flg) addedge(v ,u ,false);
}
int n ,dp[MX][MX] ,S[MX][MX] ,suf[MX][MX] ,pre[MX][MX];
void dapai(int x ,int f){
int ch = 0;
for(int i = head[x] ,d ; i ; i = h[i].next){
if((d = h[i].node) == f) continue;
dapai(d ,x);
}
for(int i = head[x] ,d ; i ; i = h[i].next){
if((d = h[i].node) == f) continue;
++ch;
for(int j = 0 ; j <= n ; ++j){
suf[ch][j] = pre[ch][j] = S[d][j];
}
}
if(!ch){
for(int i = 1 ; i <= n ; ++i){
dp[x][i] = 1 % MOD;
S[x][i] = (S[x][i - 1] + dp[x][i]) % MOD;
}
return ;
}
for(int j = 0 ; j <= n ; ++j){
for(int i = 1 ; i <= ch ; ++i)
pre[i][j] = 1LL * pre[i][j] * pre[i - 1][j] % MOD;
for(int i = ch ; i >= 1 ; --i)
suf[i][j] = 1LL * suf[i][j] * suf[i + 1][j] % MOD;
}
for(int i = 1 ; i <= n ; ++i) dp[x][i] = pre[ch][i];
if(x != 1) for(int i = head[x] ,d ,c = 0 ; i ; i = h[i].next){
if((d = h[i].node) == f) continue;
++c;
LL sum = 0;
for(int mx = 1 ; mx <= n ; ++mx){
dp[x][mx] = (dp[x][mx] + sum * dp[d][mx]) % MOD;
sum = (sum + 1LL * pre[c - 1][mx] * suf[c + 1][mx]) % MOD;
}
}
for(int i = 1 ; i <= ch ; ++i)
for(int j = 0 ; j <= n ; ++j)
suf[i][j] = pre[i][j] = 1 % MOD;
for(int i = 1 ; i <= n ; ++i)
S[x][i] = (S[x][i - 1] + dp[x][i]) % MOD;
}
int C[MX][MX];
void init(){
for(int i = 0 ; i < MX ; ++i) C[i][0] = 1 % MOD;
for(int i = 1 ; i < MX ; ++i)
for(int j = 1 ; j < MX ; ++j)
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % MOD;
}
int main(){
n = read() ,MOD = read();
init();
for(int i = 0 ; i < MX ; ++i)
for(int j = 0 ; j < MX ; ++j)
suf[i][j] = pre[i][j] = 1 % MOD;
for(int i = 2 ; i <= n ; ++i){
addedge(read() ,read());
// addedge(rand() % (i - 1) + 1 ,i);
}
dapai(1 ,0);
for(int i = 1 ; i < n ; ++i){
LL ans = 0;
for(int j = 1 ; j <= i ; ++j){
ans += ((i - j) & 1 ? -1LL : 1LL) * C[i][j] * dp[1][j] % MOD;
}
ans = (ans % MOD + MOD) % MOD;
printf("%lld%c" ,ans ," \n"[i == n]);
}
return 0;
}
|
1707
|
E
|
Replace
|
You are given an integer array $a_1,\ldots, a_n$, where $1\le a_i \le n$ for all $i$.
There's a "replace" function $f$ which takes a pair of integers $(l, r)$, where $l \le r$, as input and outputs the pair $$f\big( (l, r) \big)=\left(\min\{a_l,a_{l+1},\ldots,a_r\},\, \max\{a_l,a_{l+1},\ldots,a_r\}\right).$$
Consider repeated calls of this function. That is, from a starting pair $(l, r)$ we get $f\big((l, r)\big)$, then $f\big(f\big((l, r)\big)\big)$, then $f\big(f\big(f\big((l, r)\big)\big)\big)$, and so on.
Now you need to answer $q$ queries. For the $i$-th query you have two integers $l_i$ and $r_i$ ($1\le l_i\le r_i\le n$). You must answer the minimum number of times you must apply the "replace" function to the pair $(l_i,r_i)$ to get $(1, n)$, or report that it is impossible.
|
Let $f([l,r])$ be the "replace" function. That means $f([l,r])=[\min\{a_i|l\le i\le r\},\max\{a_i|l\le i\le r\}]$. $f^k([l,r])$ means applying the function $k$ times. When $[a_1,b_1]\bigcap[a_2,b_2]\ne \emptyset$, Let $j=\max\{a_1,a_2\}$, then $j\in[a_1,b_1]$ and $j\in[a_{2},b_{2}]$. So $a_j\in f([a_1,b_1])$ and $a_j\in f([a_{2},b_{2}])$. That means $f([a_1,b_1])\bigcap f([a_{2},b_{2}])\ne \emptyset$, so $f([\min\{a_1,a_{2}\},\max\{b_1,b_{2}\}])=f([a_1,b_1])\bigcup f([a_{2},b_{2}])$. When $m>2$ it can be similarly proved that if $\forall 1\le i<m,[a_i,b_i]\bigcap [a_{i+1},b_{i+1}]\ne \emptyset$, then $f(\bigcup\limits_{1\le i\le m}[a_i,b_i])=\bigcup\limits_{1\le i\le m}f([a_i,b_i])$. And we also know that if $[a_1,b_1]\bigcap [a_2,b_2]\ne \emptyset$, then $f([a_1,b_1])\bigcap f([a_2,b_2])\ne \emptyset$, then $f^k([a_1,b_1])\bigcap f^k([a_2,b_2])\ne \emptyset$. So we know $f^k(\bigcup\limits_{1\le i\le m}[a_i,b_i])=\bigcup\limits_{1\le i\le m}f^k([a_i,b_i])$. So $f^k([l,r])=\bigcup\limits_{l\le i<r}f^k([i,i+1])$. We can use $f^{p+q}([l,r])=f^p(f^q([l,r]))$ to easily get $f^{2^k}([i,i+1])$ in $O(n\log^2n)$ at first, then we can calculate $f^{2^k}([l,r])$ in $O(\log n)$. Use binary search we can get answer in $O(\log^2n)$. So the time complexity is $O((n+q)\log^2n)$. We can use BIT instead of segment tree to make our program run faster.
|
[
"binary search",
"data structures"
] | 3,500
|
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ch() getchar()
#define pc(x) putchar(x)
using namespace std;
template<typename T>void read(T&x){
static char c;static int f;
for(f=1,c=ch();c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch()){x=x*10+(c&15);}x*=f;
}
template<typename T>void write(T x){
static char q[64];int cnt=0;
if(x==0)return pc('0'),void();
if(x<0)pc('-'),x=-x;
while(x)q[cnt++]=x%10+'0',x/=10;
while(cnt--)pc(q[cnt]);
}
const int maxn=100005,maxq=100005,maxt=34;
const int inf=0x3f3f3f3f;
int a[maxn];
struct Segment{
int l,r;
Segment(int l=inf,int r=-inf):
l(l),r(r){}
Segment operator * (const Segment o)const{
return Segment(min(l,o.l),max(r,o.r));
}
bool operator != (const Segment o)const{
return l!=o.l||r!=o.r;
}
void input(void){
read(l),read(r);
}
}sg[maxt][maxn],tr[maxn],qy[maxq];
int n;
void res(void){
for(int i=1;i<n;++i)
tr[i]=Segment();
}
void add(int p,Segment v){
while(p<n){
tr[p]=tr[p]*v;
p+=(p&(-p));
}
}
Segment ask(int p){
Segment re;
while(p){
re=re*tr[p];
p^=(p&(-p));
}
return re;
}
struct Edge{
int v,w,nt;
Edge(int v=0,int w=0,int nt=0):
v(v),w(w),nt(nt){}
}e[maxn];
int num,hd[maxn];
void ins(int u,int v,int w){
e[++num]=Edge(v,w,hd[u]),hd[u]=num;
}
int st[maxq],tp;
long long Ans[maxq];
int main(){
int q;read(n),read(q);
if(n==1){while(q--)puts("0");return 0;}
for(int i=1;i<=n;++i)read(a[i]);
for(int i=1;i<n;++i){
if(a[i]<=a[i+1])
sg[0][i]=Segment(a[i],a[i+1]);
else
sg[0][i]=Segment(a[i+1],a[i]);
}
for(int i=1;i<maxt;++i){
for(int j=1;j<n;++j){
if(sg[i-1][j].l>=sg[i-1][j].r)sg[i][j]=Segment();
else ins(sg[i-1][j].l,sg[i-1][j].r-1,j);
}
res();
for(int j=n-1;j>=1;--j){
add(j,sg[i-1][j]);
for(int k=hd[j];k;k=e[k].nt){
sg[i][e[k].w]=ask(e[k].v);
}
hd[j]=0;
}
num=0;
}
for(int i=1;i<=q;++i){
qy[i].input();
if(qy[i].l==qy[i].r)Ans[i]=-2;
else ins(qy[i].l,qy[i].r-1,i);
}
res();
for(int i=n-1;i>=1;--i){
add(i,sg[maxt-1][i]);
for(int j=hd[i];j;j=e[j].nt){
if(i==1&&e[j].v==n-1)
Ans[e[j].w]=-1;
else if(ask(e[j].v)!=Segment(1,n))
Ans[e[j].w]=-2;
else
st[++tp]=e[j].w;
}
hd[i]=0;
}
num=0;
for(int i=maxt-2;~i;--i){
for(int j=1;j<=tp;++j){
ins(qy[st[j]].l,qy[st[j]].r-1,st[j]);
}
res();
for(int j=n-1;j>=1;--j){
add(j,sg[i][j]);
for(int k=hd[j];k;k=e[k].nt){
Segment tmp=ask(e[k].v);
int id=e[k].w;
if(tmp!=Segment(1,n))
Ans[id]|=(1ll<<i),qy[id]=tmp;
}
hd[j]=0;
}
num=0;
}
for(int i=1;i<=q;++i)
write(++Ans[i]),pc('\n');
return 0;
}
|
1707
|
F
|
Bugaboo
|
A transformation of an array of positive integers $a_1,a_2,\dots,a_n$ is defined by replacing $a$ with the array $b_1,b_2,\dots,b_n$ given by $b_i=a_i\oplus a_{(i\bmod n)+1}$, where $\oplus$ denotes the bitwise XOR operation.
You are given integers $n$, $t$, and $w$. We consider an array $c_1,c_2,\dots,c_n$ ($0 \le c_i \le 2^w-1$) to be bugaboo if and only if there exists an array $a_1,a_2,\dots,a_n$ such that after transforming $a$ for $t$ times, $a$ becomes $c$.
For example, when $n=6$, $t=2$, $w=2$, then the array $[3,2,1,0,2,2]$ is bugaboo because it can be given by transforming the array $[2,3,1,1,0,1]$ for $2$ times:
$$ [2,3,1,1,0,1]\to [2\oplus 3,3\oplus 1,1\oplus 1,1\oplus 0,0\oplus 1,1\oplus 2]=[1,2,0,1,1,3]; \\ [1,2,0,1,1,3]\to [1\oplus 2,2\oplus 0,0\oplus 1,1\oplus 1,1\oplus 3,3\oplus 1]=[3,2,1,0,2,2]. $$
And the array $[4,4,4,4,0,0]$ is not bugaboo because $4 > 2^2 - 1$. The array $[2,3,3,3,3,3]$ is also not bugaboo because it can't be given by transforming one array for $2$ times.
You are given an array $c$ with some positions lost (only $m$ positions are known at first and the remaining positions are lost). And there are $q$ modifications, where each modification is changing a position of $c$. A modification can possibly change whether the position is lost or known, and it can possibly redefine a position that is already given.
You need to calculate how many possible arrays $c$ (with arbitrary elements on the lost positions) are bugaboos after each modification. Output the $i$-th answer modulo $p_i$ ($p_i$ is a given array consisting of $q$ elements).
|
We can first solve an easier condition when $n=2^h(h\ge 0)$. We know for any array $a_1,a_2,\ldots,a_{2^h}$, transforming it for $2^h$ times $a_i=0$. If you transform it more than $2^h$ times it is also guaranteed that $a_i=0$. So in this condition, if $t\ge 2^h$, we only need to test whether for all $i$, $c_i$ can be $0$. When $t<2^h$, if transforming an array $a_1,a_2,\ldots,a_n$ for $t$ times $a$ becomes $c$, then it can be proved that $\bigoplus\limits_{i=1}^{2^h}a_i$ depends on $t,h$ and the array $c$. We can let $f(t,h,c_1,c_2,\ldots,c_{2^h})=\bigoplus\limits_{i=1}^{2^h}a_i$. Proof: When $h=0$, $t$ must be $0$, so $f(t,h,c_1)=c_1$. When $h>0$, $f(t,h,c_1,c_2,\ldots,c_{2^h})$ can be given by $f(\lfloor\frac{t}{2}\rfloor,h-1,c_1,c_3,\ldots,c_{2^h-1})$ and $f(\lfloor\frac{t}{2}\rfloor,h-1,c_2,c_4,\ldots,c_{2^h})$. The specific process is below. If $t$ is an even number, then we know transforming $a_1,a_3,\ldots,a_{2^h-1}$ for $\frac{t}{2}$ times it becomes $c_1,c_3,\ldots,c_{2^h-1}$. Also transforming $a_2,a_4,\ldots,a_{2^h}$ for $\frac{t}{2}$ times it becomes $c_2,c_4,\ldots,c_{2^h}$. So in this case, $f(t,h,c_1,c_2,\ldots,c_{2^h})=f(\lfloor\frac{t}{2}\rfloor,h-1,c_1,c_3,\ldots,c_{2^h-1})\oplus f(\lfloor\frac{t}{2}\rfloor,h-1,c_2,c_4,\ldots,c_{2^h})$. If $t$ is an odd number, then we can first transform $a$ once, then it becomes the even number case. That is to say, $a$ now becomes $a_1\oplus a_2,a_2\oplus a_3,\ldots,a_{2^h}\oplus a_1$. Transforming $a_1\oplus a_2,a_3\oplus a_4,\ldots,a_{2^h-1}\oplus a_{2^h}$ for $\lfloor\frac{t}{2}\rfloor$ times it becomes $c_1,c_3,\ldots,c_{2^h-1}$. Transforming $a_2\oplus a_3,a_4\oplus a_5,\ldots,a_{2^h}\oplus a_1$ for $\lfloor\frac{t}{2}\rfloor$ times it becomes $c_2,c_4,\ldots,c_{2^h}$. So in this case, $f(t,h,c_1,c_2,\ldots,c_{2^h})=f(\lfloor\frac{t}{2}\rfloor,h-1,c_1,c_3,\ldots,c_{2^h-1})=f(\lfloor\frac{t}{2}\rfloor,h-1,c_2,c_4,\ldots,c_{2^h})$. Actually the process above can inspire us to find an easy way to judge whether an array is a bugaboo. We just need to use divide and conquer to calculate $f(t,h,c_1,\ldots,c_{2^h})$ .When it becomes the second case, judge whether $f(\lfloor\frac{t}{2}\rfloor,h-1,c_1,c_3,\ldots,c_{2^h-1})=f(\lfloor\frac{t}{2}\rfloor,h-1,c_2,c_4,\ldots,c_{2^h})$. If and only if all the requirements are met, the array $c$ is a bugaboo. And the good news is that it can be used to calculate the number of bugaboos. Let $dp(t,h,d_1,d_2,\ldots,d_{2^h},k)=$ the number of arrays $c_{d_1},c_{d_2},\ldots,c_{d_{2^h}}$ which are bugaboos and $f(t,h,c_{d_1},c_{d_2},\ldots,c_{d_{2^h}})=k$. Just like the process above, when $t$ is an even number, $dp(t,h,d_1,d_2,\ldots,d_{2^h},k)=\sum\limits_{l=0}^{2^w-1}dp(\lfloor\frac{t}{2}\rfloor,h-1,d_1,d_3,\ldots,d_{2^h-1},l)\cdot dp(\lfloor\frac{t}{2}\rfloor,h-1,d_2,d_4,\ldots,d_{2^h},k\oplus l)$; When $t$ is an odd number, $dp(t,h,d_1,d_2,\ldots,d_{2^h},k)=dp(\lfloor\frac{t}{2}\rfloor,h-1,d_1,d_3,\ldots,d_{2^h-1},k)\cdot dp(\lfloor\frac{t}{2}\rfloor,h-1,d_2,d_4,\ldots,d_{2^h},k)$.When $c_d$ is lost, $dp(0,0,d,k)=1$. When $c_d=k_0$, $dp(0,0,d,k)=[k=k_0]$. The answer is $\sum\limits_{k=0}^{2^w-1}dp(t,h,1,2,\ldots,2^h,k)$. However, $2^w$ is so huge that we cannot do it in a short time. After some careful observations, we can surprisingly find that for $dp(t,h,d_1,d_2,\ldots,d_{2^h},?)$ either $\forall k,dp(t,h,d_1,d_2,\ldots,d_{2^h},k)=(2^w)^A$, or $\forall k,dp(t,h,d_1,d_2,\ldots,d_{2^h},k)=[k=B]\cdot(2^w)^C$, or $\forall k,dp(t,h,d_1,d_2,\ldots,d_{2^h},k)=0$. We can use this to simplify our process, making our time complexity free from $w$. By the way, the divide and conquer process above is very similar to FFT. That is to say, we can reverse the indexes' binary bit to make the process faster. So, when $n=2^h$, without modifications we can work out the answer in $O(n)$. And the process is just like the structure of segment tree, so we can do a modification in $O(\log n)$. The total time complexity is $O(n+(m+q)\log n)$. When $n$ cannot be given by $2^h$, we can simply let $h$ be the lowest bit of $n$, that is to say, $n=2^h\cdot o$($o$ is an odd number). Then we can consider $i,i+2^h,\ldots,i+2^h\cdot(o-1)$ as a whole to do the process above. The only thing we need to notice is that when $t>2^h$, the requirement is that for all $i$, $\bigoplus\limits_{l=0}^{o-1}c_{i+2^h\cdot l}$ can be $0$. Now we can solve the problem in $O(n+(m+q)\log n)$.
|
[
"bitmasks",
"constructive algorithms",
"dp",
"number theory"
] | 3,500
|
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<assert.h>
#define ch() getchar()
#define pc(x) putchar(x)
template<typename T>void read(T&x){
static char c;static int f;
for(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;
for(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;
}
template<typename T>void write(T x){
static char q[65];int cnt=0;
if(x<0)pc('-'),x=-x;
q[++cnt]=x%10,x/=10;
while(x)
q[++cnt]=x%10,x/=10;
while(cnt)pc(q[cnt--]+'0');
}
const int maxn=20000005;
struct Count{
int pos,val;
Count(int pos=-1,int val=-1):
pos(pos),val(val){}
};
int plus(int x,int y){
return (x<0||y<0)?-1:x+y;
}
Count operator + (const Count A,const Count B){
int Ap=A.pos,Bp=B.pos,va=plus(A.val,B.val);
if(~Ap&&~Bp)return Ap^Bp?Count():Count(Ap|Bp,va);
if(~Ap||~Bp)return Count(Ap&Bp,va);
return Count(-1,va);
}
Count operator * (const Count A,const Count B){
int Ap=A.pos,Bp=B.pos,va=plus(A.val,B.val);
if(~Ap&&~Bp)return Count(Ap^Bp,va);
if(~Ap||~Bp)return Count(-1,va);
return Count(-1,plus(va,1));
}
int c[maxn];
int tn,Op[maxn],Cn[maxn];
Count dp[maxn];
int t,hb[maxn],rev[maxn];
void pushup(int p){
int l=p<<1,r=l|1;
dp[p]=((t&hb[p])?(dp[l]+dp[r]):(dp[l]*dp[r]));
}
int va1,sum;
void ins(int i){
int p=rev[(i&(tn-1))];
if(~c[i])Op[p]^=c[i];else ++Cn[p];
if(dp[p+tn].pos>0)--va1;else sum-=dp[p+tn].val;
dp[p+tn]=(Cn[p]?Count(-1,Cn[p]-1):Count(Op[p],0));
if(dp[p+tn].pos>0)++va1;else sum+=dp[p+tn].val;
}
void del(int i){
int p=rev[(i&(tn-1))];
if(~c[i])Op[p]^=c[i];else --Cn[p];
}
int power(int a,int x,int p){
if(x==-1)return 0;
int re=1;
while(x){
if(x&1)re=1ll*re*a%p;
a=1ll*a*a%p;x>>=1;
}
return re;
}
int main(){
int n,m,w;
read(n),read(m),read(t),read(w);
memset(c,-1,sizeof c);
for(int i=1;i<=m;++i){
int d;read(d);--d;read(c[d]);
}
tn=(n&(-n));
hb[0]=0;hb[1]=1;
for(int i=2;i<tn*2;++i)
hb[i]=(hb[i>>1]<<1);
int cn=-1;for(;(1<<(cn+1))<tn;++cn);
for(int i=1;i<tn;++i)
rev[i]=(rev[i>>1]>>1)|((i&1)<<cn);
for(int i=0;i<tn;++i)dp[i+tn].val=0;
for(int i=0;i<n;++i)ins(i);
if(t<tn)for(int i=tn-1;i>=1;--i)pushup(i);
int q;read(q);
while(q--){
int f;read(f);--f;
del(f);read(c[f]);ins(f);
int p;read(p);
if(t>=tn){
write(va1?0:power((1<<w)%p,sum,p));
}
else{
int now=(rev[(f&(tn-1))]|tn);while(now>>=1)pushup(now);
write(power((1<<w)%p,plus(dp[1].val,dp[1].pos==-1),p));
}
pc('\n');
}
return 0;
}
|
1708
|
A
|
Difference Operations
|
You are given an array $a$ consisting of $n$ positive integers.
You are allowed to perform this operation any number of times (possibly, zero):
- choose an index $i$ ($2 \le i \le n$), and change $a_i$ to $a_i - a_{i-1}$.
Is it possible to make $a_i=0$ for all $2\le i\le n$?
|
Solution 1 For all $i \ge 2$, $a_i$ is the multiple of $a_1$ is equivalent to the YES answer. Proof of necessity $a_2$ must be the multiple of $a_1$. Otherwise $a_2$ cannot become zero. In the whole process, $a_2$ is always the multiple of $a_1$. So $a_3$ must be the multiple of $a_1$. Otherwise $a_3$ cannot become zero. In the whole process, $a_3$ is always the multiple of $a_1$. So $a_4$ must be the multiple of $a_1$. Otherwise $a_4$ cannot become zero. ... Proof of sufficiency For all $i \ge 2$, $a_i$ is the multiple of $a_1$. So we can perform operations to make $a=[a_1,a_1,a_1,\cdots]$ and then make $a=[a_1,0,0,\cdots]$. Solution 2 Consider everything in the reverse order. You are given an array $b$ consisting of $n$ positive integers, where $b=[b_1,0,0,\cdots,0]$ ($b_1$ and $n-1$ zeros). You are given an array $a$ consisting of $n$ positive integers. It is guaranteed that $a_1=b_1$. You are allowed to perform this operation any number of times (possibly, zero): Choose an index $i$ ($2\le i \le n$), and change $b_i$ to $b_i+b_{i-1}$. Is it possible to change $b$ to $a$? Check if $a_i$ is the multiple of $a_1$.
|
[
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
#define debug(...) fprintf(stderr ,__VA_ARGS__)
#define LL long long
const LL MOD = 1e9 + 7;
const int MX = 1e5 + 23;
int read(){
char k = getchar(); LL x = 0;
while(k < '0' || k > '9') k = getchar();
while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();
return x;
}
int n ,a[MX];
void solve(){
n = read();
for(int i = 1 ; i <= n ; ++i) a[i] = read();
int ok = 1;
for(int i = 1 ; i <= n ; ++i){
if(a[i] % a[1]) ok = false;
}
puts(ok ? "YES" : "NO");
}
int main(){
int T = read();
while(T--) solve();
return 0;
}
|
1708
|
B
|
Difference of GCDs
|
You are given three integers $n$, $l$, and $r$. You need to construct an array $a_1,a_2,\dots,a_n$ ($l\le a_i\le r$) such that $\gcd(i,a_i)$ are all distinct or report there's no solution.
Here $\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
|
$\gcd(i,a_i)\le i$. Because all $\gcd(i,a_i)$ are different, then $\gcd(i,a_i)=i$, which means $a_i$ is the multiple of $i$. To check if there is such $a_i$, just check if $a_i=\left(\lfloor \frac{l-1}{i} \rfloor +1\right)\cdot i$ (the minimum multiple of $i$ that is strictly bigger than $l-1$) is less than $r$. Time complexity $O(n)$ for each test case.
|
[
"constructive algorithms",
"math"
] | 1,100
|
#include <bits/stdc++.h>
#define debug(...) fprintf(stderr ,__VA_ARGS__)
#define __FILE(x)\
freopen(#x".in" ,"r" ,stdin);\
freopen(#x".out" ,"w" ,stdout)
#define LL long long
const int MX = 1e5 + 23;
const LL MOD = 998244353;
int read(){
char k = getchar(); int x = 0;
while(k < '0' || k > '9') k = getchar();
while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();
return x;
}
int a[MX];
void solve(){
int n = read() ,l = read() ,r = read();
int ok = 1;
for(int i = 1 ; i <= n ; ++i){
a[i] = ((l - 1) / i + 1) * i;
ok = ok && a[i] <= r;
}
if(ok){
puts("YES");
for(int i = 1 ; i <= n ; ++i)
printf("%d%c" ,a[i] ," \n"[i == n]);
}
else puts("NO");
}
int main(){
int T = read();
for(int i = 1 ; i <= T ; ++i){
solve();
}
return 0;
}
|
1709
|
A
|
Three Doors
|
There are three doors in front of you, numbered from $1$ to $3$ from left to right. Each door has a lock on it, which can only be opened with a key with the same number on it as the number on the door.
There are three keys — one for each door. Two of them are hidden behind the doors, so that there is no more than one key behind each door. So two doors have one key behind them, one door doesn't have a key behind it. To obtain a key hidden behind a door, you should first unlock that door. The remaining key is in your hands.
Can you open all the doors?
|
Note that we never have a choice in what door should we open. First, we open the door with the same number as the key in our hand. Then, the door with the same number as the key behind the first opened door. Finally, the door with the same number as the key behind the second opened door. If any of the first and second opened doors didn't have a key behind it, then it's impossible. Otherwise, we open every door. Let $a_1, a_2, a_3$ be the keys behind the corresponding doors. Then we should check if $a[x]$ is not zero and $a[a[x]]$ is not zero. Overall complexity: $O(1)$ per testcase.
|
[
"brute force",
"greedy",
"implementation",
"math"
] | 800
|
for _ in range(int(input())):
x = int(input())
a = [0] + [int(x) for x in input().split()]
print("YES" if a[x] != 0 and a[a[x]] != 0 else "NO")
|
1709
|
B
|
Also Try Minecraft
|
You are beta testing the new secret Terraria update. This update will add quests to the game!
Simply, the world map can be represented as an array of length $n$, where the $i$-th column of the world has height $a_i$.
There are $m$ quests you have to test. The $j$-th of them is represented by two integers $s_j$ and $t_j$. In this quest, you have to go from the column $s_j$ to the column $t_j$. At the start of the quest, you are appearing at the column $s_j$.
In one move, you can go from the column $x$ to the column $x-1$ or to the column $x+1$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $p$ to the column with the height $q$, then you get some amount of fall damage. If the height $p$ is greater than the height $q$, you get $p - q$ fall damage, otherwise you fly up and get $0$ damage.
For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
|
So, the first idea that is coming into mind is prefix sums. Let's define two values $l_i = max(0, a_i - a_{i + 1})$ and $r_i = max(0, a_{i + 1} - a_i)$. The value $l_i$ means the amount of fall damage when we are going to the right from the column $i$ to the column $i + 1$, and $r_i$ means the amount of fall damage when we are going to the left from the column $i + 1$ to the column $i$. Then let's build prefix sums on these two arrays. Now let $pl_i$ be the sum of all $l_i$ on a prefix $[0; i)$ (i. e. $pl_0 = 0$), and $pr_i$ be the sum of all $r_i$ on a prefix $[0; i)$. Then if $s < t$ in a query, the answer is $pl_{t - 1} - pl_{s - 1}$, otherwise (if $s > t$) the answer is $pr_{s - 1} - pr_{t - 1}$. Time complexity: $O(n)$.
|
[
"data structures",
"dp",
"implementation"
] | 900
|
n, m = map(int, input().split())
a = list(map(int, input().split()))
l = [0] + [max(0, a[i] - a[i + 1]) for i in range(n - 1)]
r = [0] + [max(0, a[i] - a[i - 1]) for i in range(1, n)]
for i in range(n - 1):
l[i + 1] += l[i]
r[i + 1] += r[i]
for _ in range(m):
s, t = map(int, input().split())
if s < t:
print(l[t - 1] - l[s - 1])
else:
print(r[s - 1] - r[t - 1])
|
1709
|
C
|
Recover an RBS
|
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example:
- bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)");
- bracket sequences ")(", "(" and ")" are not.
There was an RBS. Some brackets have been replaced with question marks. Is it true that there is a \textbf{unique} way to replace question marks with brackets, so that the resulting sequence is an RBS?
|
There are many different approaches to this problem, but I think the model solution has the most elegant one. First of all, let's construct an RBS from the given string (it always exists, so it is always possible). By calculating the number of opening brackets, closing brackets and questions in the given string, we can compute the number of question marks that should be replaced with opening brackets (it is easy since exactly half of the characters in each RBS are opening brackets). Then, let's form the RBS greedily: replace the first several question marks with opening brackets, and all remaining ones with closed brackets. Okay, then what about finding a second RBS? Recall that a bracket sequence is an RBS when for each of its positions, the number of closing brackets before it is not greater than the number of opening brackets before it (and these two values should be equal at the end of the sequence, but it is less important now). Consider the segment between the last question mark replaced with an opening bracket, and the first question mark replaced by the closing bracket. If we try to change the order of characters corresponding to question marks, the balance on this segment will decrease at least by $2$ (since at least one opening bracket to the left of it will become a closing bracket). Is there a way to affect only this segment, and change the balance on it only by $2$? Yes - just swap the endpoints of this segment (i. e. the last opening bracket that was a question mark and the first closing bracket that was also a question mark). If it yields an RBS, then the answer is NO. Otherwise, the answer is YES since any other permutation of characters that were replacing question marks will also decrease the balance on this segment by at least $2$.
|
[
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
auto check = [](const string& s) {
int bal = 0;
for (char c : s) {
if (c == '(') ++bal;
if (c == ')') --bal;
if (bal < 0) return false;
}
return bal == 0;
};
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
vector<int> pos;
int op = s.size() / 2, cl = s.size() / 2;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '?') pos.push_back(i);
if (s[i] == '(') --op;
if (s[i] == ')') --cl;
}
for (int i = 0; i < pos.size(); ++i) {
if (i < op) s[pos[i]] = '(';
else s[pos[i]] = ')';
}
bool ok = true;
if (op > 0 && cl > 0) {
swap(s[pos[op - 1]], s[pos[op]]);
if (check(s)) ok = false;
}
cout << (ok ? "YES\n" : "NO\n");
}
}
|
1709
|
D
|
Rorororobot
|
There is a grid, consisting of $n$ rows and $m$ columns. The rows are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. The $i$-th column has the bottom $a_i$ cells blocked (the cells in rows $1, 2, \dots, a_i$), the remaining $n - a_i$ cells are unblocked.
A robot is travelling across this grid. You can send it commands — move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.
However, the robot is broken — it executes each received command $k$ times. So if you tell it to move up, for example, it will move up $k$ times ($k$ cells). You can't send it commands while the robot executes the current one.
You are asked $q$ queries about the robot. Each query has a start cell, a finish cell and a value $k$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $k$ times?
The robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.
|
What if there were no blocked cells? Then the movement is easy. From cell $(x, y)$ we can go to cells $(x + k, y)$, $(x, y + k)$, $(x - k, y)$ or $(x, y - k)$. Thus, we can visit all cells that have the same remainder modulo $k$ over both dimensions. The answer would be "YES" if $x_s \bmod k = x_f \bmod k$ and $y_s \bmod k = y_f \bmod k$. Let's choose the following path from start to finish. Let $x_s$ be less or equal to $x_f$. If that isn't the case, swap the cells. First, move up until the row is the same, then move to the side until the column is the same. What stops us from doing the same on a grid with blocked cells? The first part of the part can remain the same - we can always move up from the cell. Only cells below the start cell can be blocked. The second part is trickier. If there is a column with too many blocked cells between the start and the finish column, then we won't be able to pass through it. Let's adjust the path for that. Move up as high as possible - to the highest cell with the same remainder modulo $k$ in this column. Then move to the finish column and go down to the finish cell. If there still exists a column with too many blocked cells, then the answer is "NO". No matter what we do, we won't be able to go around that column. Otherwise, the answer is "YES". Thus, the solution is to check for remainders, then find the largest number of blocked cells between the query columns and compare it to the highest row with the same remainder modulo $k$ as the start or the finish. You can use any RMQ data structure you want. Overall complexity: $O(n \log n + q)$ with sparse table for RMQ, for example.
|
[
"binary search",
"data structures",
"greedy",
"math"
] | 1,700
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int n, m;
scanf("%d%d", &n, &m);
vector<int> a(m);
forn(i, m) scanf("%d", &a[i]);
int l = 0;
while ((1 << l) <= m) ++l;
vector<vector<int>> st(l, vector<int>(m));
forn(i, m) st[0][i] = a[i];
for (int j = 1; j < l; ++j) forn(i, m){
st[j][i] = st[j - 1][i];
if (i + (1 << (j - 1)) < m)
st[j][i] = max(st[j][i], st[j - 1][i + (1 << (j - 1))]);
}
vector<int> pw(m + 1, 0);
for (int i = 2; i <= m; ++i) pw[i] = pw[i / 2] + 1;
auto get = [&](int l, int r){
if (l > r) swap(l, r);
++r;
int len = pw[r - l];
return max(st[len][l], st[len][r - (1 << len)]);
};
int q;
scanf("%d", &q);
forn(_, q){
int xs, ys, xf, yf, k;
scanf("%d%d%d%d%d", &xs, &ys, &xf, &yf, &k);
--xs, --ys, --xf, --yf;
if (ys % k != yf % k || xs % k != xf % k){
puts("NO");
continue;
}
int mx = (n - xs - 1) / k * k + xs;
puts(get(ys, yf) <= mx ? "YES" : "NO");
}
return 0;
}
|
1709
|
E
|
XOR Tree
|
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.
Recall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tree is good if no simple path has weight $0$.
You can apply the following operation any number of times (possibly, zero): select a vertex of the tree and replace the value written on it with an arbitrary positive integer. What is the minimum number of times you have to apply this operation in order to make the tree good?
|
To begin with, we note that there are no restrictions on the values that can be written on the vertices, so we can use numbers of the form $2^{30+x}$ for the $x$-th replacement. Then, if we replaced the value of a vertex, then no path passing through this vertex has weight $0$. Let's root the tree at the vertex number $1$. We can use a greedy approach: consider some vertex $v$ such that it is the LCA for two vertices $x$ and $y$, the path between which has XOR equal to $0$. Among such vertices $v$, pick one with the maximum distance from the root. We need to change at least one vertex on the path $(x, y)$. It turns out that changing the vertex $v$ is always no worse than changing any other vertex $u$ on this path, because all the remaining bad paths that pass through the vertex $u$ also pass through the vertex $v$ (that's why we have chosen the deepest LCA). This means that in order to solve the problem, it is necessary to quickly find the deepest LCA of some bad path. For the convenience of solving the problem, let's denote the XOR on the path $(x,y)$ as $b_x \oplus b_y \oplus a_{LCA(x,y)}$, where $b_v$ is XOR on the path from the root to the vertex $v$. For all vertices $v$, let's maintain a set of values $b_x$, such that $x$ belongs to the subtree of $v$. Let's use the small-to-large method to obtain such sets. Also, during the union of sets, we can check if there is a bad path in this subtree, i. e. if two values in the sets we merge have the same XOR as the value written on the current vertex (because that's when the XOR on path is $0$). If such a path exists, then we have to change the value of the vertex $v$ and mark that the vertices of this subtree cannot be the ends of a bad path anymore - that means we just clear the set instead of pulling it up the tree. This solution works in $O(n \log^2 n)$.
|
[
"bitmasks",
"data structures",
"dfs and similar",
"dsu",
"greedy",
"trees"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int N = 200 * 1000 + 13;
int n;
int a[N], b[N];
vector<int> g[N];
set<int> vals[N];
void init(int v, int p) {
b[v] = a[v];
if (p != -1) b[v] ^= b[p];
for (int u : g[v]) if (u != p)
init(u, v);
}
int ans;
void calc(int v, int p) {
bool bad = false;
vals[v].insert(b[v]);
for (int u : g[v]) if (u != p) {
calc(u, v);
if (vals[v].size() < vals[u].size()) vals[v].swap(vals[u]);
for (int x : vals[u]) bad |= vals[v].count(x ^ a[v]);
for (int x : vals[u]) vals[v].insert(x);
vals[u].clear();
}
if (bad) {
ans += 1;
vals[v].clear();
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
for (int i = 0; i < n - 1; ++i) {
int x, y;
cin >> x >> y;
--x; --y;
g[x].push_back(y);
g[y].push_back(x);
}
init(0, -1);
calc(0, -1);
cout << ans << '\n';
}
|
1709
|
F
|
Multiset of Strings
|
You are given three integers $n$, $k$ and $f$.
Consider all binary strings (i. e. all strings consisting of characters $0$ and/or $1$) of length from $1$ to $n$. For every such string $s$, you need to choose an integer $c_s$ from $0$ to $k$.
A multiset of binary strings of length \textbf{exactly} $n$ is considered beautiful if for every binary string $s$ with length from $1$ to $n$, the number of strings in the multiset such that $s$ is their prefix is not exceeding $c_s$.
For example, let $n = 2$, $c_{0} = 3$, $c_{00} = 1$, $c_{01} = 2$, $c_{1} = 1$, $c_{10} = 2$, and $c_{11} = 3$. The multiset of strings $\{11, 01, 00, 01\}$ is beautiful, since:
- for the string $0$, there are $3$ strings in the multiset such that $0$ is their prefix, and $3 \le c_0$;
- for the string $00$, there is one string in the multiset such that $00$ is its prefix, and $1 \le c_{00}$;
- for the string $01$, there are $2$ strings in the multiset such that $01$ is their prefix, and $2 \le c_{01}$;
- for the string $1$, there is one string in the multiset such that $1$ is its prefix, and $1 \le c_1$;
- for the string $10$, there are $0$ strings in the multiset such that $10$ is their prefix, and $0 \le c_{10}$;
- for the string $11$, there is one string in the multiset such that $11$ is its prefix, and $1 \le c_{11}$.
Now, for the problem itself. You have to calculate the number of ways to choose the integer $c_s$ for every binary string $s$ of length from $1$ to $n$ in such a way that the \textbf{maximum} possible size of a beautiful multiset is \textbf{exactly} $f$.
|
First of all, let's visualize the problem in a different way. We have to set some constraints on the number of strings which have some kind of prefix. Let's think about a data structure that would allow us to understand it better. One of the most common data structures to store strings which works with their prefixes and maintains the number of strings with some prefix is a trie; so, we can reformulate this problem using tries. Now the problem is the following one: we have a binary trie of depth $n$; the leaves of this trie may store strings, and for each vertex except for the root, we can set a constraint on the number of strings stored in the subtree; what is the number of ways to choose these constraints so that the maximum number of strings (possibly with copies) the trie can store is exactly $f$? To handle it, we can use dynamic programming of the form $dp_{v,i}$ - the number of ways to choose the constraints for the vertex $v$ and its subtree so that the maximum number of strings which can be stored in the subtree is exactly $i$. When calculating $dp_{v,i}$, we can iterate on the constraint for the vertex $v$ (let it be $a$), and the maximum number of strings in the subtrees of $v_1$ and $v_2$ (let these be $b$ and $c$), and make updates of the form "add $dp_{v_1,b} \cdot dp_{v_2,c}$ to the value of $dp_{v, \min(a,b+c)}$". This dynamic programming will work in $O(2^n k^2)$ or $O(2^n k^3)$ depending on the implementation, which is too slow. However, we can use the following optimizations to improve the complexity of the solution: all vertices on the same depth can be treated as equivalent, so we can actually calculate this dynamic programming not for $O(2^n)$ vertices, but just for $O(n)$; when handling transitions from some node's children to that node, let's split these transitions into two steps. The first step is iterating on the number of strings which fit into the subtrees of the children; the second step is iterating on the constraint for the subtree of the node. The first step is actually a convolution: if we don't consider the constraint for the node itself, then the transitions would be something like "add $dp_{v_1,b} \cdot dp_{v_2,c}$ to the value of $dp_{v, b+c)}$"; so it can be improved to $O(k \log k)$ with FFT. The second step can be improved to $O(k)$ as well, if we iterate on the minimum between the constraint for the node and the total number of strings which can be stored in the children, and maintain the sum on suffix for the values of dynamic programming. Overall, these optimizations lead to a solution with complexity $O(n k \log k)$.
|
[
"bitmasks",
"brute force",
"dp",
"fft",
"flows",
"graphs",
"math",
"meet-in-the-middle",
"trees"
] | 2,500
| null |
1710
|
A
|
Color the Picture
|
A picture can be represented as an $n\times m$ grid ($n$ rows and $m$ columns) so that each of the $n \cdot m$ cells is colored with one color. You have $k$ pigments of different colors. You have a limited amount of each pigment, more precisely you can color at most $a_i$ cells with the $i$-th pigment.
A picture is considered beautiful if each cell has \textbf{at least} $3$ \textbf{toroidal} neighbors with the same color as itself.
Two cells are considered \textbf{toroidal} neighbors if they \textbf{toroidally} share an edge. In other words, for some integers $1 \leq x_1,x_2 \leq n$ and $1 \leq y_1,y_2 \leq m$, the cell in the $x_1$-th row and $y_1$-th column is a toroidal neighbor of the cell in the $x_2$-th row and $y_2$-th column if one of following two conditions holds:
- $x_1-x_2 \equiv \pm1 \pmod{n}$ and $y_1=y_2$, or
- $y_1-y_2 \equiv \pm1 \pmod{m}$ and $x_1=x_2$.
Notice that each cell has exactly $4$ toroidal neighbors. For example, if $n=3$ and $m=4$, the toroidal neighbors of the cell $(1, 2)$ (the cell on the first row and second column) are: $(3, 2)$, $(2, 2)$, $(1, 3)$, $(1, 1)$. They are shown in gray on the image below:
\begin{center}
{\small The gray cells show toroidal neighbors of $(1, 2)$.}
\end{center}
Is it possible to color all cells with the pigments provided and create a beautiful picture?
|
The picture must consist of some stripes with at least $2$ rows or at least $2$ columns. When $n$ is odd and all $\lfloor \frac{a_i}{m} \rfloor=2$, we cannot draw a beautiful picture using row stripes. Let's first prove hint1 first. If there is a pair of toroidal neighbors with different colors. For example, $col_{x,y}=a$ and $col_{x+1,y}=b(a\neq b)$. Then we will find $col_{x-1,y}=col_{x,y+1}=col_{x,y-1}=a$,$col_{x+2,y}=col_{x+1,y+1}=col_{x+1,y-1}=b$ must hold. Then we find another two pairs of toroidal neighbors $col_{x,y+1},col_{x+1,y+1}$ and $col_{x,y-1},col_{x+1,y-1}$. Repeat such process, we will find the boundary should be like: Similar, the boundaries can be vertical lines, but horizontal lines and vertical lines can not exist in one picture. So the pattern should be row stripes all with at least $2$ rows or column stripes all with at least $2$ columns. Check if one can draw a beautiful picture with row stripes only or with column stripes only. We consider only the case of row stripes, the reasoning is analogous for column stripes. If it is possible, then $\sum_{a_i \geq 2m} \lfloor \frac{a_i}{m} \rfloor \geq n$ must hold. If $n$ is even, then such a condition is enough. If $n$ is odd, there must be some $\lfloor \frac{a_i}{m} \rfloor \geq 3$. In this case, you can draw a beautiful picture using such algorithm: Sort $a_i$ from large to small. Sort $a_i$ from large to small. Draw $2$ rows stripes of each color if possible. Draw $2$ rows stripes of each color if possible. If the picture still has some rows empty, insert new rows into each stripe. If the picture still has some rows empty, insert new rows into each stripe. Total time complexity: $O(n)$.
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100010
int n,m,k;
int a[MAXN];
void work()
{
cin>>n>>m>>k;
for (int i=1;i<=k;i++)
cin>>a[i];
bool flag;
long long tot=0;
flag=0;
tot=0;
for (int i=1;i<=k;i++)
{
if (a[i]/n>2)
flag=1;
if (a[i]/n>=2)
tot+=a[i]/n;
}
if (tot>=m && (flag || m%2==0))
{
cout<<"Yes"<<endl;
return ;
}
flag=0;
tot=0;
for (int i=1;i<=k;i++)
{
if (a[i]/m>2)
flag=1;
if (a[i]/m>=2)
tot+=a[i]/m;
}
if (tot>=n && (flag || n%2==0))
{
cout<<"Yes"<<endl;
return ;
}
cout<<"No"<<endl;
}
int main()
{
int casenum=1;
cin>>casenum;
for (int testcase=1;testcase<=casenum;testcase++)
work();
return 0;
}
|
1710
|
B
|
Rain
|
You are the owner of a harvesting field which can be modeled as an infinite line, whose positions are identified by integers.
It will rain for the next $n$ days. On the $i$-th day, the rain will be centered at position $x_i$ and it will have intensity $p_i$. Due to these rains, some rainfall will accumulate; let $a_j$ be the amount of rainfall accumulated at integer position $j$. Initially $a_j$ is $0$, and it will increase by $\max(0,p_i-|x_i-j|)$ after the $i$-th day's rain.
A flood will hit your field if, at any moment, there is a position $j$ with accumulated rainfall $a_j>m$.
You can use a magical spell to erase \textbf{exactly one} day's rain, i.e., setting $p_i=0$. For each $i$ from $1$ to $n$, check whether in case of erasing the $i$-th day's rain there is no flood.
|
The maximum can always be achieved in the center position of one day's rain. $a_i$ is a piecewise linear function and the slope of $a_i$ will only change for $O(n)$ times. Supposing you know an invalid position $j$ where $a_j>m$, what are the properties of a rain that, if erase, makes it valid? Let's call position $j$ a key position if it is the center position of a rain. i.e. there exists $i$ so that $x_i=j$. You can calculate $a_j$ for all key positions $j$ using the difference array. Let $d^{1}_{j}=a_{j}-a_{j-1}$, $d^{2}_{j}=d^{1}_{j}-d^{1}_{j-1}$, then the $i$-th day's rain will change it as follows: $d^{2}_{x_i-p_i+1} \leftarrow d^{2}_{x_i-p_i+1}+1$ $d^{2}_{x_i+1} \leftarrow d^{2}_{x_i+1}-2$ $d^{2}_{x_i+p_i+1} \leftarrow d^{2}_{x_i+p_i+1}+1$ This can be calculated efficiently using prefix sums. We say that a position $j$ is valid if $a_j\le m$. Now, consider an invalid position $j$; erasing the $i$-th day's rain will make it valid if and only if $p_i-|x_i-j| \geq a_j-m$. One can check that the region of $(x, p)$ satisfying such an inequality is a quadrant rotated $45^\circ$ anticlockwise and translated. And in particular, even the intersections of two such regions have the same structure and can be computed easily (to avoid using floating point numbers, one can multiply all $x_i,p_i$ by $2$). In the end, for each $i$, you only need to check whether point $(x_i,p_i)$ belongs to such region. Total time complexity: $O(n\log n)$.
|
[
"binary search",
"brute force",
"data structures",
"geometry",
"greedy",
"implementation",
"math"
] | 2,100
|
#include <bits/stdc++.h>
#define MAXN 200100
#define LL long long
using namespace std;
typedef pair<LL,LL> pll;
LL n,m;
LL x[MAXN],p[MAXN];
vector<pll> diff;
pll key;
pll getIntersection(pll p1,pll p2)
{
LL tx=max(p1.first+p1.second,p2.first+p2.second);
LL ty=max(p1.second-p1.first,p2.second-p2.first);
return {(tx-ty)/2,(tx+ty)/2};
}
void work()
{
diff.clear();
key={0,-0x3f3f3f3f3f3f3f3f};
cin>>n>>m;
m*=2;
for (int i=1;i<=n;i++)
{
cin>>x[i]>>p[i];
x[i]*=2;
p[i]*=2;
diff.push_back({x[i]-p[i],1});
diff.push_back({x[i],-2});
diff.push_back({x[i]+p[i],1});
}
sort(diff.begin(), diff.end());
LL a=0,d=0;
LL lst=0;
for (auto p:diff)
{
if (p.first!=lst)
{
a=a+(p.first-lst)*d;
lst=p.first;
if (a>m)
key=getIntersection(key,{p.first,a-m});
}
d+=p.second;
}
for (int i=1;i<=n;i++)
if (getIntersection(key,{x[i],p[i]})==pll(x[i],p[i]))
cout<<'1';
else
cout<<'0';
cout<<endl;
}
int main()
{
int casenum=1;
cin>>casenum;
for (int testcase=1;testcase<=casenum;testcase++)
work();
return 0;
}
|
1710
|
C
|
XOR Triangle
|
You are given a positive integer $n$. Since $n$ may be very large, you are given its binary representation.
You should compute the number of triples $(a,b,c)$ with $0 \leq a,b,c \leq n$ such that $a \oplus b$, $b \oplus c$, and $a \oplus c$ are the sides of a non-degenerate triangle.
Here, $\oplus$ denotes the bitwise XOR operation.
You should output the answer modulo $998\,244\,353$.
Three positive values $x$, $y$, and $z$ are the sides of a non-degenerate triangle if and only if $x+y>z$, $x+z>y$, and $y+z>x$.
|
Consider the same bit of three integers at the same time. $a\bigoplus b \leq a+b$ Define $cnt_{i_1 i_2 i_3}$ as: $j$th bit of $cnt_{i_1 i_2 i_3}$ is $1$ iif $i_1=a_j,i_2=b_j,i_3=c_j$ e.g. $a=(10)_2,b=(11)_2,c=(01)_2$ then $cnt_{110}=(10)_2,cnt_{011}=(01)_2$, other $cnt$ is 0. $a=cnt_{100}+cnt_{101}+cnt_{110}+cnt_{111}$ $b=cnt_{010}+cnt_{011}+cnt_{110}+cnt_{111}$ $c=cnt_{001}+cnt_{011}+cnt_{101}+cnt_{111}$ $a\bigoplus b = cnt_{010}+cnt_{011}+cnt_{100}+cnt_{101}$ $a\bigoplus c = cnt_{001}+cnt_{011}+cnt_{100}+cnt_{110}$ $b\bigoplus c = cnt_{001}+cnt_{010}+cnt_{101}+cnt_{110}$ $a\bigoplus b + a\bigoplus c > b \bigoplus c \iff cnt_{011}+cnt_{100}>0$ similar: $cnt_{101}+cnt_{010}>0$ $cnt_{110}+cnt_{001}>0$ then we use digit dp: $dp[n][i][j]$ means when we consider first $n$ bits, state of reaching the upper bound is $i$, state of conditions is $j$. Enumerate $a_j b_j c_j$ for $j$ from $|n|-1$ to $0$ and make transition. Time complexity is $O(2^9 |n|)$ where $|n|$ is the length of input.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"greedy",
"math"
] | 2,500
|
#include <bits/stdc++.h>
#define MAXN 200100
#define LL long long
#define MOD 998244353
using namespace std;
LL dp[MAXN][8][8];
string s;
int main()
{
cin>>s;
dp[0][0][0]=1;
for (int i=0;i<s.size();i++)
for (int mask1=0;mask1<8;mask1++)
for (int mask2=0;mask2<8;mask2++)
{
dp[i][mask1][mask2]%=MOD;
for (int m=0;m<8;m++)
{
bool flag=false;
for (int j=0;j<3;j++)
if (s[i]=='0' && (mask2>>j)%2==0 && (m>>j)%2==1)
{
flag=true;
break;
}
if (flag)
continue;
int tmpmask1=mask1;
int tmpmask2=mask2;
for (int j=0;j<3;j++)
if (s[i]-'0'!=((m>>j)&1))
tmpmask2|=(1<<j);
for (int j=0;j<3;j++)
if (m==(1<<j) || m==7-(1<<j))
tmpmask1|=(1<<j);
dp[i+1][tmpmask1][tmpmask2]+=dp[i][mask1][mask2];
}
}
LL ans=0;
for (int i=0;i<8;i++)
ans+=dp[s.size()][7][i];
cout<<ans%MOD<<endl;
return 0;
}
|
1710
|
D
|
Recover the Tree
|
Rhodoks has a tree with $n$ vertices, but he doesn't remember its structure. The vertices are indexed from $1$ to $n$.
A segment $[l,r]$ ($1 \leq l \leq r \leq n$) is good if the vertices with indices $l$, $l + 1$, ..., $r$ form a connected component in Rhodoks' tree. Otherwise, it is bad.
For example, if the tree is the one in the picture, then only the segment $[3,4]$ is bad while all the other segments are good.
For each of the $\frac{n(n+1)}{2}$ segments, Rhodoks remembers whether it is good or bad. Can you help him recover the tree? If there are multiple solutions, print any.
It is guaranteed that the there is at least one tree satisfying Rhodoks' description.
|
Thank dario2994, the key part of the proof is from him. If interval $A,B$ are all good and $A \cap B \neq \emptyset$, then $A \cap B$ is good, too. If interval $A,B$ are all good and $A \cap B \neq \emptyset$, then $A \cup B$ is good, too. Consider enumerating good intervals according to their length. Let's consider the interval in the order of its length (small to large) and add the edge one by one. Initially, the graph has no edge. There are $n$ connected components each consisting of exactly one vertex. Note our algorithm will guarantee that at every moment every connected component's indices compose an interval. Let $[L_i,R_i]$ be the connected component vertex $i$ in. If $[x,y]$ is good and $x$ and $y$ are not in the same connected component, we can merge $[L_x,R_y]$ into a larger connected component. Supposing $[L_x,R_y]$ consist of $k+2$ connected components now, let's call them $[l_0,r_0],[l_1,r_1],\cdots,[l_{k+1},r_{k+1}](x\in [l_0,r_0],y\in [l_{k+1},r_{k+1}])$, you can link edges like: $\cdots-l_4-l_2-x-y-l_1-l_3-\cdots$ If $[x,y]$ is good and $x$ and $y$ are in the same connected component, then we do nothing. Finally, you will get a valid tree. Total time complexity: $O(n^2)$. Let $ans[x][y]$ be if interval $[x,y]$ is good as the input data demands. Let $res[x][y]$ be if interval $[x,y]$ is good in our answer tree. Assume that the intervals we have considered are consistent with the input and we are considering $[x,y]$. Let's first prove if $ans[x][y]=1$ then $res[x][y]=1$. If interval $x,y$ are in different connected components when $[x,y]$ is enumerated. The edge-link method will ensure $[x,y]$ is good in our answer tree. If interval $x,y$ are in the same connected components when $[x,y]$ is enumerated. Since $[x,y]$ has been merged into a larger connected component, then there must be a series of good intervals: $I_1,I_2,\cdots,I_k,I_{i+1} \cap I_i \neq \emptyset,I_i \cap [x,y] \neq \emptyset, [x,y] \subset \cup I_i$ Let $J_i=I_i \cap [x,y]$ Then according to hint1, all $J_i$ is good. $J_{i+1} \cap J_i \neq \emptyset, \cup J_i =[x,y]$ Then we know $[x,y]$ is good in our tree, too. Let's then prove if $ans[x][y]=0$ then $res[x][y]=0$. Assume that we are processing the interval $[x, y]$ and up to now we did not create an invalid interval. I will prove that even after "connecting" $[x, y]$ it still remains true that bad intervals are not connected. Let $I=[a,b]$ not be connected before performing the operation on $[x, y]$ and become connected later. Let CC be "connected component". Case1: $I$ does not contain $x$ or does not contain $y$, and at least one of $a,b$ is in $(R_x,L_y)$. When $a,b$ are in different CC, $I$ does not contain both of $x$ and $y$ while they are the key vertices to walk from CC $i$ to CC $i+1$. When $a,b$ are in the same CC, the link will have no influence on its connectivity. Case2: $I$ contains $[x,y]$. If $[a,b]$ becomes connected after the linking, since we only add edges in $[x,y]$, $[a,x]$ and $[y,b]$ must be connected. Since $[a,x],[x,y],[y,b]$ are all good, $[a,b]$ is good and we are happy. case3: $b \leq R_x$ or $a \geq L_y$. $I$'s connectivity will not be influenced. The proof is rather long and hard, and if you have some better ideas please share them.
|
[
"constructive algorithms",
"trees"
] | 3,400
|
#include <bits/stdc++.h>
using namespace std;
#define MAXN 5100
typedef pair<int,int> pii;
int n;
char good[MAXN][MAXN];
int lv[MAXN],rv[MAXN];
vector<pii> ans;
void work()
{
ans.clear();
cin>>n;
for (int i=1;i<=n;i++)
{
lv[i]=rv[i]=i;
cin>>(good[i]+i);
}
for (int len=2;len<=n;len++)
for (int l=1;l<=n+1-len;l++)
{
int r=l+len-1;
if (good[l][r]=='1' && lv[l]!=lv[r] && rv[l]!=rv[r])
{
ans.push_back({l,r});
vector<int> tmp[2];
int id=1;
tmp[0].push_back({l});
tmp[1].push_back({r});
for (int i=rv[l]+1;i<lv[r];i++)
if (lv[i]==i)
{
ans.push_back({tmp[id].back(),i});
tmp[id].push_back(i);
id^=1;
}
int lm=lv[l];
int rm=rv[r];
for (int i=lm;i<=rm;i++)
{
lv[i]=lm;
rv[i]=rm;
}
}
}
for (auto p:ans)
cout<<p.first<<' '<<p.second<<endl;
}
int main()
{
int casenum=1;
cin>>casenum;
for (int testcase=1;testcase<=casenum;testcase++)
work();
return 0;
}
|
1710
|
E
|
Two Arrays
|
You are given two arrays of integers $a_1,a_2,\dots,a_n$ and $b_1,b_2,\dots,b_m$.
Alice and Bob are going to play a game. Alice moves first and they take turns making a move.
They play on a grid of size $n \times m$ (a grid with $n$ rows and $m$ columns). Initially, there is a rook positioned on the first row and first column of the grid.
During her/his move, a player can do one of the following two operations:
- Move the rook to a \textbf{different} cell on the same row or the same column of the current cell. A player cannot move the rook to a cell that has been visited $1000$ times before (i.e., the rook can stay in a certain cell at most $1000$ times during the entire game). Note that the starting cell is considered to be visited once at the beginning of the game.
- End the game immediately with a score of $a_r+b_c$, where $(r, c)$ is the current cell (i.e., the rook is on the $r$-th row and $c$-th column).
Bob wants to maximize the score while Alice wants to minimize it. If they both play this game optimally, what is the final score of the game?
|
Since they are very smart, they know the result of the game at the beginning. If the result is $x$, then Alice will end the game when Bob moves to a cell with score less than $x$, and something analogous holds for Bob. Thus, Alice can only move to a certain subset of cells, and the same holds for Bob. Knowing the above facts, it is clear that we can apply binary search on the answer $Z$, which is less than $a_1+b_1$, or Alice can end the game immediately to get $a_1+b_1$. Let's color white all the cells with $a_r+b_c \leq Z$, and black all the cells with $a_r+b_c > Z$. Then we shall add edges between cells in the same row or same column with different colors. These edges and cells form a bipartite graph. Consider the game on the bipartite graph. Initially, we are at cell $(1,1)$. Alice moves first, then they take turns to move. Each player can only move the cell to another place with an edge connecting them, or the other player will end the game immediately. Each cell can be visited at most $1000$ times, whoever cannot move loses. If Alice wins, then the answer is no greater than $Z$, otherwise, the answer is greater than $Z$. The version of this game where each vertex can be visited exactly once is known. If both players play optimally, the first player wins iff the starting vertex belongs to all possible maximum matchings. I'll explain why at the end of the editorial. It turns out that the condition is exactly the same even if each vertex can be visited at most $1000$ times. Let us show why. First, calculate the maximum matching. Then we erase the starting vertex and calculate the maximum matching in the new graph. If two matchings have the same size, the vertex does not belong to all maximum matchings and vice versa. Now, we know that if we copy a cell $1000$ times and copy the edges as well, this problem is exactly the same as the model mentioned above. If we consider the initial bipartite graph, it's easy to see that we only need to check whether $(1,1)$ is in all maximum matchings of the initial graph, because the maximum matching remains unchanged in the other $999$ parts. So, we have shifted the problem to see if the initial cell belongs to all matchings. According to [Kőnig's theorem in graph theory](https://en.wikipedia.org/wiki/K%C5%91nig%27s_theorem_(graph_theory)), the size of the maximum matching is equal to the size of the minimum vertex cover. And if you erase all vertices in the minimum vertex cover, you get an independent set, which is the maximum independent set. Using $M$ to refer to the maximum matching, $I$ to refer to the maximum independent set, $V$ to refer to the set of vertices, we know that $|M|+|I|=|V|$ So, if we erase one vertex and $|M|$ remains unchanged, then $|I|$ must be changed and vice versa. Now our issue is to calculate the maximum independent set in this graph, with or without the initial cell. Let us sort $a_i$ and $b_i$ (notice that reordering rows and columns do not change the game at all). Now the white cells form a "decreasing histogram". We can still find the starting cell $(va,vb)$. First, let's compute the maximum independent set with the initial cell. Before that, consider the following constraints: It's obvious that one column has at most one color of its cells in the independent set(we shall call it $I$), so does a row. Let's call a column white if only white cells of it are in $I$, otherwise, we shall call it black. What is the maximum size of $I$, when we must have $i$ white columns and $j$ white rows? The answer is simple. We shall select the first $i$ columns to be white and the first $j$ rows to be white, the rest of the columns and rows to be black. Then the independent set consists of black cells on black rows and black columns, and white cells on white columns and white rows. It's easy to prove this greedy strategy is correct. Now we fix the number of white columns as $i$, and try to find a $j$ that maximizes $|I|$. If we make an array $da[i]$ satisfying $a_i+b_{da[i]}\leq Z$ and $a_i + b_{da[i]+1} > Z$, and a similar array $db[j]$, we can easily calculate the change of $|I|$ when we turn row $j$ from black to white and vice versa, which is $n-max(i,db[j])-min(i,db[j])$, $-min(i,db[j])$ means remove the white part from $I$, $+n-max(i,db[j])$ means add the black part to $I$. For a fixed $i$, it's easy to see that the change increases with $j$. So you can maintain all positive changes of $|I|$, just decrease the $j$ with $i$ decreasing. Now you can calculate the maximum of $|I|$ in $O(n+m)$ time. It's easy to see that $da[i]$ and $db[i]$ are non-increasing, so they can be calculated in $O(n+m)$ time. For the maximum independent set without the initial cell, you just need to remove it when it is in $I$. Since the cell is always black, it is quite easy. Using binary search on the answer, you can solve the whole problem in $O((n+m)\log A+n\log n+m\log m)$, where $A$ is the maximum value of the arrays $a$ and $b$. Let us conclude with the idea of the known game on bipartite graphs. \textbf{Lemma}: The first player can win if and only if all possible maximum matchings include the initial vertex $H$. Let's prove it when $H$ satisfies the constraint. The first player can just choose any matching $M$ and move to the vertex $P$ matching with current vertex, then any unvisited neighbor of $P$ still matches with other unvisited vertices. If $P$ has a neighbor unmatched in a certain matching $M$, we find an augmenting path and a matching $M'$ that doesn't include $H$, which is in conflict with the constraint. So no matter how the second player chooses to move, the first player always has a vertex to go after that. Otherwise, we add a vertex $P$ with the only edge $(P,H)$, move the initial cell to $P$, swap the two players, then it turns into the situation above.
|
[
"binary search",
"games",
"graph matchings"
] | 2,400
|
#include <bits/stdc++.h>
using ll=long long;
using std::cin;
using std::cerr;
using std::cout;
using std::min;
using std::max;
template<class T>
void ckmx(T &A,T B){
A<B?A=B:B;
}
const int N=2e5+7;
int n,m,va,vb;
int a[N],b[N];
int da[N],db[N];
bool check(int x){
ll sm=0,f1=0,f2=0;
for(int j=m,i=0;j>=1;--j){
while(i<n&&a[i+1]+b[j]<=x)
++i;
db[j]=i;
sm+=db[j];
}
for(int i=n,j=0;i>=1;--i){
while(j<m&&a[i]+b[j+1]<=x)
++j;
da[i]=j;
}
f1=f2=sm;
for(int i=n,j=m;i>=1;--i){
sm-=min(j,da[i]);
sm+=m-max(j,da[i]);
ckmx(f1,sm);
ckmx(f2,sm-(i<=va&&j<vb));
while(j&&min(db[j],i-1)<=n-max(db[j],i-1)){
sm-=min(db[j],i-1);
sm+=n-max(db[j],i-1);
--j;
ckmx(f1,sm);
ckmx(f2,sm-(i<=va&&j<vb));
}
}return f1==f2;
}
void Main(){
cin>>n>>m;
for(int i=1;i<=n;++i)
cin>>a[i];
for(int j=1;j<=m;++j)
cin>>b[j];
va=a[1],vb=b[1];
std::sort(a+1,a+n+1);
std::sort(b+1,b+m+1);
int l=a[1]+b[1],r=va+vb;
va=std::lower_bound(a+1,a+n+1,va)-a;
vb=std::lower_bound(b+1,b+m+1,vb)-b;
while(l<r){
int mid=(l+r)>>1;
if(check(mid))
r=mid;
else
l=mid+1;
}cout<<l<<"\n";
}
inline void File(){
cin.tie(nullptr)->sync_with_stdio(false);
#ifdef zxyoi
freopen("my.in","r",stdin);
#endif
}signed main(){File();Main();return 0;}
|
1711
|
A
|
Perfect Permutation
|
You are given a positive integer $n$.
The weight of a permutation $p_1, p_2, \ldots, p_n$ is the number of indices $1\le i\le n$ such that $i$ divides $p_i$. Find a permutation $p_1,p_2,\dots, p_n$ with the minimum possible weight (among all permutations of length $n$).
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).
|
The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$.
|
[
"constructive algorithms"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void work()
{
int n;
cin>>n;
cout<<n<<' ';
for (int i=1;i<n;i++)
cout<<i<<' ';
cout<<endl;
}
int main()
{
int casenum=1;
cin>>casenum;
for (int testcase=1;testcase<=casenum;testcase++)
work();
return 0;
}
|
1711
|
B
|
Party
|
A club plans to hold a party and will invite some of its $n$ members. The $n$ members are identified by the numbers $1, 2, \dots, n$. If member $i$ is not invited, the party will gain an unhappiness value of $a_i$.
There are $m$ pairs of friends among the $n$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.
However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.
What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?
|
See the party as a graph. Divide the vertices into two categories according to their degrees' parity. Let's consider the case where $m$ is odd only, since if $m$ is even the answer is $0$. Assume that you delete $x$ vertices with even degrees and $y$ vertices with odd degrees. If $y \geq 1$, then only deleting one vertex with an odd degree would lead to a not worse answer, so you do not need to consider it except for $(x,y)=(0,1)$. If $y=0$, then the parity of the edges at the end is determined only by the number of edges whose both endpoints are deleted. In particular, there must be at least two adjacent vertices deleted with even degrees. So you do not need to consider it except for $(x,y)=(2,0)$ and they are neighbours. Thus, an optimal solution either has $(x, y) = (0, 1)$ or $(x, y) = (2, 0)$ and the two vertices are adjacent. One can iterate over all possible solutions with such a structure and take the optimal one. Total time complexity: $O(n+m)$.
|
[
"brute force",
"graphs"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100010
int x[MAXN],y[MAXN],a[MAXN],degree[MAXN];
int n,m;
void work()
{
cin>>n>>m;
for (int i=1;i<=n;i++)
{
degree[i]=0;
cin>>a[i];
}
for (int i=1;i<=m;i++)
{
cin>>x[i]>>y[i];
degree[x[i]]++;
degree[y[i]]++;
}
int ans=INT_MAX;
if (m%2==0)
ans=0;
for (int i=1;i<=n;i++)
if (degree[i]%2==1)
ans=min(ans,a[i]);
for (int i=1;i<=m;i++)
if (degree[x[i]]%2==0 && degree[y[i]]%2==0)
ans=min(ans,a[x[i]]+a[y[i]]);
cout<<ans<<endl;
}
int main()
{
int casenum=1;
cin>>casenum;
for (int testcase=1;testcase<=casenum;testcase++)
work();
return 0;
}
|
1712
|
A
|
Wonderful Permutation
|
\begin{quote}
God's Blessing on This PermutationForces!
\hfill A Random Pebble
\end{quote}
You are given a permutation $p_1,p_2,\ldots,p_n$ of length $n$ and a positive integer $k \le n$.
In one operation you can choose two indices $i$ and $j$ ($1 \le i < j \le n$) and swap $p_i$ with $p_j$.
Find the minimum number of operations needed to make the sum $p_1 + p_2 + \ldots + p_k$ as small as possible.
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).
|
For any permutation $p$ of length $n$, the final sum $p_1 + p_2 + \ldots + p_k$ after some number of operations can't be less than $1 + 2 + \ldots + k$. This means that we need to apply the operation at least once for every $i$ such that $1 \le i \le k$ and $p_i > k$. Every time we apply it, we have to choose some index $j$ such that $k < j \le n$ and $p_j \le k$. This is always possible since initially the number of suitable $i$ is equal to the number of suitable $j$, and one operation decreases both the number of suitable $i$ and the number of suitable $j$ by one. It is easy to see that in the end, the set $\{p_1, p_2, \ldots, p_k \}$ only contains the values $\{1, 2, \ldots , k \}$, which means that the sum is equal to $1 + 2 + \ldots + k$, which is the smallest sum we can get. So the answer is the the number of $i$ such that $1 \le i \le k$ and $p_i > k$. Complexity: $\mathcal{O}(n)$ Bonus: solve for every $k$ from $1$ to $n$ for $n \le 10^5$.
|
[
"greedy",
"implementation"
] | 800
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
vector<int> b = a;
sort(all(b));
int x = b[k - 1];
int ans = 0;
for (int i = 0; i < k; i++) {
if (a[i] > x) ans++;
}
cout << ans << nl;
}
}
|
1712
|
B
|
Woeful Permutation
|
\begin{quote}
I wonder, does the falling rain
\end{quote}
\begin{quote}
Forever yearn for it's disdain?
\hfill Effluvium of the Mind
\end{quote}
You are given a positive integer $n$.
Find any permutation $p$ of length $n$ such that the sum $\operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorname{lcm}(n, p_n)$ is as large as possible.
Here $\operatorname{lcm}(x, y)$ denotes the least common multiple (LCM) of integers $x$ and $y$.
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).
|
A well know fact is that $\gcd(a,b) \cdot \operatorname{lcm}(a,b) = a \cdot b$ for any two positive integers $a$ and $b$. Since $\gcd(x, x + 1) = 1$ for all positive $x$, we get that $\operatorname{lcm}(x,x+1) = x \cdot (x + 1)$. All of this should hint that for even $n$, the optimal permutation looks like this: $2,1,4,3,\ldots,n,n-1$. Add for odd $n$, it looks like this: $1,3,2,5,4,\ldots,n,n-1$. Complexity: $\mathcal{O}(n)$ Turns out the formal proof is pretty hard. You are welcome to try and find something simpler. Define $f(x, y)$ as $x \cdot y$ if $x \ne y$, and $x$ otherwise. It is easy to see that $\operatorname{lcm}(x, y) \le f(x, y)$. We will find the maximum possible value of $f(1, p_1) + \ldots f(n, p_n)$ and show that it is reached by our construction. Suppose we want to solve this problem: find the max possible value of $1 \cdot p_1 + \ldots + n \cdot p_n$, if for all $i > 1$, $p_i \ne i$. This is equivalent to maximizing $f(1, p_1) + \ldots f(n, p_n)$, because if there is such an index $i$, it is always optimal to swap $p_i$ with $p_j$ for any $1 \le j < i$. Let's build a graph on this permutation with n vertices and add all edges $i \rightarrow p_i$. Except for maybe $p_1 = 1$, all the other cycles have a length of at least 2. Let's look at one such cycle $x_1, x_2, \ldots, x_k$. The optimal value with no restrictions on the value of $p_i$ would be $x_1^2 + x_2^2 + \ldots + x_k^2$, but right now we have $x_1 \cdot x_2 + x_2 \cdot x_3 + \ldots + x_k \cdot x_1$. Subtracting one from the other: $x_1^2 + x_2^2 + \ldots + x_k^2 - (x_1 \cdot x_2 + x_2 \cdot x_3 + \ldots + x_k \cdot x_1) =$ $= \frac{x_1^2}{2} - x_1 \cdot x_2 + \frac{x_2^2}{2} + \frac{x_2^2}{2} - x_2 \cdot x_3 + \frac{x_3^2}{2} + \ldots + \frac{x_k^2}{2} - x_k \cdot x_1 + \frac{x_1^2}{2} =$ $= \frac{(x_1 - x_2)^2 + (x_2 - x_3)^2 + \ldots + (x_k - x_1)^2}{2} \ge$ $\ge \frac{|x_1 - x_2| + |x_2 - x_3| \ldots + |x_k - x_1|}{2} \ge$ $\ge \max(x_1 \ldots x_k) - \min(x_1 \ldots x_k)$ So we need to minimize the sum of $\max(x_1 \ldots x_k) - \min(x_1 \ldots x_k)$ over all cycles. If $n$ is even, it is easy to see the minimum possible value of this is $\frac{n}{2}$, and it doesn't matter what $p_1$ equals to. For odd $n$ we have to look at two cases: $p_1 = 1$ and $p_1 \ne 1$. In the first case, the minimum possible sum is $\frac{n - 1}{2}$, in the second case, it is $\frac{n + 1}{2}$, which is worse that in the previous case. Returning to the original problem, our constructions also achieve this minimal difference from $1^2 + 2^2 + \ldots n$ even when we change $f$ back into $\operatorname{lcm}$, so they are optimal. Bonus: try to prove the solution without the editorial!
|
[
"constructive algorithms",
"greedy",
"number theory"
] | 800
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
if (n % 2 == 0) {
for (int i = 1; i <= n; i += 2) {
cout << i + 1 << ' ' << i << ' ';
}
cout << nl;
} else {
cout << 1 << ' ';
for (int i = 2; i <= n; i += 2) {
cout << i + 1 << ' ' << i << ' ';
}
cout << nl;
}
}
}
|
1712
|
C
|
Sort Zero
|
\begin{quote}
An array is sorted if it has no inversions
\hfill A Young Boy
\end{quote}
You are given an array of $n$ \textbf{positive} integers $a_1,a_2,\ldots,a_n$.
In one operation you do the following:
- Choose \textbf{any} integer $x$.
- For all $i$ such that $a_i = x$, do $a_i := 0$ (assign $0$ to $a_i$).
Find the minimum number of operations required to sort the array in non-decreasing order.
|
An array is sorted in non-decreasing order if and only if there is no index $i$ such that $a_i > a_{i + 1}$. This leads to a strategy: while there is at least one such index $i$, apply one operation with $x = a_i$. Why is this optimal? Since our operation can only decrease values, and we must decrease $a_i$ so that $a_i > a_{i + 1}$ is no longer true, this leaves us no choice but to use the operation with $x = a_i$. You can simulate this strategy by maintaining a set of bad indices, since if an index $i$ becomes bad, after you apply an operation with $x = a_i$, it can never become bad again. So in total, there are at most $2 \cdot (n - 1)$ operations with the set. Complexity: $\mathcal{O}(n \log n)$ or $\mathcal{O}(n)$, depending on which set you use. Note: you can solve the problem in $\mathcal{O}(n)$ by noticing that if an index $i$ is bad, we need to apply the operation for all unique non-zero values in $\{a_1 \ldots a_i\}$. This is also quite a bit shorter to code. Bonus: solve for when $a_i$ can also be negative.
|
[
"greedy",
"sortings"
] | 1,100
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<int> a(n);
map<int, vector<int>> p;
for (int i = 0; i < n; i++) {
cin >> a[i];
p[a[i]].push_back(i);
}
int ans = 0;
set<int> ts;
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) ts.insert(i);
}
while (!ts.empty()) {
int i = *ts.begin();
int x;
if (a[i] > 0) {
x = a[i];
} else {
x = a[i + 1];
}
for (int j: p[x]) {
a[j] = 0;
ts.erase(j - 1);
ts.erase(j);
if (j > 0 && a[j - 1] > a[j]) ts.insert(j - 1);
if (j + 1 < n && a[j] > a[j + 1]) ts.insert(j);
}
ans++;
}
cout << ans << nl;
}
}
|
1712
|
D
|
Empty Graph
|
\begin{quote}
— Do you have a wish?
\end{quote}
\begin{quote}
— I want people to stop gifting each other arrays.
\hfill O_o and Another Young Boy
\end{quote}
An array of $n$ \textbf{positive} integers $a_1,a_2,\ldots,a_n$ fell down on you from the skies, along with a positive integer $k \le n$.
You can apply the following operation at most $k$ times:
- Choose an index $1 \le i \le n$ and an integer $1 \le x \le 10^9$. Then do $a_i := x$ (assign $x$ to $a_i$).
Then build a complete undirected \textbf{weighted} graph with $n$ vertices numbered with integers from $1$ to $n$, where edge $(l, r)$ ($1 \le l < r \le n$) has weight $\min(a_{l},a_{l+1},\ldots,a_{r})$.
You have to find the maximum possible diameter of the resulting graph after performing at most $k$ operations.
The diameter of a graph is equal to $\max\limits_{1 \le u < v \le n}{\operatorname{d}(u, v)}$, where $\operatorname{d}(u, v)$ is the length of the shortest path between vertex $u$ and vertex $v$.
|
First of all, we will always use the operation to assign $10^9$ to $a_i$. 1. Suppose $u < v$. Then $\operatorname{d}(u, v) = \min(\min(a_u \ldots a_v), 2 \cdot \min(a_1 \ldots a_n))$. Proof: since the weight of an edge is always $\ge \min(a_1 \ldots a_n)$, the best we can do with one edge is $\min(a_u \ldots a_v)$. And the best we can possibly do with two edges is $2 \cdot \min(a_1 \ldots a_n)$, which turns out possible to achieve. Subproof: suppose $i_{min}$ is the index of one of the minimums in the array. If $u \le i_{min} \le v$, then $\min(a_u \ldots a_v)$ is optimal, so we don't need two edges in the first place. Else, either $i_{min} < u$ or $i_{min} > v$. In the first case, we can notice that $\operatorname{d}(u, 1) + \operatorname{d}(1, v) = 2 \cdot \min(a_1 \ldots a_n)$. In the second case, $\operatorname{d}(u, n) + \operatorname{d}(n, v) = 2 \cdot \min(a_1 \ldots a_n)$. 2. The diameter of the graph is equal to $\max\limits_{1 \le i \le n - 1}{\operatorname{d}(i, i + 1)} = \min \left( \max\limits_{1 \le i \le n - 1}{\min(a_i,a_{i+1})}, 2 \cdot \min(a_1 \ldots a_n) \right)$. Proof: since the minimum of a subsegment can only decrease when it's length increases, it is optimal to look only at the distance between two adjacent vertices. Now we can either do binary search on the answer, or we can do a clever greedy. Binary search solution: Suppose the answer is $\ge ans$. First of all, we need to apply the operation for all $a_i < \frac{ans}{2}$. If there are not enough operations to do this, return false. Otherwise assign $10^9$ to such $a_i$. If there are no operations left, just calculate the diameter and see if it is $\ge ans$. If there is at least one operation left, there are two cases: $k = 1$ and $k \ge 2$. If the first case, it is optimal to apply our operation near one of the maximums in the array to maximize $\min(a_i, a_{i + 1})$, so we need to return true if $\max(a_1 \ldots a_n) \ge ans$. With $k > 1$, it is optimal to apply the operation near an index which has been turned into $10^9$, so we always return true. Make sure to binary search on $ans$ from $1$ to $10^9$ inclusive. Doing it from $1$ to $2\cdot 10^9$ needs another case to work. Complexity: $\mathcal{O}(n \log A)$. Greedy solution: We can actually maintaining the diameter of the graph while supporting point update queries (set $a_i$ to some value). To do this, we can use any structure that can get $\max\limits_{1 \le i \le n - 1}{\min(a_i,a_{i+1})}$ (multiset, segment tree) and another structure to maintain the minimum in the array. Change the $k - 1$ smallest values in the array into $10^9$. For every $i$ from $1$ to $n$, change $a_i$ to $10^9$, get the diameter, and then change $a_i$ back to it's original value. The answer is the max value over all the returned diameters. Proof: obviously works for $k = 1$, so suppose $k \ge 2$. Since we changed at least one value, we will check if having two adjacent $10^9$ is optimal, maximizing $\max\limits_{1 \le i \le n - 1}{\min(a_i,a_{i+1})}$. And we will also check if we need to change the $k$-th smallest value, in this case maximizing $2 \cdot \min(a_1 \ldots a_n)$. Complexity: $\mathcal{O}(n \log n)$ Note: it is also possible to solve without data structures by doing a bit more casework, but the solution is still $\mathcal{O}(n \log n)$ due to sorting. Bonus: solve for every $k$ from $1$ to $n$.
|
[
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"shortest paths"
] | 2,000
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int inf = 1000000000;
bool f(vector<int> a, int k, int ans) {
int n = gsize(a);
int dk = 0;
for (int i = 0; i < n; i++) {
if (a[i] * 2 < ans) {
a[i] = inf;
k--;
dk++;
}
}
if (k < 0) return false;
if ((k > 0 && dk > 0) || k >= 2) return true;
if (k == 1 && dk == 0) {
return *max_element(all(a)) >= ans;
}
for (int i = 0; i < n - 1; i++) {
if (min(a[i], a[i + 1]) >= ans) return true;
}
return false;
}
void solve() {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int lb = 0, ub = inf, tans = 0;
while (lb <= ub) {
int tm = (lb + ub) / 2;
if (f(a, k, tm)) {
tans = tm;
lb = tm + 1;
} else {
ub = tm - 1;
}
}
cout << tans << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) solve();
}
|
1712
|
E2
|
LCM Sum (hard version)
|
\begin{quote}
We are sum for we are many
\hfill Some Number
\end{quote}
\textbf{This version of the problem differs from the previous one only in the constraint on $t$. You can make hacks only if both versions of the problem are solved.}
You are given two positive integers $l$ and $r$.
Count the number of distinct triplets of integers $(i, j, k)$ such that $l \le i < j < k \le r$ and $\operatorname{lcm}(i,j,k) \ge i + j + k$.
Here $\operatorname{lcm}(i, j, k)$ denotes the least common multiple (LCM) of integers $i$, $j$, and $k$.
|
Let's count the number of bad triplets that don't satisfy the condition, i.e. $\operatorname{lcm}(i,j,k) < i + j + k$. Then the answer for one test case is $\frac{(r - l + 1) \cdot (r - l) \cdot (r - l - 1)}{6} -$ the number of bad triplets. Since $i < j < k$, a triplet is bad only when $\operatorname{lcm}(i,j,k) = k$ or ($\operatorname{lcm}(i,j,k) = 2 \cdot k$ and $i + j > k$). This means that both $i$ and $j$ must be a divisor of $2\cdot k$. For every segment $[i; k]$ where $i$ is a divisor of $2 \cdot k$, let's count the number of $j$ such that $i < j < k$. Let's call it the weight of the segment. Turns out that for the current constraints, for every $k$, we can iterate over all pairs of $1 \le i < j < k$, where $i$ and $j$ are divisors of $2 \cdot k$, and check if the triplet is bad. If it is, then we increase the weight of the segment $[i; k]$ by one. To get answers for the test cases, we just need to find the sum of the weights of the segments $[i; k]$ that are inside $[l; r]$. This is a pretty standard problem, which can be solved in offline using a data structure that supports point add and range sum. It is possible to solve E1 without a data structure by iterating over the segments and checking for every one of them if it lies inside $[l; r]$. Complexity: $\mathcal{O}(n \log^2 n + t \log n + \sum_{i = 1}^n \sigma_0(2 \cdot i)^2)$ with a seg tree ($\sum_{i = 1}^n \sigma_0(2 \cdot i)$ is about $n \log n$ and a seg tree update works in $\mathcal{O}(\log n)$, so we get $n \log^2 n$). You can also use sqrt decomposition to get $\mathcal{O}(n \log n + t \sqrt n + \sum_{i = 1}^n \sigma_0(2 \cdot i)^2)$. Bonus: solve the problem in $\mathcal{O}((n + t) \log n)$ or better.
|
[
"brute force",
"data structures",
"math",
"number theory",
"two pointers"
] | 2,500
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int maxn = 200000;
int t[(maxn + 1) * 4];
void update(int v, int tl, int tr, int i, int x) {
t[v] += x;
if (tl != tr - 1) {
int tm = (tl + tr) / 2;
if (i < tm) update(2*v + 1, tl, tm, i, x);
else update(2*v + 2, tm, tr, i, x);
}
}
int query(int v, int tl, int tr, int l, int r) {
if (l >= r) return 0;
if (tl == l && tr == r) return t[v];
else {
int tm = (tl + tr) / 2;
int r1 = query(2*v + 1, tl, tm, l, min(r, tm));
int r2 = query(2*v + 2, tm, tr, max(l, tm), r);
return r1 + r2;
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
vector<vector<int>> d(2*maxn + 1);
for (int i = 1; i <= maxn; i++) {
for (int j = i; j <= 2*maxn; j += i) {
d[j].push_back(i);
}
}
vector<vector<pair<int, int>>> segs(maxn + 1);
for (int k = 1; k <= maxn; k++) {
for (int ti = 0; ti < gsize(d[2*k]); ti++) {
int i = d[2*k][ti], ct = 0;
for (int tj = ti + 1; tj < gsize(d[2*k]); tj++) {
int j = d[2*k][tj];
if (j >= k) break;
if (i + j > k || (k % i == 0 && k % j == 0)) ct++;
}
if (ct > 0) {
segs[i].emplace_back(k, ct);
}
}
}
int T;
cin >> T;
vector<ll> ans(T);
vector<array<int, 3>> queries;
for (int i = 0; i < T; i++) {
ll l, r;
cin >> l >> r;
queries.push_back({l, r, i});
ans[i] = (r - l + 1) * (r - l) * (r - l - 1) / 6;
}
sort(all(queries));
int ti = T - 1;
for (int i = maxn; i >= 1; i--) {
// Update ST
for (auto [r, ct]: segs[i]) {
update(0, 0, maxn + 1, r, ct);
}
// Get Answers
while (ti >= 0 && queries[ti][0] == i) {
ans[queries[ti][2]] -= query(0, 0, maxn + 1, i, queries[ti][1] + 1);
ti--;
}
}
for (int i = 0; i < T; i++) cout << ans[i] << nl;
}
|
1712
|
F
|
Triameter
|
\begin{quote}
— What is my mission?
\end{quote}
\begin{quote}
— To count graph diameters.
\hfill You and Your Submission
\end{quote}
A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The degree of a vertex is the number of edges connected to this vertex.
You are given a weighted tree with $n$ vertices, each edge has a weight of $1$. Let $L$ be the set of vertices with degree equal to $1$.
You have to answer $q$ \textbf{independent} queries. In the $i$-th query:
- You are given a positive integer $x_i$.
- For all $u,v \in L$ such that $u < v$, add edge $(u, v)$ with weight $x_i$ to the graph (initially the given tree).
- Find the diameter of the resulting graph.
The diameter of a graph is equal to $\max\limits_{1 \le u < v \le n}{\operatorname{d}(u, v)}$, where $\operatorname{d}(u, v)$ is the length of the shortest path between vertex $u$ and vertex $v$.
|
We will solve the problem independently $q$ times. Let $f_v$ be the distance to the closest leaf from vertex $v$, can be found using a simple bfs with multiple start sources. Let $d'(u, v)$ be the distance in the resulting graph. Then $d'(u, v) = \min(f_u + f_v + x, d(u, v))$. A short proof: we'll either go through an edge between two leaves or we won't. In the second case, the answer is clearly $d(u, v)$. In the first case, our objective is to get to a leaf as fast as possible, use an edge with weight $x$, and then move to the destination vertex. We want to find the maximum possible value of $d'(u, v)$. As is pretty standard in tree problems, we can do small-to-large merging. Let's maintain $val[v][i] =$ the max value of $depth_u$ over all $u$ in the subtree of $v$ with $f_u = i$. We have a variable $ans$, initially $ans = 0$. For some $lca$, we will first merge all the subtrees, and then add $lca$ to the merged $val[lca]$. We will also update $ans$ during this. The final answer will be $ans - 1$. Merging two subtrees: Suppose we are merging subtree $u$ into subtree $v$, $len(val[u]) \le len(val[v])$, with some current $lca$: First of all, iterate $i$ from $0$ to $len(val[u]) - 1$. For every $i$, do this cycle: $j = max(0, ans - i - x)$; if $j < len(val[v])$ and $val[u][i] + val[v][j] - 2 \cdot depth_{lca} \ge ans$, then do $ans := ans + 1$ and continue, else break and continue to the next $i$. Why does this work? Because all $val$ arrays are sorted in decreasing order. Why? Because for some vertex $v$ with $f_v > 0$, there is always a vertex $u$ in it's subtree with $depth_u > depth_v$. After we are done with that, update $val[v][i] := \max(val[v][i], val[u][i])$ for every $i < len(val[u])$. Adding $lca$ to the merged $val[lca]$: When we are adding $lca$ to $val[lca]$, we update the answer in almost the same way, only we set $i$ to $f_{lca}$ and $val[u][i]$ to $depth_{lca}$. After that we either do $val[lca][i] := max(val[lca][i], depth_{lca})$ or if $len(val[lca]) = f_{lca}$, just append $depth_{lca}$ to the back of $val[lca]$. Complexity: This particular variant of small to large merging works in $\mathcal{O}(n)$ since when merging two structures of size $a$ and $b$, the new size is $\min(a, b)$. You can find the proof here. Since we increase $ans$ at most $n$ times, and we can calculate $f_v$ for all vertices in $\mathcal{O}(n)$, the complexity is $\mathcal{O}(n)$ per query, so $\mathcal{O}(q \cdot n)$ for all queries. Note that doing small-to-large merging once and updating $q$ answers simultaneously is much faster that doing small-to-large merging $q$ times. In the first case, you can even get away with using binary search to update the answer, in the second case you cannot. Bonus: solve for $n, q \le 10^6$. Don't forget to rate the problems! Good problem 391 Mid problem 87 Bad problem 18 Good problem 334 Mid problem 104 Bad problem 52 Good problem 416 Mid problem 79 Bad problem 20 Good problem 350 Mid problem 38 Bad problem 84 Good problem 213 Mid problem 35 Bad problem 18 Good problem 152 Mid problem 13 Bad problem 23 Good problem 63 Mid problem 10 Bad problem 10 PS: Solution codes probably will be added later. UPD: explanations of the references: Hope you liked them! The quote is just a modification of the original title of KonoSuba. This is just something I invented, no reference here. Hope you liked the short poem! The quote is the meme "people die when they are killed" in the Fate series, changed to fit the programming context. And the title is just "Fate Zero" changed to "Sort Zero". "Do you have a wish?" is a recurring phrase in the LN series HakoMari, referring to the wish granting "boxes". The title is just "Empty Box" changed to "Empty Graph". Also, "O_o" is a reference to one of the main characters, "O". The quote can probably be traced to many origins, but I personally modified the quote "We are legion, for we are many" from the series 86. There were also a lot of 6's and 8's in the sample, which might have helped you guess. I didn't really think about this one, just modified a quote from Vivy a bit. UPD2: added solution codes (better late than never...)
|
[
"binary search",
"data structures",
"dfs and similar",
"trees"
] | 3,200
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int maxn = 1000000;
int f[maxn], d[maxn];
vector<int> g[maxn], g2[maxn], val[maxn];
int n, q;
vector<int> ans, x;
void solve() {
for (int v = n - 1; v >= 0; v--) {
for (int u: g[v]) {
if (gsize(val[u]) > gsize(val[v])) swap(val[u], val[v]);
for (int fu = 0; fu < gsize(val[u]); fu++) {
for (int qi = 0; qi < q; qi++) {
while (true) {
int fv = max(0, ans[qi] - fu - x[qi]);
if (fv < gsize(val[v]) &&
val[v][fv] + val[u][fu] - 2*d[v] >= ans[qi]) ans[qi]++;
else break;
}
}
}
for (int fu = 0; fu < gsize(val[u]); fu++) {
val[v][fu] = max(val[v][fu], val[u][fu]);
}
val[u].clear();
val[u].shrink_to_fit();
}
{
int fu = f[v];
for (int qi = 0; qi < q; qi++) {
while (true) {
int fv = max(0, ans[qi] - fu - x[qi]);
if (fv < gsize(val[v]) &&
val[v][fv] - d[v] >= ans[qi]) ans[qi]++;
else break;
}
}
if (fu == gsize(val[v])) {
val[v].push_back(d[v]);
}
}
}
for (int i = 0; i < q; i++) {
ans[i]--;
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> n;
vector<int> deg(n);
for (int i = 1; i < n; i++) {
int p;
cin >> p;
d[i] = d[p - 1] + 1;
g[p - 1].push_back(i);
g2[i].push_back(p - 1);
}
{
queue<int> qe;
vector<bool> used(n, false);
for (int i = 0; i < n; i++) {
if (gsize(g2[i]) + gsize(g[i]) == 1) {
qe.push(i);
used[i] = true;
}
}
while (!qe.empty()) {
int v = qe.front();
qe.pop();
for (int u: g[v]) {
if (used[u]) continue;
f[u] = f[v] + 1;
qe.push(u);
used[u] = true;
}
for (int u: g2[v]) {
if (used[u]) continue;
f[u] = f[v] + 1;
qe.push(u);
used[u] = true;
}
}
}
cin >> q;
for (int i = 0; i < q; i++) {
int tx;
cin >> tx;
x.push_back(tx);
ans.push_back(0);
}
solve();
for (int tans: ans) cout << tans << ' ';
cout << nl;
}
|
1713
|
A
|
Traveling Salesman Problem
|
You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down).
More formally, if you are standing at the point $(x, y)$, you can:
- go left, and move to $(x - 1, y)$, or
- go right, and move to $(x + 1, y)$, or
- go up, and move to $(x, y + 1)$, or
- go down, and move to $(x, y - 1)$.
There are $n$ boxes on this plane. The $i$-th box has coordinates $(x_i,y_i)$. It is guaranteed that the boxes are either on the $x$-axis or the $y$-axis. That is, either $x_i=0$ or $y_i=0$.
You can collect a box if you and the box are at the same point. Find the minimum number of moves you have to perform to collect all of these boxes if you have to \textbf{start and finish} at the point $(0,0)$.
|
Suppose we only have boxes on the $Ox+$ axis, then the optimal strategy is going in the following way: $(0, 0), (x_{max}, 0), (0, 0)$. There is no way to do in less than $2 \cdot |x_{max}|$ moves. What if we have boxes on two axis? Let's assume it is $Oy+$, suppose we have a strategy to go in the following way: $(0, 0), (x_{max}, 0),..., (0, y_{max}), (0, 0)$. In this case it is optimal to fill the three dots with $(0, 0)$, which is just solving each axis independently. Therefore, the number of axis does not matters. For each axis that has at least one box, go from $(0, 0)$ to the farthest one, then come back to $(0, 0)$. Time complexity: $O(n)$
|
[
"geometry",
"greedy",
"implementation"
] | 800
|
def solve():
n = int(input())
minX, minY, maxX, maxY = 0, 0, 0, 0
for i in range(n):
x, y = list(map(int, input().split()))
minX = min(x, minX)
maxX = max(x, maxX)
minY = min(y, minY)
maxY = max(y, maxY)
print(2 * (maxX + maxY - minX - minY))
test = int(input())
while test > 0:
test -= 1
solve()
|
1713
|
B
|
Optimal Reduction
|
Consider an array $a$ of $n$ positive integers.
You may perform the following operation:
- select two indices $l$ and $r$ ($1 \leq l \leq r \leq n$), then
- decrease all elements $a_l, a_{l + 1}, \dots, a_r$ by $1$.
Let's call $f(a)$ the minimum number of operations needed to change array $a$ into an array of $n$ zeros.
Determine if for all permutations$^\dagger$ $b$ of $a$, $f(a) \leq f(b)$ is true.
$^\dagger$ An array $b$ is a permutation of an array $a$ if $b$ consists of the elements of $a$ in arbitrary order. For example, $[4,2,3,4]$ is a permutation of $[3,2,4,4]$ while $[1,2,2]$ is not a permutation of $[1,2,3]$.
|
Let's call $M = max(a_1, a_2, \dots, a_n)$. The problem asks us to make all its elements become $0$ in some operations. And for each operation, we subtract each elements in an subarray by $1$. Thus, every largest elements of the array have to be decreased in at least $M$ operations. And also because of that, $min(f(p))$ over all permutations $p$ of $a$ is never less than $M$. Every permutations $p$ of $a$ such that $f(p) = M$ have the same construction. That is, they can be divided into $2$ subarrays where the left subarray is sorted in non-decreasing order, and the right subarray is sorted in non-increasing order. In other words, the elements of the array should form a mountain. This is how to perform the operations: assign $l$ equal to the index of the leftmost element whose value is not $0$, and assign $r$ equal to the index of the rightmost element whose value is also not $0$, then subtract each element $a_l, a_{l+1}, \dots, a_r$ by $1$. Repeat the operation until all elements become $0$. The thing is each element of the array is always greater or equal than every elements in the left side or the right side of it so it can never become negative at some point of performing the operations. Besides, all the largest elements are also included in each operation that we perform, which mean we've achieved the goal to make all elements of the array become $0$ in $M$ operations. So how to check whether $f(a) = M$ or not? Well, we can define $preLen$ equal to the length of the longest prefix which is sorted in non-decreasing order. Then define $sufLen$ equal to the length of the longest suffix which is sorted in non-increasing order. If $preLen + sufLen \ge n$, the answer is YES. Time complexity: $O(n)$
|
[
"constructive algorithms",
"sortings"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, a[N];
int main() {
int tc;
for (cin >> tc; tc--; ) {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
int preLen = 1;
while (preLen < n && a[preLen] <= a[preLen + 1])
preLen++;
int sufLen = 1;
while (sufLen < n && a[n-sufLen] >= a[n-sufLen + 1])
sufLen++;
if (preLen + sufLen >= n)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
|
1713
|
C
|
Build Permutation
|
A \textbf{$\mathbf{0}$-indexed} array $a$ of size $n$ is called good if for all valid indices $i$ ($0 \le i \le n-1$), $a_i + i$ is a perfect square$^\dagger$.
Given an integer $n$. Find a permutation$^\ddagger$ $p$ of $[0,1,2,\ldots,n-1]$ that is good or determine that no such permutation exists.
$^\dagger$ An integer $x$ is said to be a perfect square if there exists an integer $y$ such that $x = y^2$.
$^\ddagger$ An array $b$ is a permutation of an array $a$ if $b$ consists of the elements of $a$ in arbitrary order. For example, $[4,2,3,4]$ is a permutation of $[3,2,4,4]$ while $[1,2,2]$ is not a permutation of $[1,2,3]$.
|
First, let's prove that the answer always exists. Let's call the smallest square number that is not smaller than $k$ is $h$. Therefore $h \leq 2 \cdot k$, which means $h - k \leq k$. Proof. So we can fill $p_i = h - i$ for $(h - k \leq i \leq k)$. Using this method we can recursively reduce $k$ to $h - k - 1$, then all the way down to $-1$. We can prove that $h - k \geq 0$, as $h \geq k$. Time complexity: $O(n)$
|
[
"constructive algorithms",
"dp",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, ans[N];
void recurse(int r) {
if (r < 0) return;
int s = sqrt(2*r); s *= s;
int l = s - r; recurse(l - 1);
for (; l <= r; l++, r--) {
ans[l] = r; ans[r] = l;
}
}
int main() {
int tc; cin >> tc;
while (tc--) {
cin >> n; recurse(n - 1);
for (int i = 0; i < n; i++)
cout << ans[i] << ' ';
cout << '\n';
}
}
|
1713
|
D
|
Tournament Countdown
|
This is an interactive problem.
There was a tournament consisting of $2^n$ contestants. The $1$-st contestant competed with the $2$-nd, the $3$-rd competed with the $4$-th, and so on. After that, the winner of the first match competed with the winner of second match, etc. The tournament ended when there was only one contestant left, who was declared the winner of the tournament. Such a tournament scheme is known as the single-elimination tournament.
You don't know the results, but you want to find the winner of the tournament. In one query, you select two integers $a$ and $b$, which are the indices of two contestants. The jury will return $1$ if $a$ won more matches than $b$, $2$ if $b$ won more matches than $a$, or $0$ if their number of wins was equal.
Find the winner in no more than $\left \lceil \frac{1}{3} \cdot 2^{n + 1} \right \rceil$ queries. Here $\lceil x \rceil$ denotes the value of $x$ rounded up to the nearest integer.
Note that the tournament is long over, meaning that the results are fixed and do not depend on your queries.
|
There is a way to erase $3$ participants in every $2$ queries. Since there are $2^n - 1$ participants to be removed, the number of queries will be $\left \lceil (2^n - 1) \cdot \frac{2}{3} \right \rceil = \left \lfloor \frac{2^{n + 1}}{3} \right \rfloor$. Suppose there are only $4$ participants. In the first query we will ask the judge to compare the $1^{st}$ and the $3^{rd}$ participants. There are three cases: The $1^{st}$ participant wins more game than the $3^{rd}$ one: the $2^{nd}$ and $3^{rd}$ cannot be the winner. The $1^{st}$ participant wins more game than the $3^{rd}$ one: the $2^{nd}$ and $3^{rd}$ cannot be the winner. The $3^{rd}$ participant wins more game than the $1^{st}$ one: the $1^{st}$ and $4^{th}$ cannot be the winner. The $3^{rd}$ participant wins more game than the $1^{st}$ one: the $1^{st}$ and $4^{th}$ cannot be the winner. The $1^{st}$ and $3^{rd}$ participants' numbers of winning games are equal: both the $1^{st}$ and $3^{rd}$ cannot be the winner. The $1^{st}$ and $3^{rd}$ participants' numbers of winning games are equal: both the $1^{st}$ and $3^{rd}$ cannot be the winner. Ask the remaining two participants, find the winner between them. If there are more than $4$ participants, we can continuously divide the number by $4$ again and again, until there are at most $2$ participants left. Now we can get the winner in one final query.
|
[
"constructive algorithms",
"greedy",
"interactive",
"number theory",
"probabilities"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int ask(vector<int> &k)
{
cout << "? " << k[0] << ' ' << k[2] << endl;
int x;
cin >> x;
if (x == 1)
{
cout << "? " << k[0] << ' ' << k[3] << endl;
cin >> x;
if (x == 1) return k[0];
return k[3];
}
else if (x == 2)
{
cout << "? " << k[1] << ' ' << k[2] << endl;
cin >> x;
if (x == 1) return k[1];
return k[2];
}
else
{
cout << "? " << k[1] << ' ' << k[3] << endl;
cin >> x;
if (x == 1) return k[1];
return k[3];
}
}
void solve()
{
int n;
cin >> n;
vector<int> a, b;
for (int i = 1; i <= (1LL << n); i++)
{
a.push_back(i);
}
while (a.size() > 2)
{
while (!a.empty())
{
vector<int> k(4);
k[0] = a.back();
a.pop_back();
k[1] = a.back();
a.pop_back();
k[2] = a.back();
a.pop_back();
k[3] = a.back();
a.pop_back();
int win = ask(k);
b.push_back(win);
}
a = b;
b.clear();
}
if (a.size() == 2)
{
cout << "? " << a[0] << ' ' << a[1] << endl;
int x;
cin >> x;
if (x == 2) a[0] = a[1];
}
cout << "! " << a[0] << endl;
}
int main(int argc, char ** argv)
{
int tests;
cin >> tests;
while(tests--) solve();
}
|
1713
|
E
|
Cross Swapping
|
You are given a square matrix $A$ of size $n \times n$ whose elements are integers. We will denote the element on the intersection of the $i$-th row and the $j$-th column as $A_{i,j}$.
You can perform operations on the matrix. In each operation, you can choose an integer $k$, then for each index $i$ ($1 \leq i \leq n$), swap $A_{i, k}$ with $A_{k, i}$. Note that cell $A_{k, k}$ remains unchanged.
For example, for $n = 4$ and $k = 3$, this matrix will be transformed like this:
\begin{center}
{\small The operation $k = 3$ swaps the blue row with the green column.}
\end{center}
You can perform this operation any number of times. Find the lexicographically smallest matrix$^\dagger$ you can obtain after performing arbitrary number of operations.
${}^\dagger$ For two matrices $A$ and $B$ of size $n \times n$, let $a_{(i-1) \cdot n + j} = A_{i,j}$ and $b_{(i-1) \cdot n + j} = B_{i,j}$. Then, the matrix $A$ is lexicographically smaller than the matrix $B$ when there exists an index $i$ ($1 \leq i \leq n^2$) such that $a_i < b_i$ and for all indices $j$ such that $1 \leq j < i$, $a_j = b_j$.
|
Let's take a look at what the lexicographically smallest matrix is. Let's call $(x, y)$ a cell that is in the intersection of row $x$ and column $y$ of the matrix, and the integer written on that cell is $A_{x, y}$. A cell $(x_p, y_p)$ of this matrix is called more significant than the another cell $(x_q, y_q)$ if and only if $x_p < x_q$, or $x_p = x_q$ and $y_p < y_q$. The problem asks us to find the smallest matrix so the best suitable way to solve this problem is to traverse through the most to the least significant cell of the matrix, then determine if the current cell can be minimized or not. Suppose the current cell we are looking at is $(x, y)$. If $x = y$ then its position will not change after performing the operations. But if $x \neq y$, there are exactly $2$ operations that swap $(x, y)$ with another cell, that is $k = x$ and $k = y$. Both of these operations swap $(x, y)$ with the same cell $(y, x)$. So the only way we can minimize the value of $(x, y)$ is to try swapping it with $(y, x)$ (if $x < y$ and $A_{x, y} > A_{y, x}$) in some way. As a result we have our constructive algorithm. Remind that for each operation $k = i$ of the matrix ($1 \le i \le n$), there are $2$ states: it is being performed and not being performed. Suppose we have traversed to the cell $(x, y)$. If $x \ge y$, ignore it. If $x < y$ then we try to make $A_{x, y} = min(A_{x, y}, A_{y, x})$ by deciding to swap or not to swap the cells. If $A_{x, y} > A_{y, x}$, try to swap $(x, y)$ with $(y, x)$ by making $2$ operations $k = x$ and $k = y$ having different states. And if $A_{x, y} < A_{y, x}$ then we should keep their positions unchanged by making $2$ operations $k = x$ and $k = y$ having the same state. Note that if $A_{x, y} = A_{y, x}$, we do nothing. Let's implement this algorithm using a simple DSU where the $ith$ node represents the operation $k = i$. We define the value $par[u]$ in such a way that, suppose $p$ is the root of the $u$ node's component, $par[u] = p$ if $2$ operations $k = u$ and $k = p$ should have the same state, or $par[u] = -p$ if $2$ operations $k = u$ and $k = p$ should have different states. Define another function $join(i, j)$ to union $2$ nodes $i$ and $j$ to the same component. Note that $u$ and $-u$ are always in the same component and $par[-u] = -par[u]$. Thus, for the current cell $(x, y)$, we want to swap it with $(y, x)$ by calling $join(x, -y)$, or keep its position unchanged by calling $join(x, y)$. After constructing the graphs, the last thing to do is to determine which operations should be performed. One way to do so is for each root of the components of the DSU, we perform the operation which this root represents for. Then for other nodes just check $par[i] > 0$ for the $ith$ node and if it is true, the $k = i$ operation should be performed. When we have the list of the operations that need to be performed, we can bruteforcely perform each operation from the list one by one and the final matrix will be the lexicographically smallest matrix. Time complexity: $O(n^2)$
|
[
"2-sat",
"data structures",
"dsu",
"greedy",
"matrices"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e3 + 5;
int n, a[N][N];
int par[N];
int getPar(int u) {
if (u < 0) return -getPar(-u);
if (u == par[u]) return u;
return par[u] = getPar(par[u]);
}
void join(int u, int v) {
u = getPar(u); v = getPar(v);
if (abs(u) != abs(v)) {
if (u > 0) par[u] = v;
else par[-u] = -v;
}
}
int main() {
cin.tie(nullptr) -> sync_with_stdio(false);
int tc; cin >> tc;
while (tc--) {
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
}
iota(par + 1, par + n + 1, 1);
// set par[i] == i for i in [1, n]
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
if (a[i][j] < a[j][i]) join(i, j);
if (a[i][j] > a[j][i]) join(i, -j);
}
for (int i = 1; i <= n; i++) {
if (getPar(i) < 0) continue;
// we only perform the operation
// if and only if getPar(i) > 0
for (int j = 1; j <= n; j++)
swap(a[i][j], a[j][i]);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << a[i][j] << ' ';
}
cout << '\n';
}
}
}
|
1713
|
F
|
Lost Array
|
\begin{quote}
{{My orzlers, we can optimize this problem from $O(S^3)$ to $O\left(T^\frac{5}{9}\right)$!}}
\hfill — Spyofgame, founder of Orzlim religion
\end{quote}
A long time ago, Spyofgame invented the famous array $a$ ($1$-indexed) of length $n$ that contains information about the world and life. After that, he decided to convert it into the matrix $b$ ($0$-indexed) of size $(n + 1) \times (n + 1)$ which contains information about the world, life and beyond.
Spyofgame converted $a$ into $b$ with the following rules.
- $b_{i,0} = 0$ if $0 \leq i \leq n$;
- $b_{0,i} = a_{i}$ if $1 \leq i \leq n$;
- $b_{i,j} = b_{i,j-1} \oplus b_{i-1,j}$ if $1 \leq i, j \leq n$.
Here $\oplus$ denotes the bitwise XOR operation.
Today, archaeologists have discovered the famous matrix $b$. However, many elements of the matrix has been lost. They only know the values of $b_{i,n}$ for $1 \leq i \leq n$ (note that these are some elements of the last \textbf{column}, not the last \textbf{row}).
The archaeologists want to know what a possible array of $a$ is. Can you help them reconstruct any array that could be $a$?
|
First, we can see that $a_i$ contribute $\binom{(n - i) + (j - 1)}{j - 1}$ times to $b_{j, n}$, which can calculate similar to Pascal's Triangle. It's easy to see that the value that $a_i$ contribute to $b_{j, n}$ equal to $a_i$ when $\binom{(n - i) + (j - 1)}{j - 1}$ is odd, $0$ otherwise. Let's solve the inverse problem: Given array $a$. Construct $b_{j, n}$ for all $j$. $(1 \le j \le n)$ By Lucas Theorem, $\binom{(n - i) + (j - 1)}{j - 1}$ is odd when $(n - i)\ AND\ (j - 1) = 0$ $\rightarrow (n - i)$ is a submask of $\sim(j - 1)$ (with $\sim a$ is inverse mask of $a$). Let define $m = 2^k$ with smallest $m$ satisfy $m \ge n$. Set $a'_i = a_i$ and $b'_j = b_{\sim(j - 1)} = b_{(m - 1) - (j - 1)}$ then $b'$ is the Zeta transform of $a'$. So we could apply Mobius transform in $b'$ to get $a'$. Since the operation is xor, mobius transform is as same as zeta transform. But unlike the inverse problem, there are some differences. We don't know the value of $b'_i$ for $i$ in $[0, m - n)$. Let $c$ be the sum over supermasks array of $b'$ (with $i$ is supermasks of $j$ when $i\ AND\ j = j)$, then set $c_k = 0$ for $k$ in $[m - n, m)$. After that, do another sum over supermasks on $c$ to get original value of $b'$. Now we can find $a'$ from $b'$ and $a$ from $a'$. Complexity: $O(nlog_2(n))$
|
[
"bitmasks",
"combinatorics",
"constructive algorithms",
"dp",
"math"
] | 2,900
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define endl '\n'
#define fi first
#define se second
#define For(i, l, r) for (auto i = (l); i < (r); i++)
#define ForE(i, l, r) for (auto i = (l); i <= (r); i++)
#define FordE(i, l, r) for (auto i = (l); i >= (r); i--)
#define Fora(v, a) for (auto v: (a))
#define bend(a) (a).begin(), (a).end()
#define isz(a) ((signed)(a).size())
using ll = long long;
using ld = long double;
using pii = pair <int, int>;
using vi = vector <int>;
using vpii = vector <pii>;
using vvi = vector <vi>;
const int N = 1 << 19;
int n;
int a[N], b[N], ta[N], tb[N];
int c[N];
int m, lm, all1;
signed main(){
cin >> n;
ForE(i, 1, n){
cin >> b[i];
}
m = 1 << __lg(n);
if (m < n){
m *= 2;
}
lm = __lg(m);
all1 = m - 1;
memset(ta, -1, sizeof(ta));
memset(tb, -1, sizeof(tb));
ForE(i, 1, n){
tb[all1 ^ (i - 1)] = b[i];
ta[n - i] = -2;
}
For(i, 0, m){
c[all1 ^ i] = max(tb[i], 0);
}
For(bit, 0, lm){
For(msk, 0, m){
if (msk >> bit & 1){
c[msk] ^= c[msk ^ (1 << bit)];
}
}
}
For(i, 0, m){
if (tb[i] == -1){
c[all1 ^ i] = 0;
}
}
For(bit, 0, lm){
For(msk, 0, m){
if (msk >> bit & 1){
c[msk] ^= c[msk ^ (1 << bit)];
}
}
}
For(i, 0, m){
if (tb[i] == -1){
tb[i] = c[all1 ^ i];
}
}
For(i, 0, m){
ta[i] = tb[i];
}
For(bit, 0, lm){
For(msk, 0, m){
if (msk >> bit & 1){
ta[msk] ^= ta[msk ^ (1 << bit)];
}
}
}
ForE(i, 1, n){
a[i] = ta[n - i];
}
ForE(i, 1, n){
cout << a[i] << ' ';
} cout << endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.