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
⌀ |
|---|---|---|---|---|---|---|---|
1972
|
A
|
Contest Proposal
|
A contest contains $n$ problems and the difficulty of the $i$-th problem is expected to be \textbf{at most} $b_i$. There are already $n$ problem proposals and the difficulty of the $i$-th problem is $a_i$. Initially, both $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$ are sorted in non-decreasing order.
Some of the problems may be more difficult than expected, so the writers must propose more problems. When a new problem with difficulty $w$ is proposed, the most difficult problem will be deleted from the contest, and the problems will be sorted in a way that the difficulties are non-decreasing.
In other words, in each operation, you choose an integer $w$, insert it into the array $a$, sort array $a$ in non-decreasing order, and remove the last element from it.
Find the minimum number of new problems to make $a_i\le b_i$ for all $i$.
|
Enumerate through the array $a$, if $a_i > b_i$ at some index $i$, then propose a problem with difficulty $b_i$. Time complexity: $\mathcal O(n^2)$ for each test case. It can also be solved in $\mathcal O(n)$ if we record the problems we've added.
|
[
"brute force",
"greedy",
"two pointers"
] | 800
|
//By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x, y, z) for(int x = (y); x <= (z); ++x)
#define per(x, y, z) for(int x = (y); x >= (z); --x)
#define endl '\n'
using namespace std;
typedef long long ll;
const int N = 105;
int T, n, a[N], b[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
for(cin >> T; T; --T) {
cin >> n;
rep(i, 1, n) cin >> a[i];
rep(i, 1, n) cin >> b[i];
int diff = 0, ans = 0;
rep(i, 1, n) {
if(a[i - diff] > b[i]) {
++ans;
++diff;
}
}
cout << ans << endl;
}
return 0;
}
|
1972
|
B
|
Coin Games
|
There are $n$ coins on the table forming a circle, and each coin is either facing up or facing down. Alice and Bob take turns to play the following game, and Alice goes first.
In each operation, the player chooses a facing-up coin, removes the coin, and flips the two coins that are adjacent to it. If (before the operation) there are only two coins left, then one will be removed and the other won't be flipped (as it would be flipped twice). If (before the operation) there is only one coin left, no coins will be flipped. If (before the operation) there are no facing-up coins, the player loses.
Decide who will win the game if they both play optimally. It can be proved that the game will end in a finite number of operations, and one of them will win.
|
It can be proved that Alice will win the game if and only if the number of facing-up coins is odd. Time complexity: $\mathcal O(n)$ for each case. Proof: Consider all possible operations: ...UUU... -> ...DD...: The number of U decreases by $3$. ...UUD... -> ...DU...: The number of U decreases by $1$. ...DUU... -> ...UD...: The number of U decreases by $1$. ...DUD... -> ...UU...: The number of U increases by $1$. It can be seen that the parity always changes. It's obvious that if the number of U is equal to $0$, the player loses because there aren't any available operations. So Alice wins if and only if the number of U is odd.
|
[
"games"
] | 900
|
//By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x, y, z) for(int x = (y); x <= (z); ++x)
#define per(x, y, z) for(int x = (y); x >= (z); --x)
#define endl '\n'
using namespace std;
typedef long long ll;
int T, n;
string s;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
for(cin >> T; T; --T) {
cin >> n >> s;
int cntU = 0;
for(char c : s) if(c == 'U') ++cntU;
if(cntU & 1) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
|
1973
|
A
|
Chess For Three
|
Three friends gathered to play a few games of chess together.
In every game, two of them play against each other. The winner gets $2$ points while the loser gets $0$, and in case of a draw, both players get $1$ point each. Note that the same pair of players could have played any non-negative number of times (possibly zero). It is also possible that no games were played at all.
You've been told that their scores after all the games were played were $p_1$, $p_2$ and $p_3$. Additionally, it is guaranteed that $p_1 \leq p_2 \leq p_3$ holds.
Find the maximum number of draws that could have happened and print it. If there isn't any way to obtain $p_1$, $p_2$ and $p_3$ as a result of a non-negative number of games between the three players, print $-1$ instead.
|
If someone would claim that the number of draws that happened between the three players are $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$, can you check in $O(1)$ whether this can be true? The constraints are very small. The number of draws between any two players is at most $30$. Hint 3: Try all the possibilities for $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$ and find the one with the biggest sum out of all possibilities that could've been the result of game that ended with scores $p_1$, $p_2$ and $p_3$. After each round, sum of players' scores increases by 2, so if the sum $p_1 + p_2 + p_3$ is odd, answer is $-1$. Now, as the hints suggest, you can try all possible combinations of $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$ with three for-loops and check for each combination whether it could result in scores $p_1$, $p_2$ and $p_3$. Specifically, it must hold that $p_1 - d_{1, 2} - d_{1, 3} \equiv 0 \mod 2$, $d_{1, 2} + d_{1, 3} \leq p_1$ and the same two conditions for $p_2$ and $p_3$ analogously. Now you can find the biggest value of $d_{1, 2}$ + $d_{1, 3}$ + $d_{2, 3}$ over all valid choices and print it as the answer. The time complexity is $O(t \cdot \max(p) ^3)$.
|
[
"brute force",
"dp",
"implementation",
"math"
] | 900
|
#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <vector>
typedef long long ll;
typedef long double ld;
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
vector<int> v(3);
cin >> v[0] >> v[1] >> v[2];
if ((v[0] + v[1] + v[2]) % 2 == 1)
{
cout << "-1\n";
continue;
}
cout << (v[0] + v[1] + v[2] - max(0, v[2] - v[0] - v[1])) / 2 << "\n";
}
return 0;
}
|
1973
|
B
|
Cat, Fox and the Lonely Array
|
Today, Cat and Fox found an array $a$ consisting of $n$ non-negative integers.
Define the loneliness of $a$ as the \textbf{smallest} positive integer $k$ ($1 \le k \le n$) such that for any two positive integers $i$ and $j$ ($1 \leq i, j \leq n - k +1$), the following holds: $$a_i | a_{i+1} | \ldots | a_{i+k-1} = a_j | a_{j+1} | \ldots | a_{j+k-1},$$ where $x | y$ denotes the bitwise OR of $x$ and $y$. In other words, for every $k$ consecutive elements, their bitwise OR should be the same. Note that the loneliness of $a$ is well-defined, because for $k = n$ the condition is satisfied.
Cat and Fox want to know how lonely the array $a$ is. Help them calculate the loneliness of the found array.
|
We will say that the array is $k$-lonely if $a_i|a_{i+1}| \ldots |a_{i+k-1}=a_j|a_{j+1}| \ldots |a_{j+k-1}$ is true for any two positive integers $1 \leq i,j \leq n-k+1$. Let $A$ be the maximum value an element in array $a$ can have. how to check if the array is $k$-lonely in $O(n \log A)$? if the array is $k$-lonely, the array is also $k+1$-lonely binary search the answer :) If the array is $k$-lonely, then since $a_i | \ldots | a_{i+k} = (a_i | \ldots | a_{i+k-1}) | (a_{i+1} | \ldots | a_{i+k}) = (a_j | \ldots | a_{j+k-1}) | (a_{j+1} | \ldots | a_{j+k}) = a_j | \ldots | a_{j+k}$, the array is also $k+1$-lonely. You can check whether an array is $k$-lonely in $O(n \log A)$ by calculating the OR of every segment of length $k$. You can do this by iterating $i$ from $1$ to $n-k+1$ and mantaining an array $t$ of size $\log n$ where $t[j]$ will be equal to the number of elements from $a_i, ..., a_{i+k-1}$ that have the bit $2^j$ set. For $i = 1$ we can calculate this array in $O (k \log A)$ and then when moving $i$ to the right, we can update the array in $O (\log A)$ complexity and we can also calculate the OR of all elements in the segment, using the array $t$, in $O (\log A)$. Once you have a checking function that runs in $O (n \log A)$, you can binary search the answer in $O(n \log A \log n)$ time, which is fast enough to pass.
|
[
"binary search",
"bitmasks",
"data structures",
"greedy",
"math",
"two pointers"
] | 1,300
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool check(vector<int>& v, int mid,int ori)
{
vector<int>frekbit(31);
for (int i = 0; i < mid; i++)
{
int x = v[i];
for (int j = 30; j >= 0; j--)
{
if (x>=(1<<j))
{
x -= (1<<j);
frekbit[j]++;
}
}
}
int or2 = 0;
for (int i = 0; i < frekbit.size(); i++)
{
if (frekbit[i] > 0)
{
or2 += (1 << i);
}
}
if (or2 != ori)
{
return false;
}
for (int i = 1; i + mid - 1 < v.size(); i++)
{
int x = v[i - 1];
for (int j = 30; j >= 0; j--)
{
if (x >= (1 << j))
{
x -= (1 << j);
frekbit[j]--;
if (frekbit[j] == 0)
{
or2 -= (1 << j);
}
}
}
x = v[i+mid - 1];
for (int j = 30; j >= 0; j--)
{
if (x >= (1 << j))
{
x -= (1 << j);
frekbit[j]++;
if (frekbit[j] == 1)
{
or2 += (1 << j);
}
}
}
if (or2 != ori)
{
return false;
}
}
return true;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int>v(n);
int ori = 0;
for (int i = 0; i < n; i++)
{
cin >> v[i];
ori |= v[i];
}
int lo = 1;
int hi = n;
while (lo < hi)
{
int mid = (lo+hi) / 2;
if (check(v,mid,ori) == true)
{
hi = mid;
}
else
{
lo = mid + 1;
}
}
cout << lo << '\n';
}
return 0;
}
|
1973
|
C
|
Cat, Fox and Double Maximum
|
Fox loves permutations! She came up with the following problem and asked Cat to solve it:
You are given an \textbf{even} positive integer $n$ and a permutation$^\dagger$ $p$ of length $n$.
The score of another permutation $q$ of length $n$ is the number of \textbf{local maximums} in the array $a$ of length $n$, where $a_i = p_i + q_i$ for all $i$ ($1 \le i \le n$). In other words, the score of $q$ is the number of $i$ such that $1 < i < n$ (note the \textbf{strict} inequalities), $a_{i-1} < a_i$, and $a_i > a_{i+1}$ (once again, note the strict inequalities).
Find the permutation $q$ that achieves the maximum score for given $n$ and $p$. If there exist multiple such permutations, you can pick any of them.
$^\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
|
$n$ is even. What is the obvious upper bound on the number of the local maximums? Right, it is ${n \over 2} - 1$. We can actually achieve this value for any permutation. Consider $p_1 = n$. Can you find $q$ such that all other odd positions will be local maximums? We can easily prove that the sequence can have at most ${n \over 2} - 1$ local maximums, because the corner elements can't be the local maximums and no two consecutive elements can be local maximums. Let's see how we can achieve this upper bound. Let's consider the case when $n$ is at odd position in the original array first. We will construct a permutation $q$ such that the resulting array $a$ will have local maximums at all the odd positions except the first one. We can do this by placing the numbers ${n \over 2} + 1, {n \over 2} + 2, \ldots n$ at the odd indexes in $q$, giving the bigger numbers to the indexes with smaller $p_i$, and placing the numbers $1, 2, \ldots, {n \over 2}$ at the even indexes in $p$, giving the smaller numbers to the indexes with bigger $p_i$. Then since $n$ belongs to an odd index, the $a_i$ for each odd $i$ will be at least $n + 1$ while the $a_i$ for each even $i$ will be at most $n$. So every element of $a$ at odd position, except for the corner, will be a local maximum. This means we will have ${n \over 2} - 1$ local maximums, which is optimal, as we noitced above. We can get the solution for the case when $n$ is at even position analogously. For example, by reversing the permutation $p$, calculating the right permutation $q$, reversing them again and printing this $q$ as the answer. Time complexity: $O(n \log n)$ because of sorting. Actually, since you are sorting a permutation, you can do it in just $O(n)$ but it's not necessary.
|
[
"constructive algorithms",
"greedy",
"implementation",
"math",
"sortings"
] | 1,700
|
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <vector>
typedef long long ll;
typedef long double ld;
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> p(n);
for (int i = 0; i < n; i++) cin >> p[i];
vector<int> q(n);
int nid = find(p.begin(), p.end(), n) - p.begin();
if (!(nid & 1)) // maximums will be on the even positions
{
vector<pair<int, int> > v;
for (int i = 1; i < n; i += 2) v.push_back({ p[i], i });
v.push_back({ p[0], 0 });
for (int i = 2; i < n; i += 2) v.push_back({ p[i], i });
sort(v.begin(), v.begin() + (n / 2), greater<pair<int, int> >());
sort(v.begin() + (n / 2) + 1, v.begin() + n, greater<pair<int, int> >());
for (int i = 0; i < n; i++) q[v[i].second] = i + 1;
}
else // maximums will be on the odd positions
{
vector<pair<int, int> > v;
for (int i = 0; i < n; i += 2) v.push_back({ p[i], i });
v.push_back({ p[n - 1], n - 1 });
for (int i = 1; i < n - 1; i += 2) v.push_back({ p[i], i });
sort(v.begin(), v.begin() + (n / 2), greater<pair<int, int> >());
sort(v.begin() + (n / 2) + 1, v.begin() + n, greater<pair<int, int> >());
for (int i = 0; i < n; i++) q[v[i].second] = i + 1;
}
for (int i = 0; i < n; i++) cout << q[i] << " \n"[i == n - 1];
}
return 0;
}
|
1973
|
D
|
Cat, Fox and Maximum Array Split
|
This is an interactive problem.
Fox gave Cat two positive integers $n$ and $k$. She has a hidden array $a_1, \ldots , a_n$ of length $n$, such that $1 \leq a_i \leq n$ for every $i$. Now they are going to play the following game:
For any two integers $l, r$ such that $1 \leq l \leq r \leq n$, define $f(l, r) = (r - l + 1) \cdot \max\limits_{x=l}^r a_x$. In other words, $f(l, r)$ is equal to the maximum of the subarray $a_l, \ldots, a_r$ multiplied by its size.
Cat can ask Fox at most $2 n$ questions about the array. He will tell her two integers $l$ and $x$ ($1 \leq l \leq n, 1 \leq x \leq 10^9$), and she will tell him one integer $p$ as the answer — the smallest positive integer $r$ such that $f(l, r) = x$, or $n+1$ if no such $r$ exists.
Now, Cat needs to find the largest value $m$ such that there exists a sequence $c_1, \ldots, c_{k-1}$ such that $1 \leq c_1 < \ldots < c_{k-1} < n$ and $f(1, c_1) = f(c_1 + 1, c_2) = \ldots = f(c_{k-1}+1, n) = m$. If no such $m$ exists, he should indicate this and take $-1$ as the answer. Note that for $k = 1$, $m$ is always equal to $f(1, n)$.
In other words, the goal is to find the largest $m$ such that you can split the array into exactly $k$ subarrays ($k$ is the constant given to you in the beginning of the interaction) so that all the subarrays have the product of their length and their maximum equal to $m$, or determine that no such $m$ exists. Every element should belong in exactly one of the subarrays.
Cat doesn't know what he should do, so he asked you to play the game for him.
|
Let $m$ be value we want to find. What values can $m$ take? Look at the maximum value in array $a$. Can you find the maximum value in array? Think about the segment containing the maximum value. Can you finish the problem in $n$ queries? Let's denote maximum value in array $a$ as $mx$. Since the element with maximum value will belong to some segment, then if $m$ exists, $m$ will be divisible by $mx$. Obviously, $m$ can't be greater than $n \cdot mx$, so now the candidates for value of $m$ are $mx, 2 \cdot mx, 3 \cdot mx, \dots, n \cdot mx$. To find the value of $mx$ we can query $?$ $1$ $n \cdot i$ for each $1\leq i \leq n$ and $mx$ will be equal to such $i$, querying which will give $n$ as the answer. We can check each of $n$ possible values in $k$ queries, but that wouldn't fit in query limit. Actually, since the length of each segment in partition will be greater than or equal to $\frac{m}{mx}$, and there are exactly $k$ segments, we can get a simple inequality $k \cdot \frac{m}{mx} \leq n$ (since sum of lengths of segments is exactly $n$), which means $m$ can not be greater than $mx \cdot \lfloor{n/k}\rfloor$, so it is enough to check first $\lfloor{n/k}\rfloor$ candidates for $m$ in $k$ queries each. Total number of queries used would be $n + k \cdot \lfloor{n/k}\rfloor$ which doesn't exceed $2n$.
|
[
"brute force",
"interactive",
"math"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#pragma GCC target("popcnt")
using ll = long long;
#define int long long
#define forn(i,n) for(int i=0; i<(n); ++i)
#define pb push_back
#define pi pair<int,int>
#define f first
#define s second
#define vii(a,n) vector<int> a(n); forn(i,n) cin>>a[i];
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
const ll inf = 1e18;
const ll mod = 1e9+7;//998244353;
void answer(int x) {
cout<<"! "<<x<<'\n'; cout.flush(); cin>>x;
}
void solve() {
int n,k; cin>>n>>k;
int mx=0;
for(int i=1; i<=n; ++i) {
cout<<"? 1 "<<i*n<<'\n'; cout.flush();
int x; cin>>x;
if (x==n) {
mx=i; break;
}
}
for(int c=mx*(n/k); ; c-=mx) {
if (!c) {
answer(-1); return;
}
int l=0;
int bad=0;
forn(it,k) {
if (l>=n) {bad=1; break;}
cout<<"? "<<l+1<<' '<<c<<'\n'; cout.flush();
int x; cin>>x;
l=x;
}
if (bad) continue;
if (l!=n) continue;
answer(c); return;
}
}
int32_t main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t=1;
cin>>t;
while (t--) solve();
return 0;
}
|
1973
|
E
|
Cat, Fox and Swaps
|
Fox has found an array $p_1, p_2, \ldots, p_n$, that is a permutation of length $n^\dagger$ of the numbers $1, 2, \ldots, n$. She wants to sort the elements in increasing order. Cat wants to help her — he is able to swap any two numbers $x$ and $y$ in the array, but only if $l \leq x + y \leq r$ (note that the constraint is imposed on the values of the elements, not their positions). He can make such swaps any number of times.
They don't know the numbers $l$, $r$ yet, they only know that it's true that $1 \leq l \leq r \leq 2 \cdot n$.
You are given the number $n$ and the array $p_1, p_2, \ldots, p_n$. Determine how many pairs $(l, r)$ satisfying the conditions are there such that you can sort the permutation if you can only swap two number $(x, y)$ such that $l \leq x + y \leq r$ (arbitrary number of times, possibly $0$).
$^\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
|
Forget about graphs and data structures, there exists a simple $O(n)$ solution. Find the number of pairs with $l = r$ for which you can sort the permutation. Okay now that you have the special case handled, let's proceed to the general case. Find the minimum and maximum number that need to be swapped. Write down the inequalities that $l$ and $r$ have to satisfy so that we can swap these two elements with some other elements. This is the obvious necessary condition, right? Right, so if $l \neq r$ and additionally, $l$ and $r$ satisfy the inequalities mentioned above, is it enough? Yes, it is enough. But you can try to find the proof too :) Let's consider the pairs $l, r$ that have $l = r$ first. Then you can swap each $x$ with at most one other element, $l - x$. So if $i \neq p_i$ for some $i$, then we need to be able to swap the element $i$ with the element $p_i$, so it must hold that $l = i + p_i$. This is obviously also a sufficient condition, so it's enough to just find all $i + p_i$ for $i \neq p_i$, if there exist more then one different value, there's no good pair with $l = r$, if there's exactly one different value, there's exactly one good pair with $l = r$ and otherwise there are $2 n$ such pairs. Now let's count the pairs with $l \neq r$. If the array is sorted already, all pairs of $l, r$ are good. From now, consider only the case when the array isn't sorted yet. Let $L$ be the smallest value such that $p_L \neq L$ and $R$ the largest such value respectively. We obviously need to be able to swap $L$ and $R$ with some other values. Note that $L \neq n$ and $R \neq 1$, otherwise the array would be sorted already. Now we can get the inequalities $l \leq L + n$ and $R + 1 \leq r$, those are the necessary conditions for being able to swap the numbers $L, R$ with at least one other element. We can actually prove that these are the sufficient conditions too. If $l, r$ satisfy these conditions, then for any number $X$ in the range $[L, R-1]$, we can find an $x$ in the range $[l, r]$ such that $1 \leq x - X \leq n$ and then we can swap the numbers $X$ and $X + 1$, while not affecting any other element, by swapping $X$ and $x - X$ first and then swapping $X + 1$ and $x - X$. Thanks to this, we can sort the whole range of values between $L$ and $R$ - while the array isn't sorted, we will always find the smallest index $i$ that doesn't have the right value and keep swapping the value $p_i$ with the value $p_i - 1$, so eventually we will get $p_i = i$ and we can continue sorting on the right. So it's enough to just count the number of pairs $l, r$ such that $l \neq r$, $l \leq L + n$ and $R + 1 \leq r$, add it to the answer and print it. All of this can be done in time and memory complexity $O(n)$.
|
[
"graphs",
"math",
"sortings"
] | 2,500
|
#include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <vector>
typedef long long ll;
typedef long double ld;
using namespace std;
ll all(ll n)
{
if (n <= 0) return 0;
return (n * (n - 1)) / 2ll;
}
void solve()
{
int n;
cin >> n;
vector<ll> p(n);
for (int i = 0; i < n; i++) cin >> p[i];
set<int> s;
for (int i = 0; i < n; i++) if (i != p[i] - 1) s.insert(p[i] + i);
if (s.empty())
{
cout << all(2 * n + 1) << "\n";
return;
}
ll ans = (s.size() == 1);
ll l = 0, r = 2 * n;
for (int i = 0; i < n; i++) if (i != p[i] - 1)
{
l = max(l, p[i] + 1);
r = min(r, p[i] + n);
}
ans += all(2ll * n) - all(l - 1) - all(2ll * n - r);
cout << ans << "\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) solve();
return 0;
}
|
1973
|
F
|
Maximum GCD Sum Queries
|
For $k$ positive integers $x_1, x_2, \ldots, x_k$, the value $\gcd(x_1, x_2, \ldots, x_k)$ is the greatest common divisor of the integers $x_1, x_2, \ldots, x_k$ — the largest integer $z$ such that all the integers $x_1, x_2, \ldots, x_k$ are divisible by $z$.
You are given three arrays $a_1, a_2, \ldots, a_n$, $b_1, b_2, \ldots, b_n$ and $c_1, c_2, \ldots, c_n$ of length $n$, containing positive integers.
You also have a machine that allows you to swap $a_i$ and $b_i$ for any $i$ ($1 \le i \le n$). Each swap costs you $c_i$ coins.
Find the maximum possible value of $$\gcd(a_1, a_2, \ldots, a_n) + \gcd(b_1, b_2, \ldots, b_n)$$ that you can get by paying in total at most $d$ coins for swapping some elements. The amount of coins you have changes a lot, so find the answer to this question for each of the $q$ possible values $d_1, d_2, \ldots, d_q$.
|
What are the possible pairs of $\gcd$'s of the two arrays we can have after some swaps? For every pair $(X, Y)$ such that $X$ divides $a_1$ and $Y$ divides $b_1$, let's calculate the total number of indices $i$ such that we can have $X | a_i$ and $Y | b_i$ (either with or without the swap), and the minimum cost of swaps to achieve this. This is all we need to solve the problem, right? Write for each $i$ the conditions that the pair $(X, Y)$ has to satisfy in order to add $i$ to the result/make swap on the position $i$. Use something like SOS-DP to add up all the values efficiently. Let $k$ be the maximum value of $a_i$, $b_i$ on input ($10^8$). Let $D(k)$ be the maximum number of divisors a number in range $[1, \ldots, k]$ can have and $P(k)$ the maximum number of prime divisors such number can have. Let's think about how to solve one query (with $M$ coins) for now. Assume that in the optimal solution, we never swap $a_1$ and $b_1$. In the end, we will just run the same solution on input where $a_1$ and $b_1$ is swapped and $M$ is decreased by $c_1$, and then we will take the maximum of the two values these two runs will find. So now, in the optimal solution, the gcd of $a$ is always a divisor of $a_1$, and the $\gcd$ of $b$ is a divisor of $b_1$. Let's start by factorizing the two numbers in $O(\sqrt k)$. Now we will precalculate something in order to be efficiently able to determine for every $X$, a divisor of $a$, and $Y$, a divisor of $b_1$, whether we can have $\gcd(a_1, \ldots, a_n) = X$ and $gcd(b_1, ..., b_n) = Y$ simultaneously (and also the minimum cost of making it so). Then we can obviously answer the query by finding the best pair with sum at most $M$. Let's create new two dimensional arrays $P$ and $S$ of size $D(a_1) \times D(b_1)$. We will use $P$ to be able to tell the number of indexes $i$ such that we have either $X | a_i$ and $Y | b_i$ or $X | b_i$ and $Y | a_i$. If this count won't be $n$, then obviously we can't have $X$ and $Y$ as $\gcd$'s of $a$ and $b$. Also, we will use $S$ to tell us the sum of costs of all swaps we need to perform to have $X | \gcd(a_1, \ldots, a_n)$ and $Y | \gcd(b_1, ..., b_n)$. Now how to make two such arrays efficiently? It is obvious that if the pair of $\gcd$ s $(X, Y)$ is consistent with some indexes in the original array, then for every pair $(x, y)$ such that $x|X$ and $y|Y$, this pair of $\gcd$s is also consistent with those indexes (and maybe even more, also maybe some swaps just became unnecessary, but the point is, it doesn't get worse). So if we want to add some value to a pair, we also want to get it added to all its divisors. That's why, in order to calculate the arrays efficiently, we will first add some values on some positions and then do something like $2D$ prefix sums - for every cell $(x, y)$ we will sum the values for all pairs $(X, Y)$ such that $x | X$ and $y | Y$ and update its current value with it. Assuming this is going to happen in the end, let's look at every $i$ and consider what pairs are "good" for this index - with or without the swap: a) If $X$ divides $a_i$ and $Y$ divides $b_i$: For this type of pairs, we don't need to make any swaps on this index. Let's add $1$ to $P[\gcd(a_1, a_i)][\gcd(b_1, b_i)]$ to indicate that for all $(X, Y)$ such that $X|a_i$ and $Y|b_i$, we don't have to perform any swaps at the position $i$, the index is good as it is. b) $X$ divides $b_i$ and $Y$ divides $a_i$: In this case we will add $1$ to $P[\gcd(a_1, b_i)][\gcd(b_1, a_i])]$ and $c_i$ to $S[\gcd(a_1, b_i)][\gcd(b_1, a_i)]$ to indicate that if we pick $X$, $Y$ such that $X|b_i$ and $Y|a_i$, we can make index $i$ good if we swap $a_i$ and $b_i$. c) $X$ and $Y$ both divide both $a_i$ and $b_i$: To avoid counting both of the previous cases and therefore overcounting, we will add $-1$ to $P[\gcd(a_1, a_i, b_i)][\gcd(b_1, a_i, b_i)]$ and $-c_i$ to $S[\gcd(a_1, a_i, b_i)][\gcd(b_1, a_i, b_i)]$ (we have to undo paying for the swap since in this case we actually don't have to pay for it, but it falls under the case b) too). This step can be done in $O(n \log k)$. Now let's fix the arrays $P$ and $S$ so they store the actual values, not just the values we need to add. We will go through all primes $p$ dividing $a_1$ and update $P[X][Y]$ with $P[p \cdot X][Y]$ and $S[X][Y]$ with $S[p \cdot X][Y]$, similarly for all primes dividing $b_1$. If we make those updates in the right order, we achieve that $P[x][y]$ is the sum of all original values $P[X][Y]$ for all the pairs $(X, Y)$ such that $x|X$ and $y|Y$ like we wanted (and we can do the same for $S$). By careful precalculation of divisors and their order while factorizing, we can do this step in $O(D(k)^2 P(k))$. Some efficient implementations with extra log might pass also, but you will have to be more careful. For multiple queries, after precalculating the possible sums of $\gcd$ s and their costs, you can sort them and use binary search to answer the queries. Time complexity: $O(n \log k + \sqrt k + D(k)^2 P(k) + D(k)^2 \log D(k) + q \log D(k))$ Memory complexity: $O(n + D(k)^2 + P(k))$
|
[
"bitmasks",
"brute force",
"dp",
"implementation",
"number theory"
] | 3,100
|
// O(n log k + sqrt(k) * log(k) + d(k)^2 * p(k)) solution, model solution for the harder version
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <vector>
typedef long long ll;
using namespace std;
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
void upd(int& a, int b) { a = max(a, b); }
void prepare(int x, vector<int>& dx, vector<int>& px, vector<int>& cx, map<int, int>& mx)
{
vector<int> cntx;
for (int i = 2; i * i <= x; i++) if (x % i == 0)
{
px.push_back(i), cntx.push_back(0);
while (x % i == 0) cntx.back()++, x /= i;
}
if (x > 1) px.push_back(x), cntx.push_back(1);
dx.push_back(1);
for (int i = 0; i < px.size(); i++)
{
cx.push_back(dx.size());
for (int j = 0; j < cx.back() * cntx[i]; j++) dx.push_back(dx[j] * px[i]);
}
for (int i = 0; i < dx.size(); i++) mx[dx[i]] = i;
}
vector<ll> solve(int n, vector<int> a, vector<int> b, vector<ll> c, vector<ll > qu)
{
int k = max(*max_element(a.begin(), a.end()), *max_element(b.begin(), b.end())) + 1;
vector<int> g(n);
for (int i = 0; i < n; i++) g[i] = gcd(a[i], b[i]);
vector<pair<ll, int> > v;
vector<ll> ans;
for (int it = 0; it < 2; it++)
{
vector<int> da, pa, ca, db, pb, cb;
map<int, int> ma, mb;
prepare(a[0], da, pa, ca, ma), prepare(b[0], db, pb, cb, mb);
vector<vector<ll> > p(da.size(), vector<ll>(db.size(), 0));
vector<vector<ll> > d(da.size(), vector<ll>(db.size(), 0));
for (int i = 1; i < n; i++)
{
p[ma[gcd(a[0], a[i])]][mb[gcd(b[0], b[i])]] += 1, d[ma[gcd(a[0], a[i])]][mb[gcd(b[0], b[i])]] += 0;
p[ma[gcd(a[0], b[i])]][mb[gcd(b[0], a[i])]] += 1, d[ma[gcd(a[0], b[i])]][mb[gcd(b[0], a[i])]] += c[i];
p[ma[gcd(a[0], g[i])]][mb[gcd(b[0], g[i])]] -= 1, d[ma[gcd(a[0], g[i])]][mb[gcd(b[0], g[i])]] -= c[i];
}
for (int ia = 0; ia < ca.size(); ia++) for (int i = da.size() - 1; i >= 0; i--) if (da[i] % pa[ia] == 0) for (int j = db.size() - 1; j >= 0; j--)
{
p[i - ca[ia]][j] += p[i][j];
d[i - ca[ia]][j] += d[i][j];
}
for (int ib = 0; ib < cb.size(); ib++) for (int i = db.size() - 1; i >= 0; i--) if (db[i] % pb[ib] == 0) for (int j = da.size() - 1; j >= 0; j--)
{
p[j][i - cb[ib]] += p[j][i];
d[j][i - cb[ib]] += d[j][i];
}
for (int i = 0; i < da.size(); i++) for (int j = 0; j < db.size(); j++) if (p[i][j] >= n - 1)
v.push_back({ d[i][j] + (it ? c[0] : 0ll), da[i] + db[j] });
swap(a[0], b[0]);
}
sort(v.begin(), v.end());
for (int i = 1; i < v.size(); i++) v[i].second = max(v[i - 1].second, v[i].second);
for (ll d : qu) ans.push_back(v[lower_bound(v.begin(), v.end(), make_pair(d + 1, 0)) - v.begin() - 1].second);
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, q;
cin >> n >> q;
vector<int> a(n), b(n);
vector<ll> c(n), qi(q);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) cin >> b[i];
for (int i = 0; i < n; i++) cin >> c[i];
for (int i = 0; i < q; i++) cin >> qi[i];
vector<ll> ans = solve(n, a, b, c, qi);
for (ll x : ans) cout << x << " ";
cout << "\n";
return 0;
}
|
1974
|
A
|
Phone Desktop
|
Little Rosie has a phone with a desktop (or launcher, as it is also called). The desktop can consist of several screens. Each screen is represented as a grid of size $5 \times 3$, i.e., five rows and three columns.
There are $x$ applications with an icon size of $1 \times 1$ cells; such an icon occupies only one cell of the screen. There are also $y$ applications with an icon size of $2 \times 2$ cells; such an icon occupies a \textbf{square} of $4$ cells on the screen. Each cell of each screen can be occupied by no more than one icon.
Rosie wants to place the application icons on the minimum number of screens. Help her find the minimum number of screens needed.
|
Note that on one screen we can put no more than two $2 \times 2$ icons. Thus, we need at least $Z = \lceil y / 2 \rceil$ screens. Then, we check how many $1 \times 1$ icons we can put on these screens: $15 \cdot Z - 4 \cdot y$. The $1 \times 1$ icons left we need to put on additional screens.
|
[
"greedy",
"math"
] | 800
|
nt = int(input())
for t in range(nt):
line = input()
x, y = [int(q) for q in line.split()]
mm = (y + 1) // 2
x -= (mm * 5 * 3 - y * 2 * 2)
x = max(x, 0)
mm += (x + 5 * 3 - 1) // (5 * 3)
print(mm)
|
1974
|
B
|
Symmetric Encoding
|
Polycarp has a string $s$, which consists of lowercase Latin letters. He encodes this string using the following algorithm:
- first, he constructs a new auxiliary string $r$, which consists of all distinct letters of the string $s$, written in alphabetical order;
- then the encoding happens as follows: each character in the string $s$ is replaced by its symmetric character from the string $r$ (the first character of the string $r$ will be replaced by the last, the second by the second from the end, and so on).
For example, encoding the string $s$="codeforces" happens as follows:
- the string $r$ is obtained as "cdefors";
- the first character $s_1$='c' is replaced by 's';
- the second character $s_2$='o' is replaced by 'e';
- the third character $s_3$='d' is replaced by 'r';
- ...
- the last character $s_{10}$='s' is replaced by 'c'.
\begin{center}
{\small The string $r$ and replacements for $s$="codeforces".}
\end{center}
Thus, the result of encoding the string $s$="codeforces" is the string "serofedsoc".
Write a program that performs decoding — that is, restores the original string $s$ from the encoding result.
|
Let's construct a string $r$ according to the definition from the condition: we write down all the letters from $s$ once in ascending order. After that, we just need to replace all the characters in $s$ with their symmetric characters in the string $r$. The length of string $r$ does not exceed $26$, so the position of this character can be found by linear search.
|
[
"implementation",
"sortings",
"strings"
] | 800
|
def solve():
n = int(input())
b = input()
cnt = [0] * 26
for c in b:
cnt[ord(c) - ord('a')] = 1
tmp = ''
for i in range(26):
if cnt[i] > 0:
tmp += chr(ord('a') + i)
a = ''
for c in b:
a += tmp[-1 - tmp.find(c)]
print(a)
for _ in range(int(input())):
solve()
|
1974
|
C
|
Beautiful Triple Pairs
|
Polycarp was given an array $a$ of $n$ integers. He really likes triples of numbers, so for each $j$ ($1 \le j \le n - 2$) he wrote down a triple of elements $[a_j, a_{j + 1}, a_{j + 2}]$.
Polycarp considers a pair of triples $b$ and $c$ beautiful if they differ in exactly one position, that is, one of the following conditions is satisfied:
- $b_1 \ne c_1$ and $b_2 = c_2$ and $b_3 = c_3$;
- $b_1 = c_1$ and $b_2 \ne c_2$ and $b_3 = c_3$;
- $b_1 = c_1$ and $b_2 = c_2$ and $b_3 \ne c_3$.
Find the number of beautiful pairs of triples among the written triples $[a_j, a_{j + 1}, a_{j + 2}]$.
|
To consider each pair only once, we will go from left to right and while adding a new triplet, we will add to the answer the number of already added triplets that form a beautiful pair with the current one. We will maintain a map with triplets, to denote a triplet with an error, we will place $0$ (or any other value that cannot occur in the array $a$) in place of the error. Thus, for each triplet $b$, the already found triplets $(0, b_2, b_3)$, $(b_1, 0, b_3)$, $(b_1, b_2, 0)$ will be good. In each case, triplets equal to $b$ will also be included, so they need to be subtracted from each of the three cases.
|
[
"combinatorics",
"data structures"
] | 1,400
|
def solve():
n = int(input())
a = [int(x) for x in input().split()]
cnt = dict()
ans = 0
for i in range(n - 2):
triplet = (a[i], a[i + 1], a[i + 2])
mist = [0] * 3
mist[0] = (0, a[i + 1], a[i + 2])
mist[1] = (a[i], 0, a[i + 2])
mist[2] = (a[i], a[i + 1], 0)
for trip in mist:
ans += cnt.get(trip, 0) - cnt.get(triplet, 0)
cnt[trip] = cnt.get(trip, 0) + 1
cnt[triplet] = cnt.get(triplet, 0) + 1
print(ans)
for i in range(int(input())):
solve()
|
1974
|
D
|
Ingenuity-2
|
Let's imagine the surface of Mars as an infinite coordinate plane. Initially, the rover Perseverance-2 and the helicopter Ingenuity-2 are located at the point with coordinates $(0, 0)$. A set of instructions $s$ consisting of $n$ instructions of the following types was specially developed for them:
- N: move one meter north (from point $(x, y)$ to $(x, y + 1)$);
- S: move one meter south (from point $(x, y)$ to $(x, y - 1)$);
- E: move one meter east (from point $(x, y)$ to $(x + 1, y)$);
- W: move one meter west (from point $(x, y)$ to $(x - 1, y)$).
Each instruction must be executed either by the rover or by the helicopter. Moreover, each device must execute \textbf{at least one} instruction. Your task is to distribute the instructions in such a way that after executing all $n$ instructions, the helicopter and the rover end up at the same point, or determine that this is impossible.
|
For the string $S$, calculate the 2D-coordinates $(x, y)$ of the point obtained as a result of sequentially executing all instructions (for example, N decreases $y$ by 1, S increases $y$ by 1, E increases $x$ by 1, W decreases $x$ by 1). Consider the following cases: $x \bmod 2 \neq 0$ or $y \bmod 2 \neq 0$. Obviously, a solution does not exist. $x = 0, y = 0, |S| = 2$. This is one of the strings NS, SN, WE, EW. Again, in this case, it is impossible to construct a solution, as both the rover and the helicopter must execute at least 1 instruction. $x = 0, y = 0, |S| > 2$. A solution exists: assign the first instruction to the helicopter, as well as one of its complements, which exists. Assign all the remaining positive number of instructions to the rover. Both will obviously end up at $(0, 0)$. All other cases: a solution exists. Assign $|x|/2$ and $|y|/2$ instructions moving in the direction of the sign of $x$ and $y$ respectively - which definitely exist - to the helicopter, and the rest to the rover. Both subsets of instructions will be non-empty.
|
[
"constructive algorithms",
"greedy",
"implementation"
] | 1,400
|
inv = {'N':'S', 'S': 'N',
'E': 'W', 'W': 'E'}
def solve():
n = int(input())
s = input()
x, y = 0, 0
for c in s:
if c == 'N':
y += 1
if c == 'S':
y -= 1
if c == 'E':
x += 1
if c == 'W':
x -= 1
if x % 2 == 1 or y % 2 == 1:
print('NO')
return
ans = ['R'] * n
if x == y == 0:
if n == 2:
print('NO')
return
ans[0] = ans[s.find(inv[s[0]])] = 'H'
else:
for i in range(n):
if s[i] == 'N' and y > 0:
y -= 2
ans[i] = 'H'
if s[i] == 'S' and y < 0:
y += 2
ans[i] = 'H'
if s[i] == 'E' and x > 0:
x -= 2
ans[i] = 'H'
if s[i] == 'W' and x < 0:
x += 2
ans[i] = 'H'
print(*ans, sep='')
for _ in range(int(input())):
solve()
|
1974
|
E
|
Money Buys Happiness
|
Being a physicist, Charlie likes to plan his life in simple and precise terms.
For the next $m$ months, starting with no money, Charlie will work hard and earn $x$ pounds per month. For the $i$-th month $(1 \le i \le m)$, there'll be a single opportunity of paying cost $c_i$ pounds to obtain happiness $h_i$.
Borrowing is not allowed. Money earned in the $i$-th month can only be spent in a later $j$-th month ($j>i$).
Since physicists don't code, help Charlie find the maximum obtainable sum of happiness.
|
Let's consider the classic knapsack problem. Let $dp[j]$ be the minimum cost required to achieve happiness $j$. In the $i$-th month, we iterate through $dp[k]$ and check if $dp[k]+c_i \le (i-1) \cdot x$, and if so, we can afford to transition to $dp[k+h_i]$ and accordingly update $dp[k+h_i]$. The complexity is $O(m \cdot \sum_i h_i)$ for each set of input data.
|
[
"dp"
] | 1,800
|
T = int(input())
big = float('inf')
for _ in range(T):
m, x = map(int, input().split())
c = []
h = []
for i in range(m):
ci, hi = map(int, input().split())
c.append(ci)
h.append(hi)
mh = sum(h)
dp = [0] + [big] * mh
for i in range(m):
for j in range(mh, h[i]-1, -1):
if dp[j-h[i]] + c[i] <= i*x:
dp[j] = min(dp[j], dp[j-h[i]]+c[i])
for i in range(mh, -1, -1):
if dp[i] != big:
print(i)
break
|
1975
|
A
|
Bazoka and Mocha's Array
|
Mocha likes arrays, so before her departure, Bazoka gave her an array $a$ consisting of $n$ positive integers as a gift.
Now Mocha wants to know whether array $a$ could become sorted in non-decreasing order after performing the following operation some (possibly, zero) times:
- Split the array into two parts — a prefix and a suffix, then swap these two parts. In other words, let $a=x+y$. Then, we can set $a:= y+x$. Here $+$ denotes the array concatenation operation.
For example, if $a=[3,1,4,1,5]$, we can choose $x=[3,1]$ and $y=[4,1,5]$, satisfying $a=x+y$. Then, we can set $a:= y + x = [4,1,5,3,1]$. We can also choose $x=[3,1,4,1,5]$ and $y=[\,]$, satisfying $a=x+y$. Then, we can set $a := y+x = [3,1,4,1,5]$. Note that we are not allowed to choose $x=[3,1,1]$ and $y=[4,5]$, neither are we allowed to choose $x=[1,3]$ and $y=[5,1,4]$, as both these choices do not satisfy $a=x+y$.
|
We can't do any insertions by the operation. If the answer is yes, we can make $a$ become non-decreasing in no more than one operation. Read the hints. If $a$ is non-decreasing initially, the answer is yes. If $a$ isn't non-decreasing initially, we can find the smallest $i$ such that $a_i> a_{i+1}$. Then we choose $x=[a_1,a_2,...,a_i]$ and $y=[a_{i+1},a_{i+2},...,a_n]$. If the array $y+x$ is non-decreasing, the answer is yes. Otherwise, the answer is no.
|
[
"brute force",
"greedy",
"implementation",
"sortings"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int pos=0;
for(int i=1;i<n;i++){
if(a[i]>a[i+1]){
pos=i;
break;
}
}
if(!pos)cout<<"Yes\n";
else{
int fl=0;
for(int i=pos+1;i<=n;i++){
int j=(i%n)+1;
if(a[i]>a[j])fl=1;
}
if(!fl)cout<<"Yes\n";
else cout<<"No\n";
}
}
}
|
1975
|
B
|
378QAQ and Mocha's Array
|
Mocha likes arrays, so before her departure, 378QAQ gave her an array $a$ consisting of $n$ positive integers as a gift.
Mocha thinks that $a$ is beautiful if there exist two numbers $i$ and $j$ ($1\leq i,j\leq n$, $i\neq j$) such that for all $k$ ($1 \leq k \leq n$), $a_k$ is divisible$^\dagger$ by either $a_i$ or $a_j$.
Determine whether $a$ is beautiful.
$^\dagger$ $x$ is divisible by $y$ if there exists an integer $z$ such that $x = y \cdot z$.
|
How to solve the problem if we only need to find a number $i$($1\leq i\leq n$) such that $a_k$ is divisible by $a_i$ for all $k$($1\leq k\leq n$)? We only need to check whether all elements are divisible by the minimum element of the array. Read the hints. Suppose the minimum element of $a$ is $x$. Then we iterate over $a$, if an element is not divisible by $x$, then we add it to $b$ ($b$ is initially empty). If $b$ is still empty after iterating $a$, the answer is yes. If $b$ isn't empty, we check whether all elements of $b$ are divisible by the minimum element of $b$. If so, the answer is yes. Otherwise, the answer is no.
|
[
"brute force",
"greedy",
"math",
"sortings"
] | 1,000
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5+10;
int a[N];
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int fl=0;
for(int i=1;i<=n;i++){
cin>>a[i];
if(a[i]==1)fl=1;
}
if(fl)cout<<"Yes\n";
else{
sort(a+1,a+1+n);
vector<int> b;
for(int i=2;i<=n;i++){
if(a[i]%a[1])b.push_back(a[i]);
}
sort(b.begin(),b.end());
n = b.size();
for(int j=1;j<n;j++){
if(b[j]%b[0]){
fl=1;
break;
}
}
if(!fl)cout<<"Yes\n";
else cout<<"No\n";
}
}
}
|
1975
|
C
|
Chamo and Mocha's Array
|
Mocha likes arrays, so before her departure, Chamo gave her an array $a$ consisting of $n$ positive integers as a gift.
Mocha doesn't like arrays containing different numbers, so Mocha decides to use magic to change the array. Mocha can perform the following three-step operation some (possibly, zero) times:
- Choose indices $l$ and $r$ ($1 \leq l < r \leq n$)
- Let $x$ be the median$^\dagger$ of the subarray $[a_l, a_{l+1},\ldots, a_r]$
- Set all values $a_l, a_{l+1},\ldots, a_r$ to $x$
Suppose $a=[1,2,3,4,5]$ initially:
- If Mocha chooses $(l,r)=(3,4)$ in the first operation, then $x=3$, the array will be changed into $a=[1,2,3,3,5]$.
- If Mocha chooses $(l,r)=(1,3)$ in the first operation, then $x=2$, the array will be changed into $a=[2,2,2,4,5]$.
Mocha will perform the operation until the array contains only the same number. Mocha wants to know what is the maximum possible value of this number.
$^\dagger$ The median in an array $b$ of length $m$ is an element that occupies position number $\lfloor \frac{m+1}{2} \rfloor$ after we sort the elements in non-decreasing order. For example, the median of $[3,1,4,1,5]$ is $3$ and the median of $[5,25,20,24]$ is $20$.
|
If a subarray of length at least $2$ contains only the same elements, we can change all elements of the array to that element by operations. Suppose the answer is $x$, we can perform no more than one operation on the original array $a$ so that there is a subarray of length at least $2$ that contains only $x$. If we can make all elements of a subarray become $x$ in one operation, then there must be a subarray of length $3$ with a median of $y$ ($y\geq x$). Read the hints. If $n=2$, the answer is the minimum element. If $n\geq 3$, we iterate over all subarrays of length $3$, and the answer is the maximum value of the median of all subarrays of length $3$.
|
[
"binary search",
"brute force",
"greedy"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int main(){
int n,t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
if(n==2)cout<<min(a[1],a[2])<<"\n";
else{
int ans = min(a[1],a[2]);
for(int i=1;i<=n-2;i++){
vector<int> tmp;
for(int k=0;k<=2;k++)
tmp.push_back(a[i+k]);
sort(tmp.begin(),tmp.end());
ans = max(ans,tmp[1]);
}
cout<<ans<<"\n";
}
}
}
|
1975
|
D
|
Paint the Tree
|
378QAQ has a tree with $n$ vertices. Initially, all vertices are white.
There are two chess pieces called $P_A$ and $P_B$ on the tree. $P_A$ and $P_B$ are initially located on vertices $a$ and $b$ respectively. In one step, 378QAQ will do the following in order:
- Move $P_A$ to a neighboring vertex. If the target vertex is white, this vertex will be painted red.
- Move $P_B$ to a neighboring vertex. If the target vertex is colored in red, this vertex will be painted blue.
Initially, the vertex $a$ is painted red. If $a=b$, the vertex $a$ is painted blue instead. Note that both the chess pieces \textbf{must} be moved in each step. Two pieces can be on the same vertex at any given time.
378QAQ wants to know the minimum number of steps to paint all vertices blue.
|
If two pieces overlap at the beginning, can you solve the problem? Consider the first time a vertex is painted blue. After this event occurs, what happens next? Read the hints. In subsequent movements after the first time a vertex is painted blue, we can ignore the process of painting vertices red and then painting them blue. We call the first vertex painted blue $r$. Then it is not difficult to find that $P_A$ arrived at this vertex earlier than $P_B$. Considering all subsequent movements of $P_B$, $P_A$ can restore these movements one by one after reaching $r$, then $P_B$ will pass through all vertices have been painted red. If we know which vertex is $r$, this will be a classic problem, assuming the distance between the farthest vertex on the tree from $r$ and $r$ is $d$, then the answer is $2(n-1)-d$. Then we consider the strategies of $P_A$ and $P_B$ at this time. The two must be close to each other, and then until the first vertex is painted blue. If another vertex is $r$, although the value of $d$ may increase, every time the value of $d$ increases by $1$, the time when $P_A$ and $P_B$ meet will also increase by at least $1$, so the answer will not decrease.
|
[
"brute force",
"dfs and similar",
"dp",
"greedy",
"shortest paths",
"trees"
] | 1,700
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 2e5+10;
vector<int> g[N];
int dep[N],f[N],mx,n,a,b;
void dfs(int x,int fa){
dep[x]=dep[fa]+1;
mx = max(mx,dep[x]);
f[x]=fa;
for(auto i:g[x]){
if(i==fa)continue;
dfs(i,x);
}
}
vector<int> move(int x,int y){
if (dep[x] > dep[y]) swap(x, y);
vector<int> track,ano;
int tmp = dep[y] - dep[x], ans = 0;
track.push_back(y);
while(tmp--){
y = f[y];
track.push_back(y);
}
if (y == x) return track;
ano.push_back(x);
while (f[x] != f[y]) {
x = f[x];
y = f[y];
ano.push_back(x);
track.push_back(y);
}
track.push_back(f[y]);
reverse(ano.begin(),ano.end());
for(auto i:ano)track.push_back(i);
return track;
}
int main(){
int t;
cin>>t;
dep[0]=-1;
while(t--){
mx = -1;
cin>>n;
for(int i=1;i<=n;i++)g[i].clear();
cin>>a>>b;
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
if(a==b){
dfs(a,0);
cout<<2*(n-1)-mx<<"\n";
continue;
}
dfs(1,0);
auto tr = move(a,b);
int m = tr.size();
if(tr[0]!=a)reverse(tr.begin(),tr.end());
int x = tr[(m-1)/2];
mx = -1;
dfs(x,0);
cout<<2*(n-1)-mx+(m-1-(m-1)/2)<<"\n";
}
}
|
1975
|
E
|
Chain Queries
|
You are given a tree of $n$ vertices numbered from $1$ to $n$. Initially, all vertices are colored white or black.
You are asked to perform $q$ queries:
- "u" — toggle the color of vertex $u$ (if it was white, change it to black and vice versa).
After each query, you should answer whether all the black vertices form a chain. That is, there exist two black vertices such that the simple path between them passes through all the black vertices and only the black vertices. Specifically, if there is only one black vertex, they form a chain. If there are no black vertices, they do \textbf{not} form a chain.
|
Suppose the tree is a rooted tree, we only need to care about the number of black child vertices of each vertex. If the black vertices form a chain, there is no black vertex that has three or more black child vertices. And there is at most one black vertex that has two black child vertices. If the black vertices form a chain, there is at most one black vertex whose parent vertex is white. Read the hints. We can maintain the number of black vertices with $0/1/2/3+$ black child vertices in $O(1)$. When we flip the color of one vertex, only it and its parent node are affected. If the black vertices form a chain: - no black vertex that has three or more black child vertices and there is at most one black vertex that has two black child vertices. - there is at most one black vertex whose parent vertex is white. - if there is one black vertex that has two black child vertices, its parent vertex must be white.
|
[
"binary search",
"data structures",
"dfs and similar",
"implementation",
"trees"
] | 2,100
|
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
int f[N];
vector<int> g[N];
int col[N],num[N];
int faw,sum_two,sum_more,tot_black,xor_two;
int n;
void init(){
sum_two=0;
tot_black=0;
sum_more=0;
faw=0;
xor_two=0;
for(int i=1;i<=n;i++){
g[i].clear();
num[i]=0;
}
}
void dfs(int x,int fa){
f[x]=fa;
if(col[x]==1)tot_black++;
int sum=0;
for(auto i:g[x]){
if(i==fa)continue;
dfs(i,x);
if(col[i]==1)sum++;
}
if(col[fa]==0&&col[x]==1)faw++;
if(col[x]==1){
if(sum==2)sum_two++,xor_two^=x;
if(sum>2)sum_more++;
}
num[x]=sum;
}
void flip(int x){
col[x]^=1;
int d = col[x]==1?1:-1;
tot_black+=d;
if(col[f[x]]==0)faw+=d;
if(num[x]==2)sum_two+=d,xor_two^=x;
if(num[x]>2)sum_more+=d;
faw-=d*num[x];
if(col[x]==1){
if(col[f[x]]==1&&num[f[x]]==2)sum_two--,sum_more++,xor_two^=f[x];
num[f[x]]++;
if(col[f[x]]==1&&num[f[x]]==2)sum_two++,xor_two^=f[x];
}else{
if(col[f[x]]==1&&num[f[x]]==2)sum_two--,xor_two^=f[x];
num[f[x]]--;
if(col[f[x]]==1&&num[f[x]]==2){
sum_two++;
sum_more--;
xor_two^=f[x];
}
}
}
bool check(){
if(!tot_black)return false;
if(sum_more||sum_two>1)return false;
if(faw>1)return false;
if(sum_two&&col[f[xor_two]]==1)return false;
return true;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
init();
int q;
scanf("%d %d",&n,&q);
for(int i=1;i<=n;i++) cin>>col[i];
for(int i=1;i<n;i++){
int u,v;
scanf("%d %d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1,0);
while(q--){
int x;
scanf("%d",&x);
flip(x);
if(check()) printf("Yes\n");
else printf("No\n");
}
}
}
|
1975
|
F
|
Set
|
Define the binary encoding of a finite set of natural numbers $T \subseteq \{0,1,2,\ldots\}$ as $f(T) = \sum\limits_{i \in T} 2^i$. For example, $f(\{0,2\}) = 2^0 + 2^2 = 5$ and $f(\{\}) = 0$. Notice that $f$ is a bijection from all such sets to all non-negative integers. As such, $f^{-1}$ is also defined.
You are given an integer $n$ along with $2^n-1$ sets $V_1,V_2,\ldots,V_{2^n-1}$.
Find all sets $S$ that satisfy the following constraint:
- $S \subseteq \{0,1,\ldots,n-1\}$. Note that $S$ can be \textbf{empty}.
- For all \textbf{non-empty} subsets $T \subseteq \{0,1,\ldots,n-1\}$, $|S \cap T| \in V_{f(T)}$.
Due to the large input and output, both input and output will be given in terms of binary encodings of the sets.
|
Consider enumerating each number from $0$ to $n-1$ whether it is contained by $S$, when we have enumerated the first $x$ numbers, there are only $2^{n-x}$ constraints. Read the hints. Consider enumerating each number from $0$ to $n-1$ whether it is contained by $S$. Suppose that the current enumeration reaches $i$, and in the remaining constraints, $T_1$ and $T_2$ are two sets, the only difference between them is whether they contain $i$ ($T_1$ contains $i$): $S$ contains $i$. We can merge $T_1$ and $T_2$ into a new constraint $T'$ and $v_{T'}=(v_{T_1}>>1)$&$v_{T_2}$. $S$ doesn't contain $i$. We can merge $T_1$ and $T_2$ into a new constraint $T'$ and $v_{T'}=v_{T_1}$&$v_{T_2}$. We can merge constraints quickly when the enumeration reaches a new number. And the time complexity is $O(n\cdot 2^n)$
|
[
"bitmasks",
"brute force",
"combinatorics",
"dfs and similar",
"divide and conquer",
"dp",
"math"
] | 2,600
|
#include<bits/stdc++.h>
using namespace std;
const int N = 24, S = (1 << 20) + 5;
int n = 0, f[N][S] = {};
vector<int> ans;
inline void dfs(int s = 0, int i = 0){
if(i < n){
int m = 1 << (n - i - 1);
for(int t = 0 ; t < m ; t ++) f[i + 1][t] = f[i][t] & f[i][m | t];
dfs(s << 1, i + 1);
for(int t = 0 ; t < m ; t ++) f[i + 1][t] = f[i][t] & (f[i][m | t] >> 1);
dfs(s << 1 | 1, i + 1);
}
else if(f[n][0] & 1) ans.push_back(s);
}
int main(){
scanf("%d", &n);
f[0][0] = 1;
for(int s = 1 ; s < 1 << n ; s ++) scanf("%d", &f[0][s]);
dfs();
printf("%d\n", int(ans.size()));
for(int s : ans) printf("%d\n", s);
return 0;
}
|
1975
|
G
|
Zimpha Fan Club
|
One day, Zimpha casually came up with a problem. As a member of "Zimpha fan club", you decided to solve that problem.
You are given two strings $s$ and $t$ of length $n$ and $m$, respectively. Both strings only consist of lowercase English letters, - and *.
You need to replace all occurrences of * and -, observing the following rules:
- For each -, you must replace it with any lowercase English letter.
- For each *, you must replace it with a string of any (possibly, zero) length which only consists of lowercase English letters.
Note that you can replace two different instances of - with different characters. You can also replace each two different instances of * with different strings.
Suppose $s$ and $t$ have been transformed into $s'$ and $t'$. Now you're wondering if there's a replacement that makes $s'=t'$.
|
If $s, t$ both have $*$, or both don't have $*$, then it will be a simple problem. Can you try to solve this problem? According to the first hint, we have discussed two cases. In the remaining cases, without loss of generality, we think that only $t$ has $*$. Suppose we write $t$ as $t'_0*t'_1*t'_2* \dots*t'_k$. Where $t'_i$ does not take $*$, assuming that $|t'_i| \leq 50$ is satisfied for all $i$, can you solve this problem? There is a strictly subproblem of this problem, namely, given two strings $s$ and $t$ consisting only of characters from $a$ to $z$ and $-$, you need to find all positions in $s$ where $t$ can be matched. This problem has a classic solution, where $-$ is set to $0$, and $a$ to $z$ are sequentially assigned values from $1$ to $26$, and then let $f_i = \sum_{j=1}^m [s_{i +j-1} > 0] \times [t_j > 0] (s_{i+j-1}-t_j)^2$, then all positions of $f_i = 0$ satisfy $s[i, i + m -1]$ can match $t$. Decompose the calculation formula, $f_i = \sum_{j=1}^m s_{i+j-1}^2+s_j^2 - 2\sum_{j=1}^m s_{i+j -1}{t_j} - \sum_{j=1}^m [s_{i+j-1} = 0] t_j^2 - \sum_{j=1}^m s_{i+j-1}^ 2[t_j=0]$. For $\sum_{j=1}^m s_{i+j-1}^2+s_j^2$, you can prefix and process it, and for the remaining part, you can use FFT in $O(n \log n )$ to be resolved. What is the use of this solution in the original problem? Read the hints. In the following, we consider $n, m$ to be of the same order. Consider the case where $s$ and $t$ do not contain $*$. We only need to be compared bit by bit. Consider the case where $s, t$ both contain $*$, if the beginning of $s$ is not $*$ or the beginning of $t$ is not $*$: If one of the first characters of $s$ and $t$ is $*$ or the first characters can match, delete the first characters of the two strings that are not $*$. Oherwise the answer is obviously No. Performing the same operation on the last characters, it is not difficult to find that it will be reduced to two strings $*s'$ and $t'*$, where $s'$ and $t'$ are arbitrary strings. Then it is not difficult to find that $t's'$ matches two strings at the same time. Therefore, as long as the head and tail can be successfully deleted, the answer must be Yes. Consider the hardest case. Without loss of generality, we assume that only $t$ contains $*$, otherwise $s, t$ can be exchanged. We still delete the beginning and the end first. It is not difficult to find that thereafter $t$ can be written as $*t'_1*t'_2*\dots*t'_k *$. Then we will have a greedy solution. We iterate $i$ from $1$ to $n$, find the first matching position of $t'_i$ in $s$ each time, and delete tthese matching characters and all preceding characters in $s$, that is, remove a prefix of $s$, and then until all matching is completed or no matching position is found in $s$. Assume that we use FFT to brute force solve this problem every time. See Hint.3 for the specific solution, then the complexity is $O(nk \log n)$. But it is not difficult to find that this is very wasteful. In fact, we can do this: When matching $t'_i$, only take out the first $|2t'_i|$ characters of $s$ each time and try to match $t'_i$. Because if the match is successful, then since all positions matching $t'_i$ are deleted, it is not difficult to find that at least $|t'_i|$ characters are deleted. And if the match fails, it is not difficult to find that the first $|t'_i|$ characters of $s$ will no longer be useful and can also be deleted. Therefore we remove at least the first $|t'_i|$ characters in $s$ in complexity $O(|t'_i| \log |t'_i|)$. Since the total length of $s$ is $n$, the total time complexity does not exceed $O(n \log n)$.
|
[
"fft",
"greedy",
"math",
"strings"
] | 3,000
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = (1 << 22) + 5, Mod = 2013265921, G = 31;
inline ll power(ll x, ll y){
ll ret = 1;
while(y){
if(y & 1) ret = ret * x % Mod;
x = x * x % Mod, y >>= 1;
}
return ret;
}
ll p[N] = {}, w[N] = {}, g[N] = {}, iv[N] = {};
inline void dft(ll n, ll a[], bool idft){
for(ll i = 0 ; i < n ; i ++) if(i < p[i]) swap(a[i], a[p[i]]);
for(ll m = 1 ; m < n ; m <<= 1) for(ll j = 0, k = 0 ; j < n ; j += m << 1, k ++) for(ll i = j ; i < j + m ; i ++){
ll x = a[i], y = a[i + m];
a[i] = x + y, a[i] >= Mod && (a[i] -= Mod);
a[i + m] = (x - y + Mod) * w[k] % Mod;
}
if(!idft) return;
reverse(a + 1, a + n);
for(int i = 0 ; i < n ; i ++) a[i] = a[i] * iv[n] % Mod;
}
inline ll sqr(ll x){
return x * x;
}
ll n = 0, m = 0, a[3][N] = {}, b[3][N] = {}, c[N] = {}, d[N] = {};
char s[N] = {}, t[N] = {};
inline ll work(ll L, ll R, ll l, ll r){
ll M = 1; while(M < R - L + r - l) M <<= 1;
w[0] = 1;
for(ll k = 1 ; k < M ; k <<= 1){
ll bit = M / 2 / k;
if(k == M / 2) for(ll i = 0; i < k ; i ++) p[i + k] = p[i] | bit;
else for(ll i = 0 ; i < k ; i ++){
w[i + k] = w[i] * g[k] % Mod;
p[i + k] = p[i] | bit;
}
}
for(ll i = 0 ; i < M ; i ++){
p[i] = p[i >> 1] >> 1;
if(i & 1) p[i] |= M >> 1;
}
ll z = 0;
for(ll i = 0 ; i < M ; i ++){
c[i] = 0;
for(ll f = 0 ; f < 3 ; f ++) a[f][i] = b[f][i] = 0;
}
for(ll i = L ; i < R ; i ++){
ll x = (s[i] == '-') ? 0 : (s[i] - 'a' + 1);
a[0][i - L] = x ? 0 : 1, a[1][i - L] = 2 * x, a[2][i - L] = sqr(x), d[i] = sqr(x);
}
d[R] = 0;
for(ll i = l ; i < r ; i ++){
ll x = (t[i] == '-') ? 0 : (t[i] - 'a' + 1);
b[0][r - i] = sqr(x), b[1][r - i] = x, b[2][r - i] = x ? 0 : 1, z += sqr(x);
}
for(ll f = 0 ; f < 3 ; f ++){
dft(M, a[f], 0), dft(M, b[f], 0);
for(ll i = 0 ; i < M ; i ++) c[i] = (c[i] + a[f][i] * b[f][i]) % Mod;
}
dft(M, c, 1);
for(ll i = 0 ; i < r - l ; i ++) z += d[i + L];
for(ll i = L ; i <= R - (r - l) ; z -= d[i], z += d[i + (r - l)], i ++) if(z % Mod == c[i - L + r - l]) return i;
return -1;
}
int main(){
for(ll i = 1 ; i < N ; i <<= 1) g[i] = power(G, Mod / 4 / i), iv[i] = power(i, Mod - 2);
scanf("%lld %lld", &n, &m);
scanf("%s %s", s, t);
while(n && m && s[n - 1] != '*' && t[m - 1] != '*'){
if(s[n - 1] != t[m - 1] && s[n - 1] != '-' && t[m - 1] != '-'){
printf("No");
return 0;
}
else n --, m --;
}
reverse(s, s + n), reverse(t, t + m);
while(n && m && s[n - 1] != '*' && t[m - 1] != '*'){
if(s[n - 1] != t[m - 1] && s[n - 1] != '-' && t[m - 1] != '-'){
printf("No");
return 0;
}
else n --, m --;
}
reverse(s, s + n), reverse(t, t + m);
if(min(n, m) == 0){
while(n && s[n - 1] == '*') n --;
while(m && t[m - 1] == '*') m --;
if(max(n, m) == 0) printf("Yes");
else printf("No");
return 0;
}
bool u = 0, v = 0;
for(ll i = 0 ; i < n ; i ++) if(s[i] == '*') u = 1;
for(ll i = 0 ; i < m ; i ++) if(t[i] == '*') v = 1;
if(u){
if(v){
printf("Yes");
return 0;
}
else swap(n, m), swap(s, t);
}
ll L = 0, R = 0;
for(ll l = 1, r = l ; l < m ; l = r + 1, r = l){
while(t[r] != '*') r ++;
if(r - l) while(1){
R = min(n, L + 2 * (r - l));
if(R - L < r - l){
printf("No");
return 0;
}
ll h = work(L, R, l, r);
if(h == -1) L = R - (r - l) + 1;
else{
L = h + r - l;
break;
}
}
}
printf("Yes");
return 0;
}
|
1975
|
H
|
378QAQ and Core
|
378QAQ has a string $s$ of length $n$. Define the core of a string as the substring$^\dagger$ with maximum lexicographic$^\ddagger$ order.
For example, the core of "$\mathtt{bazoka}$" is "$\mathtt{zoka}$", and the core of "$\mathtt{aaa}$" is "$\mathtt{aaa}$".
378QAQ wants to rearrange the string $s$ so that the core is lexicographically minimum. Find the lexicographically minimum possible core over all rearrangements of $s$.
$^\dagger$ A substring of string $s$ is a continuous segment of letters from $s$. For example, "$\mathtt{defor}$", "$\mathtt{code}$" and "$\mathtt{o}$" are all substrings of "$\mathtt{codeforces}$" while "$\mathtt{codes}$" and "$\mathtt{aaa}$" are not.
$^\ddagger$ A string $p$ is lexicographically smaller than a string $q$ if and only if one of the following holds:
- $p$ is a prefix of $q$, but $p \ne q$; or
- in the first position where $p$ and $q$ differ, the string $p$ has a smaller element than the corresponding element in $q$ (when compared by their ASCII code).
For example, "$\mathtt{code}$" and "$\mathtt{coda}$" are both lexicographically smaller than "$\mathtt{codeforces}$" while "$\mathtt{codeforceston}$" and "$\mathtt{z}$" are not.
|
Consider the maximum character $m$ of the string $s$. If $m$ only appears once, then obviously the string starting with it is the largest in lexicographical order. To make it the smallest, $m$ should be arranged at the end. Other characters can be arranged arbitrarily. If $m$ appears more than twice, it can be proven that the beginning and end of the answer string must be $m$. If the beginning of the string is not $m$, moving the character at the beginning to somewhere before a non-first $m$ can make the suffix lexicographical order starting with this $m$ smaller, while the suffix lexicographical order starting with $m$ after this remains unchanged. For suffixes that do not start with $m$, they are definitely not the largest, so they do not need to be considered. If the end of the string is not $m$, first remove it, and all suffix lexicographical orders become smaller. Similarly, it can also be placed in front of a certain $m$ to reduce the lexicographical order. In this case, the answer is always in the form of $ms_{1}ms_{2}m\dots ms_{t}m$. Where $s_{1},s_{2},\dots,s_{t}$ contain characters that are less than $m$, it could also be an empty string. Now suppose that the set ${s_{1},s_{2},\dots,s_{t}}$ is determined, and consider how to arrange their order. Suppose we are currently comparing two suffixes $S_{i}=ms_{i}m\dots ms_{t}m$ and $S_{j}=ms_{j}m\dots ms_{t}m$, and suppose $s_{i+k}$ and $s_{j+k}$ are the first two substrings that appear differently. Then $ms_{i}m\dots ms_{i+k-1}$ and $ms_{j}m\dots ms_{j+k-1}$ must be equal, and the size relationship between $S_{i}$ and $S_{j}$ is the same as the size relationship between $ms_{i+k}$ and $ms_{j+k}$. In this way, all $ms_{i}$ can be sorted according to lexicographical order, and regarded as a new character, and Solving the original problem for $(ms1)(ms_2) \dots (ms_t)$ is sufficient. Now consider how to determine the set ${s_{1},s_{2},\dots,s_{t}}$. For a certain $s_{i}$, it should obviously be ordered, because this can make $ms_{i}$ smaller. There is also another property. Suppose there are $s_{i}=p_{i}c$ and $s_{j}$ such that $ms_{j}$ is the current lexicographically largest string, and $mp_{i}<ms_{j}$, where $c$ is a character less than $m$. Putting $c$ after $s_{j}$ can make the answer smaller. The proof of the property is as follows. Without loss of generality, let $f_{1}=p_{i}c$, $f_{2}=p_{i}$, $f_{3}=s_{j}c$, $f_{4}=s_{j}$, then we have $mf_{2}<mf_{1}<mf_{4}$ and $f_{3}m<f_{4}m$. Consider the subproblem after iteration, by definition, $f_{4}$ is the largest character in the problem. If $f_{1}$ and $f_{4}$ are used, and there is an $f_{4}$ to the left of some $f_{1}$ in the optimal solution string, then replacing this $f_{1}$ and its nearest $f_{4}$ on the left with $f_{2}$ and $f_{3}$ respectively, it is easy to prove that the largest suffix will definitely become smaller or unchanged. Otherwise, all $f_{1}$ are to the left of all $f_{4}$, at this time you can arbitrarily replace some $f_{1}$ and $f_{4}$ with $f_{2}$ and $f_{3}$ respectively, it is easy to prove that the largest suffix still becomes smaller or unchanged. Based on the above discussion, we can now give the final greedy algorithm for the problem. Suppose the largest character $m$ has $t+1$ occurrences. If $t=0$, then put the only $m$ at the end, and the other characters can be arranged arbitrarily. Otherwise, suppose there are $p$ characters less than $m$, if $p\le t$, it can be proved that there is at most one character between any two $m$. Consider $|s_{i}|\ge2$, $s_{j}=\varepsilon$ (empty string), then they meet the above properties, and it is more optimal to exchange the last character of $s_{i}$ to $s_{j}$. Therefore, $s_{1},\dots,s_{p}$ is a single character, $s_{p+1}=\dots=s_{t}=\varepsilon$, and recursively solve the subproblem. Note that to ensure time complexity, when $t\gg p$, multiple rounds of recursion need to be combined. If $p>t$, it can be similarly proved that there will not be an $s_{i}$ that is an empty string. In addition, consider the first character of all $s_{i}$, for those among these $t$ characters that are not the largest, using the same property, it can be proved that the length of the string they are in must be $1$, and no other characters will follow. Also, since $s_{i}$ is ordered, it can be proved that the first character of all $s_{i}$ must be the smallest $t$ characters less than $m$. Next, the remaining characters will only be filled after those largest characters among these $t$ characters, and it can be similarly proved that those filled in the second position of these strings are also the smallest among the remaining characters, and so on, until all characters are used up. Notice that the complexity of each recursion is linear, and each recursion at least halves the number of characters, so the total complexity is $O(n\log n)$. How to solve this problem in $O(n)$?
|
[
"greedy",
"strings"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
struct ch{
string c;
ch(){c = "";}
ch(string cc){c=cc;}
bool operator == (const ch& p)const{
return c==p.c;
}
bool operator != (const ch& p)const{
return c!=p.c;
}
void add(ch& p){
c.append(p.c);
}
};
vector<ch> solve(vector<ch> cs){
int n = cs.size();
int t = 0;
if(cs.empty())return cs;
for(int i=n-2;i>=0;i--){
if(cs[i]!=cs[n-1])break;
t++;
}
if(t==0){
vector<ch> res;
res.push_back(cs[n-1]);
return res;
}
int p = n-(t+1);
if(p<=t){
vector<ch> res;
vector<ch> nxt;
int k = (t+1)/(p+1);
int le = (t+1)%(p+1);
ch m = cs[n-1];
for(int j=1;j<k;j++){
m.add(cs[n-1]);
}
for(int i=0;i<p;i++){
ch tmp = m;
tmp.add(cs[i]);
nxt.push_back(tmp);
}
for(int i=0;i<le;i++){
nxt.push_back(cs[n-1]);
}
auto nxt_solved = solve(nxt);
for(auto i:nxt_solved)res.push_back(i);
res.push_back(m);
return res;
}else{
vector<ch> res;
vector<ch> nxt;
ch m = cs[n-1];
for(int i=0;i<t;i++){
nxt.push_back(m);
}
int now = 0,beg=0;
for(int i=0;i<p;i++){
nxt[now].add(cs[i]);
if(now>=1){
if(cs[i]!=cs[i-1]){
beg=now;
}
}
now++;
if(now>=t)now=beg;
}
auto nxt_solved = solve(nxt);
for(auto i:nxt_solved)res.push_back(i);
res.push_back(m);
return res;
}
}
vector<ch> trans(string s){
vector<ch> tmp;
for(auto i:s){
string tmpp = "";
tmpp+=i;
tmp.push_back(tmpp);
}
return tmp;
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
string s;
cin>>s;
sort(s.begin(),s.end());
auto tmp = trans(s);
auto ans= solve(tmp);
for(auto c:ans)cout<<c.c;
cout<<"\n";
}
}
|
1975
|
I
|
Mind Bloom
|
\begin{quote}
This is the way it always was.
\end{quote}
\begin{quote}
This is the way it always will be.
\end{quote}
\begin{quote}
All will be forgotten again soon...
\end{quote}
Jellyfish is playing a one-player card game called "Slay the Spire". There are $n$ cards in total numbered from $1$ to $n$. The $i$-th card has power $c_i$.
There is a binary string $s$ of length $n$. If $s_i = 0$, the $i$-th card is initially in the draw pile. If $s_i = 1$, the $i$-th card is initially in Jellyfish's hand.
Jellyfish will repeat the following process until either her hand or the draw pile is empty.
- Let $x$ be the power of the card with the largest power in her hand.
- Place a single card with power $x$ back into the draw pile.
- Randomly draw $x$ cards from the draw pile. All subsets of $x$ cards from the draw pile have an equal chance of being drawn. If there are fewer than $x$ cards in the draw pile, Jellyfish will draw all cards.
At the end of this process, find the probability that Jellyfish can empty the draw pile, modulo $1\,000\,000\,007$.
Formally, let $M=1\,000\,000\,007$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
|
Play "Slay the Spire". Unfortunately, it doesn't help much. It may be helpful to calculate the probability that your hand becomes empty instead of the probability that the draw pile becomes empty. The intended solution is a $O(n^5)$ DP. The constant factor is small enough to run. If all the cards in your hand is $0$, you immediately lose. Therefore, we only need to consider whether we can empty our hand by playing cards with non-$0$ value. Consider a sequence of playing cards that will lead to use losing. The sum over the probabilities of all these losing sequences is the probability of us losing. To simplify the process, we will consider drawing $x$ random cards from the deck as drawing a random card from the deck $x$ times. Consider a sequence of played cards as $z_1, z_2, \ldots, z_k$ where $z_i$ is the index of the card played. Consider how $z_i$ was drawn into our hand. It is not hard to see that either: $z_i$ was in our hand at the start $z_i$ from drawn from card $a_j$ where $j$ is the maximum index such that $z_j \leq z_i$ and $j < i$. From our previous observation, we can motivate the following range DP. Let $f(i,0/1,u,p,x)$ denote the a sequence of played cards with the following: the minimum index of a card we played is $i$ whether there are any cards with value greater than $i$ that is one of the cards that were in our hand in the start before we played this sequence, we played a card of value $u$ before we played this sequence, the deck has $p$ cards The net number of cards that we draw is $x$ We will use $g(i,0/1,u,p,x)$ to help us transition quickly. It is defined as the suffix sum (on dimension $i$) of $f$. Consider transitioning based on the card of index $i$. We have the following transition for $f(*,0,*,*,*)$: $f(i, 0, u, p, x) = \sum_{y=0}^{x-(c_i-1)} g(i+1, 0, u, p, y) \times g(i, 0, c_i, p - (c_i - 1) - y, x - (c_i - 1) - y) \times \frac {u+y} {(p-y+1)^{\underline c_i}}$ $g(i, 0, u, p, x) = g(i+1, 0, u, p, x) + f(i, 0, u, p, x)$ For $f(*,1,*,*,*)$, To handle the fact that there are some cards that are initially in our hands, let $h$ denote the the number of $j>i$ such that $s_j=1$. If $s_i = 1$, we have the following transitions: $f(i, 1, u, p, x) = \sum_{y=h}^{x-c_i} g(i+1, 1, u, p, y) \times g(i, 0, c_i, p - (c_i - 1) - y+h, x - c_i - y) \times \frac {1} {(p-y+1+h)^{\underline c_i}}$ $g(i, 1, u, p, x) = f(i, 1, u, p, x)$ If $s_i = 0$, we have the following transitions: $f(i, 1, u, p, x) = \sum_{y=h}^{x-(c_i-1)} g(i+1, 1, u, p, y) \times g(i, 0, c_i, p - (c_i - 1) - y+h, x - (c_i - 1) - y) \times \frac {u+y} {(p-y+1+h)^{\underline c_i}}$ $g(i, 1, u, p, x) = g(i+1, 1, u, p, x) + f(i, 1, u, p, x)$ The time complexity is $O(n^5)$. Now consider adding the cards with value $1$. It is possible that our game never terminates when we keep on drawing cards with value $1$. We will instead force that when we play a card of value $1$, we are not allowed to draw a card of value $1$. It is not hard to observe that the answer will not change. Consider $dp(i,x)$ to be the probability that we have in our hand: $i$ card of value $0$ $x$ card of value $1$ It is not hard to observe that for the initial state, $dp(i, o+x)$ is $g(1, 1, i+x, 0, m) \times \binom {i+x} i \times (m-o)^{\underline x}$. Next, consider the transitions. There are only two cases, we draw a card with value $0$, or a card with value greater than $0$: $dp(i, x) \times \frac 1 {w+k-i}\rightarrow dp(i + 1, x - 1)$ $dp(i, x) \times \frac 1 {w+k-i}\rightarrow dp(i + 1, x - 1)$ $\forall j+y>1, dp(i, x) \times g(1, 0, 1, n-d-i-x,j+y-1) \times \frac 1 {w+k-i} \times \binom {j+y} j \times (m-x+1)^{\underline y}\rightarrow dp(i+j, x+y-1)$ $\forall j+y>1, dp(i, x) \times g(1, 0, 1, n-d-i-x,j+y-1) \times \frac 1 {w+k-i} \times \binom {j+y} j \times (m-x+1)^{\underline y}\rightarrow dp(i+j, x+y-1)$ Finally, the answer is $\sum_{i=0}^k dp(i, 0) \times k^{\underline i}$. The time complexity is $O(n^4)$. Therefore, the total complexity is $O(n^5)$. If we use FFT, it can be $O(n^4 \log n)$, but it was not required in our solution and would probably make the code slower. Furthermore, we can record $v$ instead of $u$, which means there are $v$ cards with $i$ or greater index drawn from $u$ draws. So it's not difficult to find $v \leq u$. And when $c_i \leq \sqrt n$, we have $v \leq u \leq c_i \leq \sqrt n$. And when $c_i > \sqrt n$, we have $v \leq \frac n {c_i - 1} \leq \sqrt n$, the complexity can become $O (n ^ {4.5})$. If we use FFT, it can be $O (n ^ {3.5} \log n)$. Let $k$ be the number of cards with value $0$. It is not hard to see that: the size of $i$ is $n-k$ the size of $x$ is $k$ the size of $u$ is $n-k$ the size of $p$ is $n$ The number of states is $(n-k)^2k^2n$, which has a constant of $\frac{1}{16}$. We also have that $y \leq x$ and $u \leq c_i$, which both gives us another constant of $\frac{1}{2}$. Since we have a flag in our dp state, it has a factor of $2$. This gives us a constant factor of rougly $\frac{1}{32}$, which is extremely small. So it is reasonable to expect $O(n^5)$ to run about $1$ second. Solution by Melania Let $S$ denote the set of cards currently in Jellyfish's hand. We assume that $a_1 = 0$ and $a_n \geq 2$. Initially, $|S| \in [1, n-1]$. Cases where these conditions do not hold are trivial. We observe that Jellyfish cannot empty the draw pile if and only if she runs out of non-zero cards to play. In the following section, we compute the probability that she eventually runs out of non-zero cards. It is clear that in any scenario where she runs out of non-zero cards, $\max(S)$ must gradually decrease to zero. We can break down the entire process into sub-procedures, where in each sub-procedure, $\max(S)$ decreases from $i$ to $\leq i-1$, ultimately reaching zero. Assume she is currently in a state where $\max(S) = i$ and $|S \setminus {i}| = x$. We denote $F_{i,x,y}$ as the probability that she will eventually transition to a state where $\max(S) \leq i-1$, and in the very first state where $\max(S) \leq i-1$, the size of $S$ is $y$. For a fixed and given pair $(i,x)$, we aim to compute all values of $F_{i,x,y}$ simultaneously. To determine the values of $F_{i,x,y}$, consider the situation after Jellyfish plays card $a_i$. For the remaining $n-x$ cards, each card is equally likely to be one of the $a_i$ cards drawn. Therefore, for any individual card outside of the initial $x$ cards, the probability of possessing that card is $p = \dfrac{a_i}{n-x}$. We define the initial event where Jellyfish plays card $a_i$ as the starting point of our timeline. Following this event, we consider $n-i+2$ key moments when $\max(S)$ becomes $\leq n$ for the first time, $\leq n-1$ for the first time, and so on, down to $\leq i+1$, $\leq i$, and finally $\leq i-1$ for the first time. We denote $G_{j,y}$ as the probability that Jellyfish will eventually reach a state where $\max(S) \leq j$, and in the very first state where $\max(S) \leq j$, the size of $S$ is $y$. Initially, $G_{n,x + a_i} = 1$. To understand the transitions of $G_{j,y}$, note that since all cards $\leq j$ (excluding the initial $x$ cards) are symmetrical, the probability of owning card $j$ is exactly $p=\dfrac{y-x}{j-x}$. If Jellyfish does not own card $j$, then the first state where $\max(S) \leq j-1$ is simply the first state where $\max(S) \leq j$. This describes a transition of $G_{j-1,y} \leftarrow (1-p)G_{j,y}$. If Jellyfish owns card $j$, we enumerate the number of cards $|S| = z$ in her hand when she first reaches $\max(S) \leq j-1$. The probability of this happening is $F_{j,y-1,z}$. Thus, we have $G_{j-1,z} \leftarrow pG_{j,y}F_{j,y-1,z}$. Here's a further explanation of why "all cards $\leq j$ (excluding the initial $x$ cards) are symmetrical": Because this state is the very first time $\max(S) \leq j$, it means that all cards played before this state and after Jellyfish initially plays $a_i$ are $\geq j+1$. From the perspective of those cards $\geq j+1$, all cards $\leq j$ (excluding the initial $x$ cards) are symmetrical. In the end, the actual algorithm we derived for computing $F_{i,x,y}$ is quite straightforward: Iterate through $j$ backwards from $n$ to $i$. For each $G_{j,y}$, make two types of transitions: $G_{j-1,z} \leftarrow pG_{j,y}F_{j,y-1,z}$, where $p = \dfrac{y-x}{j-x}$; $G_{j-1,y} \leftarrow (1-p)G_{j,y}$. Finally, $F_{i,x,y} = G_{i-1,y}$. A small catch is that we could have self-loops. If $a_i = 1$, then in the final step where $j = i$, there will be some transitions where $F_{i,x,y} \leftarrow cF_{i,x,y}$. For a given $F_{i,x,y}$, if all the other known values that contribute to it sum to $A$ and all the $c$ coefficients sum to $C$, then we have $F_{i,x,y} = A + CF_{i,x,y}$. This results in $F_{i,x,y} = \dfrac{A}{1-C}$. We can address this by calculating the inverse. It can be shown that if we also iterate through $x$ from larger to smaller values, no $F_{i,x,y}$ will use other values of $F_{i',x',y'}$ that are neither known nor equal to $F_{i,x,y}$ itself. In other words, the value of $F_{i,x,y}$ does not invoke other unknown values of $F_{i',x',y'}$. After computing all values of $F_{i,x,y}$, we proceed to determine the final answer. We define $\text{ans}_{i,x}$ as the average probability that Jellyfish will eventually run out of non-zero cards (thus losing the game) if she starts with all $s_i$ cards in $[1, i]$ (which she owns initially) plus an additional $x$ cards drawn randomly from the remaining $i - s_i$ cards in $[1, i]$ (which she does not own initially). If $c_i = 1$, the transition is given by: $\text{ans}_{i,x}=\displaystyle\sum F_{i,x-1,y}\text{ans}_{i-1,y}$; If $c_i = 0$, the transition is given by: $\text{ans}_{i,x}=(1-p)\text{ans}_{i-1,x}+p\displaystyle\sum F_{i,x-1,y}\text{ans}_{i-1,y}$, where $p=\dfrac{x-s_i}{i-s_i}$. Finally, we compute $1 - \text{ans}_{n,s_n}$ to obtain the probability that Jellyfish will eventually win the game. The time complexity of this approach is $\mathcal{O}(n^5 + n^3 \log p)$, and the space complexity is $\mathcal{O}(n^3)$. It is also possible to optimize the $\mathcal{O}(n^5)$ time complexity to $\mathcal{O}(n^4 \sqrt{n})$ by using Lagrange interpolation. To achieve this speedup, we notice that the values of $i$ and $x$ do not play a crucial role in the transition of $G_{j,y}$. Specifically, the influence of the values $i$ and $x$ on the transition of $G_{j,y}$ can be described as follows: The initial value is $G_{n,x+a_i} = 1$. During the transition, $p = \dfrac{y-x}{j-x}$ and $1-p = \dfrac{j-y}{j-x}$. We can fix the value of $k = x + a_i$ and treat $x$ as a variable, maintaining a polynomial in $x$ as the value of $G_{j,y}$. We observe that it is only necessary to keep the point values between $[k-1, k-\sqrt{n}]$ to track the polynomial accurately. For $a_i > \sqrt{n}$, since each transition involving multiplication by $p$ will increase the value of $y$ by at least $a_i$, it is clear that the degree of the polynomial $G_{j,y}$ is at most $\sqrt{n}$. Thus, keeping track of $\sqrt{n}$ values is sufficient to restore the polynomial, and we can use linear Lagrange interpolation to obtain the point values outside these $\sqrt{n}$ points. For $a_i \leq \sqrt{n}$, since $x = k - a_i$, we only care about the point values in the range $[k-1, k-\sqrt{n}]$. Although the polynomial restored may be inaccurate beyond this range, these point values are the ones that matter for our calculations anyway. By applying this optimization, we effectively reduce the time complexity to $\mathcal{O}(n^4 \sqrt{n} + n^3 \log p)$.
|
[
"dp"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 120 + 5, Mod = 1e9 + 7;
inline ll power(ll x, ll y){
ll ret = 1;
while(y){
if(y & 1) ret = ret * x % Mod;
x = x * x % Mod, y >>= 1;
}
return ret;
}
inline ll inv(ll x){
return power(x, Mod - 2);
}
ll n = 0, m = 0, w = 0, o = 0, d = 0, r = 0, k = 0, c[N] = {}, v[N] = {};
ll iv[N] = {}, a[N][N] = {}, b[N][N] = {}, binom[N][N] = {};
ll f[2][2][N][N][N] = {}, g[2][2][N][N][N] = {}, dp[N][N] = {};
char s[N] = {};
inline void init(){
n = m = w = o = d = r = k = 0;
memset(c, 0, sizeof(c)), memset(v, 0, sizeof(v)), memset(s, 0, sizeof(s));
memset(f, 0, sizeof(f)), memset(g, 0, sizeof(g)), memset(dp, 0, sizeof(dp));
}
inline void solve(){
scanf("%lld", &n);
v[0] = v[1] = 1;
for(ll i = 1 ; i <= n ; i ++){
scanf("%lld", &c[i]);
v[c[i]] = 1;
}
scanf("%s", s + 1);
for(ll i = 1 ; i <= n ; i ++){
if(s[i] == '0') r ++;
if(c[i] > 1) w ++;
else if(c[i] == 1){
if(s[i] == '1') o ++;
m ++;
}
else{
if(s[i] == '1') d ++;
else k ++;
}
}
if(c[n] <= 1){
for(ll i = 1 ; i <= n ; i ++) if(s[i] == '0'){
printf("0\n");
return;
}
printf("1\n");
return;
}
for(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[n] ; u ++) if(v[u]){
f[1][0][u][p][0] = f[1][1][u][p][0] = 1;
g[1][0][u][p][0] = g[1][1][u][p][0] = 1;
}
for(ll i = n, h = 0 ; c[i] > 1 ; i --){
for(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]){
g[0][0][u][p][0] = 1;
if(s[i] == '0') g[0][1][u][p][0] = g[1][1][u][p][0];
}
for(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]) for(ll x = 1 ; x <= k ; x ++){
for(ll y = 0 ; y <= x - (c[i] - 1) ; y ++) f[0][0][u][p][x] = (f[0][0][u][p][x] + (g[1][0][u][p][y] * g[0][0][c[i]][p - (c[i] - 1) - y][x - (c[i] - 1) - y] % Mod) * ((u + y) * b[p - y + 1][c[i]] % Mod)) % Mod;
g[0][0][u][p][x] = (g[1][0][u][p][x] + f[0][0][u][p][x]) % Mod;
}
for(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]) for(ll x = 1 ; x <= k ; x ++){
if(s[i] == '1'){
for(ll y = h ; y <= x - c[i] ; y ++) f[0][1][u][p][x] = (f[0][1][u][p][x] + (g[1][1][u][p][y] * g[0][0][c[i]][p - (c[i] - 1) - y + h][x - c[i] - y] % Mod) * b[p - y + 1 + h][c[i]]) % Mod;
g[0][1][u][p][x] = f[0][1][u][p][x];
}
else{
for(ll y = h ; y <= x - (c[i] - 1) ; y ++) f[0][1][u][p][x] = (f[0][1][u][p][x] + (g[1][1][u][p][y] * g[0][0][c[i]][p - (c[i] - 1) - y + h][x - (c[i] - 1) - y] % Mod) * ((u + y) * b[p - y + 1 + h][c[i]] % Mod)) % Mod;
g[0][1][u][p][x] = (g[1][1][u][p][x] + f[0][1][u][p][x]) % Mod;
}
}
for(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]) for(ll x = 0 ; x <= k ; x ++){
f[1][0][u][p][x] = f[0][0][u][p][x], f[1][1][u][p][x] = f[0][1][u][p][x];
g[1][0][u][p][x] = g[0][0][u][p][x], g[1][1][u][p][x] = g[0][1][u][p][x];
f[0][0][u][p][x] = f[0][1][u][p][x] = g[0][0][u][p][x] = g[0][1][u][p][x] = 0;
}
if(s[i] == '1') h ++;
}
for(ll i = 0 ; i <= k ; i ++) for(ll x = 0 ; x <= m - o ; x ++) dp[i][o + x] = g[1][1][0][r][i + x] * (binom[i + x][i] * a[m - o][x] % Mod) % Mod;
for(ll i = 0 ; i <= k ; i ++) for(ll x = 1 ; x <= m ; x ++) if(dp[i][x]){
if(i < k) dp[i + 1][x - 1] = (dp[i + 1][x - 1] + dp[i][x] * iv[w + k - i]) % Mod;
for(ll j = 0 ; i + j <= k ; j ++) for(ll y = 0 ; x + y - 1 <= m ; y ++) if(j + y > 1) dp[i + j][x + y - 1] = (dp[i + j][x + y - 1] + (dp[i][x] * g[1][0][1][n - d - i - x][j + y - 1] % Mod) * (iv[w + k - i] * (binom[j + y][j] * a[m - x + 1][y] % Mod) % Mod)) % Mod;
}
ll ans = 1;
for(ll i = 0 ; i <= k ; i ++) ans = (ans + (Mod - dp[i][0]) * a[k][i]) % Mod;
printf("%lld\n", ans);
}
ll T = 0;
int main(){
for(ll x = 0 ; x < N ; x ++){
a[x][0] = b[x][0] = 1, iv[x] = inv(x), binom[x][0] = 1;
for(ll y = 1 ; y <= x ; y ++){
a[x][y] = a[x][y - 1] * (x - y + 1) % Mod, b[x][y] = inv(a[x][y]);
binom[x][y] = (binom[x - 1][y - 1] + binom[x - 1][y]) % Mod;
}
}
scanf("%lld", &T);
for(ll i = 1 ; i <= T ; i ++) init(), solve();
return 0;
}
|
1976
|
A
|
Verify Password
|
Monocarp is working on his new site, and the current challenge is to make the users pick strong passwords.
Monocarp decided that strong passwords should satisfy the following conditions:
- password should consist only of lowercase Latin letters and digits;
- there should be no digit that comes after a letter (so, after each letter, there is either another letter or the string ends);
- all digits should be sorted in the non-decreasing order;
- all letters should be sorted in the non-decreasing order.
Note that it's allowed for the password to have only letters or only digits.
Monocarp managed to implement the first condition, but he struggles with the remaining ones. Can you help him to verify the passwords?
|
There's no real idea in the problem, the main difficulty is the implementation. Many programming languages have functions to check if a character is a digit or if it's a letter. They can be used to check that no digit follows a letter. How does the order check work? Well, most languages allow you to compare characters with inequality signs (so, we have to check that $s_i \le s_{i + 1}$ for all corresponding $i$ - separately for digits and letters). How does that work? Inside the language, every character is assigned a code. That's called an ASCII table. It contains digits, letters and lots of other characters. And the less or equal check uses that table. If you look at the table carefully, you'll notice that the digits come before the lowercase Latin letters. Digits have codes from 48 to 57 and the lowercase letters have codes from 97 to 122. Thus, you can ignore the check that the digits come before the letters and just make sure that all characters of the string (regardless of their types) and sorted in a non-decreasing order. For example, you can sort the string and compare the result with the original string. If they are the same, then the answer is "YES". Alternatively, you can use function is_sorted if your language has it. Overall complexity: $O(n)$ or $O(n \log n)$ per testcase.
|
[
"implementation",
"sortings",
"strings"
] | 800
|
for _ in range(int(input())):
n = int(input())
s = input()
print("YES" if list(s) == sorted(s) else "NO")
|
1976
|
B
|
Increase/Decrease/Copy
|
You are given two integer arrays: array $a$ of length $n$ and array $b$ of length $n+1$.
You can perform the following operations any number of times in any order:
- choose any element of the array $a$ and increase it by $1$;
- choose any element of the array $a$ and decrease it by $1$;
- choose any element of the array $a$, copy it and append the copy to the end of the array $a$.
Your task is to calculate the minimum number of aforementioned operations (possibly zero) required to transform the array $a$ into the array $b$. It can be shown that under the constraints of the problem, it is always possible.
|
Let's fix the index of the element to be copied (denote it as $i$). For all other elements of the array, the number of required operations is $|a_j-b_j|$ for all $j \ne i$. Consider the case when $a_i \le b_i$ (similar to the case when $a_i \ge b_i$). There are three possible relative location of the desired element $b_{n + 1}$: if $b_{n + 1} < a_i$, you can proceed as follows: copy $i$-th element, increase $a_{n + 1}$ to $b_{n + 1}$ and increase $a_i$ to $b_i$, then the number of operations is equal to $1 + (b_{n + 1} - a_i) + (b_i - a_i)$; if $a_i \le b_{n + 1} \le b_i$, you can proceed as follows: increase $a_i$ to $b_{n + 1}$, copy it, and keep increasing to $b_i$, then the number of operations is equal to $(b_{n + 1} - a_i) + 1 + (b_i - b_{n + 1}) = (b_i - a_i) + 1$; if $b_i < b_{n + 1}$, you can proceed as follows: increase $a_i$ to $b_i$, copy $i$-th element, and increase $a_{n + 1}$ to $b_{n + 1}$, then the number of operations is equal to $(b_i - a_i) + 1 + (b_{n + 1} - b_i)$. As you can see, regardless of the case, $|b_i-a_i|$ is also added to the answer. So the answer looks like this: $\sum\limits_{j=1}^{n} |b_j-a_j|$ plus some extra operations to get $b_{n + 1}$. That extra value is equal to the minimum value of $f(i)$ over all indices $i$, where $f(i)$ is equal to $1 + |b_{n + 1} - a_i|$ or $1$ or $1 + |b_{n + 1} - b_i|$ depending on the cases described above.
|
[
"greedy",
"implementation"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
using li = long long;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<li> a(n), b(n + 1);
for (auto& x : a) cin >> x;
for (auto& x : b) cin >> x;
li sum = 0, ext = 1e18;
for (int i = 0; i < n; ++i) {
sum += abs(a[i] - b[i]);
ext = min(ext, abs(a[i] - b[n]));
ext = min(ext, abs(b[i] - b[n]));
if (min(a[i], b[i]) <= b[n] && b[n] <= max(a[i], b[i]))
ext = 0;
}
cout << sum + ext + 1 << '\n';
}
}
|
1976
|
C
|
Job Interview
|
Monocarp is opening his own IT company. He wants to hire $n$ programmers and $m$ testers.
There are $n+m+1$ candidates, numbered from $1$ to $n+m+1$ in chronological order of their arriving time. The $i$-th candidate has programming skill $a_i$ and testing skill $b_i$ (a person's programming skill is different from their testing skill). The skill of the team is the sum of the programming skills of all candidates hired as programmers, and the sum of the testing skills of all candidates hired as testers.
When a candidate arrives to interview, Monocarp tries to assign them to the most suitable position for them (if their programming skill is higher, then he hires them as a programmer, otherwise as a tester). If all slots for that position are filled, Monocarp assigns them to the other position.
Your task is, for each candidate, calculate the skill of the team if everyone except them comes to interview. Note that it means that exactly $n+m$ candidates will arrive, so all $n+m$ positions in the company will be filled.
|
Let's naively calculate the answer for the $(n+m+1)$-th candidate. While calculating it, let's store two values: $type_i$ - the type of job the $i$-th candidate was hired for; $bad$ - the index of the first candidate who was hired for a suboptimal role. We can show that this first candidate $bad$ who was hired for a suboptimal role is the only possible candidate who can change his role if another candidate doesn't show up. So, for all other candidates among the first $n+m$ candidates, their roles are fixed. To prove this, we can consider the following cases: if the candidate who doesn't show up has an index $bad$ or greater, then for all candidates after them, there is only one possible job (when we consider that candidate $bad$, all positions on one of the job are already filled); if the index who doesn't show up has index less than $bad$, then the candidate $bad$ will take the same job as that candidate has taken, and in any case, all positions of the optimal job of the candidate $bad$ will be filled after we take that candidate. Now we can use the $(n+m+1)$-th candidate's answer to calculate the answer for the $i$-th candidate as follows: if $i < bad$ and $type_i \ne type_{bad}$, we can "move" the $bad$-th candidate to the role $type_i$ and the $(n+m+1)$-th candidate to the role $type_{bad}$, this will change the answer by $(a_{bad} - a_i) + (b_{n+m+1} - b_{bad})$ in case of the $i$-th candidate was hired as programmer (similarly for tester); otherwise, we can simply "move" the $(n+m+1)$-th candidate to the role $type_i$, this will change the answer by $(a_{n+m+1} - a_i)$ in case of the $i$-th candidate was hired as programmer (similarly for tester).
|
[
"binary search",
"dp",
"greedy",
"implementation",
"two pointers"
] | 1,600
|
for _ in range(int(input())):
n, m = map(int, input().split())
bounds = [n, m]
a = []
a.append(list(map(int, input().split())))
a.append(list(map(int, input().split())))
bad = -1
badType = -1
cur = [0, 0]
ans = 0
types = [0 for i in range(n + m + 1)]
for i in range(n + m):
curType = 0
if a[0][i] < a[1][i]:
curType = 1
if cur[curType] == bounds[curType]:
curType = 1 - curType
if bad == -1:
bad = i
badType = 1 - curType
types[i] = curType
ans += a[types[i]][i]
cur[types[i]] += 1
res = []
for i in range(n + m):
val = ans - a[types[i]][i]
if bad != -1 and i < bad and types[i] == badType:
val = val + a[badType][bad] - a[1 - badType][bad] + a[1 - badType][n + m]
else:
val = val + a[types[i]][n + m]
res.append(val)
res.append(ans)
print(*res)
|
1976
|
D
|
Invertible Bracket Sequences
|
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example:
- bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)");
- bracket sequences ")(", "(" and ")" are not.
Let's define the inverse of the bracket sequence as follows: replace all brackets '(' with ')', and vice versa (all brackets ')' with '('). For example, strings "()((" and ")())" are inverses of each other.
You are given a regular bracket sequence $s$. Calculate the number of pairs of integers $(l,r)$ ($1 \le l \le r \le |s|$) such that if you replace the substring of $s$ from the $l$-th character to the $r$-th character (inclusive) with its inverse, $s$ will still be a regular bracket sequence.
|
Let's define $bal_i$ as the number of characters '(' minus the number of characters ')' if we consider a prefix of length $i$. The bracket sequence is regular if both of the following conditions holds: there is no index $i$ such that $bal_i < 0$; $bal_n = 0$, where $n$ is the length of the sequence. Using that fact, we can say that the substring $[l, r]$ is "good" if both of the following conditions holds: $bal_{l-1} \ge bal_i - bal_{l-1}$ should hold for all $i$ in $[l, r]$, otherwise that would lead to the negative balance after inverting the substring; $bal_{l-1} = bal_r$, otherwise that would lead to $bal_n \ne 0$ after inverting substring. There are many solutions that are based on these two facts. Let's consider one of them. Let's iterate over the right bound of the substring (denote it as $r$). According to the second condition, $bal_{l-1} = bal_r$, therefore, we can maintain a map that stores the number of positions for each balance value. But, unfortunately, not all such left borders form a good substring because of the first condition. Luckily, it is easy to fix, if the current balance $bal_r$ and there is balance $x$ in the map such that $x < bal_r - x$, we can remove all its occurrences from the map (i. e. remove the key $x$ from the map). This fix works because the current position lies between the left border (which we store in the map) and the potential right border, and the current balance is too high (which violates the first condition). So, we get a solution that works in $O(n\log{n})$.
|
[
"binary search",
"combinatorics",
"data structures",
"divide and conquer",
"implementation",
"two pointers"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
map<int, int> cnt;
int b = 0;
++cnt[b];
long long ans = 0;
for (auto& c : s) {
b += (c == '(' ? +1 : -1);
ans += cnt[b];
++cnt[b];
while (cnt.begin()->first * 2 < b)
cnt.erase(cnt.begin());
}
cout << ans << '\n';
}
}
|
1976
|
E
|
Splittable Permutations
|
Initially, we had one array, which was a permutation of size $n$ (an array of size $n$ where each integer from $1$ to $n$ appears exactly once).
We performed $q$ operations. During the $i$-th operation, we did the following:
- choose any array we have with at least $2$ elements;
- split it into two non-empty arrays (prefix and suffix);
- write two integers $l_i$ and $r_i$, where $l_i$ is the maximum element in the left part which we get after the split, and $r_i$ is the maximum element in the right part;
- remove the array we've chosen from the pool of arrays we can use, and add the two resulting parts into the pool.
For example, suppose the initial array was $[6, 3, 4, 1, 2, 5]$, and we performed the following operations:
- choose the array $[6, 3, 4, 1, 2, 5]$ and split it into $[6, 3]$ and $[4, 1, 2, 5]$. Then we write $l_1 = 6$ and $r_1 = 5$, and the arrays we have are $[6, 3]$ and $[4, 1, 2, 5]$;
- choose the array $[4, 1, 2, 5]$ and split it into $[4, 1, 2]$ and $[5]$. Then we write $l_2 = 4$ and $r_2 = 5$, and the arrays we have are $[6, 3]$, $[4, 1, 2]$ and $[5]$;
- choose the array $[4, 1, 2]$ and split it into $[4]$ and $[1, 2]$. Then we write $l_3 = 4$ and $r_3 = 2$, and the arrays we have are $[6, 3]$, $[4]$, $[1, 2]$ and $[5]$.
You are given two integers $n$ and $q$, and two sequences $[l_1, l_2, \dots, l_q]$ and $[r_1, r_2, \dots, r_q]$. A permutation of size $n$ is called valid if we can perform $q$ operations and produce the given sequences $[l_1, l_2, \dots, l_q]$ and $[r_1, r_2, \dots, r_q]$.
Calculate the number of valid permutations.
|
First, let's deal with the case $q=n-1$. In this case, after all operations are performed, all arrays have only one element each, and can no longer be split. We can show that the initial order of elements can be restored uniquely in this case. For example, we can start with $n$ arrays consisting of single elements (one array for each integer from $1$ to $n$), and "undo" the operations to restore the initial order. "Undoing" the operations means linking two arrays together, and we don't have any choice which arrays and in which order we link, so the result of each operation is uniquely determined. So, in the case $q = n-1$, the answer is $1$. What about the case $q < n-1$? Let's divide all integers from $1$ to $n$ into two groups: the integers from the sequences $l$ and/or $r$, and all other integers. We can use the same process to show that the order of elements from the first group (the ones which were present in at least one of the given sequences) is unique, and we can restore their order using something like DSU (performing operations from the last to the first) or a double-linked list (performing operations from the first to the last). So, suppose we restored the order of elements which are present in the input; we need to insert all of the remaining integers and don't make the sequence of operations invalid. We have an array of $q+1$ elements, the order of which is fixed; and there are $q+2$ "buckets" where we can insert the remaining elements (before the first element, between the first and the second, and so on). For each of these "buckets", let's consider the maximum between the elements on the borders of the bucket (the fixed elements between which we insert the remaining elements). It's quite easy to see that each element we insert in a "bucket" should be less than this maximum: suppose the fixed element on the left border is $y$, the fixed element on the right border is $z$, and there was an element $x > \max(y,z)$ between them. After we performed all operations, $x$ is either in the same array as $y$ or in the same array as $z$; so when we "made" that array during an operation, we would have written the integer $x$ (or some even greater integer) instead of $y$ or $z$. And we can also show the opposite: if each element in each "bucket" is less than the maximum of the two elements bordering the bucket, the operation sequence is valid. To prove it, let's merge every bucket with the greater of the elements on its borders, and then again "undo" all operations to restore the original order of elements. So, for each remaining element, there are some buckets where we can put it, and some buckets where we can't. However, we also have to consider the relative order of the elements we insert in the same bucket. Let's start with the sequence of "fixed" elements, and insert the remaining elements one by one from the greatest integer to the smallest integer. We can show that every time we insert an element in this order, the number of places where it can go does not depend on where we inserted the previous elements. Suppose we insert an element which "fits" into $b$ buckets, and before inserting it, we also inserted $k$ other elements. Then there are exactly $b+k$ places where this element can fit, because every element we inserted earlier went into one of those same $b$ buckets and split that bucket into two. So, maintaining these two numbers (the number of available buckets and the number of elements we already inserted) is enough, and the positions of elements we inserted does not matter. This allows us to count the number of possible permutations in $O(n)$.
|
[
"combinatorics",
"data structures",
"dfs and similar",
"greedy",
"math",
"trees"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
const int N = 300043;
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 nxt[N], prv[N];
bool exists[N];
int main()
{
int n, q;
scanf("%d %d", &n, &q);
for(int i = 1; i <= n; i++) nxt[i] = prv[i] = -1;
exists[n] = true;
vector<int> l(q), r(q);
for(int i = 0; i < q; i++) scanf("%d", &l[i]);
for(int i = 0; i < q; i++) scanf("%d", &r[i]);
for(int i = 0; i < q; i++)
{
int L = l[i], R = r[i];
if(exists[L])
{
exists[R] = true;
nxt[R] = nxt[L];
if(nxt[R] != -1) prv[nxt[R]] = R;
prv[R] = L;
nxt[L] = R;
}
else
{
exists[L] = true;
prv[L] = prv[R];
if(prv[L] != -1) nxt[prv[L]] = L;
nxt[L] = R;
prv[R] = L;
}
}
vector<int> seq;
int start = -1;
for(int i = 1; i <= n; i++)
if(prv[i] == -1 && exists[i])
start = i;
seq.push_back(start);
while(nxt[start] != -1)
{
start = nxt[start];
seq.push_back(start);
}
vector<int> cnt_segments(n + 1);
cnt_segments[seq[0]]++;
cnt_segments[seq[q]]++;
for(int i = 0; i < q; i++)
cnt_segments[max(seq[i], seq[i + 1])]++;
int ans = 1;
int places = 0;
for(int i = n; i >= 1; i--)
{
if(exists[i])
places += cnt_segments[i];
else
{
ans = mul(ans, places);
places++;
}
}
printf("%d\n", ans);
}
|
1976
|
F
|
Remove Bridges
|
You are given a rooted tree, consisting of $n$ vertices, numbered from $1$ to $n$. Vertex $1$ is the root. Additionally, the root only has one child.
You are asked to add exactly $k$ edges to the tree (possibly, multiple edges and/or edges already existing in the tree).
Recall that a bridge is such an edge that, after you remove it, the number of connected components in the graph increases. So, initially, all edges of the tree are bridges.
After $k$ edges are added, some original edges of the tree are still bridges and some are not anymore. You want to satisfy two conditions:
- for every bridge, all tree edges in the subtree of the lower vertex of that bridge should also be bridges;
- the number of bridges is as small as possible.
Solve the task for all values of $k$ from $1$ to $n - 1$ and output the smallest number of bridges.
|
What does an extra edge change in the configuration of the bridges? Well, all tree edges on the path between the two vertices that an extra edge connects, stop being bridges. So, the task can be restated as follows: choose $k$ pairs of distinct vertices such that: a root is present in at least one pair; the number of edges in the union of the paths between the vertices of all pairs is as large as possible; there is no vertex covered by at least one path such that an edge to its parent is not a part of any path. The next idea is quite intuitive. It only makes sense to choose a root or the leaves of the tree into the pairs. If any pair has a non-leaf vertex, you can safely prolong the path until any of the leaves in its subtree, and the union of the paths will not become smaller. Now for the tricky idea. Instead of choosing $k$ pairs of root/leaves, you can actually just take a root and $2k - 1$ leaves, and there will always be a way to split them into pairs to satisfy all conditions. Let's show that. Traverse the tree with a DFS and record the order you visit the leaves. Pair up a root with the middle leaf in that order. Then pair up leaves $1$ and $2k-1$, $2$ and $2k-2$ and so on. This way, the path for every pair includes a vertex on the path of the first pair (the one that includes the root). Thus, the union of the paths is the same as the union of all vertical paths from the leaves to the root. That obviously satisfies the condition on the connectedness of the bridges. Notice how that union of the paths is also the largest possible on that set of leaves. Every path between the leaves can be viewed at as two vertical paths from each leaf. The longest vertical path from each leaf is the one going to the root. And we have exactly the union of these vertical paths as our solution. Thus, the task actually becomes as follows: choose $2k - 1$ leaves in such a way that the union of their paths to the root is as large as possible. That can actually be done greedily. Take a leaf with the longest path to the root. Then keep taking leaves that add as many new edges into the union as possible. That idea can be implemented as follows. For every vertex, calculate the longest path that starts in it and ends in some leaf. Can be done with a single DFS. Maintain a set of all vertices sorted by their longest paths. On each step, take a vertex with the largest value and remove all vertices on that path (any path of the maximum length if there are multiple) from the set. Overall complexity: $O(n \log n)$ per testcase.
|
[
"data structures",
"dfs and similar",
"dp",
"greedy",
"sortings",
"trees"
] | 2,800
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
vector<int> h;
vector<vector<int>> g;
void dfs(int v, int p = -1){
for (int u : g[v]) if (u != p){
dfs(u, v);
h[v] = max(h[v], h[u] + 1);
}
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--){
int n;
cin >> n;
g.assign(n, {});
forn(i, n - 1){
int v, u;
cin >> v >> u;
--v, --u;
g[v].push_back(u);
g[u].push_back(v);
}
h.assign(n, 0);
dfs(0);
set<pair<int, int>> cur;
forn(i, n) cur.insert({h[i], i});
vector<int> ans;
int tmp = n;
while (!cur.empty()){
int v = cur.rbegin()->second;
while (v != -1){
--tmp;
cur.erase({h[v], v});
int pv = -1;
for (int u : g[v]) if (h[u] == h[v] - 1){
pv = u;
break;
}
v = pv;
}
ans.push_back(tmp);
}
for (int i = 0; i < int(ans.size()); i += 2){
cout << ans[i] << ' ';
}
for (int i = (int(ans.size()) + 1) / 2; i < n - 1; ++i){
cout << 0 << ' ';
}
cout << '\n';
}
return 0;
}
|
1977
|
A
|
Little Nikita
|
The little boy Nikita was given some cubes as a present. He decided to build a tower out of them.
Initially, the tower doesn't have any cubes. In one move, Nikita either puts exactly $1$ cube on top of the tower or removes exactly $1$ cube from the top of the tower. Is it possible that after $n$ moves, the resulting tower has exactly $m$ cubes?
|
Note that one action with the cube changes the parity of the number of cubes in the tower. Therefore, if the parities of $n$ and $m$ do not match, it is impossible to build the tower. Also, if $n < m$, the tower cannot be built either. In all other cases, it is possible to build a tower of height $m$ in $m$ operations, and then add and remove a cube until the operations are exhausted.
|
[
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n, m;
cin >> n >> m;
cout << (n >= m && (n%2) == (m%2) ? "Yes" : "No") << '\n';
}
}
|
1977
|
B
|
Binary Colouring
|
You are given a positive integer $x$. Find any array of integers $a_0, a_1, \ldots, a_{n-1}$ for which the following holds:
- $1 \le n \le 32$,
- $a_i$ is $1$, $0$, or $-1$ for all $0 \le i \le n - 1$,
- $x = \displaystyle{\sum_{i=0}^{n - 1}{a_i \cdot 2^i}}$,
- There does not exist an index $0 \le i \le n - 2$ such that both $a_{i} \neq 0$ and $a_{i + 1} \neq 0$.
It can be proven that under the constraints of the problem, a valid array always exists.
|
We will iterate over the prefix of $i$ bits and construct a correct answer for the number formed by the prefix bits of the number $x$. We are interested in considering only the one bits, as they are the only ones that affect the value of the number $x$. If we have already placed a one at position $i$ in the answer, we need to somehow add $2^i$ to the number. To do this, we simply zero out the $i$-th bit in the answer and set it at $i + 1$ - this will add $2 \cdot 2^i = 2^{i+1}$. Now, the $i$-th position in the answer holds $0$. Let's consider what we placed at position $i-1$ in the answer. If it's $0$, then everything is fine; we just place $1$ at position $i$. If it's $1$, we have a situation of [1 1], which we correct by making it [-1 0 1] - placing $-1$ at $i-1$, leaving $0$ at $i$, and placing $1$ at $i+1$. This will add $2^i$ to the sum because $2^i + 2^{i-1} = 2^{i+1} - 2^{i-1}$. The remaining case is when $i-1$ holds $-1$, but this is impossible because our forward operations only place ones, and $-1$ is placed behind. The final time complexity is $O(\log(x))$ per test case.
|
[
"bitmasks",
"constructive algorithms",
"greedy",
"math"
] | 1,100
|
#include "bits/stdc++.h"
#define all(a) a.begin(), a.end()
#define pb push_back
typedef long long ll;
using namespace std;
mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());
/// Actual code starts here
const int N = 100005;
void solve() {
ll x;
cin >> x;
vector<int> res(31, 0);
for (int i = 0; i < 30; i++) {
if (1ll & (x >> i)) {
if (res[i]) {
res[i + 1] = 1;
res[i] = 0;
} else if (i > 0) {
if (res[i - 1] == 1) {
res[i + 1] = 1;
res[i - 1] = -1;
} else {
res[i] = 1;
}
} else if (i == 0) {
res[i] = 1;
}
}
}
cout << 31 << '\n';
for (int i = 0; i <= 30; i++) {
cout << res[i] << ' ';
}
cout << '\n';
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int tt = 1;
cin >> tt;
while (tt--)
solve();
}
|
1977
|
C
|
Nikita and LCM
|
Nikita is a student passionate about number theory and algorithms. He faces an interesting problem related to an array of numbers.
Suppose Nikita has an array of integers $a$ of length $n$. He will call a subsequence$^\dagger$ of the array special if its least common multiple (LCM) is not contained in $a$. The LCM of an empty subsequence is equal to $0$.
Nikita wonders: what is the length of the longest special subsequence of $a$? Help him answer this question!
$^\dagger$ A sequence $b$ is a subsequence of $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements, without changing the order of the remaining elements. For example, $[5,2,3]$ is a subsequence of $[1,5,7,8,2,4,3]$.
|
Try to check if the entire array $a$ can be the answer. First, let's understand if we can take the entire array $a$ as the special subsequence. To do this, find the LCM($a_1, a_2, \dots, a_n$). If it is greater than max($a_1, a_2, \dots, a_n$), then obviously such a number is not in the subsequence, because $LCM \geq max$. After this check, it becomes known that each $a_i \ | \ max(a_1, a_2, \dots, a_n)$. Then we iterate over the divisors of the maximum and greedily check for the presence of a subsequence with such an LCM. If we do this naively, it will be $O(\sqrt{C} + n \cdot d(C) \cdot \log(C))$, but this is already sufficient. Note that we can count the occurrence of each number and check only the distinct numbers. Then the complexity will be $O(\sqrt{C} + d(C)^2 \cdot \log(C))$.
|
[
"brute force",
"data structures",
"dp",
"greedy",
"math",
"number theory",
"sortings"
] | 1,900
|
#include "bits/stdc++.h"
#define err(x) cerr << "["#x"] " << (x) << "\n"
#define errv(x) {cerr << "["#x"] ["; for (const auto& ___ : (x)) cerr << ___ << ", "; cerr << "]\n";}
#define errvn(x, n) {cerr << "["#x"] ["; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << ", "; cerr << "]\n";}
#define all(a) a.begin(), a.end()
#define pb push_back
typedef long long ll;
typedef long double ld;
using namespace std;
const int MOD = 1000000007;
mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());
template<typename T1, typename T2>
inline bool relaxmi(T1 &a, const T2 &b) {
return a > b ? a = b, true : false;
}
template<typename T1, typename T2>
inline bool relaxma(T1 &a, const T2 &b) {
return a < b ? a = b, true : false;
}
double GetTime() { return clock() / (double) CLOCKS_PER_SEC; }
/// Actual code starts here
const int N = 100005;
int calc(vector<pair<int, int>> &t, int d) {
int LCM = 0, cnt = 0;
for (auto [j, c]: t) {
if (d % j == 0) {
if (LCM == 0) LCM = j;
else LCM = lcm(LCM, j);
cnt += c;
}
}
if (LCM != d) cnt = 0;
return cnt;
}
void solve() {
int n;
cin >> n;
vector<int> v(n);
for (auto &i: v) cin >> i;
ll LCM = 1;
int mx = *max_element(all(v));
for (auto i: v) {
LCM = lcm(LCM, i);
if (LCM > mx) {
cout << n << '\n';
return;
}
}
map<int, int> cnt;
for (auto i: v) cnt[i]++;
vector<pair<int, int>> t;
for (auto i: cnt)
t.push_back(i);
int res = 0;
for (int i = 1; i * i <= mx; i++) {
if (mx % i == 0) {
if (!cnt.contains(i))
relaxma(res, calc(t, i));
if (!cnt.contains(mx / i))
relaxma(res, calc(t, mx / i));
}
}
cout << res << '\n';
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int tt = 1;
cin >> tt;
while (tt--)
solve();
}
|
1977
|
D
|
XORificator
|
You are given a binary (consisting only of 0s and 1s) $n \times m$ matrix. You are also given a XORificator, using which you can invert all the values in a chosen row (i.e. replace 0 with 1 and 1 with 0).
A column in the matrix is considered special if it contains exactly one 1. Your task is to find the maximum number of columns that can be made special at the same time, and the set of rows the XORificator should be used on to achieve that.
|
Try to fix the specialty of column $i$ and the presence of a one in cell $i, j$. Let's assume that the value in the $i$-th row and $j$-th column is strictly one and it is the only one in the column. Then the entire table is uniquely determined, as well as the XORificator. For each possible state of the XORificator that constructs the required table, Let's maintain a counter. Then the state that maximizes the number of columns with exactly one 1 has the maximum counter. To efficiently maintain the counter, it is necessary to maintain the hash of the XORificator and quickly recalculate it when moving to the next row. The answer can be easily reconstructed by traversing the table again and counting the hash. If the desired hash is obtained, simply output the state of the XORificator. The final time complexity is $O(nm \log{(nm)})$ or $O(nm)$ if a hash map is used. For hashing, it is convenient to use Zobrist hashing.
|
[
"bitmasks",
"brute force",
"greedy",
"hashing"
] | 2,300
|
#include "bits/stdc++.h"
using namespace std;
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());
void solve() {
int n, m;
cin >> n >> m;
vector<vector<bool>> table(n, vector<bool>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
char c;
cin >> c;
table[i][j] = c - '0';
}
}
vector<long long> rands(n), rands2(n);
for (int i = 0; i < n; ++i) {
rands[i] = rnd();
rands2[i] = rnd();
}
map<pair<long long, long long>, int> ans;
int res = 0;
pair<int, int> ind_ans = {0, 0};
for (int j = 0; j < m; ++j) {
long long summ = 0, summ2 = 0;
for (int i = 0; i < n; ++i) {
if (table[i][j]) {
summ ^= rands[i];
summ2 ^= rands2[i];
}
}
for (int i = 0; i < n; ++i) {
summ ^= rands[i];
summ2 ^= rands2[i];
ans[{summ, summ2}]++;
if (res < ans[{summ, summ2}]) {
res = ans[{summ, summ2}];
ind_ans = {j, i};
}
summ ^= rands[i];
summ2 ^= rands2[i];
}
}
cout << res << "\n";
string inds(n, '0');
for (int i = 0; i < n; ++i) {
if (table[i][ind_ans.first]) {
if (i != ind_ans.second) {
inds[i] = '1';
}
} else if (ind_ans.second == i) {
inds[i] = '1';
}
}
cout << inds << "\n";
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt = 1;
cin >> tt;
while (tt--) {
solve();
}
}
|
1977
|
E
|
Tensor
|
This is an interactive problem.
You are given an integer $n$.
The jury has hidden from you a directed graph with $n$ vertices (numbered from $1$ to $n$) and some number of edges. You additionally know that:
- The graph only contains edges of the form $i \leftarrow j$, where $1 \le i < j \le n$.
- For any three vertices $1 \le i < j < k \le n$, at least one of the following holds$^\dagger$:
- Vertex $i$ is reachable from vertex $j$, or
- Vertex $i$ is reachable from vertex $k$, or
- Vertex $j$ is reachable from vertex $k$.
You want to color each vertex in either black or white such that for any two vertices $i$ and $j$ ($1 \le i < j \le n$) of the same color, vertex $i$ is reachable from vertex $j$.
To do that, you can ask queries of the following type:
- ? i j — is vertex $i$ reachable from vertex $j$ ($1 \le i < j \le n$)?
Find any valid vertex coloring of the hidden graph in at most $2 \cdot n$ queries. It can be proven that such a coloring always exists.
Note that the grader is \textbf{not} adaptive: the graph is fixed before any queries are made.
$^\dagger$ Vertex $a$ is reachable from vertex $b$ if there exists a path from vertex $b$ to vertex $a$ in the graph.
|
First, let's understand why 2 colors are indeed sufficient. Notice that the reachability relation in a graph defines a Partially Ordered Set. According to Dilworth's Theorem, the size of the maximum antichain is equal to the minimum number of chains that cover the Partially Ordered Set. Note that the condition on the reachability of pairs of vertices within any triplet implies a constraint on the maximum size of the antichain. It is simply no more than 2. Therefore, 2 colors are indeed sufficient. The remaining task is to understand how to explicitly construct these 2 chains. We will build this inductively. Let's maintain 3 stacks - the last vertices painted in black, white, and red respectively. These will correspond to the chains we are building. Suppose we have built chains on $n$ vertices and want to build them on $n + 1$: If the white or black stacks are empty, simply add vertex $n+1$ to the empty stack. If the white or black stacks are empty, simply add vertex $n+1$ to the empty stack. If the red stack is empty: If the red stack is empty: Ask about the reachability of the last vertices in the white and black stacks from vertex $n+1$. Ask about the reachability of the last vertices in the white and black stacks from vertex $n+1$. If both vertices are reachable, put vertex $n+1$ in the red stack. If both vertices are reachable, put vertex $n+1$ in the red stack. If only one vertex is reachable, put vertex $n+1$ in the stack whose last vertex is reachable from $n+1$. If only one vertex is reachable, put vertex $n+1$ in the stack whose last vertex is reachable from $n+1$. The case where neither vertex is reachable is impossible as it contradicts the condition. The case where neither vertex is reachable is impossible as it contradicts the condition. If the red stack is not empty: If the red stack is not empty: Ask about the reachability of the last vertex in the red stack from vertex $n+1$. Ask about the reachability of the last vertex in the red stack from vertex $n+1$. If it is reachable, put it in the red stack. If it is reachable, put it in the red stack. If it is not reachable, ask about the end of the white stack. If it is not reachable, ask about the end of the white stack. If the vertex at the end of the white stack is not reachable, then the vertex at the end of the black stack must be reachable, otherwise, it contradicts the problem's condition. If the vertex at the end of the white stack is not reachable, then the vertex at the end of the black stack must be reachable, otherwise, it contradicts the problem's condition. Color vertex $n+1$ black if the black vertex is reachable or white if the white vertex is reachable. Color vertex $n+1$ black if the black vertex is reachable or white if the white vertex is reachable. Recolor all vertices in the red stack to the opposite color relative to vertex $n+1$. We can do this because, by construction, all vertices in the white and black stacks are reachable from all vertices in the red stack. Recolor all vertices in the red stack to the opposite color relative to vertex $n+1$. We can do this because, by construction, all vertices in the white and black stacks are reachable from all vertices in the red stack. Do not forget to clear the red stack. Do not forget to clear the red stack. Each time a new vertex is added, no more than 2 queries are used. Therefore, we will use no more than $2 \cdot n$ queries in total. During the algorithm, all operations are performed in $O(1)$ time, resulting in an overall complexity of $O(n)$. As an exercise for the reader, try to prove the lower bound on the number of queries.
|
[
"constructive algorithms",
"graphs",
"interactive"
] | 2,600
|
#include "bits/stdc++.h"
#define err(x) cerr << "["#x"] " << (x) << "\n"
#define errv(x) {cerr << "["#x"] ["; for (const auto& ___ : (x)) cerr << ___ << ", "; cerr << "]\n";}
#define errvn(x, n) {cerr << "["#x"] ["; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << ", "; cerr << "]\n";}
#define all(a) a.begin(), a.end()
#define pb push_back
typedef long long ll;
typedef long double ld;
using namespace std;
const int MOD = 1000000007;
mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());
template<typename T1, typename T2>
inline bool relaxmi(T1 &a, const T2 &b) {
return a > b ? a = b, true : false;
}
template<typename T1, typename T2>
inline bool relaxma(T1 &a, const T2 &b) {
return a < b ? a = b, true : false;
}
double GetTime() { return clock() / (double) CLOCKS_PER_SEC; }
/// Actual code starts here
const int N = 100005;
bool ask(int i, int j) {
cout << "? " << j << ' ' << i << endl;
string resp;
cin >> resp;
if (resp == "-1") assert(false);
if (resp == "YES") return true;
else return false;
}
void solve() {
int n;
cin >> n;
vector<int> st, st2, st3;
st = {1};
for (int i = 2; i <= n; i++) {
if (st2.empty()) {
if (ask(i, st.back())) {
st.push_back(i);
} else {
st2.push_back(i);
}
} else if (st3.empty()) {
int ok1 = ask(i, st.back()), ok2 = ask(i, st2.back());
if (ok1 && ok2) {
st3.push_back(i);
} else if (ok1) {
st.push_back(i);
} else if (ok2) {
st2.push_back(i);
} else {
assert(false);
}
} else {
if (ask(i, st3.back())) {
st3.push_back(i);
} else {
if (ask(i, st.back())) {
st.push_back(i);
for (auto j: st3)
st2.push_back(j);
st3.clear();
} else {
st2.push_back(i);
for (auto j: st3)
st.push_back(j);
st3.clear();
}
}
}
}
if (!st3.empty()) {
for (auto i: st3)
st.push_back(i);
st3.clear();
}
vector<int> colors(n + 1);
for (auto i: st2)
colors[i] = 1;
cout << "! ";
for (int i = 1; i <= n; i++) cout << colors[i] << ' ';
cout << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int tt = 1;
cin >> tt;
while (tt--)
solve();
}
|
1978
|
A
|
Alice and Books
|
Alice has $n$ books. The $1$-st book contains $a_1$ pages, the $2$-nd book contains $a_2$ pages, $\ldots$, the $n$-th book contains $a_n$ pages. Alice does the following:
- She divides all the books into two non-empty piles. Thus, each book ends up in exactly one of the two piles.
- Alice reads one book with the \textbf{highest number} in each pile.
Alice loves reading very much. Help her find the maximum total number of pages she can read by dividing the books into two piles.
|
Note that we will always be required to take a book with the number $n$. Thus, the answer can be all pairs of the form $(k, n)$, where $k < n$. We will find a pair with the maximum sum among these, and it will be the answer.
|
[
"constructive algorithms",
"greedy",
"sortings"
] | 800
|
#include <random>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define ll long long
#define pii pair<int, int>
#define pb emplace_back
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &c : a) cin >> c;
int mx = 0;
for (int i = 0; i < n - 1; i++) mx = max(mx, a[i]);
cout << mx + a[n - 1] << "\n";
}
return 0;
}
|
1978
|
B
|
New Bakery
|
Bob decided to open a bakery. On the opening day, he baked $n$ buns that he can sell. The usual price of a bun is $a$ coins, but to attract customers, Bob organized the following promotion:
- Bob chooses some integer $k$ ($0 \le k \le \min(n, b)$).
- Bob sells the first $k$ buns at a modified price. In this case, the price of the $i$-th ($1 \le i \le k$) sold bun is $(b - i + 1)$ coins.
- The remaining $(n - k)$ buns are sold at $a$ coins each.
Note that $k$ can be equal to $0$. In this case, Bob will sell all the buns at $a$ coins each.
Help Bob determine the maximum profit he can obtain by selling all $n$ buns.
|
If $b < a$, then the answer is obviously equal to $a \cdot n$. Otherwise, the profit will be maximized when $k = \min(b - a, n)$. Indeed, if we take $k$ larger, then Bob will sell some buns for less than $a$ coins, which is not profitable. If we take $k$ smaller, then he will sell some buns for $a$ coins, although he could have sold them for more. Knowing that $a + (a + 1) + \ldots + (b - 1) + b = \frac{a + b}{2} \cdot (b - a + 1)$, we can find the answer. It will be equal to $\frac{b + (b - k + 1)}{2} \cdot k + (n - k) \cdot a$.
|
[
"binary search",
"greedy",
"math",
"ternary search"
] | 800
|
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long n, a, b;
cin >> n >> a >> b;
if (b <= a) {
cout << n * a << endl;
} else {
long long k = min(b — a + 1, n);
cout << (b — k + 1) * n + k * (k — 1) / 2 << endl;
}
}
}
|
1978
|
C
|
Manhattan Permutations
|
Let's call the Manhattan value of a permutation$^{\dagger}$ $p$ the value of the expression $|p_1 - 1| + |p_2 - 2| + \ldots + |p_n - n|$.
For example, for the permutation $[1, 2, 3]$, the Manhattan value is $|1 - 1| + |2 - 2| + |3 - 3| = 0$, and for the permutation $[3, 1, 2]$, the Manhattan value is $|3 - 1| + |1 - 2| + |2 - 3| = 2 + 1 + 1 = 4$.
You are given integers $n$ and $k$. Find a permutation $p$ of length $n$ such that its Manhattan value is equal to $k$, or determine that no such permutation exists.
$^{\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
|
Notice that if $k$ is odd, then there is no solution. Also notice that the maximum $max_k$ is achieved with the permutation $[n, n - 1, n - 2, ..., 1]$, so if $k > max_k$, then there is also no solution. It is claimed that for any other $k$, a solution exists. Let's consider what happens if we swap $x$ and $1$ in the identity permutation. The Manhattan value for such a permutation will be equal to $|x - 1| + |x - 1| = 2 \cdot |x - 1|$. Then any even $k$ from $0$ to $2 \cdot (n - 1)$ can be achieved. If $k > 2 \cdot (n - 1)$, let's swap $1$ and $n$ elements. Notice that we have reduced the problem to a smaller size of $(n - 2)$, just now the indices start from $2$ instead of $1$. Now we can do exactly the same as with the identity permutation, i.e., swap $2$ with some $x$ ($x > 1$ and $x < n$). The value of the permutation will change by $|x - 2| \cdot 2$, so any even $k$ from $0$ to $2 \cdot (n - 1) + 2 \cdot (n - 3)$ can be achieved. Notice that if we continue to do this further, in the end we will get the permutation $[n, n - 1, ..., 1]$, and we have proved that any even $k$ from $0$ to $max_k$ is achievable. Hence, it is clear how to reconstruct the permutation itself in $O(n)$ time.
|
[
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"math"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
cin >> T;
while (T--) {
int n;
ll k;
cin >> n >> k;
ll max_s = 0;
for (int i = 0; i < n; i++) max_s += abs(n — 1 — i — i);
if (k % 2 != 0 || k > max_s) {
cout << "No\n";
} else {
cout << "Yes\n";
vector<int> p(n);
k /= 2;
iota(p.begin(), p.end(), 0);
for (int i = 0; k > 0; i++) {
if (k >= n — 1 — 2 * i) {
swap(p[i], p[n — 1 — i]);
k -= n — 1 — 2 * i;
} else {
swap(p[i], p[i + k]);
k = 0;
}
}
for (int i = 0; i < n; i++) {
cout << p[i] + 1 << " ";
}
cout << "\n";
}
}
}
|
1978
|
D
|
Elections
|
Elections are taking place in Berland. There are $n$ candidates participating in the elections, numbered from $1$ to $n$. The $i$-th candidate has $a_i$ fans who will vote for him. Additionally, there are $c$ people who are undecided about their favorite candidate, let's call them undecided. Undecided people will vote for the candidate with the lowest number.
The candidate who receives the maximum number of votes wins the elections, and if multiple candidates receive the same maximum number of votes, the candidate with the lowest number among them wins.
You found these elections too boring and predictable, so you decided to exclude some candidates from them. If you do not allow candidate number $i$ to participate in the elections, all $a_i$ of his fans will become undecided, and will vote for the candidate with the lowest number.
You are curious to find, for each $i$ from $1$ to $n$, the minimum number of candidates that need to be excluded from the elections for candidate number $i$ to win the elections.
|
Notice that if candidate $i$ does not win initially (when no one is removed), then for their victory, we must definitely remove all candidates with numbers less than $i$. Because if someone remains unremoved with a number less than $i$, then the votes for candidate $i$ will not increase, and the maximum number of votes for someone else will not decrease. Let's find the winner of the election initially, for them the answer is $0$, for all other candidates we need to remove all people with numbers less than $i$. But sometimes these removals alone may not be enough, so we need to additionally remove several candidates so that their fans' votes go to us. Notice that then it is enough to remove only one candidate with the maximum $a_i$, then we will definitely win, so the answer for candidate $i$ is either $0$, or $i$, or $i + 1$. So we end up with a solution which works in $O(n)$.
|
[
"data structures",
"greedy",
"implementation",
"math"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
int n, c;
cin >> n >> c;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
if (n == 1) {
cout << "0\n";
return;
}
int mx = *max_element(a.begin() + 1, a.end());
int mxc = max(a[0] + c, mx);
int winner = mxc == a[0] + c ? 0 : find(a.begin() + 1, a.end(), mx) - a.begin();
ll sum = c;
for (int i = 0; i < n; sum += a[i], ++i) {
int answer;
if (i == winner) {
answer = 0;
} else if (sum + a[i] >= mx) {
answer = i;
} else {
answer = i + 1;
}
cout << answer << " \n"[i == n - 1];
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int test = 1;
cin >> test;
while (test--) {
solve();
}
return 0;
}
|
1978
|
E
|
Computing Machine
|
Sasha has two binary strings $s$ and $t$ of the same length $n$, consisting of the characters 0 and 1.
There is also a computing machine that can perform two types of operations on binary strings $a$ and $b$ of the same length $k$:
- If $a_{i} = a_{i + 2} =$ 0, then you can assign $b_{i + 1} :=$ 1 ($1 \le i \le k - 2$).
- If $b_{i} = b_{i + 2} =$ 1, then you can assign $a_{i + 1} :=$ 1 ($1 \le i \le k - 2$).
Sasha became interested in the following: if we consider the string $a=s_ls_{l+1}\ldots s_r$ and the string $b=t_lt_{l+1}\ldots t_r$, what is the maximum number of 1 characters in the string $a$ that can be obtained using the computing machine. Since Sasha is very curious but lazy, it is up to you to answer this question for several pairs $(l_i, r_i)$ that interest him.
|
Notice that it is advantageous to perform only operations of the first type first, and then only operations of the second type. Perform all possible operations of the first type on the string $t$ and save it in $t'$. Perform all possible operations of the second type on the string $s$, using $t'$, and save it in $s'$. Calculate the prefix sums on the string $s'$. Let $len$ be the length of the query range. The answer to queries with small length ranges ($len < 5$) can be computed by simulating the proposed process. For longer strings, it can be guaranteed that in the string $a$ with the maximum number of 1 characters, $a_{3}a_{4}\ldots a_{len - 2}$ will match the characters $s'_{3}s'_{4}\ldots s'_{len - 2}$, their count can be found using prefix sums. Separately check if $a_{1}$, $a_{2}$, $a_{len - 1}$, $a_{len}$ can become 1.
|
[
"brute force",
"data structures",
"dp",
"greedy",
"implementation"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
int n;
string s, t;
cin >> n >> s >> t;
auto get_range = [&] (int i) {
if (s[i] == '1') return make_pair(i, i);
int l = -1, r = -1;
if (i > 0 && t[i-1] == '1') l = i-1;
else if (i > 1 && t[i-1] == '0' && s[i-2] == '0') l = i-2;
if (i+1 < n && t[i+1] == '1') r = i+1;
else if (i+2 < n && t[i+1] == '0' && s[i+2] == '0') r = i+2;
if (l == -1) r = -1;
if (r == -1) l = -1;
return make_pair(l, r);
};
vector<int> pref(n+1);
for (int i = 0; i < n; i++) pref[i+1] = pref[i] + (get_range(i).first != -1);
int q;
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
int ans = 0;
if (r-l <= 5) {
for (int i = l-1; i < r; i++) {
auto [ll, rr] = get_range(i);
if (ll >= l-1 && rr < r) ans++;
}
}
else {
ans = pref[r] - pref[l-1];
for (int j: {l-1, l, r-2, r-1}) {
auto [ll, rr] = get_range(j);
if (ll != -1 && (ll < l-1 || rr >= r)) ans--;
}
}
cout << ans << '\n';
}
}
}
|
1978
|
F
|
Large Graph
|
Given an array $a$ of length $n$. Let's construct a square matrix $b$ of size $n \times n$, in which the $i$-th row contains the array $a$ cyclically shifted to the right by $(i - 1)$. For example, for the array $a = [3, 4, 5]$, the obtained matrix is
$$b = \begin{bmatrix} 3 & 4 & 5 \\ 5 & 3 & 4 \\ 4 & 5 & 3 \end{bmatrix}$$
Let's construct the following graph:
- The graph contains $n^2$ vertices, each of which corresponds to one of the elements of the matrix. Let's denote the vertex corresponding to the element $b_{i, j}$ as $(i, j)$.
- We will draw an edge between vertices $(i_1, j_1)$ and $(i_2, j_2)$ if $|i_1 - i_2| + |j_1 - j_2| \le k$ and $\gcd(b_{i_1, j_1}, b_{i_2, j_2}) > 1$, where $\gcd(x, y)$ denotes the greatest common divisor of integers $x$ and $y$.
Your task is to calculate the number of connected components$^{\dagger}$ in the obtained graph.
$^{\dagger}$A connected component of a graph is a set of vertices in which any vertex is reachable from any other via edges, and adding any other vertex to the set violates this rule.
|
Notice that since we have cyclic shifts to the right and k > 1, the diagonals parallel to the main one will be in the same connected component, except for the case with ones. Diagonals consisting of ones will be counted separately and forgotten. After that, we can solve the problem for the one-dimensional case, where each element is a representative of its diagonal. By definition, if the GCD of some pair of elements is greater than $1$, then this means that they are both divisible by some prime number. Let's find all the elements of the array-diagonals that are divisible by each prime number. Let the indices of the current prime number be $c_1, c_2, \ldots, c_t$. We will draw edges between $c_i$ and $c_{i + 1}$ if $c_{i + 1} - c_{i} \leqslant k$. It is claimed that the connected components in such a graph will coincide with the connected components if we draw edges between all valid pairs. Indeed, if there is an edge between two elements in the complete graph, this means that the distance between them is not greater than $k$, and we can reach them in the new graph either by one edge or through elements that are divisible by the same prime number. Using the sieve of Eratosthenes, we can quickly factorize all numbers into prime divisors, after which the number of connected components in the graph can be calculated using DSU or DFS. The time complexity of this solution is $O(n \log \log n)$.
|
[
"data structures",
"dfs and similar",
"dsu",
"graphs",
"number theory",
"two pointers"
] | 2,400
|
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <cstring>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include <ctime>
using namespace std;
using ll = long long;
const int MAXA = 1e6;
int n, k;
vector<int> a;
vector<int> primes_x[MAXA + 1];
unordered_map<int, int> last_ind_p;
vector<bool> is_prime(MAXA + 1, true);
vector<int> primes;
void read() {
cin >> n >> k;
a.assign(n, 0);
for (int& elem : a) {
cin >> elem;
}
}
vector<int> p, sz, p_rs;
int col(int A) {
return (A == p[A] ? A : p[A] = col(p[A]));
}
void unique(int A, int B) {
A = col(A); B = col(B);
if (A == B) return;
if (sz[A] < sz[B]) {
swap(A, B);
}
p[B] = A;
sz[A] += sz[B];
}
void solve() {
last_ind_p.clear();
vector<int> aa;
for (int i = 1; i < n; i++) {
aa.push_back(a[i]);
}
for (int i = 0; i < n; i++) {
aa.push_back(a[i]);
}
a = aa;
int n2 = n;
n = a.size();
p.assign(n, -1);
p_rs.assign(n, -1);
sz.assign(n, -1);
for (int i = 0; i < n; i++) {
p[i] = i;
sz[i] = 1;
}
for (int i = 0; i < n2; i++) {
p_rs[i] = i + 1;
p_rs[2 * n2 - 2 - i] = i + 1;
}
vector<int> a2 = a;
sort(a2.begin(), a2.end());
a2.resize(unique(a2.begin(), a2.end()) - a2.begin());
unordered_set<int> to_clean;
for (int elem : a2) {
int cur_elem = elem;
for (ll p : primes) {
if (p * p > elem) break;
if (elem % p == 0) {
primes_x[cur_elem].push_back(p);
if (primes_x[cur_elem].size() == 1) {
to_clean.insert(cur_elem);
}
}
while (elem % p == 0) {
elem /= p;
}
}
if (elem > 1) {
primes_x[cur_elem].push_back(elem);
if (primes_x[cur_elem].size() == 1) {
to_clean.insert(cur_elem);
}
}
}
for (int i = 0; i < n; i++) {
for (int cur_p : primes_x[a[i]]) {
if (last_ind_p.count(cur_p) && i - last_ind_p[cur_p] <= k) {
unique(last_ind_p[cur_p], i);
}
last_ind_p[cur_p] = i;
}
}
for (int i : to_clean)
primes_x[i].clear();
}
void write() {
ll ans = 0;
for (int i = 0; i < n; i++) {
if (p[i] == i) {
if (a[i] > 1) {
ans += 1;
}
else {
ans += p_rs[i];
}
}
}
cout << ans << endl;
}
int main() {
for (ll i = 2; i <= MAXA; i++) {
if (is_prime[i]) {
primes.push_back(i);
for (ll j = i * i; j <= MAXA; j += i) {
is_prime[j] = false;
}
}
}
ios_base::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
read();
solve();
write();
}
}
|
1979
|
A
|
Guess the Maximum
|
Alice and Bob came up with a rather strange game. They have an array of integers $a_1, a_2,\ldots, a_n$. Alice chooses a certain integer $k$ and tells it to Bob, then the following happens:
- Bob chooses two integers $i$ and $j$ ($1 \le i < j \le n$), and then finds the maximum among the integers $a_i, a_{i + 1},\ldots, a_j$;
- If the obtained maximum is \textbf{strictly greater} than $k$, Alice wins, otherwise Bob wins.
Help Alice find the maximum $k$ at which she is guaranteed to win.
|
Let $m$ be the maximum among the numbers $a_i, a_{i + 1},\ldots, a_j$. Notice that there always exists such $k$ that $i \le k < j$ and $a_k = m$ or $a_{k + 1} = m$. Therefore, we can assume that Bob always chooses the pair of numbers $p$ and $p + 1$ ($1 \le p < n$) as $i$ and $j$. Therefore you need to consider the maximums in pairs of adjacent elements and take the minimum among them. Let $min$ be the found minimum, then it is obvious that the answer is equal to $min - 1$.
|
[
"brute force",
"greedy",
"implementation"
] | 800
|
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n];
for (int& i : a) {
cin >> i;
}
int mini = max(a[0], a[1]);
for (int i = 1; i < n - 1; i++) {
mini = min(mini, max(a[i], a[i + 1]));
}
cout << mini - 1 << "\n";
}
}
|
1979
|
B
|
XOR Sequences
|
You are given two distinct non-negative integers $x$ and $y$. Consider two infinite sequences $a_1, a_2, a_3, \ldots$ and $b_1, b_2, b_3, \ldots$, where
- $a_n = n \oplus x$;
- $b_n = n \oplus y$.
Here, $x \oplus y$ denotes the bitwise XOR operation of integers $x$ and $y$.
For example, with $x = 6$, the first $8$ elements of sequence $a$ will look as follows: $[7, 4, 5, 2, 3, 0, 1, 14, \ldots]$. Note that the indices of elements start with $1$.
Your task is to find the length of the longest common subsegment$^\dagger$ of sequences $a$ and $b$. In other words, find the maximum integer $m$ such that $a_i = b_j, a_{i + 1} = b_{j + 1}, \ldots, a_{i + m - 1} = b_{j + m - 1}$ for some $i, j \ge 1$.
$^\dagger$A subsegment of sequence $p$ is a sequence $p_l,p_{l+1},\ldots,p_r$, where $1 \le l \le r$.
|
Look at samples. Consider two numbers $v$ and $u$ such that $x \oplus v = y \oplus u$. Then consider the numbers $x \oplus (v + 1)$ and $y \oplus (u + 1)$. Let's look at the last bit of $v$ and $u$. Possible scenarios: Both bits are equal to $0$ - adding one will change the bits at the same positions, therefore $x \oplus (v + 1) = y \oplus (u + 1)$; Both bits are equal to $1$ - adding one will change the bits at the same positions and also add one to the next bit, therefore we can similarly consider the next bit; Bits are different - adding one to the zero bit will only change one bit, while the subsequent bit of the other number will be changed. This means that $x \oplus (v + 1) \neq y \oplus (u + 1)$. It is clear that we need to maximize the number of zeros in the maximum matching suffix of $u$ and $v$. Obviously, this number is equal to the maximum matching suffix of $x$ and $y$. Let $k$ be the length of the maximum matching suffix of $x$ and $y$, then the answer is $2^k$. This can be calculated in $O(\log C)$ time for one test case, where $C$ is the limit on $x$ and $y$.
|
[
"bitmasks",
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
for (int i = 0; i < 30; i++) {
if ((a & (1 << i)) != (b & (1 << i))) {
cout << (1ll << i) << "\n";
break;
}
}
}
}
|
1979
|
C
|
Earning on Bets
|
You have been offered to play a game. In this game, there are $n$ possible outcomes, and for each of them, you must bet a certain \textbf{integer} amount of coins. In the event that the $i$-th outcome turns out to be winning, you will receive back the amount of coins equal to your bet on that outcome, multiplied by $k_i$. Note that \textbf{exactly one} of the $n$ outcomes will be winning.
Your task is to determine how to distribute the coins in such a way that you will come out ahead in the event of \textbf{any} winning outcome. More formally, the total amount of coins you bet on all outcomes must be \textbf{strictly less} than the number of coins received back for each possible winning outcome.
|
Try to come up with a condition for the existence of an answer. Let $S$ be the total amount of coins placed on all possible outcomes. Then, if the coefficient for winning is $k_i$, we have to place more than $\frac{S}{k_i}$ on this outcome. We can obtain the following inequality: $\sum_{i = 1}^n \frac{S}{k_i} < S.$ Dividing both sides by $S$, we obtain the necessary and sufficient condition for the existence of an answer: $\sum_{i = 1}^n \frac{1}{k_i} < 1.$ This check can be performed by reducing all fractions to a common denominator. Notice that the numerators of the reduced fractions correspond to the required bets on the outcomes.
|
[
"binary search",
"combinatorics",
"constructive algorithms",
"number theory"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int gcd(int a, int b) {
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
void solve() {
int n;
cin >> n;
vector <int> k(n);
for (int i = 0; i < n; i++) {
cin >> k[i];
}
int z = 1;
for (int i = 0; i < n; i++) {
z = lcm(z, k[i]);
}
int suma = 0;
for (int i = 0; i < n; i++) {
suma += z / k[i];
}
if (suma < z) {
for (int i = 0; i < n; i++) {
cout << z / k[i] << " ";
}
cout << "\n";
} else {
cout << -1 << "\n";
}
}
signed main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1979
|
D
|
Fixing a Binary String
|
You are given a binary string $s$ of length $n$, consisting of zeros and ones. You can perform the following operation \textbf{exactly once}:
- Choose an integer $p$ ($1 \le p \le n$).
- Reverse the substring $s_1 s_2 \ldots s_p$. After this step, the string $s_1 s_2 \ldots s_n$ will become $s_p s_{p-1} \ldots s_1 s_{p+1} s_{p+2} \ldots s_n$.
- Then, perform a cyclic shift of the string $s$ to the left $p$ times. After this step, the initial string $s_1s_2 \ldots s_n$ will become $s_{p+1}s_{p+2} \ldots s_n s_p s_{p-1} \ldots s_1$.
For example, if you apply the operation to the string 110001100110 with $p=3$, after the second step, the string will become {\textbf{011}001100110}, and after the third step, it will become {001100110\textbf{011}}.
A string $s$ is called $k$-proper if two conditions are met:
- $s_1=s_2=\ldots=s_k$;
- $s_{i+k} \neq s_i$ for any $i$ ($1 \le i \le n - k$).
For example, with $k=3$, the strings 000, 111000111, and 111000 are $k$-proper, while the strings 000000, 001100, and 1110000 are not.
You are given an integer $k$, which \textbf{is a divisor} of $n$. Find an integer $p$ ($1 \le p \le n$) such that after performing the operation, the string $s$ becomes $k$-proper, or determine that it is impossible. Note that if the string is initially $k$-proper, you still need to apply exactly one operation to it.
|
Let's consider the block of characters at the end. Notice that their quantity cannot decrease. Let $x$ be the number of identical characters at the end; there are three possible cases: $x = k$ - it is enough to find any block of length greater than $k$ and separate a block of length $k$ from it; $x > k$ - obviously, there is no solution; $x < k$ - find a block of length $k - x$ or $2k - x$ and separate a block of length $k - x$ from it. This solution works in $O(n)$, but it is not the only correct one. Your solution may differ significantly from the one proposed.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"greedy",
"hashing",
"strings"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
int x = 0;
for (int i = n - 1; i >= 0; i--) {
if (s[i] == s[n - 1]) {
x++;
} else {
break;
}
}
auto check = [&]() {
for (int i = 0; i < k; i++) {
if (s[i] != s[0]) return false;
}
for (int i = 0; i + k < n; i++) {
if (s[i] == s[i + k]) return false;
}
return true;
};
auto operation = [&](int p) {
reverse(s.begin(), s.begin() + p);
s = s.substr(p, (int)s.size() - p) + s.substr(0, p);
if (check()) {
cout << p << "\n";
} else {
cout << -1 << "\n";
}
};
if (x == k) {
int p = n;
for (int i = n - 1 - k; i >= 0; i--) {
if (s[i] == s[i + k]) {
p = i + 1;
break;
}
}
operation(p);
} else if (x > k) {
cout << -1 << "\n";
} else {
bool was = false;
for (int i = 0; i < n; i++) {
if (s[i] != s.back()) continue;
int j = i;
while (j + 1 < n && s[i] == s[j + 1]) {
j++;
}
if (j - i + 1 + x == k) {
operation(j + 1);
was = true;
break;
} else if (j - i + 1 - k + x == k) {
operation(i + k - x);
was = true;
break;
}
i = j;
}
if (!was) {
operation(n);
}
}
}
}
|
1979
|
E
|
Manhattan Triangle
|
The Manhattan distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is defined as: $$|x_1 - x_2| + |y_1 - y_2|.$$
We call a Manhattan triangle three points on the plane, the Manhattan distances between each pair of which are equal.
You are given a set of pairwise distinct points and an \textbf{even} integer $d$. Your task is to find any Manhattan triangle, composed of three distinct points from the given set, where the Manhattan distance between any pair of vertices is equal to $d$.
|
In every Manhattan triangle there are two points such that $|x_1 - x_2| = |y_1 - y_2|$. Note this fact: in every Manhattan triangle there are two points such that $|x_1 - x_2| = |y_1 - y_2|$. Let's start with distributing all points with their $(x + y)$ value. For each point $(x; y)$ find point $(x + d / 2; y - d / 2)$ using lower bound method in corresponding set. Then we have to find the third point: it can be in either $(x + y + d)$ or $(x + y - d)$ diagonal. Borders at $x$ coordinate for them are $[x + d / 2; x + d]$ and $[x - d / 2; x]$ - it can be found using the same lower bound method. Then, distribute all points with $(x - y)$ value and do the same algorithm. Total time complexity is $O(n \log n)$.
|
[
"binary search",
"constructive algorithms",
"data structures",
"geometry",
"implementation",
"two pointers"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int MAXC = 1e5;
const int MAXD = 4e5 + 10;
set <pair <int, int>> diag[MAXD];
void solve() {
int n, d;
cin >> n >> d;
vector <int> x(n), y(n);
for (int i = 0; i < n; i++) {
cin >> x[i] >> y[i];
x[i] += MAXC;
y[i] += MAXC;
}
bool found = false;
{
for (int i = 0; i < n; i++) {
diag[x[i] + y[i]].insert({x[i], i});
}
for (int i = 0; i < n; i++) {
auto it1 = diag[x[i] + y[i]].lower_bound({x[i] + d / 2, -1});
if (it1 == diag[x[i] + y[i]].end() || it1->first != x[i] + d / 2) continue;
if (x[i] + y[i] + d < MAXD) {
auto it2 = diag[x[i] + y[i] + d].lower_bound({x[i] + d / 2, -1});
if (it2 != diag[x[i] + y[i] + d].end() && it2->first <= it1->first + d / 2) {
cout << i + 1 << " " << it1->second + 1 << " " << it2->second + 1 << "\n";
found = true;
break;
}
}
if (x[i] + y[i] - d >= 0) {
auto it2 = diag[x[i] + y[i] - d].lower_bound({x[i] - d / 2, -1});
if (it2 != diag[x[i] + y[i] - d].end() && it2->first <= it1->first - d / 2) {
cout << i + 1 << " " << it1->second + 1 << " " << it2->second + 1 << "\n";
found = true;
break;
}
}
}
for (int i = 0; i < n; i++) {
diag[x[i] + y[i]].erase({x[i], i});
}
}
if (!found) {
for (int i = 0; i < n; i++) {
y[i] -= 2 * MAXC;
diag[x[i] - y[i]].insert({x[i], i});
}
for (int i = 0; i < n; i++) {
auto it1 = diag[x[i] - y[i]].lower_bound({x[i] + d / 2, -1});
if (it1 == diag[x[i] - y[i]].end() || it1->first != x[i] + d / 2) continue;
if (x[i] - y[i] + d < MAXD) {
auto it2 = diag[x[i] - y[i] + d].lower_bound({x[i] + d / 2, -1});
if (it2 != diag[x[i] - y[i] + d].end() && it2->first <= it1->first + d / 2) {
cout << i + 1 << " " << it1->second + 1 << " " << it2->second + 1 << "\n";
found = true;
break;
}
}
if (x[i] - y[i] - d >= 0) {
auto it2 = diag[x[i] - y[i] - d].lower_bound({x[i] - d / 2, -1});
if (it2 != diag[x[i] - y[i] - d].end() && it2->first <= it1->first - d / 2) {
cout << i + 1 << " " << it1->second + 1 << " " << it2->second + 1 << "\n";
found = true;
break;
}
}
}
for (int i = 0; i < n; i++) {
diag[x[i] - y[i]].erase({x[i], i});
}
}
if (!found) {
cout << "0 0 0\n";
}
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1979
|
F
|
Kostyanych's Theorem
|
This is an interactive problem.
Kostyanych has chosen a complete undirected graph$^{\dagger}$ with $n$ vertices, and then removed exactly $(n - 2)$ edges from it. You can ask queries of the following type:
- "? $d$" — Kostyanych tells you the number of vertex $v$ with a degree \textbf{at least} $d$. Among all possible such vertices, he selects the vertex \textbf{with the minimum degree}, and if there are several such vertices, he selects the one with the minimum number. He also tells you the number of another vertex in the graph, with which $v$ is not connected by an edge (if none is found, then $0$ is reported). Among all possible such vertices, he selects the one with the minimum number. Then he removes the vertex $v$ and all edges coming out of it. If the required vertex $v$ is not found, then "$0\ 0$" is reported.
Find a Hamiltonian path$^{\ddagger}$ in the \textbf{original} graph in at most $n$ queries. It can be proven that under these constraints, a Hamiltonian path always exists.
$^{\dagger}$A complete undirected graph is a graph in which there is exactly one undirected edge between any pair of distinct vertices. Thus, a complete undirected graph with $n$ vertices contains $\frac{n(n-1)}{2}$ edges.
$^{\ddagger}$A Hamiltonian path in a graph is a path that passes through each vertex exactly once.
|
Let's consider the following recursive algorithm. We will store the Hamiltonian path as a double-ended queue, maintaining the start and end. In case there are only $1$ or $2$ vertices left in the graph, the problem is solved trivially. Suppose we know that the current graph has $n$ vertices, and there are at most $(n - 2)$ edges missing. Then the total number of edges in such a graph is at least $\frac{n(n - 1)}{2} - (n - 2) = \frac{n^2 - 3n + 4}{2}.$ Let all vertices in the graph have a degree of at most $(n - 3)$, then the total number of edges does not exceed $\frac{n(n-3)}{2} = \frac{n^2 - 3n}{2},$ which is less than the stated value. Hence, we conclude that there is at least one vertex with a degree greater than $(n - 3)$. If there exists a vertex $v$ with a degree of $(n - 2)$, then it is sufficient to run our recursive algorithm for the remaining graph. Since $v$ is only not connected by an edge to one vertex, $v$ is connected either to the start or the end of the maintained path in the remaining graph. Thus, we can insert the vertex $v$ either at the beginning or at the end of the path. Otherwise, let $u$ be the vertex with a degree of $(n - 1)$. There is at least one vertex $w$ with a degree not exceeding $(n - 3)$. Remove $u$ and $w$ from the graph. Notice that the number of edges in such a graph does not exceed $\frac{n^2 - 3n + 4}{2} - (n - 1) - (n - 3) + 1 = \frac{n^2 - 7n + 14}{2}$ $\frac{n^2 - 7n + 14}{2} = \frac{n^2 - 5n + 6}{2} - \frac{2n - 8}{2}$ $\frac{n^2 - 5n + 6}{2} - \frac{2n - 8}{2} = \frac{(n - 2)(n - 3)}{2} - (n - 4)$ $\frac{(n - 2)(n - 3)}{2} - (n - 4) = \frac{(n - 2)((n - 2) - 1)}{2} - ((n - 2) - 2).$ The invariant is preserved, so we can run the algorithm for the remaining graph. Then, we can arrange the vertices in the following order: $w$ - $u$ - $s$ - ..., where $s$ - the start of the Hamiltonian path in the remaining graph. It remains to understand how to use queries. Make a query $d = (n - 2)$. Let $u$ be the second number in the response to our query. If $u \neq 0$, the degree of vertex $v$ is $(n - 2)$. Run our recursive algorithm, and then compare the start and end of the obtained path with $u$. Otherwise, if $u = 0$, it means the degree of vertex $v$ is $(n - 1)$. In this case, ask about any vertex with a low degree (this can be done with a query $d = 0$). Then simply arrange the vertices in the order mentioned above. We will make no more than $n$ queries, and the final asymptotic will be $O(n)$.
|
[
"brute force",
"constructive algorithms",
"graphs",
"interactive"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
pair <int, int> ask(int d) {
cout << "? " << d << endl;
int v, u;
cin >> v >> u;
return {v, u};
}
pair <int, int> get(int n, vector <int>& nxt) {
if (n == 1) {
int v = ask(0).first;
return {v, v};
}
if (n == 2) {
int u = ask(0).first;
int v = ask(0).first;
nxt[u] = v;
return {u, v};
}
pair <int, int> t = ask(n - 2);
int v = t.first;
int ban = t.second;
if (ban != 0) {
pair <int, int> res = get(n - 1, nxt);
if (ban != res.first) {
nxt[v] = res.first;
return {v, res.second};
} else {
nxt[res.second] = v;
return {res.first, v};
}
} else {
int u = ask(0).first;
nxt[u] = v;
pair <int, int> res = get(n - 2, nxt);
nxt[v] = res.first;
return {u, res.second};
}
}
void solve() {
int n;
cin >> n;
vector <int> nxt(n + 1, -1);
pair <int, int> ans = get(n, nxt);
int v = ans.first;
cout << "! ";
do {
cout << v << " ";
v = nxt[v];
} while (v != -1);
cout << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1980
|
A
|
Problem Generator
|
Vlad is planning to hold $m$ rounds next month. Each round should contain one problem of difficulty levels 'A', 'B', 'C', 'D', 'E', 'F', and 'G'.
Vlad already has a bank of $n$ problems, where the $i$-th problem has a difficulty level of $a_i$. There may not be enough of these problems, so he may have to come up with a few more problems.
Vlad wants to come up with as few problems as possible, so he asks you to find the minimum number of problems he needs to come up with in order to hold $m$ rounds.
For example, if $m=1$, $n = 10$, $a=$ 'BGECDCBDED', then he needs to come up with two problems: one of difficulty level 'A' and one of difficulty level 'F'.
|
It is necessary to have at least $m$ problems of each difficulty level. If there are already at least $m$ problems of difficulty level $c$, then there is no need to come up with more problems of this difficulty level. Otherwise, it is necessary to come up with $m - cnt_c$ problems, where $cnt_c$ is the number of problems of difficulty level $c$ (if more problems of this difficulty level are created, the number will not be minimum).
|
[
"math"
] | 800
|
def solve():
n, m = map(int, input().split())
a = input()
ans = 0
for ch in range(ord('A'), ord('H')):
ans += max(0, m - a.count(chr(ch)))
print(ans)
for _ in range(int(input())):
solve()
|
1980
|
B
|
Choosing Cubes
|
Dmitry has $n$ cubes, numbered from left to right from $1$ to $n$. The cube with index $f$ is his favorite.
Dmitry threw all the cubes on the table, and the $i$-th cube showed the value $a_i$ ($1 \le a_i \le 100$). After that, he arranged the cubes in non-increasing order of their values, from largest to smallest. If two cubes show the same value, they can go in any order.
After sorting, Dmitry removed the first $k$ cubes. Then he became interested in whether he removed his favorite cube (note that its position could have changed after sorting).
For example, if $n=5$, $f=2$, $a = [4, \color{green}3, 3, 2, 3]$ (the favorite cube is highlighted in green), and $k = 2$, the following could have happened:
- After sorting $a=[4, \color{green}3, 3, 3, 2]$, since the favorite cube ended up in the second position, it will be removed.
- After sorting $a=[4, 3, \color{green}3, 3, 2]$, since the favorite cube ended up in the third position, it will not be removed.
|
Let $x$ be the value of the cube with the number $f$. Let's sort all the cubes by non-growth. Then let's look at the value of the $k$-th cube in order. Since the cubes are removed by non-growth, all cubes with large values will be removed, some (perhaps not all) cubes with the same value, and cubes with smaller values will not be removed. If the value of the $k$-th cube is greater than $x$, then Dmitry's favorite cube will not be removed, because all the removed cubes will have more values. If it is less than $x$, then the favorite cube will always be removed, since the cube with the lower value will also be removed. If the value of the $k$ th cube is equal to $x$, then some cubes with this value will be removed. However, if there are several such cubes, then perhaps not all of them will be removed. If the $k + 1$th cube is missing (for $k = n$) or if its value is less than $x$, then all cubes with this value will be removed, and the answer is YES. Otherwise, only a part of the cubes with the value $x$ will be removed, and the answer is MAYBE, because cubes with the same values are indistinguishable when sorting.
|
[
"sortings"
] | 800
|
def solve():
n, f, k = map(int, input().split())
f -= 1
k -= 1
a = list(map(int, input().split()))
x = a[f]
a.sort(reverse=True)
if a[k] > x:
print("NO")
elif a[k] < x:
print("YES")
else:
print("YES" if k == n - 1 or a[k + 1] < x else "MAYBE")
t = int(input())
for _ in range(t):
solve()
|
1980
|
C
|
Sofia and the Lost Operations
|
Sofia had an array of $n$ integers $a_1, a_2, \ldots, a_n$. One day she got bored with it, so she decided to \textbf{sequentially} apply $m$ modification operations to it.
Each modification operation is described by a pair of numbers $\langle c_j, d_j \rangle$ and means that the element of the array with index $c_j$ should be assigned the value $d_j$, i.e., perform the assignment $a_{c_j} = d_j$. After applying \textbf{all} modification operations \textbf{sequentially}, Sofia discarded the resulting array.
Recently, you found an array of $n$ integers $b_1, b_2, \ldots, b_n$. You are interested in whether this array is Sofia's array. You know the values of the original array, as well as the values $d_1, d_2, \ldots, d_m$. The values $c_1, c_2, \ldots, c_m$ turned out to be lost.
Is there a sequence $c_1, c_2, \ldots, c_m$ such that the \textbf{sequential} application of modification operations $\langle c_1, d_1, \rangle, \langle c_2, d_2, \rangle, \ldots, \langle c_m, d_m \rangle$ to the array $a_1, a_2, \ldots, a_n$ transforms it into the array $b_1, b_2, \ldots, b_n$?
|
First, in the array $b_1, b_2, \ldots, b_n$, the number $d_m$ must be present. Second, if $a_i = b_i$, we will not apply any operations to $i$. All extra operations can be applied to $a_j$, where $b_j = d_m$, they will be overwritten by the operation $d_m$. For all other $i$ ($a_i \neq b_i$) we must apply the operation $d_k = b_i$, so it remains to check that the multiset of such $b_i$ is included in the multiset $d_1, d_2, \ldots, d_m$. This solution can be implemented using sorting and two pointers or std::map, resulting in a time complexity of $O((n + m) \log n)$. If you used std::unordered_map or dict, you were most likely hacked. Check out this post.
|
[
"constructive algorithms",
"greedy"
] | 1,300
|
#include <stdio.h>
#include <stdbool.h>
#define MAXN 200200
#define MAXM 200200
int n, m, k;
int arr[MAXN], brr[MAXN], drr[MAXM], buf[MAXN];
int cmp_i32(const void* pa, const void* pb) {
return *(const int*)pa - *(const int*)pb;
}
void build() {
k = 0;
for (int i = 0; i < n; ++i) {
if (arr[i] != brr[i])
buf[k++] = brr[i];
}
qsort(buf, k, sizeof(*buf), cmp_i32);
}
bool check() {
for (int i = 0; i < n; ++i)
if (brr[i] == drr[m - 1])
return true;
return false;
}
bool solve() {
if (!check()) return false;
qsort(drr, m, sizeof(*drr), cmp_i32);
int ib = 0, id = 0;
while (ib < k && id < m) {
if (buf[ib] == drr[id])
++ib, ++id;
else if (buf[ib] < drr[id])
return false;
else ++id;
}
return ib == k;
}
int main() {
int t; scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 0; i < n; ++i)
scanf("%d", arr + i);
for (int i = 0; i < n; ++i)
scanf("%d", brr + i);
scanf("%d", &m);
for (int j = 0; j < m; ++j)
scanf("%d", drr + j);
build();
if (solve()) printf("YES\n");
else printf("NO\n");
}
}
|
1980
|
D
|
GCD-sequence
|
GCD (Greatest Common Divisor) of two integers $x$ and $y$ is the maximum integer $z$ by which both $x$ and $y$ are divisible. For example, $GCD(36, 48) = 12$, $GCD(5, 10) = 5$, and $GCD(7,11) = 1$.
Kristina has an array $a$ consisting of exactly $n$ positive integers. She wants to count the GCD of each neighbouring pair of numbers to get a new array $b$, called GCD-sequence.
So, the elements of the GCD-sequence $b$ will be calculated using the formula $b_i = GCD(a_i, a_{i + 1})$ for $1 \le i \le n - 1$.
Determine whether it is possible to remove \textbf{exactly one} number from the array $a$ so that the GCD sequence $b$ is non-decreasing (i.e., $b_i \le b_{i+1}$ is always true).
For example, let Khristina had an array $a$ = [$20, 6, 12, 3, 48, 36$]. If she removes $a_4 = 3$ from it and counts the GCD-sequence of $b$, she gets:
- $b_1 = GCD(20, 6) = 2$
- $b_2 = GCD(6, 12) = 6$
- $b_3 = GCD(12, 48) = 12$
- $b_4 = GCD(48, 36) = 12$
The resulting GCD sequence $b$ = [$2,6,12,12$] is non-decreasing because $b_1 \le b_2 \le b_3 \le b_4$.
|
Let's loop through the initial array $a$, counting the GCD of neighbouring elements. If at some point, the GCD of the previous pair becomes greater than the GCD of the next pair, we remember the index $i$ of the first element of the pair that gave the greater GCD and stop the loop. Then consider the following cases: the sequence of GCDs for array $a$ was already non-decreasing. Then it is enough to remove the last element from it, the previous elements of the GCD-sequence will not be affected. The answer in this case is always YES. some element $a_i$ has been found such that $GCD(a_{i-1}, a_i) \gt GCD(a_i, a_{i+1})$. Then, since there is already at least one place in the original GCD-sequence where it ceases to be non-decreasing, we can try to fix it by removing the $i-1$-th, $i$-th or $i+1$-th element from the array $a$. Let's create $3$ new arrays of length $n-1$, and in each of them remove one of the above elements. If at least one of these arrays has a non-decreasing GCD-sequence - the answer is YES, otherwise - NO.
|
[
"greedy",
"implementation",
"math",
"number theory"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
bool good(vector<int>&b){
int g = __gcd(b[0], b[1]);
for(int i = 1; i < int(b.size()) - 1; i++){
int cur_gcd = __gcd(b[i], b[i + 1]);
if(g > cur_gcd) return false;
g = cur_gcd;
}
return true;
}
bool solve(){
int n;
cin >> n;
vector<int>a(n);
for(int i = 0; i < n; i++){
cin >> a[i];
}
int g = -1;
int to_del = -1;
for(int i = 0; i < n - 1; i++){
int cur_gcd = __gcd(a[i], a[i + 1]);
if(cur_gcd < g){
to_del = i;
break;
}
g = cur_gcd;
}
if(to_del == -1) return true;
vector<int>b0 = a, b1 = a, b2 = a;
if(to_del > 0) b0.erase(b0.begin() + to_del - 1);
b1.erase(b1.begin() + to_del);
if(to_del < n - 1) b2.erase(b2.begin() + to_del + 1);
return good(b0) || good(b1) || good(b2);
}
int main(){
int t;
cin >> t;
while(t--){
cout << (solve() ? "YES" : "NO") << "\n";
}
}
|
1980
|
E
|
Permutation of Rows and Columns
|
You have been given a matrix $a$ of size $n$ by $m$, containing a permutation of integers from $1$ to $n \cdot m$.
A permutation of $n$ integers is an array containing all numbers from $1$ to $n$ exactly once. For example, the arrays $[1]$, $[2, 1, 3]$, $[5, 4, 3, 2, 1]$ are permutations, while the arrays $[1, 1]$, $[100]$, $[1, 2, 4, 5]$ are not.
A matrix contains a permutation if, when all its elements are written out, the resulting array is a permutation. Matrices $[[1, 2], [3, 4]]$, $[[1]]$, $[[1, 5, 3], [2, 6, 4]]$ contain permutations, while matrices $[[2]]$, $[[1, 1], [2, 2]]$, $[[1, 2], [100, 200]]$ do not.
You can perform one of the following two actions in one operation:
- choose columns $c$ and $d$ ($1 \le c, d \le m$, $c \ne d$) and swap these columns;
- choose rows $c$ and $d$ ($1 \le c, d \le n$, $c \ne d$) and swap these rows.
You can perform any number of operations.
You are given the original matrix $a$ and the matrix $b$. Your task is to determine whether it is possible to transform matrix $a$ into matrix $b$ using the given operations.
|
For each element, you can calculate its positions in both matrices. You can see that the rearrangement of rows does not affect the column positions of the elements being rearranged. Similarly, column rearrangement does not affect row positions. Since the permutation of rows affects the entire rows, for all elements that have the same position row in the original matrix, the position row in the resulting matrix must also match. Similarly, the columns must match. In order to check the coincidence of rows and columns, let's count 4 arrays - the positions of rows and columns in the original and received matrices. Then you need to check that for all $x$ with the same row value in the original matrix, the row values in the resulting matrix are the same. Similarly, the values of the columns should be the same.
|
[
"constructive algorithms",
"data structures",
"greedy",
"hashing",
"implementation",
"math",
"matrices",
"sortings"
] | 1,600
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
vi read_ints(int n) {
vi res(n);
for (int i = 0; i < n; ++i) {
cin >> res[i];
}
return res;
}
vvi read_matrix(int n, int m) {
vvi res(n);
for (int i = 0; i < n; ++i) {
res[i] = read_ints(m);
}
return res;
}
void solve() {
int n, m;
cin >> n >> m;
vvi a = read_matrix(n, m), b = read_matrix(n, m);
int nm = n * m;
vi pos1i(nm), pos2i(nm), pos1j(nm), pos2j(nm);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int x = a[i][j] - 1;
int y = b[i][j] - 1;
pos1i[x] = pos2i[y] = i;
pos1j[x] = pos2j[y] = j;
}
}
vector<set<int>> pi(nm), pj(nm);
for (int x = 0; x < nm; ++x) {
int i1 = pos1i[x], i2 = pos2i[x];
int j1 = pos1j[x], j2 = pos2j[x];
pi[i1].insert(i2);
pj[j1].insert(j2);
}
for (int x = 0; x < nm; ++x) {
if (pi[x].size() > 1 || pj[x].size() > 1) {
cout << "NO\n";
return;
}
}
cout << "YES\n";
}
int main() {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
solve();
}
return 0;
}
|
1980
|
F1
|
Field Division (easy version)
|
\textbf{This is an easy version of the problem; it differs from the hard version only by the question. The easy version only needs you to print whether some values are non-zero or not. The hard version needs you to print the exact values.}
Alice and Bob are dividing the field. The field is a rectangle of size $n \times m$ ($2 \le n, m \le 10^9$), the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The cell at the intersection of row $r$ and column $c$ is denoted as ($r, c$).
Bob has $k$ ($2 \le k \le 2 \cdot 10^5$) fountains, all of them are located in different cells of the field. Alice is responsible for dividing the field, but she must meet several conditions:
- To divide the field, Alice will start her path in any free (without a fountain) cell on the left or top side of the field and will move, each time moving to the adjacent cell \textbf{down} or \textbf{right}. Her path will end on the right or bottom side of the field.
- Alice's path will divide the field into two parts — one part will belong to Alice (this part includes the cells of her path), the other part — to Bob.
- Alice will own the part that includes the cell ($n, 1$).
- Bob will own the part that includes the cell ($1, m$).
Alice wants to divide the field in such a way as to get as many cells as possible.
Bob wants to keep ownership of all the fountains, but he can give one of them to Alice. First, output the integer $\alpha$ — the maximum possible size of Alice's plot, if Bob does not give her any fountain (i.e., all fountains will remain on Bob's plot). Then output $k$ non-negative integers $a_1, a_2, \dots, a_k$, where:
- $a_i=0$, if after Bob gives Alice the $i$-th fountain, the maximum possible size of Alice's plot does not increase (i.e., remains equal to $\alpha$);
- $a_i=1$, if after Bob gives Alice the $i$-th fountain, the maximum possible size of Alice's plot increases (i.e., becomes greater than $\alpha$).
|
Since Alice can only move down or to the right, if in the $i$-th row $x$ cells belong to her, then in the $(i-1)$-th row she can have no more than $x$ cells. The construction of the maximum plot can be represented as follows: we will go through the rows from bottom to top and keep track of how many cells we have collected in the row below. In the current row, we will collect either the same number of cells, or all the cells up to the leftmost fountain in the row, if there are fewer such cells. There are three possible positions of the fountains relative to the boundary with Alice's plot: the fountain has no adjacent cells belonging to Alice's plot; the fountain has one adjacent cell belonging to Alice's plot; the fountain has two adjacent cells belonging to Alice's plot. The area of Alice's plot changes only when removing the third type of fountain position, which we will call the corner. Since a corner has formed, in the row below Alice had more cells, and when removing this fountain, she will be able to take at least one cell with this fountain, and the answer for it will be $1$. For the other two types of positions, removing the fountain will not change the size of the plot, and the answer for them will be $0$ (you can proof it by yourself). To ensure that the solution does not depend on the size of the field, we will sort the fountains in descending order of the $x$ coordinate, and in case of equality of $x$, in ascending order of the $y$ coordinate. We will iterate through the fountains in this order, keep track of the coordinates of the last corner, and update the answer when a new corner is found.
|
[
"data structures",
"math",
"sortings"
] | 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(time(nullptr));
const ll inf = 1e9 + 1;
const ll M = 998244353;
const ld pi = atan2(0, -1);
const ld eps = 1e-6;
bool cmp(pair<int, int> &a, pair<int, int> &b){
if(a.x != b.x) return a.x > b.x;
return a.y < b.y;
}
void solve(int tc){
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int>> a(k);
map<pair<int, int>, int> idx;
for(int i = 0; i < k; ++i){
cin >> a[i].x >> a[i].y;
idx[a[i]] = i;
}
sort(all(a), cmp);
vector<int> ans(k);
int total = 0;
int cur = m + 1;
int last = n;
for(auto e: a){
if(cur > e.y) {
ans[idx[e]] = 1;
total += (cur - 1) * (last - e.x);
cur = e.y;
last = e.x;
}
}
total += (cur - 1) * last;
cout << total << "\n";
for(int e: ans) cout << e << " ";
}
bool multi = true;
signed main() {
int t = 1;
if (multi)cin >> t;
for (int i = 1; i <= t; ++i) {
solve(i);
cout << "\n";
}
return 0;
}
|
1980
|
F2
|
Field Division (hard version)
|
\textbf{This is a hard version of the problem; it differs from the easy version only by the question. The easy version only needs you to print whether some values are non-zero or not. The hard version needs you to print the exact values.}
Alice and Bob are dividing the field. The field is a rectangle of size $n \times m$ ($2 \le n, m \le 10^9$); the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The cell at the intersection of row $r$ and column $c$ is denoted as ($r, c$).
Bob has $k$ ($2 \le k \le 2 \cdot 10^5$) fountains, all of them are located in different cells of the field. Alice is responsible for dividing the field, but she must meet several conditions:
- To divide the field, Alice will start her path in any free (without a fountain) cell on the left or top side of the field and will move, each time moving to the adjacent cell \textbf{down} or \textbf{right}. Her path will end on the right or bottom side of the field.
- Alice's path will divide the field into two parts — one part will belong to Alice (this part includes the cells of her path), the other part — to Bob.
- Alice will own the part that includes the cell ($n, 1$).
- Bob will own the part that includes the cell ($1, m$).
Alice wants to divide the field in such a way as to get as many cells as possible.
Bob wants to keep ownership of all the fountains, but he can give one of them to Alice. First, output the integer $\alpha$ — the maximum possible size of Alice's plot, if Bob does not give her any fountain (i.e., all fountains will remain on Bob's plot).
Then output $k$ non-negative integers $a_1, a_2, \dots, a_k$, where $a_i$ is a value such that after Bob gives Alice the $i$-th fountain, the maximum size of her plot will be $\alpha + a_i$.
|
First, read the editorial of the easy version. Let's use the solution of the easy version to precalculate the stored information on the prefix. The fountain will stop being a corner only when it is removed, because the leftmost corner on the prefix could not become further left as a result of removal. To calculate the change in area, let's make an important observation: if fountain $j$ is not a corner, then it either cannot become one, or will become one only after the removal of the last corner that comes before it in sorted order. It was the leftmost corner that came before fountain $j$, and the next corner in sorted order will be strictly higher. Thus, we need to do the following: for each corner, calculate the area without considering it until the next corner, and this will be helped by the precalculation we did when calculating the area. Each fountain will be processed only once, so the time complexity is $O(n)$.
|
[
"math",
"sortings"
] | 2,400
|
#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(time(nullptr));
const ll inf = 1e9 + 1;
const ll M = 998244353;
const ld pi = atan2(0, -1);
const ld eps = 1e-6;
bool cmp(pair<int, int> &a, pair<int, int> &b){
if(a.x != b.x) return a.x > b.x;
return a.y < b.y;
}
void solve(int tc){
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int>> a(k);
map<pair<int, int>, int> idx;
for(int i = 0; i < k; ++i){
cin >> a[i].x >> a[i].y;
idx[a[i]] = i;
}
idx[{0, 0}] = k++;
a.emplace_back(0, 0);
sort(all(a), cmp);
vector<int> ans(k);
vector<int> total(k + 1), cur(k + 1, m + 1), last(k + 1, n);
for(int i = 1; i <= k; ++i){
auto e = a[i - 1];
total[i] = total[i - 1];
cur[i] = cur[i - 1];
last[i] = last[i - 1];
if(cur[i] > e.y) {
ans[idx[e]] = 1;
total[i] += (cur[i] - 1) * (last[i] - e.x);
cur[i] = e.y;
last[i] = e.x;
}
}
cout << total[k] << "\n";
for(int i = 1; i <= k; ++i){
auto e = a[i - 1];
if(ans[idx[e]] == 0)continue;
int tot = total[i - 1];
int cr = cur[i - 1];
int lst = last[i - 1];
for(int j = i + 1; j <= k; ++j){
auto ee = a[j - 1];
if(cr > ee.y){
tot += (cr - 1) * (lst - ee.x);
cr = ee.y;
lst = ee.x;
}
if(ans[idx[ee]] == 1){
ans[idx[e]] = tot - total[j];
break;
}
}
}
ans.pop_back();
for(int e: ans) cout << e << " ";
}
bool multi = true;
signed main() {
int t = 1;
if (multi)cin >> t;
for (int i = 1; i <= t; ++i) {
solve(i);
cout << "\n";
}
return 0;
}
|
1980
|
G
|
Yasya and the Mysterious Tree
|
Yasya was walking in the forest and accidentally found a tree with $n$ vertices. A tree is a connected undirected graph with no cycles.
Next to the tree, the girl found an ancient manuscript with $m$ queries written on it. The queries can be of two types.
The first type of query is described by the integer $y$. The weight of \textbf{each} edge in the tree is replaced by the bitwise exclusive OR of the weight of that edge and the integer $y$.
The second type is described by the vertex $v$ and the integer $x$. Yasya chooses a vertex $u$ ($1 \le u \le n$, $u \neq v$) and mentally draws a bidirectional edge of weight $x$ from $v$ to $u$ in the tree.
Then Yasya finds a simple cycle in the resulting graph and calculates the bitwise exclusive OR of all the edges in it. She wants to choose a vertex $u$ such that the calculated value is \textbf{maximum}. This calculated value will be the answer to the query. It can be shown that such a cycle exists and is unique under the given constraints (independent of the choice of $u$). If an edge between $v$ and $u$ already existed, a simple cycle is the path $v \to u \to v$.
Note that the second type of query is performed mentally, meaning the tree does \textbf{not} change in any way after it.
Help Yasya answer all the queries.
|
We will hang the tree on the vertex $1$ and count for each vertex $d_v$ - xor on the path from it to the root. This can be done by depth-first traversal in $O(n)$. Now let's learn how to solve the problem in $O(n)$ for each query. The first type of query can be executed straightforwardly. Notice that due to the properties of the xor operation, the values will only change for vertices at odd depth (the depth of the root is $0$). At the same time, they will change trivially: they will be xored with $y$. To answer the second query, it is necessary to realize that the xor on a simple cycle $v \to \text{lca}(v, u) \to u \to v$ is equal to $d_v \oplus d_u \oplus x$. Indeed, the path from $\text{lca(v, u)}$ to the root will be counted twice, so it will turn into $0$, and no other extra edges will be included in this xor. With due skill, you can try to speed up such a solution with AVX instructions, but the time constraints were chosen strictly. For a complete solution to the problem, you can use the data structure prefix tree (trie). With its help, you can find in $O(\log x)$ for the number $x$ such a $y$ in the set, that $x \oplus y$ is maximal. Since $d_v$ change differently, you will have to use two tries - for vertices at even and odd heights. Operations of the first type can be accumulated in the variable $w_\text{odd}$ and added to the xor expression. In addition, you must not forget to remove $d_v$ from the necessary trie when answering the second query, and then insert it back. To do this, you can maintain a counter of terminal leaves in each vertex and use this information during descent. Thus, the final asymptotic is $O((n + m) \log 10^9)$.
|
[
"bitmasks",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"strings",
"trees"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
struct trie {
int l, c;
vector<array<int, 2>> node;
vector<int> cnt;
trie(int l, int max_members) : l(l), c(0), node((l + 2) * max_members + 3), cnt((l + 2) * max_members + 3) {}
void add(int x) {
int cur = 0;
for (int i = l; i >= 0; --i) {
bool has_bit = (1 << i) & x;
if (!node[cur][has_bit]) {
node[cur][has_bit] = ++c;
}
cur = node[cur][has_bit];
++cnt[cur];
}
}
void remove(int x) {
int cur = 0;
for (int i = l; i >= 0; --i) {
bool has_bit = (1 << i) & x;
if (!node[cur][has_bit]) {
node[cur][has_bit] = ++c;
}
cur = node[cur][has_bit];
--cnt[cur];
}
}
int find_max(int x) {
int cur = 0, ans = 0;
for (int i = l; i >= 0; --i) {
bool has_bit = (1 << i) & x;
if (node[cur][!has_bit] && cnt[node[cur][!has_bit]]) {
ans += 1 << i;
cur = node[cur][!has_bit];
}
else {
cur = node[cur][has_bit];
}
}
return ans;
}
};
const int N = 2e5 + 2;
int x[N];
bitset<N> dp;
vector<array<int, 2>> e[N];
void dfs(int c, int p) {
for (auto [i, w] : e[c]) {
if (i == p) {
continue;
}
dp[i] = !dp[c];
x[i] = x[c] ^ w;
dfs(i, c);
}
}
void solve() {
int n, m, gx = 0;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
e[i].clear();
}
for (int i = 1, u, v, w; i < n; ++i) {
cin >> u >> v >> w;
e[u].push_back({v, w});
e[v].push_back({u, w});
}
dfs(1, 0);
vector<trie> t(2, trie(30, n));
for (int i = 1; i <= n; ++i) {
t[dp[i]].add(x[i]);
}
while (m--) {
char c;
cin >> c;
if (c == '^') {
int y;
cin >> y;
gx ^= y;
}
else {
int a, b;
cin >> a >> b;
t[dp[a]].remove(x[a]);
int same_group = t[dp[a]].find_max(x[a] ^ b);
int diff_group = t[1 - dp[a]].find_max(x[a] ^ b ^ gx);
t[dp[a]].add(x[a]);
cout << max(same_group, diff_group) << "\n";
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
1981
|
A
|
Turtle and Piggy Are Playing a Game
|
Turtle and Piggy are playing a number game.
First, Turtle will choose an integer $x$, such that $l \le x \le r$, where $l, r$ are given. It's also guaranteed that $2l \le r$.
Then, Piggy will keep doing the following operation until $x$ becomes $1$:
- Choose an integer $p$ such that $p \ge 2$ and $p \mid x$ (i.e. $x$ is a multiple of $p$).
- Set $x$ to $\frac{x}{p}$, and the score will increase by $1$.
The score is initially $0$. Both Turtle and Piggy want to maximize the score. Please help them to calculate the maximum score.
|
For a specific $x$, Piggy always chooses $p$ such that $p$ is a prime number, so the score is the number of prime factors of $x$. It is easy to see that the number with at least $t$ prime factors is $2^t$. The largest integer $t$ satisfying $2^t \le r$ is $\left\lfloor\log_2 r\right\rfloor$. Also, because $2l \le r$, then $\log_2 l + 1 \le \log_2 r$, so $\log_2 l < \left\lfloor\log_2 r\right\rfloor \le \log_2 r$, hence $l < 2^{\left\lfloor\log_2 r\right\rfloor} \le r$. So the answer is $\left\lfloor\log_2 r\right\rfloor$. Time complexity: $O(1)$ or $O(\log r)$ per test case.
|
[
"brute force",
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int T;
scanf("%d", &T);
while (T--) {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", __lg(r));
}
return 0;
}
|
1981
|
B
|
Turtle and an Infinite Sequence
|
There is a sequence $a_0, a_1, a_2, \ldots$ of infinite length. Initially $a_i = i$ for every non-negative integer $i$.
After every second, each element of the sequence will \textbf{simultaneously} change. $a_i$ will change to $a_{i - 1} \mid a_i \mid a_{i + 1}$ for every positive integer $i$. $a_0$ will change to $a_0 \mid a_1$. Here, $|$ denotes bitwise OR.
Turtle is asked to find the value of $a_n$ after $m$ seconds. In particular, if $m = 0$, then he needs to find the initial value of $a_n$. He is tired of calculating so many values, so please help him!
|
Each bit of the answer is independent, so we can calculate the value of each bit of the answer separately. Let's consider the $d$-th bit. Then, $a_i = \left\lfloor\frac{i}{2^d}\right\rfloor \bmod 2$. Every second, a $1$ will "spread" one position to the left and right. If $a_n$ is initially $1$, then the answer for this bit is $1$. Otherwise, $a_n$ is in a continuous segment of $0$s, and we need to calculate whether the $1$s on the left and right of this segment can "spread" to $a_n$. Let $x = n \bmod 2^{d + 1}$, then $0 \le x \le 2^d - 1$. The left $1$ spreading to $a_n$ takes $x + 1$ seconds, and the right $1$ spreading to $a_n$ takes $2^d - x$ seconds. Therefore, if $\min(x + 1, 2^d - x) \le m$, then $a_n$ can become $1$. Specifically, if $n < 2^d$, then there is no $1$ on the left. Therefore, in this case, if $2^d - x \le m$, then $a_n$ can become $1$. Time complexity: $O(\log (n + m))$ per test case. The answer is the bitwise OR of the range $[\max(0, n - m), n + m]$. Let's figure out how to calculate the bitwise OR of the range $[l, r]$. We can consider each bit separately. If the $d$-th bit of $l$ is $1$ or the $d$-th bit of $r$ is $1$, then the $d$-th bit of the answer is $1$. Otherwise, if $\left\lfloor\frac{l}{2^{d + 1}}\right\rfloor \ne \left\lfloor\frac{r}{2^{d + 1}}\right\rfloor$, then the $d$-th bit has been flipped at least twice from $l$ to $r$, so in this case the $d$-th bit of the answer is also $1$. Time complexity: $O(\log (n + m))$ per test case.
|
[
"bitmasks",
"math"
] | 1,300
|
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;
void solve() {
ll n, m;
scanf("%lld%lld", &n, &m);
ll l = max(0LL, n - m), r = n + m, ans = 0;
for (int i = 31; ~i; --i) {
if ((l & (1LL << i)) || (r & (1LL << i)) || (l >> (i + 1)) != (r >> (i + 1))) {
ans |= (1LL << i);
}
}
printf("%lld\n", ans);
}
int main() {
int T = 1;
scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}
|
1981
|
C
|
Turtle and an Incomplete Sequence
|
Turtle was playing with a sequence $a_1, a_2, \ldots, a_n$ consisting of positive integers. Unfortunately, some of the integers went missing while playing.
Now the sequence becomes incomplete. There may exist an arbitrary number of indices $i$ such that $a_i$ becomes $-1$. Let the new sequence be $a'$.
Turtle is sad. But Turtle remembers that for every integer $i$ from $1$ to $n - 1$, either $a_i = \left\lfloor\frac{a_{i + 1}}{2}\right\rfloor$ or $a_{i + 1} = \left\lfloor\frac{a_i}{2}\right\rfloor$ holds for the original sequence $a$.
Turtle wants you to help him complete the sequence. But sometimes Turtle makes mistakes, so you need to tell him if you can't complete the sequence.
Formally, you need to find another sequence $b_1, b_2, \ldots, b_n$ consisting of positive integers such that:
- For every integer $i$ from $1$ to $n$, if $a'_i \ne -1$, then $b_i = a'_i$.
- For every integer $i$ from $1$ to $n - 1$, either $b_i = \left\lfloor\frac{b_{i + 1}}{2}\right\rfloor$ or $b_{i + 1} = \left\lfloor\frac{b_i}{2}\right\rfloor$ holds.
- For every integer $i$ from $1$ to $n$, $1 \le b_i \le 10^9$.
If there is no sequence $b_1, b_2, \ldots, b_n$ that satisfies all of the conditions above, you need to report $-1$.
|
Handle the special case where all elements are $-1$ first. Consider extracting all positions where the values are not $-1$, denoted as $c_1, c_2, \ldots, c_k$. The segments $[1, c_1 - 1]$ and $[c_k + 1, n]$ with $-1$s are easy to handle by repeatedly multiplying and dividing by $2$. It's easy to see that the constructions of the segments $[c_1 + 1, c_2 - 1], [c_2 + 1, c_3 - 1], \ldots, [c_{k - 1} + 1, c_k - 1]$ are independent of each other. Therefore, we now only need to solve the problem where $a'_1 \ne -1$, $a'_n \ne -1$, and $a'_2 = a'3 = \cdots = a'{n - 1} = -1$. It's clear that if $a_i$ is determined, then $a_{i + 1}$ can only be one of $\left\lfloor\frac{a_i}{2}\right\rfloor$, $2a_i$, or $2a_i + 1$. We observe that the transition $a_i \to a_{i + 1}$ is essentially moving along an edge in a complete binary tree. Therefore, the problem is reduced to finding a path in a complete binary tree with a given start point $a'_1$, end point $a'_n$, and passing through $n$ nodes. For example, $a' = [3, -1, -1, -1, 9]$ is equivalent to finding a path from $3$ to $9$ in the complete binary tree that passes through $5$ nodes: First, consider finding the shortest path from $a'_1$ to $a'_n$ in the complete binary tree (which can be found by computing the LCA of $a'_1$ and $a'_n$; the shortest path is $a'_1 \to \text{LCA}(a'_1, a'_n) \to a'_n$). Let the number of nodes in this shortest path be $l$. There is no solution if and only if $l > n$ or if the parities of $l$ and $n$ are different. Otherwise, we first fill $a'_1, a'_2, \ldots, a'_l$ with the nodes from the shortest path, and then alternate between $a'_n$ and $2a'_n$ to fill the remaining positions. Time complexity: $O(n)$ or $O(n \log V)$ per test case.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,800
|
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;
const int maxn = 200100;
int n, a[maxn];
inline vector<int> path(int x, int y) {
vector<int> L, R;
while (__lg(x) > __lg(y)) {
L.pb(x);
x >>= 1;
}
while (__lg(y) > __lg(x)) {
R.pb(y);
y >>= 1;
}
while (x != y) {
L.pb(x);
R.pb(y);
x >>= 1;
y >>= 1;
}
L.pb(x);
reverse(R.begin(), R.end());
for (int x : R) {
L.pb(x);
}
return L;
}
void solve() {
scanf("%d", &n);
int l = -1, r = -1;
vector<int> vc;
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
if (a[i] != -1) {
if (l == -1) {
l = i;
}
r = i;
vc.pb(i);
}
}
if (l == -1) {
for (int i = 1; i <= n; ++i) {
printf("%d%c", (i & 1) + 1, " \n"[i == n]);
}
return;
}
for (int i = l - 1; i; --i) {
a[i] = (((l - i) & 1) ? a[l] * 2 : a[l]);
}
for (int i = r + 1; i <= n; ++i) {
a[i] = (((i - r) & 1) ? a[r] * 2 : a[r]);
}
for (int _ = 1; _ < (int)vc.size(); ++_) {
int l = vc[_ - 1], r = vc[_];
vector<int> p = path(a[l], a[r]);
if (((int)p.size() & 1) != ((r - l + 1) & 1) || r - l + 1 < (int)p.size()) {
puts("-1");
return;
}
for (int i = 0; i < (int)p.size(); ++i) {
a[l + i] = p[i];
}
for (int i = l + (int)p.size(), o = 1; i <= r; ++i, o ^= 1) {
a[i] = (o ? a[i - 1] * 2 : a[i - 1] / 2);
}
}
for (int i = 1; i <= n; ++i) {
printf("%d%c", a[i], " \n"[i == n]);
}
}
int main() {
int T = 1;
scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}
|
1981
|
D
|
Turtle and Multiplication
|
Turtle just learned how to multiply two integers in his math class, and he was very excited.
Then Piggy gave him an integer $n$, and asked him to construct a sequence $a_1, a_2, \ldots, a_n$ consisting of integers which satisfied the following conditions:
- For all $1 \le i \le n$, $1 \le a_i \le 3 \cdot 10^5$.
- For all $1 \le i < j \le n - 1$, $a_i \cdot a_{i + 1} \ne a_j \cdot a_{j + 1}$.
Of all such sequences, Piggy asked Turtle to find the one with the \textbf{minimum} number of \textbf{distinct} elements.
Turtle definitely could not solve the problem, so please help him!
|
The necessary condition for $a_i \cdot a_{i + 1} = a_j \cdot a_{j + 1}$ is that the unordered pairs $(a_i, a_{i + 1})$ and $(a_j, a_{j + 1})$ are identical. In fact, if $a_i$ are all prime numbers, then this necessary condition becomes sufficient. If we consider $(a_i, a_{i + 1})$ as an edge, then the problem can be transformed into finding the undirected complete graph with the fewest nodes (where each node also has a self-loop) such that this complete graph contains a path of $n - 1$ edges without repeating any edge. Next, we consider how to calculate the length of the longest path in a complete graph with a given number of vertices that does not repeat any edges. Let the number of vertices in the complete graph be $m$. If $m$ is odd, then the degree of each node is even, so this graph contains an Eulerian path, and the path length is equal to the number of edges, which is $\frac{m(m + 1)}{2}$. If $m$ is even, then the degree of each node is odd, and we need to remove some edges to make this graph contain an Eulerian path. It is easy to see that each edge removed can reduce the number of vertices with odd degrees by at most $2$, so we need to remove at least $\frac{m}{2} - 1$ edges. Removing the edges $(2, 3), (4, 5), \ldots, (m - 2, m - 1)$ will suffice, and the path length will be $\frac{m(m - 1)}{2} - \frac{m}{2} + 1 + m = \frac{m^2}{2} + 1$. When $n = 10^6$, the smallest $m$ is $1415$, and the $1415$-th smallest prime number is $11807$, which satisfies $a_i \le 3 \cdot 10^5$. We can use binary search to find the smallest $m$ and use Hierholzer's algorithm to find an Eulerian path in an undirected graph. Time complexity: $O(n)$ per test case.
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"number theory"
] | 2,400
|
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<int, int> pii;
const int maxn = 4000100;
const int N = 1000000;
int n, a[maxn], pr[maxn], tot, stk[maxn], top;
bool vis[maxn];
inline void init() {
for (int i = 2; i <= N; ++i) {
if (!vis[i]) {
pr[++tot] = i;
}
for (int j = 1; j <= tot && i * pr[j] <= N; ++j) {
vis[i * pr[j]] = 1;
if (i % pr[j] == 0) {
break;
}
}
}
mems(vis, 0);
}
inline bool check(int x) {
if (x & 1) {
return x + 1 + x * (x - 1) / 2 >= n;
} else {
return x * (x - 1) / 2 - x / 2 + 2 + x >= n;
}
}
vector<pii> G[10000];
void dfs(int u) {
while (G[u].size()) {
pii p = G[u].back();
G[u].pop_back();
if (vis[p.scd]) {
continue;
}
vis[p.scd] = 1;
dfs(p.fst);
}
stk[++top] = pr[u];
}
void solve() {
scanf("%d", &n);
int l = 1, r = 10000, ans = -1;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
for (int i = 1; i <= ans; ++i) {
vector<pii>().swap(G[i]);
}
int tot = 0;
for (int i = 1; i <= ans; ++i) {
for (int j = i; j <= ans; ++j) {
if (ans % 2 == 0 && i % 2 == 0 && i + 1 == j) {
continue;
}
G[i].pb(j, ++tot);
G[j].pb(i, tot);
}
}
for (int i = 1; i <= tot; ++i) {
vis[i] = 0;
}
top = 0;
dfs(1);
reverse(stk + 1, stk + top + 1);
for (int i = 1; i <= n; ++i) {
printf("%d%c", stk[i], " \n"[i == n]);
}
}
int main() {
init();
int T = 1;
scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}
|
1981
|
E
|
Turtle and Intersected Segments
|
Turtle just received $n$ segments and a sequence $a_1, a_2, \ldots, a_n$. The $i$-th segment is $[l_i, r_i]$.
Turtle will create an undirected graph $G$. If segment $i$ and segment $j$ intersect, then Turtle will add an undirected edge between $i$ and $j$ with a weight of $|a_i - a_j|$, for every $i \ne j$.
Turtle wants you to calculate the sum of the weights of the edges of the minimum spanning tree of the graph $G$, or report that the graph $G$ has no spanning tree.
We say two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if and only if $\max(l_1, l_2) \le \min(r_1, r_2)$.
|
We observe that for three segments $(l_1, r_1, a_1), (l_2, r_2, a_2), (l_3, r_3, a_3)$ where each pair of segments intersects (assume $a_1 \le a_2 \le a_3$), we only need to keep the edges between $(1, 2)$ and $(2, 3)$, because $a_3 - a_1 = a_2 - a_1 + a_3 - a_2$ and for every cycle in a graph, the edge with the maximum weight will not appear in the minimum spanning tree. Therefore, consider the following scanline process: each segment is added at $l$ and removed at $r$. When adding a segment, find its predecessor and successor in the order sorted by $a$ and connect edges accordingly. Essentially, we maintain all the segments that exist at each moment as a chain sorted by $a$. It is easy to see that after the scanline process, the number of edges is reduced to $O(n)$. Then we can directly compute the minimum spanning tree. Time complexity: $O(n \log n)$ per test case.
|
[
"data structures",
"dsu",
"graphs",
"greedy"
] | 2,600
|
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<int, int> pii;
const int maxn = 1000100;
int n, lsh[maxn], tot, fa[maxn];
pii b[maxn];
struct node {
int l, r, x;
} a[maxn];
struct edg {
int u, v, d;
edg(int a = 0, int b = 0, int c = 0) : u(a), v(b), d(c) {}
} E[maxn];
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
inline bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
fa[x] = y;
return 1;
} else {
return 0;
}
}
void solve() {
tot = 0;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i].l >> a[i].r >> a[i].x;
lsh[++tot] = a[i].l;
lsh[++tot] = (++a[i].r);
}
int m = 0;
sort(lsh + 1, lsh + tot + 1);
tot = unique(lsh + 1, lsh + tot + 1) - lsh - 1;
for (int i = 1; i <= n; ++i) {
a[i].l = lower_bound(lsh + 1, lsh + tot + 1, a[i].l) - lsh;
a[i].r = lower_bound(lsh + 1, lsh + tot + 1, a[i].r) - lsh;
b[++m] = mkp(a[i].l, i);
b[++m] = mkp(a[i].r, -i);
}
set<pii> S;
sort(b + 1, b + m + 1);
int tt = 0;
for (int i = 1; i <= m; ++i) {
int j = b[i].scd;
if (j > 0) {
auto it = S.insert(mkp(a[j].x, j)).fst;
if (it != S.begin()) {
int k = prev(it)->scd;
E[++tt] = edg(j, k, abs(a[j].x - a[k].x));
}
if (next(it) != S.end()) {
int k = next(it)->scd;
E[++tt] = edg(j, k, abs(a[j].x - a[k].x));
}
} else {
j = -j;
S.erase(mkp(a[j].x, j));
}
}
for (int i = 1; i <= n; ++i) {
fa[i] = i;
}
sort(E + 1, E + tt + 1, [&](const edg &a, const edg &b) {
return a.d < b.d;
});
ll ans = 0, cnt = 0;
for (int i = 1; i <= tt; ++i) {
if (merge(E[i].u, E[i].v)) {
++cnt;
ans += E[i].d;
}
}
cout << (cnt == n - 1 ? ans : -1) << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T = 1;
cin >> T;
while (T--) {
solve();
}
return 0;
}
|
1981
|
F
|
Turtle and Paths on a Tree
|
\textbf{Note the unusual definition of $\text{MEX}$ in this problem.}
Piggy gave Turtle a \textbf{binary tree}$^{\dagger}$ with $n$ vertices and a sequence $a_1, a_2, \ldots, a_n$ on his birthday. The binary tree is rooted at vertex $1$.
If a set of paths $P = \{(x_i, y_i)\}$ in the tree covers each edge \textbf{exactly once}, then Turtle will think that the set of paths is good. Note that a good set of paths can cover a vertex twice or more.
Turtle defines the value of a set of paths as $\sum\limits_{(x, y) \in P} f(x, y)$, where $f(x, y)$ denotes the $\text{MEX}^{\ddagger}$ of all $a_u$ such that vertex $u$ is on the simple path from $x$ to $y$ in the tree (including the starting vertex $x$ and the ending vertex $y$).
Turtle wonders the \textbf{minimum} value over all good sets of paths. Please help him calculate the answer!
$^{\dagger}$A binary tree is a tree where every non-leaf vertex has at most $2$ sons.
$^{\ddagger}\text{MEX}$ of a collection of integers $c_1, c_2, \ldots, c_k$ is defined as the smallest \textbf{positive} integer $x$ which does not occur in the collection $c$. For example, $\text{MEX}$ of $[3, 3, 1, 4]$ is $2$, $\text{MEX}$ of $[2, 3]$ is $1$.
|
Let's consider dp. Let $f_{u, i}$ denote the path extending upward within the subtree rooted at $u$, with the condition that this path does not include the value $i$. The value of $i$ ranges from $[1, n + 1]$. In this case, we can directly take the MEX of this path as $i$, because if the MEX is not $i$, then the MEX will be smaller, making this dp state suboptimal. Let $f_{u,i}$ denote the minimum result of the $\operatorname{MEX}$ of a path that extends outside the subtree of $u$ and is specified to be $i$ (where $i$ is not included in the result). Since the $\operatorname{MEX}$ of each path does not exceed $n+1$, the values of $i$ range from $1$ to $n+1$. Consider all the transitions for the dp: If $u$ is a leaf, then: $f_{u,i} = \begin{cases} 0, & i \neq a_u \\ +\infty, & i = a_u \end{cases}$ $f_{u,i} = \begin{cases} 0, & i \neq a_u \\ +\infty, & i = a_u \end{cases}$ If $u$ has only one child, let the child be $x$. Let $\text{minx} = \min\limits_{i \neq a_u} (f_{x,i} + i)$, then: $f_{u,i} = \begin{cases} \min(f_{x,i}, \text{minx}), & i \neq a_u \\ +\infty, & i = a_u \end{cases}$ $f_{u,i} = \begin{cases} \min(f_{x,i}, \text{minx}), & i \neq a_u \\ +\infty, & i = a_u \end{cases}$ If $u$ has two children, let the children be $x$ and $y$. Let $\text{minx} = \min\limits_{i \neq a_u} (f_{x,i} + i)$ and $\text{miny} = \min\limits_{i \neq a_u} (f_{y,i} + i)$. There are four possible transitions: Continuing the path from the subtree of $x$, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, f_{x,i} + \text{miny})$ Continuing the path from the subtree of $y$, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, f_{y,i} + \text{minx})$ Creating a new path and merging the paths from both subtrees, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, \min\limits_{j \neq a_u} (f_{x,j} + f_{y,j} + j))$ Creating a new path without merging the paths from the two subtrees, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, \text{minx} + \text{miny})$ Let $k = \min(\min\limits_{i \neq a_u} (f_{x,i} + f_{y,i} + i), \text{minx} + \text{miny})$, then the transition can be written as follows: $f_{u,i} = \begin{cases} \min(f_{x,i} + \text{miny}, f_{y,i} + \text{minx}, k), & i \neq a_u \\ +\infty, & i = a_u \end{cases}$ Continuing the path from the subtree of $x$, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, f_{x,i} + \text{miny})$ Continuing the path from the subtree of $y$, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, f_{y,i} + \text{minx})$ Creating a new path and merging the paths from both subtrees, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, \min\limits_{j \neq a_u} (f_{x,j} + f_{y,j} + j))$ Creating a new path without merging the paths from the two subtrees, i.e., $\forall i \neq a_u, f_{u,i} = \min(f_{u,i}, \text{minx} + \text{miny})$ Let $k = \min(\min\limits_{i \neq a_u} (f_{x,i} + f_{y,i} + i), \text{minx} + \text{miny})$, then the transition can be written as follows: $f_{u,i} = \begin{cases} \min(f_{x,i} + \text{miny}, f_{y,i} + \text{minx}, k), & i \neq a_u \\ +\infty, & i = a_u \end{cases}$ This results in a time complexity of $O(n^2)$. In fact, we can prove that we only need to consider MEX values up to $O(\frac{n}{\ln n})$ (for $n = 25000$, we only need to consider MEX values up to $3863$). Therefore, the second dimension of the dp only needs to be enumerated up to $O(\frac{n}{\ln n})$ (or $3863$). Also, we have a construction of a chain that can achieve the MEX value of $O(\frac{n}{\ln n})$, which is enumerating $i$ from $1$ and listing all the divisors of $i$ in descending order, such as $[1, 2, 1, 3, 1, 4, 2, 1, 5, 1]$. Time complexity: $O(\frac{n^2}{\ln n})$ per test case. Proof of the upper bound for MEX: Let's only consider the case of a chain. For a fixed $x$, consider a sequence like $[a, \ldots, b, x, c, \ldots, d, x, e, \ldots, f, x, g, \ldots, h]$. We can divide it into segments as follows: $[a, \ldots, b], [b, x, c], [c, \ldots, d], [d, x, e], [e, \ldots, f], [f, x, g], [g, \ldots, h]$ Where segments without $x$ have a MEX value $\le x$, and segments with $x$ have a MEX value $\le 4$. Let $t$ be the answer. Then, $t$ satisfies: (where $c_i$ is the number of occurrences of $i$) $\min_{i \ge 1} (c_i + 1) i + 4 c_i \ge t$ Expanding, we get: $\min_{i \ge 1} (c_i + 1) (i + 4) \ge t$ Furthermore, for segments like $[b, x, c]$, if $x \ge 4$, then the term $4c_i$ above can be reduced to $3c_i$ (since $x$ can be none of $1, 2, 3$). So, we have: $\min(\min_{i = 1}^3 (c_i + 1)(i + 4), \min_{i \ge 4}(c_i + 1)(i + 3)) \ge t$ Hence: $c_i \ge \begin{cases} \left\lceil\frac{t}{i + 4}\right\rceil - 1 & 1 \le i \le 3 \\ \left\lceil\frac{t}{i + 3}\right\rceil - 1 & i \ge 4 \end{cases}$ This means we need $O(\frac{t}{i})$ occurrences of $i$, and since $n = O(t \ln t)$, we have $t = O(\frac{n}{\ln n})$. We also have: $n = \sum_{i \ge 1} c_i \ge \sum_{i = 1}^3 (\left\lceil\frac{t}{i + 4}\right\rceil - 1) + \sum_{i \ge 4} (\left\lceil\frac{t}{i + 3}\right\rceil - 1)$ By fixing $n$, we can binary search for the largest $t$ satisfying the above condition, and for $n = 25000$, we find $t = 3863$. Read the $O(n^2)$ part of Solution 1 first. Consider using a segment tree to maintain the dp values. The transitions for $u$ with at most one child are easy to maintain, so we only need to consider the case with two children. First, use a segment tree to maintain the minimum value of $f_{u,i} + i$, so $\text{minx}$ and $\text{miny}$ can be computed. The value of $f_{u,a_u}$ can be set to $+\infty$ by a point update. Ignoring how to compute $k$ for now, in the end, all $f_{x,i}$ are incremented by $\text{miny}$, all $f_{y,i}$ are incremented by $\text{minx}$, and the segment trees are merged. Finally, all $f_{u,i}$ are taken as the minimum with $k$. To compute $k$, which is $\min\limits_{i \neq a_u} (f_{x,i} + f_{y,i} + i)$, we can use a similar segment tree merging method, quickly computing this as we recursively descend to the leaf nodes of the segment tree. Additionally, we need to maintain the minimum value of $f_{u,i}$. Time complexity: $\mathcal{O}(n \log n)$ per test case.
|
[
"data structures",
"dp",
"trees"
] | 3,000
|
#include<bits/stdc++.h>
using namespace std;
namespace my_std{
#define ll long long
#define bl bool
ll my_pow(ll a,ll b,ll mod){
ll res=1;
if(!b) return 1;
while(b){
if(b&1) res=(res*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return res;
}
ll qpow(ll a,ll b){
ll res=1;
if(!b) return 1;
while(b){
if(b&1) res*=a;
a*=a;
b>>=1;
}
return res;
}
#define db double
#define pf printf
#define pc putchar
#define fr(i,x,y) for(register ll i=(x);i<=(y);i++)
#define pfr(i,x,y) for(register ll i=(x);i>=(y);i--)
#define go(u) for(ll i=head[u];i;i=e[i].nxt)
#define enter pc('\n')
#define space pc(' ')
#define fir first
#define sec second
#define MP make_pair
#define il inline
#define inf 1e18
#define random(x) rand()*rand()%(x)
#define inv(a,mod) my_pow((a),(mod-2),(mod))
il ll read(){
ll sum=0,f=1;
char ch=0;
while(!isdigit(ch)){
if(ch=='-') f=-1;
ch=getchar();
}
while(isdigit(ch)){
sum=sum*10+(ch^48);
ch=getchar();
}
return sum*f;
}
il void write(ll x){
if(x<0){
x=-x;
pc('-');
}
if(x>9) write(x/10);
pc(x%10+'0');
}
il void writeln(ll x){
write(x);
enter;
}
il void writesp(ll x){
write(x);
space;
}
}
using namespace my_std;
#define LC tree[x].lc
#define RC tree[x].rc
ll t,n,a[25025],ch[25025][2],ans=inf;
ll rt[25025],tot=0;
struct node{
ll minn1,minn2,lz,lzmin,lc,rc;
il void addtag(ll v,ll vmin,ll l){
minn1=min(minn1+v,vmin);
minn2=min(minn2+v,vmin+l);
lz+=v;
lzmin=min(lzmin+v,vmin);
}
}tree[1000010];
il void pushup(ll x){
tree[x].minn1=min(tree[LC].minn1,tree[RC].minn1);
tree[x].minn2=min(tree[LC].minn2,tree[RC].minn2);
}
il ll newnode(){
tree[++tot]=(node){(ll)inf,(ll)inf,0,(ll)inf,0,0};
return tot;
}
il void pushdown(ll x,ll l,ll r){
if(!LC) LC=newnode();
if(!RC) RC=newnode();
ll mid=(l+r)>>1;
tree[LC].addtag(tree[x].lz,tree[x].lzmin,l);
tree[RC].addtag(tree[x].lz,tree[x].lzmin,mid+1);
tree[x].lz=0;
tree[x].lzmin=inf;
}
void upd(ll &x,ll l,ll r,ll pos){
if(!x) x=newnode();
if(l==r){
tree[x].minn1=tree[x].minn2=inf;
return;
}
ll mid=(l+r)>>1;
pushdown(x,l,r);
if(pos<=mid) upd(LC,l,mid,pos);
else upd(RC,mid+1,r,pos);
pushup(x);
}
void add(ll &x,ll l,ll r,ll ql,ll qr,ll v){
if(!x) x=newnode();
if(ql<=l&&r<=qr){
tree[x].addtag(v,(ll)inf,l);
return;
}
ll mid=(l+r)>>1;
pushdown(x,l,r);
if(ql<=mid) add(LC,l,mid,ql,qr,v);
if(mid<qr) add(RC,mid+1,r,ql,qr,v);
pushup(x);
}
void mdf(ll &x,ll l,ll r,ll ql,ll qr,ll v){
if(!x) x=newnode();
if(ql<=l&&r<=qr){
tree[x].addtag(0,v,l);
return;
}
ll mid=(l+r)>>1;
pushdown(x,l,r);
if(ql<=mid) mdf(LC,l,mid,ql,qr,v);
if(mid<qr) mdf(RC,mid+1,r,ql,qr,v);
pushup(x);
}
ll merge(ll x,ll y,ll l,ll r){
if(!LC&&!RC){
tree[y].addtag(0,tree[x].minn1,l);
return y;
}
if(!tree[y].lc&&!tree[y].rc){
tree[x].addtag(0,tree[y].minn1,l);
return x;
}
ll mid=(l+r)>>1;
pushdown(x,l,r);
pushdown(y,l,r);
LC=merge(LC,tree[y].lc,l,mid);
RC=merge(RC,tree[y].rc,mid+1,r);
pushup(x);
return x;
}
ll query(ll x,ll y,ll l,ll r){
if(!LC&&!RC) return tree[x].minn1+tree[y].minn2;
if(!tree[y].lc&&!tree[y].rc) return tree[y].minn1+tree[x].minn2;
ll mid=(l+r)>>1,res=inf;
pushdown(x,l,r);
pushdown(y,l,r);
res=min(res,query(LC,tree[y].lc,l,mid));
res=min(res,query(RC,tree[y].rc,mid+1,r));
return res;
}
void dfs(ll u){
if(!ch[u][0]){
mdf(rt[u],1,n+1,1,n+1,0);
if(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);
if(u==1) ans=0;
}
else if(!ch[u][1]){
dfs(ch[u][0]);
rt[u]=rt[ch[u][0]];
if(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);
ll minn=tree[rt[u]].minn2;
mdf(rt[u],1,n+1,1,n+1,minn);
if(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);
if(u==1) ans=minn;
}
else{
ll x=ch[u][0],y=ch[u][1];
dfs(x);
dfs(y);
if(a[u]<=(n+1)){
upd(rt[x],1,n+1,a[u]);
upd(rt[y],1,n+1,a[u]);
}
ll minx=tree[rt[x]].minn2,miny=tree[rt[y]].minn2,k=min(query(rt[x],rt[y],1,n+1),minx+miny);
add(rt[x],1,n+1,1,n+1,miny);
add(rt[y],1,n+1,1,n+1,minx);
rt[u]=merge(rt[x],rt[y],1,n+1);
mdf(rt[u],1,n+1,1,n+1,k);
if(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);
if(u==1) ans=k;
}
}
il void clr(){
fr(i,1,n) ch[i][0]=ch[i][1]=rt[i]=0;
tot=0;
ans=inf;
}
int main(){
t=read();
while(t--){
n=read();
fr(i,1,n) a[i]=read();
fr(i,2,n){
ll x=read();
if(!ch[x][0]) ch[x][0]=i;
else ch[x][1]=i;
}
dfs(1);
writeln(ans);
clr();
}
}
/*
1
5
3 2 2 1 1
1 1 2 2
ans:
4
*/
|
1982
|
A
|
Soccer
|
Dima loves watching soccer. In such a game, the score on the scoreboard is represented as $x$ : $y$, where $x$ is the number of goals of the first team, and $y$ is the number of goals of the second team. At any given time, only one team can score a goal, so the score $x$ : $y$ can change to either $(x + 1)$ : $y$, or $x$ : $(y + 1)$.
While watching a soccer game, Dima was distracted by very important matters, and after some time, he returned to watching the game. Dima remembers the score right before he was distracted, and the score right after he returned. Given these two scores, he wonders the following question. Is it possible that, \textbf{while Dima was not watching the game}, the teams never had an equal score?
It is guaranteed that at neither of the two time points Dima remembers the teams had equal scores. However, it is possible that the score did not change during his absence.
Help Dima and answer the question!
|
In all cases where the first team initially led the score, and then the second team, there will be a moment when the score is equal, so it is enough to check only this condition. If it is met, the answer is "NO", otherwise the answer is "YES". Let's demonstrate how events could have unfolded without an equal score, if the condition is not met. Let $x_{1} > y_{1}$ and $x_{2} > y_{2}$, then the events could have occurred as follows: $x_{1}$ : $y_{1}$($x_{1} + 1$) : $y_{1}$ ($x_{1} + 2$) : $y_{1}$ ... $x_{2}$ : $y_{1}$ $x_{2}$ : ($y_{1} + 1$) $x_{2}$ : ($y_{1} + 2$) ... $x_{2}$ : $y_{2}$ ($x_{1} + 1$) : $y_{1}$ ($x_{1} + 2$) : $y_{1}$ ... $x_{2}$ : $y_{1}$ $x_{2}$ : ($y_{1} + 1$) $x_{2}$ : ($y_{1} + 2$) ... $x_{2}$ : $y_{2}$
|
[
"greedy",
"implementation",
"math",
"sortings"
] | 800
|
t = int(input())
for T in range(t):
la, lb = map(int, input().split())
ra, rb = map(int, input().split())
if la > lb:
la, lb, ra, rb = lb, la, rb, ra
if la < lb and rb < ra:
print("NO")
else:
print("YES")
|
1982
|
B
|
Collatz Conjecture
|
Recently, the first-year student Maxim learned about the Collatz conjecture, but he didn't pay much attention during the lecture, so he believes that the following process is mentioned in the conjecture:
There is a variable $x$ and a constant $y$. The following operation is performed $k$ times:
- increase $x$ by $1$, then
- while the number $x$ is divisible by $y$, divide it by $y$.
Note that both of these actions are performed sequentially within one operation.For example, if the number $x = 16$, $y = 3$, and $k = 2$, then after one operation $x$ becomes $17$, and after another operation $x$ becomes $2$, because after adding one, $x = 18$ is divisible by $3$ twice.
Given the initial values of $x$, $y$, and $k$, Maxim wants to know what is the final value of $x$.
|
Let's write down what happens in the problem and try to speed it up. The first observation: we will perform operations until $x \neq 1$, after which the answer can be found using the formula $ans = 1 + k\,\%\,(y - 1)$. Indeed, after $x$ becomes equal to $1$, if we continue applying operations to it, it will change as follows: $1 \to 2 \to ... \to (y - 1) \to 1 \to 2 \to ... \to (y - 1) \to 1 \to ...$ The second optimization is to group the operations that only add one, so instead of $1$ we will add the next value to $x$ in one action $min(k, \lceil \frac{x}{y} \rceil \cdot y - x)$. After this (if we added at least $1$), we should try to divide the number by $y$ (if it is divisible). If we use these two optimizations, our solution will work in $O(\log x)$ for one set of input data, since in one action $x$ decreases to $\lceil \frac{x + 1}{y} \rceil$, and therefore $x$ becomes $1$ in no more than $O(\log x)$ actions.
|
[
"brute force",
"implementation",
"math",
"number theory"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
long long x, y, k;
cin >> x >> y >> k;
while (k > 0 && x != 1) {
long long ost = (x / y + 1) * y - x;
ost = max(1ll, ost);
ost = min(ost, k);
x += ost;
while (x % y == 0) {
x /= y;
}
k -= ost;
}
cout << x + k % (y - 1) << '\n';
}
int main()
{
#ifdef FELIX
auto _clock_start = chrono::high_resolution_clock::now();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tests = 1;
cin >> tests;
for (int test = 0; test < tests; test++){
solve();
}
#ifdef FELIX
cerr << "Executed in " << chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now()
- _clock_start).count() << "ms." << endl;
#endif
return 0;
}
|
1982
|
C
|
Boring Day
|
On another boring day, Egor got bored and decided to do something. But since he has no friends, he came up with a game to play.
Egor has a deck of $n$ cards, the $i$-th card from the top has a number $a_i$ written on it. Egor wants to play a certain number of rounds until the cards run out. In each round, he takes a non-zero number of cards from the top of the deck and finishes the round. If the sum of the numbers on the cards collected during the round is between $l$ and $r$, inclusive, the round is won; otherwise, it is lost.
Egor knows by heart the order of the cards. Help Egor determine the maximum number of rounds he can win in such a game. Note that Egor is not required to win rounds consecutively.
|
Solution 1: Let $dp[i]$ - the maximum number of rounds won by Egor for the first $i$ elements (top cards). It is possible to come up with a solution in $O(n^{2})$ right now. For each state of the dynamic programming $i$, you can either skip the next card (not take it in any winning segment), or iterate over the length of the segment that will start with the next card. If you calculate prefix sums and compute the sum over a segment in $O(1)$, the solution works exactly in $O(n^{2})$. Let's try to optimize the transitions in such a dynamic. First, it can be noticed that all $a_{i}$ are positive, which means that the sum of the segment $(a, b)$ will be less than $(a, b + 1)$. This means that the first suitable segment (with a sum $\ge l$) can be found using binary search or two pointers. Secondly, if the segment has a suitable sum (from $l$ to $r$), it does not make sense to increase its length, as this can only worsen the answer. Thus, for each state of the dynamic programming, there are only $O(1)$ transitions, so the entire problem can be solved in $O(n)$ or $O(n\log n)$. Solution 2: Let's try to solve the problem greedily. Let's look for a segment $(a, b)$ in the prefix such that the sum of all its elements is not less than $l$ and not greater than $r$, and among all such segments, we will take the segment with the minimum $b$. After that, we will consider that the array starts from the $(b + 1)$-th element and continue to search for the next segment in the same way. How to find $(a, b)$? Let's start by finding the minimum prefix $k$ (which is also the segment $(1, k)$) such that the sum of the elements in it is $\ge l$. If this sum is also not greater than $r$, then this prefix is the segment we need $(a, b)$. Otherwise, we know that the sum of the elements in any subsegment of this prefix that does not contain the last element $a_{k}$ is less than $l$, so we can try to find a subsegment that ends at $k$, for this, we can iterate over the left boundary from $1$ to $k$. At the same time, the sum of the elements in the iterated segment will decrease and it may happen again that at some point it becomes $< l$, in this case, we already know that we will not find the required segment with the right boundary $k$, so it needs to be increased (again until the sum becomes $\ge l$). By repeating these actions, we will either find the required segment $(a, b)$, or the right boundary will become equal to $n$. The algorithm is nothing but "two pointers", we keep two boundaries $l$ and $r$ and move them only to the right, so in total, this all works in $O(n)$.
|
[
"binary search",
"data structures",
"dp",
"greedy",
"two pointers"
] | 1,200
|
t = int(input())
for T in range(t):
n, l, r = map(int, input().split())
a = [int(x) for x in input().split()]
ans = 0
cur = 0
L, R = 0, 0
while L < n:
while R < n and cur < l:
cur += a[R]
R += 1
if l <= cur and cur <= r:
ans += 1
L = R
cur = 0
else:
cur -= a[L]
L += 1
print(ans)
|
1982
|
D
|
Beauty of the mountains
|
Nikita loves mountains and has finally decided to visit the Berlyand mountain range! The range was so beautiful that Nikita decided to capture it on a map. The map is a table of $n$ rows and $m$ columns, with each cell containing a non-negative integer representing the height of the mountain.
He also noticed that mountains come in two types:
- With snowy caps.
- Without snowy caps.
Nikita is a very pragmatic person. He wants the sum of the heights of the mountains with snowy caps to be equal to the sum of the heights of the mountains without them. He has arranged with the mayor of Berlyand, Polikarp Polikarpovich, to allow him to transform the landscape.
Nikita can perform transformations on submatrices of size $k \times k$ as follows: he can add an integer constant $c$ to the heights of the mountains within this area, but the type of the mountain remains unchanged. Nikita can choose the constant $c$ independently for each transformation. \textbf{Note that $c$ can be negative}.
Before making the transformations, Nikita asks you to find out if it is possible to achieve equality of the sums, or if it is impossible. It doesn't matter at what cost, even if the mountains turn into canyons and have negative heights.
If only one type of mountain is represented on the map, then the sum of the heights of the other type of mountain is considered to be zero.
|
First, let's calculate the current difference between the heights of different types of mountains, denoted as $D$. Then, for each submatrix of size $k \times k$, we will calculate how the difference in the sums of heights of different types of mountains changes. That is, for each submatrix, we will calculate the difference in the number of zeros and ones in it, let these values be $d_{i}$ and there will be $q = (n - k + 1) \cdot (m - k + 1)$. This can be done using two-dimensional prefix sums or a "sliding window". After that, formally we can write the following equation: $c_{1} \cdot d_{1} + c_{2} \cdot d_{2} + \dots + c_{q} \cdot d_{q} = D$ , where $c_{1}$, $c_{2}$, ..., $c_{q}$ - are constants $c$ that Nikita chose for a specific submatrix ($0$ if we did not transform using this submatrix). This is very similar to a Diophantine equation, in fact, it is, but with $q$ unknowns. What can be said about the existence of a solution to this equation in integers? For this, it is sufficient that $D \bmod gcd(d_{1}, d_{2}, \dots, d_{q}) = 0$ It is worth mentioning that it is necessary to carefully handle the case when all $d_{i} = 0$, and also not to forget about the case when $D$ is initially equal to $0$. In total, the solution is in $O(n \cdot m + \log A)$
|
[
"brute force",
"data structures",
"implementation",
"math",
"number theory"
] | 1,700
|
import math
def solve():
n, m, k = map(int, input().split())
a = [[int(x) for x in input().split()] for j in range(n)]
s = [input() for i in range(n)]
pref = [[0 for i in range(m + 1)] for j in range(n + 1)]
diff = 0
for i in range(n):
cur = 0
for j in range(m):
if s[i][j] == '1':
cur += 1
diff += a[i][j]
else:
diff -= a[i][j]
pref[i + 1][j + 1] = pref[i][j + 1] + cur
if diff == 0:
print("YES")
return
g = 0
for i in range(n - k + 1):
for j in range(m - k + 1):
f = pref[i + k][j + k] - pref[i + k][j] - pref[i][j + k] + pref[i][j]
f = abs(k * k - 2 * f)
g = math.gcd(g, f)
if g == 0 or diff % g != 0:
print("NO")
else:
print("YES")
if __name__ == "__main__":
t = int(input())
for _ in range(t):
solve()
|
1982
|
E
|
Number of k-good subarrays
|
Let $bit(x)$ denote the number of ones in the binary representation of a non-negative integer $x$.
A subarray of an array is called $k$-good if it consists only of numbers with no more than $k$ ones in their binary representation, i.e., a subarray $(l, r)$ of array $a$ is good if for any $i$ such that $l \le i \le r$ condition $bit(a_{i}) \le k$ is satisfied.
You are given an array $a$ of length $n$, consisting of consecutive non-negative integers starting from $0$, i.e., $a_{i} = i$ for $0 \le i \le n - 1$ (in $0$-based indexing). You need to count the number of $k$-good subarrays in this array.
As the answer can be very large, output it modulo $10^{9} + 7$.
|
Let $f(n, k)$ be a function to solve the problem, which will return three values $(l, r, ans)$ such that: $l$ - for the first $l$ numbers (i.e. from $0$ to $l - 1$) $bit(x) \le k$ holds, while $bit(l) > k$ or $l \ge n$; $r$ - for the last $r$ numbers (i.e. from $n - r$ to $n - 1$) $bit(x) \le k$ holds, while $bit(n - r - 1) > k$ or $n - r - 1 < 0$; $ans$ - the answer for the pair $(n, k)$. Let's use the "divide and conquer" approach. Divide the segment from $0$ to $n$ into two segments: from $0$ to $2^{m} - 1$, where $m$ is the maximum such that $2^{m} < n$; from $2^{m}$ to $n - 1$. It can be noticed that instead of calculating the function on the segment from $2^{k}$ to $n - 1$, it is possible to calculate it from $0$ to $n - 1 - 2^{m}$, but with a smaller $k$. More formally, $f(n, k)$ can be recalculated through $f(2^{m}, k)$ and $f(n - 2^{m}, k - 1)$. Based on the pair of triples $(l_{1}, r_{1}, ans_{1})$, which is obtained after calculating $f(2^{m}, k)$ and $(l_{2}, r_{2}, ans_{2})$, which is obtained after calculating $f(n - 2^{m}, k - 1)$, it is quite trivial to recalculate the triple for $f(n, k)$ using the formula in $O(1)$. However, the solution still works in $O(n)$ time, as we will have a complete binary tree of recursive calls. To fix this, it is only necessary to precalculate all $f(2^{m}, k)$ for each possible $k$ and $m$. For $f(2^{m}, k)$, it can be noticed that it is recalculated through $f(2^{m - 1}, k)$ and $f(2^{m - 1}, k - 1)$, so all values can be calculated using dynamic programming. After this, in the recursive function, we always calculate $f(2^{m}, k)$ in $O(1)$, and for the next call, the first argument is halved, so now everything works in $O(\log n)$ for one test case. In total, the solution is in $O(\log n)$ for the test case.
|
[
"bitmasks",
"brute force",
"combinatorics",
"divide and conquer",
"dp",
"math",
"meet-in-the-middle"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
map<pair<long long, int>, tuple<int, long long, long long>> mem;
tuple<int, long long, long long> calc(long long n, int k){
if (k < 0){
return tuple{0, 0ll, 0ll};
}
if (n == 1){
return tuple{1, 1ll, 1ll};
}
int bit = 63 - __builtin_clzll(n);
long long mid = (1ll << bit);
if (mid == n){
mid >>= 1;
if (mem.count({n, k})){
return mem[{n, k}];
}
}
auto [f1, s1, e1] = calc(mid, k);
auto [f2, s2, e2] = calc(n - mid, k - 1);
int sub1 = (e1 % MOD) * ((e1 + 1) % MOD) % MOD * 500000004 % MOD;
f1 = (f1 * 1ll - sub1 + MOD) % MOD;
int sub2 = (s2 % MOD) * ((s2 + 1) % MOD) % MOD * 500000004 % MOD;
f2 = (f2 * 1ll - sub2 + MOD) % MOD;
long long p = (e1 + s2) % MOD;
int f_cur = (f1 * 1ll + f2 + (p * 1ll * ((p + 1) % MOD) % MOD * 500000004 % MOD)) % MOD;
long long s_cur = s1;
long long e_cur = e2;
if (s1 == e1 && s1 != 0){
s_cur = (s1 + s2);
}
if (s2 == e2 && s2 != 0){
e_cur = (e1 + e2);
}
if ((mid << 1) == n){
mem[{n, k}] = tuple{f_cur, s_cur, e_cur};
}
return tuple{f_cur, s_cur, e_cur};
};
void solve(){
long long n;
int k;
cin >> n >> k;
cout << get<0>(calc(n, k)) << '\n';
}
int main()
{
#ifdef FELIX
auto _clock_start = chrono::high_resolution_clock::now();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tests = 1;
cin >> tests;
for (int test = 0; test < tests; test++){
solve();
}
#ifdef FELIX
cerr << "Executed in " << chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now()
- _clock_start).count() << "ms." << endl;
#endif
return 0;
}
|
1982
|
F
|
Sorting Problem Again
|
You have an array $a$ of $n$ elements. There are also $q$ modifications of the array. Before the first modification and after each modification, you would like to know the following:
What is the minimum length subarray that needs to be sorted in non-decreasing order in order for the array $a$ to be completely sorted in non-decreasing order?
More formally, you want to select a subarray of the array $(l, r)$ with the minimum value of $r - l + 1$. After that, you will sort the elements $a_{l}, a_{l + 1}, \ldots, a_{r}$ and want the condition $a_{i} \le a_{i + 1}$ to hold for all $1 \le i < n$. If the array is already sorted in non-decreasing order, then $l$ and $r$ should be considered as equal to $-1$.
Note that finding such $(l, r)$ does not change the array in any way. The modifications themselves take the form: assign $a_{pos} = x$ for given $pos$ and $x$.
|
Let's maintain a set $s$ of positions $i$ such that $a_{i} < a_{i - 1}$, and also a segment tree (or any other data structure that allows changing the value at a position and finding the minimum/maximum on a segment). Recalculating the set and the segment tree is quite simple for each change in the array $a$. To answer a query, let's notice a few facts: If $s$ is empty, then the array $a$ is completely sorted. If $s$ is not empty, then we can find the minimum and maximum elements from this set, denote them as $pos_{min}$, $pos_{max}$. With these elements, we can easily answer queries. Similarly to the previous point, we can say that the prefix of size $pos_{min}$ and the suffix of size $n - 1 - pos_{max}$ are sorted in non-decreasing order. Now, at the very least, we need to sort the segment $(l, r)$ such that $l \le pos_{min}$, $r > pos_{max}$. How can we find exactly these $l$ and $r$? First, let's find $l$. To do this, we find the minimum on the segment $(pos_{min} - 1, pos_{max})$, this value will be somewhere in the prefix of the entire array, so we need to find the position in the prefix between which elements it should be inserted. But we also know that the prefix is sorted, so we can use binary search (as in insertion sort) and find the position for this value. This position will be our $l$. For $r$, everything is similar, we find the maximum on the segment $(pos_{min} - 1, pos_{max})$ and also find its position in the sorted suffix. In conclusion, to find the answer after changing the array, we need to find the maximum/minimum positions in $s$, the maximum/minimum on the segment, and perform $2$ binary searches on the prefix and suffix. All of this works in $O(\log n)$. Complexity: $O((n + q) \cdot \log n)$ It is also worth noting that some solutions with $O((n + q) \cdot \log^{2} n)$ can also fit within the time limit if they are very carefully written and use a non-recursive segment tree.
|
[
"binary search",
"data structures",
"sortings"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000007;
struct SegTree{
vector<int> mn, mx;
int n;
SegTree(int _n): n(_n){
mx.assign(2 * n, -inf);
mn.resize(2 * n, inf);
}
void upd(int pos, int val){
mx[pos + n] = val;
mn[pos + n] = val;
pos = (pos + n) >> 1;
for (;pos > 0; pos >>= 1){
mx[pos] = max(mx[pos << 1], mx[(pos << 1) | 1]);
mn[pos] = min(mn[pos << 1], mn[(pos << 1) | 1]);
}
}
pair<int,int> get(int l, int r){
pair<int,int> res = {-inf, inf};
l += n;
r += n + 1;
for (;l < r; l >>= 1, r >>= 1){
if (l & 1) {
res.first = max(res.first, mx[l]);
res.second = min(res.second, mn[l++]);
}
if (r & 1) {
res.first = max(res.first, mx[--r]);
res.second = min(res.second, mn[r]);
}
}
return res;
}
};
void solve(){
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++){
cin >> a[i];
}
SegTree tree(n);
set<int> st;
for (int i = 0; i < n; i++){
tree.upd(i, a[i]);
if (i > 0 && a[i] < a[i - 1]){
st.insert(i);
}
}
function<int(int, int)> find_pref = [&](int pos, int x){
if (pos < 0){
return 0;
}
int l = 0, r = pos;
while(l <= r){
int m = l + (r - l) / 2;
if (a[m] > x){
r = m - 1;
}
else{
l = m + 1;
}
}
return r + 1;
};
function<int(int, int)> find_suff = [&](int pos, int x){
if (pos >= n){
return n - 1;
}
int l = pos, r = n - 1;
while(l <= r){
int m = l + (r - l) / 2;
if (a[m] >= x){
r = m - 1;
}
else{
l = m + 1;
}
}
return r;
};
function<void()> query = [&](){
if (st.empty()){
cout << -1 << ' ' << -1 << '\n';
return;
}
int l = *st.begin() - 1;
int r = *(--st.end());
auto [mx, mn] = tree.get(l, r);
cout << find_pref(l - 1, mn) + 1 << ' ' << find_suff(r + 1, mx) + 1 << '\n';
};
query();
int q;
cin >> q;
for (int i = 0; i < q; i++){
int pos, val;
cin >> pos >> val;
pos--;
if (pos > 0 && a[pos] < a[pos - 1]){
st.erase(pos);
}
if (pos + 1 < n && a[pos + 1] < a[pos]){
st.erase(pos + 1);
}
a[pos] = val;
tree.upd(pos, val);
if (pos > 0 && a[pos] < a[pos - 1]){
st.insert(pos);
}
if (pos + 1 < n && a[pos + 1] < a[pos]){
st.insert(pos + 1);
}
query();
}
}
int main()
{
#ifdef FELIX
auto _clock_start = chrono::high_resolution_clock::now();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tests = 1;
cin >> tests;
for (int test = 0; test < tests; test++){
solve();
}
#ifdef FELIX
cerr << "Executed in " << chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now()
- _clock_start).count() << "ms." << endl;
#endif
return 0;
}
|
1983
|
A
|
Array Divisibility
|
An array of integers $a_1,a_2,\cdots,a_n$ is beautiful subject to an integer $k$ if it satisfies the following:
- The sum of $a_{j}$ over all $j$ such that $j$ is a multiple of $k$ and $1 \le j \le n $, itself, is a multiple of $k$.
- More formally, if $\sum_{k | j} a_{j}$ is divisible by $k$ for all $1 \le j \le n$ then the array $a$ is beautiful subject to $k$. Here, the notation ${k|j}$ means $k$ divides $j$, that is, $j$ is a multiple of $k$.
Given $n$, find an array of positive nonzero integers, with each element less than or equal to $10^5$ that is beautiful subject to all $1 \le k \le n$.It can be shown that an answer always exists.
|
The construction $a[i] = i$ for all $1 \le i \le n$ satisfies all the required conditions.
|
[
"constructive algorithms",
"math"
] | 800
|
t = int(input())
for _ in range(t):
n = int(input())
for i in range(1, n + 1):
print(i, end=" ")
print()
|
1983
|
B
|
Corner Twist
|
You are given two grids of numbers $a$ and $b$, with $n$ rows and $m$ columns. All the values in the grid are $0$, $1$ or $2$.
You can perform the following operation on $a$ any number of times:
- Pick any subrectangle in the grid with length and width $\ge 2$. You are allowed to choose the entire grid as a subrectangle.
- The subrectangle has four corners. Take any pair of diagonally opposite corners of the chosen subrectangle and add $1$ to their values modulo $3$.
- For the pair of corners not picked, add $2$ to their values modulo $3$.
Note that the operation only changes the values of the corners of the picked subrectangle.
Is it possible to convert the grid $a$ into grid $b$ by applying the above operation any number of times (possibly zero)?
|
Notice how the operations affect each row and column. The problem offers a really simple solution: the sum of each row and each column modulo $3$ needs to remain constant throughout all the operations. It is easy to see that this is a necessary condition. Let's prove that this is sufficient as well. Notice that using the 2x2 versions of the operations defined in the statement, i.e., addition of $\begin{matrix}1 & 2 \\ 2 & 1\end{matrix}$ or $\begin{matrix}2 & 1 \\ 1 & 2\end{matrix}$ along the corners of a 2x2 square can be used to generate the same result as the operation applied on any rectangle. For instance, we can combine two 2x2 operations sideways to get a 2x3 operation: $\begin{matrix}1 & \fbox{2+1} & 2\\ 2 & \fbox{1+2} & 1\end{matrix} \equiv \begin{matrix}1 & 0 & 2\\ 2 & 0 & 1\end{matrix} \pmod{3}$ If $a[i][j] + 1 \equiv b[i][j] \pmod{3}$, add $\begin{matrix}1 & 2 \\ 2 & 1\end{matrix}$ to the subrectange of $a$ starting at $a[i[j]$. If $a[i][j] + 2 \equiv b[i][j] \pmod{3}$, add $\begin{matrix}2 & 1 \\ 1 & 2\end{matrix}$ to the subrectange of $a$ starting at $a[i[j]$. Make no changes otherwise. We see that it is always possible to make all the elements in the first $n-1$ rows and $m-1$ columns equal using this method. Note that the sum of each row and each column stays constant after each operation. If $b$ is derived from $a$ using these operations, then all the values for the remaining $n + m - 1$ elements of the grid can be uniquely determined using the row and column sums and need to be equal. Hence, proving sufficiency.
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,200
|
t = int(input())
while(t):
t -= 1
n, m = list(map(int,input().split(' ')))
grid_a = []
grid_b = []
for i in range(n):
grid_a.append(list(map(int, list(input()))))
for i in range(n):
grid_b.append(list(map(int, list(input()))))
ac = [0] * n
ar = [0] * m
bc = [0] * n
br = [0] * m
for i in range(n):
for j in range(m):
ac[i] += grid_a[i][j]
bc[i] += grid_b[i][j]
ar[j] += grid_a[i][j]
br[j] += grid_b[i][j]
ok = True
for i in range(n):
ok &= (ac[i] % 3 == bc[i] % 3)
for i in range(m):
ok &= (br[i] % 3 == ar[i] % 3)
if ok:
print("Yes")
else:
print("No")
|
1983
|
C
|
Have Your Cake and Eat It Too
|
Alice, Bob and Charlie want to share a rectangular cake cut into $n$ pieces. Each person considers every piece to be worth a different value. The $i$-th piece is considered to be of value $a_i$ by Alice, $b_i$ by Bob and $c_i$ by Charlie.
The sum over all $a_i$, all $b_i$ and all $c_i$ individually is the same, equal to $tot$.
Given the values of each piece of the cake for each person, you need to give each person a contiguous slice of cake. In other words, the indices at the left and right ends of these subarrays (the slices given to each person) can be represented as $(l_a, r_a)$, $(l_b, r_b)$ and $(l_c, r_c)$ respectively for Alice, Bob and Charlie. The division needs to satisfy the following constraints:
- No piece is assigned to more than one person, i.e., no two subarrays among $[l_a,\ldots,r_a]$, $[l_b, \ldots, r_b]$ and $[l_c, \ldots, r_c]$ intersect.
- $ \sum_{i = l_a}^{r_a} a_i, \sum_{i = l_b}^{r_b} b_i, \sum_{i = l_c}^{r_c} c_i \geq \lceil \frac{tot}{3} \rceil$.
Here, the notation $\lceil \frac{a}{b} \rceil$ represents ceiling division. It is defined as the smallest integer greater than or equal to the exact division of $a$ by $b$. In other words, it rounds up the division result to the nearest integer. For instance $\lceil \frac{10}{3} \rceil = 4$ and $\lceil \frac{15}{3} \rceil = 5$.
|
There can be several correct answers. It is sufficient to find any correct answer. Although it is not necessary to finish the entire cake, we can easily find a way such that the entire cake is given away. We can start by trying to give a prefix to Alice. To determine if it is possible to divide the cake such that Alice gets at least one-third of the total value by taking a prefix, and Bob and Charlie can split the remaining cake into two parts where each gets at least one-third of the total value, we can use the following approach: We start by calculating the prefix sums for Alice, Bob, and Charlie. Using these prefix sums, we iterate left to right to search for the minimum prefix size for Alice, where she gets at least one-third of the total value. Once we find an index, we give that prefix to Alice and search again on array $b$ to check if we can give a prefix of the remaining cake to Bob such that Bob gets at least one-third of the total sum, and so does Charlie. If, after removing the prefix of the remaining cake, the value left for Charlie is not enough, we repeat the last step on array $c$ instead and check if the value of the cake left for Bob after Alice and Charlie get theirs' is enough. If the above fails, we repeat the process starting with a prefix of $b$. If that fails too, we try again, beginning with a prefix of $c$. Here are the specific steps for each of the 6 permutations of Alice, Bob, and Charlie: 1. Start with a prefix for Alice, then check Bob's prefix and Charlie gets the rest of the cake. 2. Start with a prefix for Alice, then check Charlie's prefix and Bob gets the rest of the cake. 3. Start with a prefix for Bob, then check Alice's prefix and Charlie gets the rest of the cake. 4. Start with a prefix for Bob, then check Charlie's prefix and Alice gets the rest of the cake. 5. Start with a prefix for Charlie, then check Alice's prefix and Bob gets the rest of the cake. 6. Start with a prefix for Charlie, then check Bob's prefix and Alice gets the rest of the cake. If after trying all permutations, none of them work, the answer is "-1". Otherwise, print the respective indices for the subarrays.
|
[
"binary search",
"brute force",
"greedy",
"implementation"
] | 1,400
|
from itertools import permutations
t = int(input())
while(t):
t -= 1
n = int(input())
val = [[0],[0],[0]]
pf = [[0],[0],[0]]
for i in range(3):
val[i] += list(map(int,input().split(' ')))
for i in range(3):
for j in range(1,n+1):
pf[i].append(pf[i][j-1] + val[i][j])
ok = False
perms = list(permutations([0,1,2]))
comp = (pf[0][n]+2)//3
for i in range(6):
cur = 1
perm = perms[i]
while(cur <= n and pf[perm[0]][cur] < comp): cur += 1
for j in range(cur+1, n):
if(pf[perm[1]][j] - pf[perm[1]][cur] >= comp and pf[perm[2]][n] - pf[perm[2]][j] >= comp):
ans = [[],[],[]]
ans[perm[0]] = [1,cur]
ans[perm[1]] = [cur+1,j]
ans[perm[2]] = [j+1,n]
for x in ans: print(x[0], x[1])
print()
ok = True
break
if(ok): break
if(not ok):
print(-1)
print()
|
1983
|
D
|
Swap Dilemma
|
Given two arrays of distinct positive integers $a$ and $b$ of length $n$, we would like to make both the arrays the same. Two arrays $x$ and $y$ of length $k$ are said to be the same when for all $1 \le i \le k$, $x_i = y_i$.
Now in one move, you can choose some index $l$ and $r$ in $a$ ($l \le r$) and swap $a_l$ and $a_r$, then choose some $p$ and $q$ ($p \le q$) in $b$ such that $r-l=q-p$ and swap $b_p$ and $b_q$.
Is it possible to make both arrays the same?
|
If both the arrays don't have the same multiset of elements then trivially the answer is "NO". Otherwise, we can convert any operation of the form $l$, $r$, $p$, $q$ to swapping $l$, $l+1$, $p$, $p+1$ multiple times. For example: swapping $l=1$, $r=3$, $p=2$, $q=4$ can be converted into three steps: swapping $l=1$, $r=2$, $p=2$, $q=3$, then swapping $l=2$, $r=3$, $p=3$, $q=4$ and finally $l=1$, $r=2$, $p=2$, $q=3$. This can be generalized for any such operation. An interesting observation here is that swapping any two adjacent elements in a distinct array leads to a change in number of inversions of that array by $1$ - which essentially means the parity of inversions of the array gets changed. So, if both the arrays don't have the same parity of inversions initially, they will never have the same parity of inversions. Now, we will prove that when both arrays have the same parity of inversions, then it is definitely possible to make them equal. Keep using operations for array $a$ of the form $l=1$ and $r=2$ while changing the operation $p, q$ to different values to make the elements at indices $3, 4, \ldots n$ the same in array $b$ as they are in array $a$. Now, since both the arrays should have the same parity of inversions at the end, $a_1 = b_1$ and $a_2 = b_2$, and so, our arrays $a$ and $b$ will become equal. Therefore, the answer is "YES" in this case.
|
[
"constructive algorithms",
"data structures",
"divide and conquer",
"greedy",
"math",
"sortings"
] | 1,700
|
#include <bits/stdc++.h>
#define int long long
using namespace std;
int inversions(int arr[],int l,int r){
if(r==l)return 0;
//divide and conquer:
int mid=(l+r)/2;
int x=inversions(arr,l,mid);
int y=inversions(arr,mid+1,r);
//simple merging:
int ans[r-l+1];
int curr=0,inv=0;
int pointx=l,pointy=mid+1;
while(pointx<=mid && pointy<=r){
if(arr[pointx]<arr[pointy]){
inv+=pointy-mid-1;
ans[curr]=arr[pointx];
pointx++;
}
else{
ans[curr]=arr[pointy];
pointy++;
}
curr++;
}
while(pointx<=mid){
inv+=pointy-mid-1;
ans[curr]=arr[pointx];
pointx++;
curr++;
}
while(pointy<=r){
ans[curr]=arr[pointy];
pointy++;
curr++;
}
//final writeback:
for(int i=l;i<=r;i++){
arr[i]=ans[i-l];
}
return x+y+inv;
}
int32_t main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int a[n],b[n],x[n],y[n];
for(int i=0;i<n;i++){
cin >> a[i];
x[i]=a[i];
}
for(int i=0;i<n;i++){
cin >> b[i];
y[i]=b[i];
}
sort(x,x+n);
sort(y,y+n);
int flag=0;
for(int i=0;i<n;i++){
if(x[i]!=y[i])flag=1;
}
cout << (((inversions(a,0,n-1)%2)==(inversions(b,0,n-1)%2)) && flag==0 ? "YES" : "NO") << "\n";
}
return 0;
}
|
1983
|
E
|
I Love Balls
|
Alice and Bob are playing a game. There are $n$ balls, out of which $k$ are special. Each ball has a value associated with it.
The players play turn by turn. In each turn, the player randomly picks a ball and adds the value of the ball to their score, which is $0$ at the beginning of the game. The selected ball is removed from the game. If the ball was special, the same player takes the next turn if at least one ball is remaining. If the ball picked was not special, the next player plays their turn.
They play this game until no balls are remaining in the game. Alice plays first.
Find the expected score that both the players have at the end of the game modulo $10^9+7$.
Formally, let $M = 10^9+7$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
|
When there are no special balls, Alice and Bob alternately pick balls starting with Alice. This means Alice picks ${\frac{n+1}{2}}$ balls if $n$ is odd or $\frac{n}{2}$ if $n$ is even. The total value of all balls is $\sum v_i$. On average, Alice's score is $\lfloor\frac{n + 1}{2}\rfloor \cdot \frac{\sum v_i}{n}$. With $k$ special balls, the picking order can be interrupted, allowing the same player to pick again. We need to distribute $k$ special balls into $n - k + 1$ possible positions (gaps). The expected number of special balls picked by Alice can be derived as the expected number of gaps encountered by Alice ($\lfloor\frac{n - k + 2}{2}\rfloor$) times the expected number of special balls per gap($\frac{k}{n - k + 1}$). The formula is $\frac{(\lfloor\frac{n - k + 2}{2} \rfloor) \cdot k}{n - k + 1}$. Expected value without special balls: $\lfloor\frac{n + 1}{2}\rfloor \cdot \frac{\sum v_i}{n}$. Expected special balls for Alice: $\frac{(\lfloor\frac{n - k}{2}\rfloor + 1) \cdot k}{n - k + 1}$. Expected normal balls for Alice when there are non-zero special balls: $\lfloor\frac{n - k + 1}{2}\rfloor$ Therefore, expected score of Alice: $\frac{(\lfloor\frac{n - k}{2}\rfloor + 1) \cdot k}{n - k + 1} \cdot \frac{\sum_{i \in \{1,2, \cdot \cdot \cdot k\}}{v_i}}{k} + \lfloor\frac{n - k + 1}{2}\rfloor \cdot \frac{\sum_{i \in \{k+1,k+2, \cdot \cdot \cdot n\}}{v_i}}{n - k}$ Similarly, expected score of Bob: $(k - \frac{(\lfloor\frac{n - k}{2}\rfloor + 1) \cdot k}{n - k + 1}) \cdot \frac{\sum_{i \in \{1,2, \cdot \cdot \cdot k\}}{v_i}}{k} + (n - k - \lfloor \frac{n - k + 1}{2} \rfloor) \cdot \frac{\sum_{i \in \{k+1,k+2, \cdot \cdot \cdot n\}}{v_i}}{n - k}$
|
[
"combinatorics",
"math",
"probabilities"
] | 2,300
|
#include <iostream>
#include <vector>
#define int long long
const int mod = 1e9 + 7;
int power(int a, int b) {
int ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return ans;
}
int inline inv(int x) { return power(x, mod - 2); }
void solve() {
int N, K;
std::cin >> N >> K;
std::vector<int> values(N);
int avg_special_value = 0, avg_normal_value = 0;
for (int i = 0; i < N; i++) {
std::cin >> values[i];
if (i < K)
avg_special_value += values[i];
else
avg_normal_value += values[i];
}
int total_score = (avg_normal_value + avg_special_value) % mod;
avg_normal_value %= mod;
avg_special_value %= mod;
avg_special_value = (avg_special_value * inv(K)) % mod;
avg_normal_value = (avg_normal_value * inv(N - K)) % mod;
int count_normal_balls = (N - K + 1) / 2;
int expected_special_balls =
(((((N - K + 2) / 2) * K) % mod) * inv(N - K + 1)) % mod;
int expected_alice_score = (count_normal_balls * avg_normal_value +
expected_special_balls * avg_special_value) %
mod;
int expected_bob_score =
((total_score - expected_alice_score) % mod + mod) % mod;
std::cout << expected_alice_score << " " << expected_bob_score << "\n";
}
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int t;
std::cin >> t;
while (t--) {
solve();
}
return 0;
}
|
1983
|
F
|
array-value
|
You have an array of non-negative integers $a_1, a_2, \ldots, a_n$.
The value of a sub-array of length $\ge 2$, $a[l, r] = [a_l, a_{l+1}, \ldots, a_r]$ is the minimum value of $a_i \oplus a_j$ such that $l \le i < j \le r$, where $\oplus$ is the xor (exclusive-or) operator.
You have to find the $k$-th smallest value over all sub-arrays of length $\ge 2$.
|
We can binary search on the the value of the $k$th-smallest and maintain the number of subarrays with xor-pair less than the value. This way, we can find the $k$th-smallest value easily. In order to maintain the number of subarrays, we can use our popular xor data structure called trie. For a given binary searched value, we will traverse from left to right, putting in the values of the array in our trie with their highest corresponding indices. For a fixed index $i$, we would like to find the highest index $j<i$ such that the subarray from $[j,i]$ contains xor-pair less than the fixed upper bound. Then all subarrays with their left end between $[1,j]$ and right end fixed at $i$ will have xor-pair less than the value. Therefore, this becomes a sliding window where we want to maximize the value of the left end $j$ so that the number of subarrays for a fixed right end $i$ becomes as large as possible. To achieve this, we would maintain in our trie the following two things: - the current bit (on/off) - the maximum index which reached this bit in our trie Now when querying: - if both searched bit and current array index bit is $1$: take the max for left index from child "on" bit and go to child "off" bit - if both searched bit and current array index bit is $0$: just go to child "off" bit - if searched bit is $1$ and current array index bit is $0$: take the max for left index from child "off" bit and go to child "on" bit - if searched bit is $0$ and current array index bit is $1$: just go to child "on" bit This is done so that we can find the maximum left index for the given fixed right index at $i$. We follow binary searched value as closely as possible while traversing the trie to stay under the upper bound as well as maximize the left index. Finally, putting the values and corresponding index in the trie is trivial. Simply follow the trie and put in the corresponding bits the maximum index which can reach that bit. This way we can solve this problem in $O(n \log^2 n)$
|
[
"binary search",
"bitmasks",
"data structures",
"greedy",
"two pointers"
] | 2,500
|
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
int ch[3000042][2]{}, mx[3000042]{};
int nc = 1;
void insert(int root,int val,int idx){
int curr=root;
for(int i=29;i>=0;i--){
int lr = ((val&(1<<i)) != 0);
if(!ch[curr][lr]){
nc++;
mx[nc]=idx;
ch[curr][lr]=nc;
}
mx[curr]=max(mx[curr],idx);
curr=ch[curr][lr];
}
mx[curr]=max(mx[curr],idx);
}
int query(int root,int mid,int val){
int curr=root;
int idx=-1;
for(int i=29;i>=0;i--){
if(!curr)return idx;
//check out with 1
if((val&(1<<i)) && (mid&(1<<i))){
if(ch[curr][1])idx=max(idx,mx[ch[curr][1]]);
curr=ch[curr][0];
}
else if((val&(1<<i))){
curr=ch[curr][1];
}
else if((mid&(1<<i))){
if(ch[curr][0])idx=max(idx,mx[ch[curr][0]]);
curr=ch[curr][1];
}
else{
curr=ch[curr][0];
}
}
if(curr)idx=max(idx,mx[curr]);
return idx;
}
int v[100069]{};
int32_t main(){
int t;
cin >> t;
while(t--){
int n;
long long k;
cin >> n >> k;
for(int i=0;i<n;i++){
cin >> v[i];
}
int l=0,r=(1<<30)-1,fin;
while(l<=r){
int mid=l+(r-l)/2;
int left=-1;
long long ans=0;
nc = 1;
int root = nc;
for(int i=0;i<n;i++){
left=max(left,query(root,mid,v[i]));
ans+=((long long)left+1);
insert(root,v[i],i);
}
for(int i=0;i<=nc;i++){
ch[i][0] = 0;
ch[i][1] = 0;
mx[i] = 0;
}
if(ans<k){
l=mid+1;
}
else{
fin=mid;
r=mid-1;
}
}
cout << fin << endl;
}
return 0;
}
|
1983
|
G
|
Your Loss
|
You are given a tree with $n$ nodes numbered from $1$ to $n$, along with an array of size $n$. The value of $i$-th node is $a_{i}$. There are $q$ queries. In each query, you are given 2 nodes numbered as $x$ and $y$.
Consider the path from the node numbered as $x$ to the node numbered as $y$. Let the path be represented by $x = p_0, p_1, p_2, \ldots, p_r = y$, where $p_i$ are the intermediate nodes. Compute the sum of $a_{p_i}\oplus i$ for each $i$ such that $0 \le i \le r$ where $\oplus$ is the XOR operator.
More formally, compute $$\sum_{i =0}^{r} a_{p_i}\oplus i$$.
|
We'll solve for each bit separately. Observe that the number of nodes contributing to the sum for a fixed bit $j$ is the sum of the bit xor'ed with an alternating pattern of $2^j$ continuous bits over the path, i.e., say for $j=2$, the bits are xor'ed with $0000111100001\ldots$. For the rest of the editorial, we will use the word "bit pattern" to refer to this binary string. Let's root the tree arbitrarily and define $dp[u][j]$ as the number of nodes that contribute $2^j$ to the sum required in the query on the path from the node $u$ to the root. Notice that for $dp[u][j]$ the pattern $000\ldots0111\ldots1$ transitions from $0$ to $1$ at the $2^j$th ancestor of $u$. Hence, you can compute $dp[u][j]$ just by knowing the value of the $dp$ at the $2^j$th ancestor and its depth, and the sum of set bits on the remaining path. You can precompute all the power of two ancestors by binary jumping and calculate sums using root-to-node prefix sums. Now, you need to keep track of a few variables to answer queries. Let there be a query from the node $u$ to the node $v$. We define $lc$ as $lca(u,v)$. For a fixed bit $j$, let there be nodes $ux[j],vx[j]$ such that the path from $ux[j]$ to $vx[j]$ is the largest subpath of the path from $u$ to $v$ with $lc$ lying on this path and all the bits from the pattern being the same over this path. Let's call it the central path. One more position to keep track of is the node $vy[j]$ such that it is the lowest ancestor of $v$ where the length of the path from $u$ to $vy$ is a multiple of $2^j$ and $vy$ lies on the path from $u$ to $v$. It is possible that this node does not exist. Notice that the bit pattern for $dp[vy][j]$ upwards will coincide or will be the exact opposite of the bit pattern for the query up to the node $lc$. With these values computed, we can split the query path into separate paths; the answer for each can be easily calculated using prefix sums and precomputed $dp$ values: The path from $u$ to $ux[j]$. The path from $ux[j]$ to $vx[j]$. The path from $vx[j]$ to $vy[j]$. The path from $vy[j]$ to $v$. To compute these three positions quickly, we will again use binary jumping, precomputing these for all queries. To compute $vy[j]$, we notice that for $vy[0] = v$. Then, we make binary jumps whenever necessary. For $ux[j]$ and $vx[j]$, we can start iterating from a bit larger than n to the smallest, noting that if $2^j >= n$, the endpoints will be $ux[j]=u$ and $vx[j]=v$. We make binary jumps when necessary, $vy[j]$ is also required for the computation. Another alternative to binary jumping is to maintain a list of ancestors of the current node while running dfs on the tree and calculate these positions directly during the dfs for each query.
|
[
"bitmasks",
"brute force",
"dp",
"trees"
] | 3,000
|
#include<bits/stdc++.h>
using namespace std;
const int MAX = 5e5+5;
const int MAXL = 20;
const int QMAX = 1e5+5;
int n,q,b[MAX];
vector<int>g[MAX];
vector<array<int,3>>qinfo(QMAX);
vector<long long>ans(QMAX,0);
int up[MAX][MAXL],depth[MAX];
int pf[MAX], dp[MAX];
int u_split[QMAX][MAXL+1], v_split[QMAX][MAXL+1], v_end[QMAX][MAXL+1]{};
void dfs(int a,int p,int d) {
up[a][0]=p;
depth[a]=d;
for(int j=1;j<MAXL;j++) {
up[a][j]=up[up[a][j-1]][j-1];
}
for(int i=0;i<g[a].size();i++) {
if(g[a][i]!=p) {
dfs(g[a][i],a,d+1);
}
}
}
// no of nodes in path [u..v] lca is lc
int get_length(int u,int v,int lc) {
return depth[u]+depth[v]-2*depth[lc]+1;
}
int get_kth(int a,int k) {
int curr=a;
for(int i=0;i<MAXL;i++) {
if((k>>i)&1) {
curr=up[curr][i];
}
}
return curr;
}
int lca(int a,int b) {
if(depth[b]<depth[a]) {
swap(a,b);
}
b=get_kth(b,depth[b]-depth[a]);
if(a==b) {
return a;
}
for(int j=MAXL-1;j>=0;j--) {
if(up[a][j]!=up[b][j]) {
a=up[a][j],b=up[b][j];
}
}
return up[a][0];
}
int get_sum(int u, int v, int lc, int k){
return pf[u] + pf[v] -2*pf[lc] + ((b[lc]>>k)&1);
}
void calc_dp_pf(int a, int p, int k){
pf[a] = pf[p] + ((b[a]>>k)&1);
int next = up[a][k];
if(depth[a]>(1<<k)) dp[a]=depth[next]-dp[next]+pf[a]-pf[next];
else dp[a] = pf[a];
for(int i=0;i<g[a].size();i++) {
if(g[a][i]!=p) {
calc_dp_pf(g[a][i],a,k);
}
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin>>t;
dp[0] = 0;
pf[0] = 0;
while(t--) {
int n,q;
cin>>n;
for(int i=0;i<n-1;i++) {
int a,b;
cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
for(int i=1;i<=n;i++) {
cin>>b[i];
}
dfs(1,0,1);
cin>>q;
for(int i=0;i<q;i++) {
int u,v;
cin>>u>>v;
qinfo[i] = {u,v,lca(u,v)};
ans[i] = 0;
}
for(int i=0;i<q;i++){
int u = qinfo[i][0], v = qinfo[i][1], lc = qinfo[i][2];
v_end[i][0] = v;
if(v == lc) v_end[i][0] = 0;
for(int j=1;j<MAXL;j++){
if(v_end[i][j-1] != 0 && (get_length(u, v_end[i][j-1], lc) & ((1 << j) - 1))){
v_end[i][j] = up[v_end[i][j-1]][j-1];
if(depth[v_end[i][j]] < depth[lc]) v_end[i][j] = 0;
}
else v_end[i][j] = v_end[i][j-1];
}
v_split[i][MAXL] = v;
u_split[i][MAXL] = u;
for(int j=MAXL-1;j>=0;j--){
if(depth[u_split[i][j+1]] - (1<<j) >= depth[lc]) u_split[i][j] = up[u_split[i][j+1]][j];
else u_split[i][j] = u_split[i][j+1];
if(v_end[i][j] && v_end[i][j+1] == 0) v_split[i][j] = v_end[i][j];
else if(depth[v_split[i][j+1]] - (1<<j) >= depth[lc]) v_split[i][j] = up[v_split[i][j+1]][j];
else v_split[i][j] = v_split[i][j+1];
}
}
for(int j=0;j<MAXL;j++) {
calc_dp_pf(1,0,j);
for(int i=0;i<q;i++) {
long long temp = 0;
int u = qinfo[i][0], v = qinfo[i][1], lc = qinfo[i][2];
int us = u_split[i][j], vs = v_split[i][j], vend = v_end[i][j];
int center = get_sum(us, vs, lc, j);
if(((depth[u] - depth[us]) >> j) & 1){
center = get_length(us, vs, lc) - center;
temp += dp[u] - depth[us] + dp[us];
}else temp += dp[u] - dp[us];
temp += center;
if(vend){
if((get_length(u,vend,lc) >> j) & 1){
temp += depth[v] - depth[vend] - pf[v] + pf[vend];
if(((depth[vend] - depth[vs]) >> j) & 1) temp += dp[vend] - depth[vs] + dp[vs];
else temp += dp[vend] - dp[vs];
}else{
temp += pf[v] - pf[vend];
if(((depth[vend] - depth[vs]) >> j) & 1) temp += depth[vend] - dp[vend] - dp[vs];
else temp += depth[vend] - dp[vend] - depth[vs] + dp[vs];
}
}
ans[i] += temp << j;
}
}
for(int i=0;i<q;i++) {
cout<<ans[i]<<"\n";
}
for(int i=1;i<=n;i++) {
g[i].clear();
}
}
return 0;
}
|
1984
|
A
|
Strange Splitting
|
Define the range of a non-empty array to be the maximum value minus the minimum value. For example, the range of $[1,4,2]$ is $4-1=3$.
You are given an array $a_1, a_2, \ldots, a_n$ of length $n \geq 3$. \textbf{It is guaranteed $a$ is sorted}.
You have to color each element of $a$ red or blue so that:
- the range of the red elements \textbf{does not equal} the range of the blue elements, and
- there is at least one element of each color.
\textbf{If there does not exist any such coloring, you should report it.} If there are multiple valid colorings, you can print any of them.
|
When is it impossible? When $a = [x, x \dots x]$ for some $x$. Only color one element red to make the range $0$. Which one do you pick to make the blue range different? Read the hints. It is impossible to color the array when all the elements are the same, because the range for the red and blue elements will always be $0$. Otherwise, notice there will always be at least $2$ distinct values in the array. This means there is a way to get a positive range for the blue elements, by taking the maximum value and the minimum value and coloring them blue. This works because $n \geq 3$, so there is at least one element left. Since we can get a positive range, we can then try to get the red elements to have a range of $0$, by coloring exactly one value red. So, we can color any $a_i$ for $2 \leq i \leq n - 1$ red since it will not affect the positive range we constructed for the blue elements. For simplicity sake, our solution chooses $i = 2$. Then, the remaining elements can be colored blue. Therefore, our final solution is to check if it is impossible, or color $a_2$ red and the rest blue.
|
[
"constructive algorithms"
] | 800
|
#include <iostream>
using namespace std;
int main(){
int T; cin >> T;
while (T--) {
int n; cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
if (a[0] == a[n - 1]) {
cout << "NO" << "\n";
}
else {
cout << "YES" << "\n";
string s(n, 'R');
s[1] = 'B';
cout << s << "\n";
}
}
}
|
1984
|
B
|
Large Addition
|
A digit is large if it is between $5$ and $9$, inclusive. A positive integer is large if all of its digits are large.
You are given an integer $x$. Can it be the sum of two large positive integers with the \textbf{same number of digits}?
|
Solution 1 What must the first (largest) digit be? What must the other non-unit digits be? What must the last digit be? Because every digit is large, every two digits being added together will carry to the next digit. The two addends have the same length, so the sum must be one greater in length, with the largest digit equal to $1$. For all other digits except for the units digit, we have the value to be the sum of two large digits, plus $1$ being carried over from the previous column. This makes the acceptable range of values be from $1$ to $9$, inclusive. For the units digit, there is no previous column to carry over a $1$, so the acceptable range of values is from $0$ to $8$, inclusive.
|
[
"implementation",
"math"
] | 1,100
|
#include <iostream>
using namespace std;
#define ll long long
void solve() {
ll n; cin >> n;
n = n - n % 10 + (n % 10 + 1) % 10;
while (n > 9) {
if (n % 10 == 0) {
cout << "NO\n";
return;
}
n /= 10;
}
cout << (n == 1 ? "YES\n" : "NO\n");
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t; cin >> t;
for (int i = 0; i < t; ++i) solve();
return 0;
}
|
1984
|
C2
|
Magnitude (Hard Version)
|
\textbf{The two versions of the problem are different. You may want to read both versions. You can make hacks only if both versions are solved.}
You are given an array $a$ of length $n$. Start with $c = 0$. Then, for each $i$ from $1$ to $n$ (in increasing order) do \textbf{exactly one} of the following:
- Option $1$: set $c$ to $c + a_i$.
- Option $2$: set $c$ to $|c + a_i|$, where $|x|$ is the absolute value of $x$.
Let the maximum final value of $c$ after the procedure described above be equal to $k$. Find the number of unique procedures that result in $c = k$. Two procedures are different if at any index $i$, one procedure chose option $1$ and another chose option $2$, even if the value of $c$ is equal for both procedures after that turn.
Since the answer may be large, output it modulo $998\,244\,353$.
|
How many times do we need to pick option $2$? We only need to pick it once. How can we calculate the final value for every position we can pick? We only need to pick option $2$ once. Why? Assume we picked option $2$ more than once, and consider the last two times it was picked. Both of these must occur when $c + a_i$ is negative, otherwise there is no reason to pick option $2$ over option $1$. Thus, if we chose option $1$ the first of these times instead of option $2$, that would cause the value of $c$ before the second operation to decrease. Because it was negative, this increases the magnitude, and thus it was more optimal to choose option $1$ for the first operation. Because we only need to use option $2$ once, we can brute force where we use that operation and compute the final value of $c$ with prefix sums. Read the solution to the easy version first. Let's think a bit more. Where do we actually end up using option $2$? We only use option $2$ when our prefix sum up to this point is minimum in the whole array. Now, focus on each individual "important" use of option $2$ (where it actually makes a difference from option $1$), Let's say it is done at index $i$. Let's consider indices before. Since the operation at index $i$ is the only important option $2$, any option $2$'s we use before must not have been different from option $1$ (meaning that the value of $c + a_j$ has to be non-negative). Thus, we have the choice of using option $2$ or option $1$ at any index $j < i$ where the prefix sum is non-negative. Let's say there exists $x$ unique values of $j$. Now, let's consider indices after. Since index $i$ is at a minimum prefix sum, that guarantees that all indices after will never have a lower value of $c$ than what $c$ is after doing the operation at index $i$. Thus, since we use option 2 at index $i$, we can use any of the two options moving forward. Thus, any index $j > i$ has two choices on which option to pick. Let's say there exists $y$ unique values of $j$. The contribution of index $i$ to the answer is then $2^{x + y}$. Special case: the prefix sum never becomes negative. What is the answer then?
|
[
"combinatorics",
"dp",
"greedy",
"math"
] | 1,700
|
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
#define ll long long
const ll MAX_N = 400001;
const ll MOD = 998244353;
vector<ll> p2(MAX_N);
void solve() {
int n; cin >> n;
vector<int> arr(n); for (int i = 0; i < n; ++i) cin >> arr[i];
ll sum = 0, mn = 0, ans = 0, abses = 0;
for (int i = 0; i < n; ++i) sum += arr[i], mn = min(mn, sum);
if (mn == 0) {
cout << p2[n] << '\n';
return;
}
sum = 0;
for (int i = 0; i < n; ++i) {
sum += arr[i];
if (sum == mn) {
ans = (ans + p2[n - i - 1 + abses]) % MOD;
}
if (sum >= 0) ++abses;
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
p2[0] = 1;
for (int i = 1; i < MAX_N; ++i) p2[i] = 2 * p2[i - 1] % MOD;
int t; cin >> t;
for (int i = 0; i < t; ++i) solve();
return 0;
}
|
1984
|
D
|
''a'' String Problem
|
You are given a string $s$ consisting of lowercase Latin characters. Count the number of nonempty strings $t \neq$ "$a$" such that it is possible to partition$^{\dagger}$ $s$ into some substrings satisfying the following conditions:
- each substring either equals $t$ or "$a$", and
- at least one substring equals $t$.
$^{\dagger}$ A partition of a string $s$ is an ordered sequence of some $k$ strings $t_1, t_2, \ldots, t_k$ (called substrings) such that $t_1 + t_2 + \ldots + t_k = s$, where $+$ represents the concatenation operation.
|
What does $t$ have to include? Special case: the string consists of only "$\texttt{a}$", then answer is $n - 1$. Otherwise, $t$ has to contain a character that is not "$\texttt{a}$". Let's consider one approach of counting. Let's force all $t$ to start with the first non-a character, and see how many work. To see if one of these strings $t$ will work, we can start with $i = 0$. As long as $i$ does not point to the end of the string, we can find the next non-a character in $s$, and then see if the next $|t|$ characters in $s$ matches $t$. The last check mentioned can be done through hashing or using the Z-function. If it doesn't, this value of $t$ doesn't work. Otherwise, we update $i$ to the new current position and continue checking. Now, if we find a string $t$ that does work, we need to count its contribution to the answer. We can just add $1$, but obviously not all working $t$ will start with a non-a character. Instead, we can find the minimum unused "$\texttt{a}$"s before all of the substrings equal to $t$ (call this $m$), and the current $t$ will be able to extend out up to $m$ "$\texttt{a}$"s at the beginning of the string. Thus, the contribution is $m + 1$ to the answer. How fast is this? Because we are checking at most one string $t$ of each length, and the check itself can be made to take $O(\frac{n}{|t|})$, we have a total time complexity of $O(n\log{n})$ due to harmonic sums.
|
[
"brute force",
"hashing",
"implementation",
"math",
"string suffix structures",
"strings"
] | 2,000
|
#include <iostream>
#include <vector>
#include <climits>
#include <set>
using namespace std;
#define ll long long
vector<int> z_function(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, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];
if (i + z[i] > r) l = i, r = i + z[i];
}
return z;
}
void solve() {
int n; // cin >> n;
string s; cin >> s;
n = s.length();
vector<int> nona(n, n);
for (int i = n - 1; i >= 0; --i) {
if (s[i] != 'a') nona[i] = i;
else if (i + 1 < n) nona[i] = nona[i + 1];
}
if (nona[0] == n) {
cout << n - 1 << '\n';
return;
}
string s2 = "";
int i1 = nona[0];
for (int i = i1; i < n; ++i) s2 += s[i];
vector<int> z = z_function(s2);
ll ans = 0;
for (int len = 1; i1 + len <= n; ++len) {
int cur = i1 + len;
int mn = i1;
bool works = true;
while (cur < n) {
if (nona[cur] == n) break;
int bt = nona[cur] - cur;
mn = min(mn, bt);
cur += bt;
if (z[cur - i1] < len) {
works = false;
break;
}
cur += len;
}
if (works) ans += mn + 1;
}
cout << ans << '\n';
}
int main() {
int t; cin >> t;
for (int i = 0; i < t; ++i) solve();
return 0;
}
|
1984
|
E
|
Shuffle
|
Two hungry red pandas, Oscar and Lura, have a tree $T$ with $n$ nodes. They are willing to perform the following \textbf{shuffle procedure} on the whole tree $T$ \textbf{exactly once}. With this shuffle procedure, they will create a new tree out of the nodes of the old tree.
- Choose any node $V$ from the original tree $T$. Create a new tree $T_2$, with $V$ as the root.
- Remove $V$ from $T$, such that the original tree is split into one or more subtrees (or zero subtrees, if $V$ is the only node in $T$).
- Shuffle each subtree with the same procedure (again choosing any node as the root), then connect all shuffled subtrees' roots back to $V$ to finish constructing $T_2$.
After this, Oscar and Lura are left with a new tree $T_2$. They can only eat leaves and are very hungry, so please find the maximum number of leaves over all trees that can be created in \textbf{exactly one} shuffle.
Note that leaves are all nodes with degree $1$. Thus, the root may be considered as a leaf if it has only one child.
|
Excluding the root, the maximum number of leaves we have is the maximum independent set (MIS) of the rest of the tree. Why? First of all, after rooting tree $T_2$, no two adjacent nodes can both be leaves. This is because, no matter which one you choose to add to $T_2$ first, it must be the ancestor of the other one. Thus, the first chosen node will not be a leaf. Furthermore, any chosen MIS of nodes can all become leaves. This is because we can essentially choose to add all of the nodes not in the MIS first to the tree, leaving all of the remaining nodes to be childless nodes, making them all leaves. To find the answer, we want to find the maximum MIS of all subtrees that are missing one leaf. The answer will be one greater than this maximum MIS due to the root of $T_2$ being also a leaf. There are multiple dynamic programming approaches to compute this efficiently, including rerooting and performing dynamic programming on tree edges. Time complexity: $O(n)$ or $O(n \log{n})$, depending on implementation.
|
[
"dp",
"greedy",
"trees"
] | 2,400
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
#define pii pair<int, int>
int n;
vector<vector<int>> adj;
vector<pii> edges;
map<pii, int> mp;
vector<vector<int>> dp;
vector<vector<int>> from;
vector<int> miss;
void dfs(int e) {
if (dp[0][e] >= 0 || dp[1][e] >= 0) return;
int p = edges[e].first, v = edges[e].second;
dp[0][e] = 0, dp[1][e] = 1;
if (miss[v] < 0) {
for (int u : adj[v]) {
if (u == p) continue;
int ne = mp[{v, u}];
dfs(ne);
from[0][v] += max(dp[1][ne], dp[0][ne]);
from[1][v] += dp[0][ne];
}
miss[v] = p;
}
if (miss[v] != p && miss[v] != n) {
int ne = mp[{v, miss[v]}];
dfs(ne);
from[0][v] += max(dp[1][ne], dp[0][ne]);
from[1][v] += dp[0][ne];
miss[v] = n;
}
if (miss[v] == n) {
int nne = mp[{v, p}];
dp[0][e] += from[0][v] - max(dp[1][nne], dp[0][nne]);
dp[1][e] += from[1][v] - dp[0][nne];
} else if (miss[v] == p) {
dp[0][e] += from[0][v];
dp[1][e] += from[1][v];
}
}
void solve() {
cin >> n;
adj.clear(), edges.clear();
adj.resize(n), edges.resize(2 * n - 2);
for (int i = 0; i < n - 1; ++i) {
int a, b; cin >> a >> b; --a, --b;
adj[a].push_back(b);
adj[b].push_back(a);
edges[2 * i] = {a, b};
edges[2 * i + 1] = {b, a};
mp[{a, b}] = 2 * i;
mp[{b, a}] = 2 * i + 1;
}
from = vector<vector<int>>(2, vector<int>(n));
miss = vector<int>(n, -1);
dp = vector<vector<int>>(2, vector<int>(2 * n - 2, -1));
for (int i = 0; i < 2 * n - 2; ++i) dfs(i);
int ans = 0;
for (int i = 0; i < n; ++i) {
if (adj[i].size() != 1) continue;
int e = mp[{i, adj[i][0]}];
ans = max(ans, 1 + max(dp[0][e], dp[1][e]));
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t; cin >> t;
for (int i = 0; i < t; ++i) solve();
return 0;
}
|
1984
|
F
|
Reconstruction
|
There is a hidden array $a_1, a_2, \ldots, a_n$ of length $n$ whose elements are integers between $-m$ and $m$, inclusive.
You are given an array $b_1, b_2, \ldots, b_n$ of length $n$ and a string $s$ of length $n$ consisting of the characters $P$, $S$, and $?$.
For each $i$ from $1$ to $n$ inclusive, we must have:
- If $s_i = P$, $b_i$ is the sum of $a_1$ through $a_i$.
- If $s_i = S$, $b_i$ is the sum of $a_i$ through $a_n$.
Output the number of ways to replace all $?$ in $s$ with either $P$ or $S$ such that there exists an array $a_1, a_2, \ldots, a_n$ with elements not exceeding $m$ by absolute value satisfying the constraints given by the array $b_1, b_2, \ldots, b_n$ and the string $s$.
Since the answer may be large, output it modulo $998\,244\,353$.
|
Solve for no question marks in the string first. Add a $0$ on both sides of $a$ and $b$, and add a $\texttt{P}$ before the start of the string and a $\texttt{S}$ after the string. Now you are guaranteed to have a $\texttt{PS}$ somewhere in the string. How does this help? You know the sum of the array. Look at adjacent elements in $b$, and its corresponding characters in the string, and see if you can determine anything about $a$. Go back to the original problem, with question marks. We do not know the sum now, but how many possible ones can there be? How to solve with no question marks? To simplify things, let's extend all arrays both ways by 1 element. In array $a$ and $b$, we can keep both values at $0$, and in the string $s$, we can assign the left value to "$\texttt{P}$" and the right value to "$\texttt{S}$" (the other values will still be satisfied -- why?) Now, somewhere within the string, we are guaranteed to see the combination "$\texttt{PS}$" because we now have a string that starts with "$\texttt{P}$" and ends with "$\texttt{S}$", therefore it must transition somewhere in between. Notice, if we add the values in $b$ of the "$\texttt{PS}$", we can gather the sum of the array. Now, solving becomes simpler. We can focus on adjacent elements in the array. Say we are currently examining indices $i$ and $i + 1$. There are four cases: We are currently at a "$\texttt{PP}$". We then know $b_i + a_{i+1} = b_{i+1}$, so $a_{i+1}$ is now known. We are currently at a "$\texttt{PS}$". Again, this must be the sum. All we have to do here is check that our sum is correct. We are currently at an "$\texttt{SP}$". Here, we have $b_{i} + b_{i+1} - SUM = a_i + a_{i+1}$ (why?). Our left side is known, and the only requirement on the right side is that both $a_i$ and $a_{i+1}$ have to have a magnitude of at most $m$. Thus, to make their maximum magnitude as small as possible, we make them as close as possible to each other. If the left side is $x$, we assign $a_i = \text{floor}(x / 2)$, and $a_{i+1} = x - a_i$. We are currently at an "$\texttt{SS}$". This is similar to the first case, as we know that $b_i = a_i + b_{i+1}$. Thus, $a[i]$ will be known. If $a_i$ is always possible, then we know our answer exists. Thus, this solves a version without question marks. For the version with question marks, we can only try to guess what the sum of the entire array is, since we don't know where "$\texttt{PS}$" might be for sure every time. There are only $n$ possibilities - the sum of every pair of adjacent numbers in $b$. For every possibility, we can run a dp[i][j] where we are currently at index $i$ and the last character within "$\texttt{P}$" and "$\texttt{S}$" in string $s$ used was $j$. This dynamic programming will run in linear time because of constant-time transitions and linear amount of states. Note that this is only possible due to the independent nature of adjacent pairs as described earlier. With this DP, we can calculate how many paths are possible, adding to our answer. Time complexity $O(n^2)$
|
[
"brute force",
"dp",
"math"
] | 2,500
|
#include <iostream>
#include <vector>
#include <cstring>
#include <assert.h>
#include <set>
using namespace std;
#define ll long long
const int INF = 998244353;
// const int BOUND = 1e9;
void solve() {
int n; cin >> n;
int BOUND; cin >> BOUND;
string s; cin >> s;
s = "P" + s + "S";
vector<ll> b(n + 2);
for (int i = 0; i < n; ++i) cin >> b[i + 1];
ll ans = 0;
set<ll> done;
for (int i = 0; i < n + 1; ++i) {
ll sum = b[i] + b[i + 1];
if (done.count(sum)) continue;
int dp[n + 2][2];
for (int j = 0; j < n + 2; ++j) for (int k = 0; k < 2; ++k) dp[j][k] = -1;
// ["P", "S"]
dp[0][0] = 1;
for (int j = 1; j < n + 2; ++j) {
bool tr[2]; tr[0] = tr[1] = true;
if (s[j] == 'P') tr[1] = false;
else if (s[j] == 'S') tr[0] = false;
if (abs(b[j] - b[j - 1]) <= BOUND) {
for (int k = 0; k < 2; ++k)
if (dp[j - 1][k] > -1 && tr[k]) dp[j][k] = dp[j - 1][k];
}
if (dp[j - 1][0] > -1 && tr[1] && sum == b[j] + b[j - 1]) {
// "P" -> "S":
if (dp[j][1] < 0) dp[j][1] = 0;
dp[j][1] = (dp[j][1] + dp[j - 1][0]) % INF;
}
if (dp[j - 1][1] > -1 && tr[0]) {
// "S" -> "P":
ll add = b[j] + b[j - 1] - sum;
ll large = max(abs(add / 2), abs(add - add / 2));
if (large <= BOUND) {
if (dp[j][0] < 0) dp[j][0] = 0;
dp[j][0] = (dp[j][0] + dp[j - 1][1]) % INF;
}
}
}
if (dp[n + 1][1] < 0) continue;
ans = (ans + dp[n + 1][1]) % INF;
done.insert(sum);
}
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(false); cin.tie(NULL);
int t; cin >> t;
for (int i = 0; i < t; ++i) solve();
return 0;
}
|
1984
|
G
|
Magic Trick II
|
The secret behind Oscar's first magic trick has been revealed! Because he still wants to impress Lura, he comes up with a new idea: he still wants to sort a permutation $p_1, p_2, \ldots, p_n$ of $[1, 2, \ldots, n]$.
This time, he chooses an integer $k$. He wants to sort the permutation in non-decreasing order using the following operation several times:
- Pick a continuous subarray of length $k$ and remove it from $p$.
- Insert the continuous subarray back into $p$ at any position (perhaps, in the very front or the very back).
To be as impressive as possible, Oscar would like to choose the maximal value of $k$ such that he can sort his permutation. Please help him find the maximal $k$ as well as a sequence of operations that will sort the permutation. You don't need to minimize the number of operations, but you are allowed to use at most $5n^2$ operations.
We have a proof that, for the maximal $k$ such that you can sort the permutation in any number of operations, you can also sort it in at most $5n^2$ operations.
|
Solve what the maximum $k$ will be for different types of arrays. The maximum is always close to $n$. There exists two trivial cases. If array is already sorted, $k = n$. If array is cyclic shift of sorted array, $k = n - 1$. Now, $k = n - 2$ and $k = n - 3$ is sufficient to sort any array. Let's assume $n$ is odd first, and construct an answer in the general case with $k = n - 2$. Because $k$ is so large, our operations are limited in choices. If we represent the array as a cyclic array with a divider representing the end of the array, an operation can be seen as two choices: Move the divider $2$ positions in any direction. Swap the two numbers around the divider, then move the divider by $1$ position in any direction. With this representation, the construction becomes quite easy. Because $n$ is odd, we can use the first type of operation to put the divider wherever we want. Then, using the second type of operation, if our divider is on the right side of a specific number, we can move it all the way to the right by swapping, then moving the divider right by $1$ position. Because we are able to do this, we can bubble sort. For each number, position the divider in $O(n)$ moves, then move it to the very right in another $O(n)$ moves. There are $n$ numbers total, so this takes a total of around $2n^2$ operations, less if optimized. What if $n$ is even? In this case $k = n - 2$ is not always guaranteed to work. The motivation for seeing this can come from the fact that you can't place the divider anywhere just by using type $1$ operations. As a lower bound, we know that $k = n - 3$ will always work. We can use operations to move the largest number to the very end, then we basically have an array of length $n - 1$ with $k = n - 3$, which is the odd case we presented earlier. So, when can we use $k = n - 2$ in the even case? Let's consider the number of inversions in the array at any given time. If $n$ is even, then $k = n - 2$ is also even, meaning that the parity of the number of inversions will never change with operations. Thus, since a sorted array will have no inversions, we cannot use $k = n - 2$ if the initial array had an odd number of inversions. If we have an even number of inversions, we can sort in a similar manner. Except, now, if the inversion constraint prevents moving the divider to the immediate right of our current number with only type $1$ operations, we can use a few type $2$ operations to fix the position of the divider (many possible strategies for this, one possible way is shown in the implementation). Overall, this should also take around $2n^2$ operations total.
|
[
"constructive algorithms",
"implementation",
"sortings"
] | 3,200
|
#include <iostream>
#include <vector>
using namespace std;
#define pii pair<int, int>
bool sorted(vector<int> arr, int n) {
for (int i = 1; i < n; ++i) if (arr[i] < arr[i - 1]) return false;
return true;
}
bool cyclic(vector<int> arr, int n) {
for (int i = 1; i < n; ++i) if (arr[i] % n != (arr[i - 1] + 1) % n) return false;
return true;
}
void solve() {
int n; cin >> n;
vector<int> arr(n); for (int i = 0; i < n; ++i) cin >> arr[i];
if (sorted(arr, n)) {
cout << n << "\n0\n";
return;
}
if (cyclic(arr, n)) {
cout << n - 1 << '\n';
int pos;
for (pos = 0; pos < n; ++pos) if (arr[pos] == 1) break;
cout << pos << '\n';
for (int i = 0; i < pos; ++i) {
cout << "2 1\n";
}
return;
}
vector<pii> ops;
if (n % 2 == 0) {
int inv = 0;
for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (arr[i] > arr[j]) ++inv;
if (inv & 1) {
int pos;
for (pos = 0; pos < n; ++pos) if (arr[pos] == n) break;
if (pos < 3) {
for (int i = 0; i <= pos; ++i) ops.push_back({2, 1});
vector<int> tmp = arr;
for (int i = 0; i < n - 2; ++i) arr[i] = tmp[(i + pos + 1) % (n - 2)];
}
for (pos = 0; pos < n; ++pos) if (arr[pos] == n) break;
for (int i = pos; i < n - 1; ++i) ops.push_back({3, 4});
vector<int> tmp = arr;
for (int i = 2; i < n; ++i) arr[i] = tmp[((i + pos - 3) % (n - 2)) + 2];
--n;
}
}
cout << n - 2 << '\n';
int div = 0;
for (int i = n; i > 0; --i) {
int pos;
for (pos = 0; pos < n; ++pos) if (arr[pos] == i) break;
pos += 1;
if (pos == i) continue;
if (div % 2 != pos % 2) {
if (n & 1) {
while (div < n) {
ops.push_back({3, 1});
div += 2;
}
div %= n;
} else {
while (div != pos - 1) {
if (div < pos - 1) {
ops.push_back({3, 1});
div += 2;
} else {
ops.push_back({1, 3});
div -= 2;
}
}
if (pos > 1) {
ops.push_back({2, 3});
swap(arr[(div + n - 1) % n], arr[div]);
div = (div + n - 1) % n;
--pos;
}
ops.push_back({3, 1});
div += 2;
ops.push_back({2, 3});
swap(arr[(div + n - 1) % n], arr[div]);
div = (div + n - 1) % n;
}
}
while (div != pos) {
if (div < pos) {
ops.push_back({3, 1});
div += 2;
} else {
ops.push_back({1, 3});
div -= 2;
}
}
for (int j = pos; j < i; ++j) {
ops.push_back({2, 1});
swap(arr[div - 1], arr[div]);
++div;
}
}
if (div % 2 == 1) {
while (div < n) {
ops.push_back({3, 1});
div += 2;
}
div %= n;
}
while (div > 0) {
ops.push_back({1, 3});
div -= 2;
}
cout << ops.size() << '\n';
for (pii p : ops) {
cout << p.first << ' ' << p.second << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t; cin >> t;
for (int i = 0; i < t; ++i) solve();
return 0;
}
|
1984
|
H
|
Tower Capturing
|
There are $n$ towers at $n$ distinct points $(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)$, such that no three are collinear and no four are concyclic. Initially, you own towers $(x_1, y_1)$ and $(x_2, y_2)$, and you want to capture all of them. To do this, you can do the following operation any number of times:
- Pick two towers $P$ and $Q$ you own and one tower $R$ you don't own, such that the circle through $P$, $Q$, and $R$ contains \textbf{all} $n$ towers inside of it.
- Afterwards, capture all towers in or on triangle $\triangle PQR$, including $R$ itself.
An attack plan is a series of choices of $R$ ($R_1, R_2, \ldots, R_k$) using the above operations after which you capture all towers. Note that two attack plans are considered different only if they differ in their choice of $R$ in some operation; in particular, two attack plans using the same choices of $R$ but different choices of $P$ and $Q$ are considered the same.Count the number of attack plans of \textbf{minimal length}. Note that it might not be possible to capture all towers, in which case the answer is $0$.
Since the answer may be large, output it modulo $998\,244\,353$.
|
Are there any useless points? Draw all triangles that contain all points inside their circumcircle. What do you notice? Claim. We can't ever pick a tower inside the convex hull. Proof. A circle can only contain all the points if the points on the circle are on the convex hull; otherwise, the circle will necessarily split the convex hull into two parts, one of which is outside. It follows that if our initial two towers aren't on the convex hull, the answer is $0$. Also, we can safely ignore all points in the convex hull, since we'll capture them anyway, as the convex hull is the union of all triangles whose vertices are vertices of the convex hull. From now on we'll only consider points on the convex hull. Now comes the key claim of the problem. Claim. Call a triangle covering if its circumcircle contains all the points. Draw all covering triangles. We claim that these triangles form a triangulation of the convex hull. Proof. Recall that a triangulation is a set of triangles with pairwise non-intersecting interiors whose union is the polygon. There are two parts to the proof: the triangles are pairwise non-intersecting. their union is the polygon. Let's prove them separately. First we'll prove point (1) directly. Consider two circles through points $ABC$ and $DEF$. Of course, the convex hull needs to lie in the intersection of the two circles. In particular, the circle through $ABC$ must contain the points $DEF$, while the circle through $DEF$ must contain the points $ABC$. It follows that the two circumcircles (say, $\Omega$ and $\Psi$ respectively) have the following property: the points $A$, $B$, $C$ lie on an arc of $\Omega$ inside $\Psi$, and the points $D$, $E$, $F$ lie on an arc of $\Psi$ inside $\Omega$. The claim follows. Formally, we can define $U$ and $V$ as the intersection points of $\Omega$ and $\Psi$. Then if we walk along the digon $UV$ (whose edges are arcs of $\Omega$ and $\Psi$), we will pass through $A$, $B$, $C$ along one of the arcs, and $D$, $E$, $F$ on the other. This means that there is some closed convex loop passing through the points $A$, $B$, $C$ before $D$, $E$, $F$, implying those two triangles don't intersect. The proof remains the same even if some of $A$, $B$, $C$, $D$, $E$, $F$ overlap. Now we'll move on to the proof of (2). Consider any covering triangle $ABC$. WLOG suppose $AB$ is not an edge of the convex hull. Consider the points in the halfplane of $AB$ not containing $C$, and let $C'$ be the point among these such that $\angle AC'B$ is minimized. Then it follows that $ABC'$ is also covering. It's easy to see why this works and why $C'$ is unique by the inscribed angle theorem. As a result, given any covering triangle, we can recursively triangulate the regions it cuts off by a chord. Thus, inductively, the whole polygon will be triangulated. We are done with the proof. Note that this implies our original three towers in the problem must form a covering triangle, since we create a covering triangle after every operation; thus, at the end of these operations, all but possibly one of these triangles is covering (the "possibly one" is the initial triangle). But such a covering triangulation exists and is unique, as shown, so our initial triangle in fact must be covering. Now on to the actual operations present in the problem. Using them, we can "construct" the triangulation one step at a time using operations like the one mentioned. Of course, the triangulation is unique, so the only change we can do is the order in which we construct the triangles. Consider the dual tree of the triangulation (that is, make a vertex for each triangle and an edge between those vertices corresponding to two triangles that share a diagonal of the convex hull). In an operation, we attach a leaf to any vertex, and in the end we end up with the final dual tree. Note that we can start growing the tree at either triangle adjacent to our original diagonal; that is, if our original points are $A$ and $B$, then we need to consider rooting our tree at either $T_1$ or $T_2$, where those are the two triangles that contain the edge $AB$ (note that $T_2$ may not exist). Let's reverse time. Then given the final tree (rooted at either $T_1$ or $T_2$), in an operation we prune a leaf (a leaf here is a vertex with no children). How many ways can we prune all the leaves? This is a standard dynamic programming problem, since at each step we need to prune all of our children before we prune ourselves. In particular, if the sizes of our childrens' subtrees are $s_1, \dots, s_k$, then our answer is $\binom{s_1 + \dots + s_k}{s_1, \dots, s_k} \cdot \prod_{i=1}^{k} \mathrm{ans}(\mathrm{child}_i)$. This DP runs in $\mathcal{O}(n)$ time, so it is not a problem to compute. We can easily compute the triangulation in $\mathcal{O}(n^2)$ time as follows: given an edge $PQ$, we need to find the point $R$ in a halfplane such that $(PQR)$ covers all points, and as mentioned before, by the inscribed angle theorem this is precisely the point $R$ such that $PQR'$ is minimized. So you can find it with an $\mathcal{O}(n)$ sweep and add the new edges to our triangulation. Therefore the solution runs in $\mathcal{O}(n^2)$, but the validator takes $\mathcal{O}(n^3)$ to check. We accepted slower solutions in $\mathcal{O}(n^3)$ as well, and even $\mathcal{O}(n^4)$ with a decent constant factor (which are relatively hard to cut). A note about implementation: I'm not very good at it, so my code below is a bit messy. Also, to keep the computations in integers, I needed to use big integers at exactly one point, but it's not so bad: you only need to implement big integer multiplication and comparison, which I shamelessly stole from jeroenodb. You may not need to use it, and can pass using floating-point numbers.
|
[
"combinatorics",
"dp",
"geometry"
] | 3,300
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 998244353;
struct bignum {
static constexpr long long B = 1LL<<30;
static constexpr int N = 6;
array<long long, N> b = {};
bignum() {}
bignum(long long a) {
b[2] = (a / B) / B;
b[1] = (a / B) % B;
b[0] = a % B;
}
bignum operator*(const bignum& o) {
bignum res;
for (int i = 0; i < N; i++) {
for (int j = 0; j + i < N; j++) {
res.b[i + j] += b[i] * o.b[j];
for (int k = i + j; k + 1 < N; k++) {
auto tmp = res.b[k] / B;
res.b[k + 1] += tmp;
res.b[k] -= tmp * B;
}
}
}
return res;
}
bool operator<=(const bignum& o) const {
if (b == o.b) return true;
return lexicographical_compare(b.rbegin(),b.rend(),o.b.rbegin(),o.b.rend());
}
};
template <class T> int sgn(T x) { return (x > 0) - (x < 0); }
template<class T>
struct Point {
typedef Point P;
T x, y;
explicit Point(T x=0, T y=0) : x(x), y(y) {}
bool operator<(P p) const { return tie(x,y) < tie(p.x,p.y); }
bool operator==(P p) const { return tie(x,y)==tie(p.x,p.y); }
P operator+(P p) const { return P(x+p.x, y+p.y); }
P operator-(P p) const { return P(x-p.x, y-p.y); }
P operator*(T d) const { return P(x*d, y*d); }
P operator/(T d) const { return P(x/d, y/d); }
T dot(P p) const { return x*p.x + y*p.y; }
T cross(P p) const { return x*p.y - y*p.x; }
T cross(P a, P b) const { return (a-*this).cross(b-*this); }
T dist2() const { return x*x + y*y; }
double dist() const { return sqrt((double)dist2()); }
// angle to x-axis in interval [-pi, pi]
double angle() const { return atan2(y, x); }
P unit() const { return *this/dist(); } // makes dist()=1
P perp() const { return P(-y, x); } // rotates +90 degrees
P normal() const { return perp().unit(); }
// returns point rotated 'a' radians ccw around the origin
P rotate(double a) const {
return P(x*cos(a)-y*sin(a),x*sin(a)+y*cos(a)); }
friend ostream& operator<<(ostream& os, P p) {
return os << "(" << p.x << "," << p.y << ")"; }
friend istream& operator>>(istream& is, P& p) {
return is >> p.x >> p.y; }
};
typedef Point<long long> P;
vector<P> convexHull(vector<P> pts) {
if (pts.size() <= 1) return pts;
sort(pts.begin(), pts.end());
vector<P> h(pts.size()+1);
int s = 0, t = 0;
for (int it = 2; it--; s = --t, reverse(pts.begin(), pts.end()))
for (P p : pts) {
while (t >= s + 2 && h[t-2].cross(h[t-1], p) <= 0) t--;
h[t++] = p;
}
return {h.begin(), h.begin() + t - (t == 2 && h[0] == h[1])};
}
int n, t;
long long inv[MAX], fact[MAX], invfact[MAX];
vector<P> v;
void orient(P &a, P &b, P &c) {
// move points a, b, c to be in counterclockwise order
long long val = (b - a).cross(c - a);
assert(val != 0);
if (val < 0) {swap(a, c);}
}
pair<long long, long long> angleComp(P a, P b, P c) {
// get a (scaled) value of f(cos(angle ABC))
P ab = a - b, cb = c - b;
long long dt = ab.dot(cb);
dt *= dt;
int sgn = (ab.dist2() + cb.dist2() >= (a - c).dist2() ? 1 : -1);
return make_pair(sgn * dt, ab.dist2() * cb.dist2());
}
bool inCircle(P a, P b, P c, P d) {
// is D in (or on) (ABC)?
orient(a, b, c);
P ad = a - d, bd = b - d, cd = c - d;
return (
ad.dist2() * (bd.x * cd.y - bd.y * cd.x) -
bd.dist2() * (ad.x * cd.y - ad.y * cd.x) +
cd.dist2() * (ad.x * bd.y - ad.y * bd.x)
) >= 0;
}
pair<bool, int> check(int l, int r) {
int start = l, finish = r;
if (finish < start) {finish += n;}
pair<long long, long long> best = make_pair(-MOD, 1);
int w = -1;
for (int i = start + 1; i < finish; i++) {
pair<long long, long long> val = angleComp(v[l], v[i % n], v[r]);
bignum v1 = bignum(val.first) * bignum(best.second);
bignum v2 = bignum(val.second) * bignum(best.first);
if (!(v1 <= v2)) {
best = val;
w = i % n;
}
}
if (w == -1) {
// cout << v[l] << ' ' << v[r] << " empty?\n";
return make_pair(true, -1);
}
// cout << v[l] << ' ' << v[r] << " connects to " << v[w] << "?\n";
for (P Q : v) {
if (!inCircle(v[l], v[w], v[r], Q)) {return make_pair(false, -1);}
}
return make_pair(true, w);
}
void reset(int n) {
v.clear();
// for (int i = 0; i < n + 5; i++) {
// g[i].clear();
// child[i].clear();
// }
t = 1;
}
void solve() {
cin >> n;
reset(n);
vector<P> pts(n);
for (int i = 0; i < n; i++) {
cin >> pts[i];
}
vector<P> us{pts[0], pts[1]};
vector<int> us_vals;
v = convexHull(pts);
n = v.size();
for (auto P : us) {
int i = 0; bool hit = false;
for (auto Q : v) {
if (P == Q) {us_vals.push_back(i); hit = true;}
i++;
}
if (!hit) {cout << 0 << '\n'; return;}
}
if (v.size() <= 3) {cout << 1 << '\n'; return;}
queue<pair<pair<int, int>, int>> q;
vector<int> child[MAX];
q.push(make_pair(make_pair(us_vals[0], us_vals[1]), -1));
q.push(make_pair(make_pair(us_vals[1], us_vals[0]), -1));
while (!q.empty()) {
auto p = q.front();
q.pop();
pair<bool, int> resp = check(p.first.first, p.first.second);
if (!resp.first) {cout << 0 << '\n'; return;}
if (resp.second == -1) {continue;}
q.push(make_pair(make_pair(p.first.first, resp.second), t));
q.push(make_pair(make_pair(resp.second, p.first.second), t));
if (p.second != -1) {
child[p.second].push_back(t);
}
t++;
}
// for (int i = 1; i <= n - 2; i++) {
// cout << i << ": ";
// for (int j : child[i]) {cout << j << ' ';}
// cout << '\n';
// }
bool edge_case = true; // both 1 and 2 are roots
for (int j : child[1]) {
if (j == 2) {edge_case = false;} // only 1 is root
}
vector<long long> dp(n + 7);
vector<int> sz(n + 7);
auto cnt = [&](auto self, int v) -> int {
if (sz[v] != -1) {return sz[v];}
int res = 1;
if (!child[v].empty()) {
for (int u : child[v]) {
res += self(self, u);
}
}
sz[v] = res;
return res;
};
auto f = [&](auto self, int v) -> long long {
if (dp[v] != -1LL) {return dp[v];}
long long res = 1LL;
if (!child[v].empty()) {
res = (res * fact[cnt(cnt, v) - 1]) % MOD;
for (int u : child[v]) {
res = (res * self(self, u)) % MOD;
res = (res * invfact[cnt(cnt, u)]) % MOD;
}
}
dp[v] = res;
return res;
};
if (edge_case) {child[1].push_back(2);}
fill(dp.begin(), dp.end(), -1LL);
fill(sz.begin(), sz.end(), -1);
long long res = f(f, 1);
if (edge_case) {
child[1].erase(remove(child[1].begin(), child[1].end(), 2), child[1].end());
child[2].push_back(1);
fill(dp.begin(), dp.end(), -1LL);
fill(sz.begin(), sz.end(), -1);
res = (res + f(f, 2)) % MOD;
}
cout << res << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
inv[0] = inv[1] = 1;
for (int i = 2; i < MAX; i++) {
inv[i] = MOD - (long long)(MOD / i) * inv[MOD % i] % MOD;
}
fact[0] = fact[1] = 1; invfact[0] = invfact[1] = 1;
for (int i = 2; i < MAX; i++) {
fact[i] = (fact[i - 1] * (long long)i) % MOD;
invfact[i] = (invfact[i - 1] * inv[i]) % MOD;
}
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1985
|
A
|
Creating Words
|
Matthew is given two strings $a$ and $b$, both of length $3$. He thinks it's particularly funny to create two new words by swapping the first character of $a$ with the first character of $b$. He wants you to output $a$ and $b$ after the swap.
Note that the new words may not necessarily be different.
|
To swap the first character of the strings, you can use the built-in method std::swap in C++, or for each string, separate the first character from the rest of the string and concatenate it with the other string.
|
[
"implementation",
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
string a, b; cin >> a >> b;
swap(a[0], b[0]);
cout << a << " " << b << endl;
}
}
|
1985
|
B
|
Maximum Multiple Sum
|
Given an integer $n$, find an integer $x$ such that:
- $2 \leq x \leq n$.
- The sum of multiples of $x$ that are less than or equal to $n$ is maximized. Formally, $x + 2x + 3x + \dots + kx$ where $kx \leq n$ is maximized over all possible values of $x$.
|
To maximize the number of multiples of $x$ less than $n$, it optimal to choose a small $x$, in this case, $2$. The only exception is $n = 3$, where it is optimal to choose $3$ instead, since both $2$ and $3$ have only one multiple less than $3$.
|
[
"brute force",
"math",
"number theory"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
int n; cin >> n;
cout << (n == 3 ? 3 : 2) << endl;
}
}
|
1985
|
C
|
Good Prefixes
|
Alex thinks some array is good if there exists some element that can be represented as the sum of all \textbf{other} elements (the sum of all other elements is $0$ if there are no other elements). For example, the array $[1,6,3,2]$ is good since $1+3+2=6$. Furthermore, the array $[0]$ is also good. However, the arrays $[1,2,3,4]$ and $[1]$ are not good.
Alex has an array $a_1,a_2,\ldots,a_n$. Help him count the number of good non-empty prefixes of the array $a$. In other words, count the number of integers $i$ ($1 \le i \le n$) such that the length $i$ prefix (i.e. $a_1,a_2,\ldots,a_i$) is good.
|
The only element that can be the sum of all other elements is the maximum element, since all elements are positive. Therefore, for each prefix $i$ from $1$ to $n$, check if $sum(a_1, a_2, ..., a_i) - max(a_1, a_2, ..., a_i) = max(a_1, a_2, ..., a_i)$. The sum and max of prefixes can be tracked with variables outside the loop.
|
[
"greedy"
] | 1,000
|
#include <iostream>
using namespace std;
int main(){
int t; cin >> t;
while(t--){
int n; cin >> n;
int a[n];
for(int i = 0; i < n; i++)
cin >> a[i];
long long sum = 0;
int mx = 0, ans = 0;;
for(int i = 0; i < n; i++){
sum += a[i];
mx = max(mx, a[i]);
if(sum - mx == mx)
ans++;
}
cout << ans << endl;
}
}
|
1985
|
D
|
Manhattan Circle
|
Given a $n$ by $m$ grid consisting of '.' and '#' characters, there exists a whole manhattan circle on the grid. The top left corner of the grid has coordinates $(1,1)$, and the bottom right corner has coordinates $(n, m)$.
Point ($a, b$) belongs to the manhattan circle centered at ($h, k$) if $|h - a| + |k - b| < r$, where $r$ is a positive constant.
On the grid, the set of points that are part of the manhattan circle is marked as '#'. Find the coordinates of the center of the circle.
|
Note that the manhattan circle is always in a diamond shape, symmetric from the center. Let's take notice of some special characteristics that can help us. One way is to find the top and bottom points of the circle. Note that these points will have columns at the center of the circle, so here we can acquire the value of $k$. To find $h$, since the circle is symmetric, it is just the middle of the rows of the top and bottom points. Note that we never needed to find the value of $r$.
|
[
"implementation",
"math"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main(){
int t; cin >> t;
while(t--){
int n, m; cin >> n >> m;
vector<vector<char>> g(n, vector<char>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> g[i][j];
}
}
pair<int, int> top = {INF, INF}, bottom = {-INF, -INF};
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(g[i][j] == '#'){
top = min(top, {i, j});
bottom = max(bottom, {i, j});
}
}
}
assert(top.second == bottom.second);
cout << (top.first + bottom.first) / 2 + 1 << " " << top.second + 1 << endl;
}
}
|
1985
|
E
|
Secret Box
|
Ntarsis has a box $B$ with side lengths $x$, $y$, and $z$. It lies in the 3D coordinate plane, extending from $(0,0,0)$ to $(x,y,z)$.
Ntarsis has a secret box $S$. He wants to choose its dimensions such that all side lengths are positive integers, and the volume of $S$ is $k$. He can place $S$ somewhere within $B$ such that:
- $S$ is parallel to all axes.
- every corner of $S$ lies on an integer coordinate.
$S$ is magical, so when placed at an integer location inside $B$, it will not fall to the ground.
Among all possible ways to choose the dimensions of $S$, determine the \textbf{maximum} number of distinct locations he can choose to place his secret box $S$ inside $B$. Ntarsis does not rotate $S$ once its side lengths are selected.
|
Since the side lengths of $S$ has to multiply to $k$, all three side lengths of $S$ has to be divisors of $k$. Let's denote the side lengths of $S$ along the $x$, $y$, and $z$ axes as $a$, $b$, and $c$ respectively. For $S$ to fit in $B$ , $a \leq x$, $b \leq y$, and $c \leq z$ must hold. Because of the low constraints, we can afford to loop through all possible values of $a$ and $b$, and deduce that $c=\frac{k}{a \cdot b}$ (make sure $c \leq z$ and $c$ is an integer). To get the amount of ways we can place $S$, we can just multiply the amount of shifting space along each axes, and that just comes down to $(x-a+1) \cdot (y-b+1) \cdot (z-c+1)$. The answer is the maximum among all possible values of $a$, $b$, and $c$ . The time complexity is $\mathcal{O}(n^2)$ where $n$ is at most $2000$.
|
[
"brute force",
"combinatorics",
"math"
] | 1,200
|
#include <iostream>
using namespace std;
using ll = long long;
int main(){
int t; cin >> t;
while(t--){
ll x, y, z, k; cin >> x >> y >> z >> k;
ll ans = 0;
for(int a = 1; a <= x; a++){
for(int b = 1; b <= y; b++){
if(k % (a * b)) continue;
ll c = k / (a * b);
if(c > z) continue;
ll ways = (ll)(x - a + 1) * (y - b + 1) * (z - c + 1);
ans = max(ans, ways);
}
}
cout << ans << "\n";
}
}
|
1985
|
F
|
Final Boss
|
You are facing the final boss in your favorite video game. The boss enemy has $h$ health. Your character has $n$ attacks. The $i$'th attack deals $a_i$ damage to the boss but has a cooldown of $c_i$ turns, meaning the next time you can use this attack is turn $x + c_i$ if your current turn is $x$. Each turn, you can use all attacks that are not currently on cooldown, \textbf{all at once}. If all attacks are on cooldown, you do nothing for the turn and skip to the next turn.
Initially, all attacks are not on cooldown. How many turns will you take to beat the boss? The boss is beaten when its health is $0$ or less.
|
Unfortunately, there was a lot of hacks on this problem, and we're sorry for it. Since our intended solution is not binary search, we didn't really take overflow using binary search seriously. I (cry) prepared this problem and I only took into account about overflow with big cooldown, but I forgot overflow can happen on attacks as well. I apologize and we will do better next time! Since the sum of $h$ is bounded by $2 \cdot 10^5$, and each attack deals at least $1$ damage. If we assume every turn we can make at least one attack, the sum of turns to kill the boss in every test case is bounded by $2 \cdot 10^5$. This means that we can afford to simulate each turn where we make at least one attack. But what if we cannot make an attack on this turn? Since the cooldown for each attack can be big, we cannot increment turns one by one. We must jump to the next turn we can make an attack. This can be done by retrieving the first element of a sorted set, where the set stores pairs {$t$, $i$} which means {next available turn you can use this attack, index of this attack} for all $i$. Here, we can set the current turn to $t$ and use all attacks in the set with first element in the pair equal to $t$. Remember to insert the pair to {$c_i + t$, $i$} back into the set after processing the attacks. The time complexity is $\mathcal{O}(h \log n)$. Try to solve this if $1 \le h \le 10^9$. We can do this by binary searching for the answer. For some time $t$, we know that we can perform an attack of cooldown $c$ exactly $\lfloor \frac{t - 1}{c} \rfloor + 1$ times. The total damage we will do in time $t$ will be: $\displaystyle \sum_{i=1}^{n}{a_i\left( \lfloor\frac{t - 1}{c_i}\rfloor + 1 \right)}$ So we binary search for the first $t$ such that the total damage we do in time $t$ is greater than or equal to $h$. This runs in $\mathcal{O(n \log {(h \cdot \max c_i)})}$. Be careful of long long overflow!
|
[
"binary search",
"data structures"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
void solve(){
ll h, n;
cin >> h >> n;
vector<ll> A(n), C(n);
for (ll &i : A)
cin >> i;
for (ll &i : C)
cin >> i;
auto chk = [&](ll t){
ll dmg = 0;
for (int i = 0; i < n and dmg < h; i++){
ll cnt = (t - 1) / C[i] + 1;
if (cnt >= h)
return true;
dmg += cnt * A[i];
}
return dmg >= h;
};
ll L = 1, H = 1e12;
while (L < H){
ll M = (L + H) / 2;
chk(M) ? H = M : L = M + 1;
}
cout << L << "\n";
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int tc;
cin >> tc;
while (tc--)
solve();
}
|
1985
|
G
|
D-Function
|
Let $D(n)$ represent the sum of digits of $n$. For how many integers $n$ where $10^{l} \leq n < 10^{r}$ satisfy $D(k \cdot n) = k \cdot D(n)$? Output the answer modulo $10^9+7$.
|
To satisfy $D(k \cdot n) = k \cdot D(n)$, each digit $d$ in $n$ must become $k \cdot d$ after multiplying $n$ by $k$. In other words, none of $n$'s digits can carry over to the next digit upon multiplication. From this, we can deduce that each digit in $n$ must be less than or equal to $\lfloor \frac{9}{k} \rfloor$. Only thing left is to count all such numbers in the range of $10^l$ inclusive and $10^r$ exclusive. Every number below ${10}^r$ has $r$ or less digits. For numbers with less than $r$ digits, let's pad the beginning with zeroes until it becomes a $r$ digit number (for example, if $r = 5$, then $69$ becomes $00069$). This allows us to consider numbers with less than $r$ digits the same way as numbers with exactly $r$ digits. For each digit, we have $\lfloor \frac{9}{k} \rfloor + 1$ choices (including zero), and there are $r$ digits, so the total number of numbers that satisfies the constraint below ${10}^r$ is $(\lfloor \frac{9}{k} \rfloor + 1)^r$. To get the count of numbers in range, it suffices to subtract all valid numbers less than $10^l$. Therefore, the answer is $(\lfloor \frac{9}{k} \rfloor + 1)^r - (\lfloor \frac{9}{k} \rfloor + 1)^l$. To exponentiate fast, we can use modular exponentiation.
|
[
"combinatorics",
"math",
"number theory"
] | 1,600
|
MOD = int(1e9+7)
t = int(input())
for _ in range(t):
l, r, k = map(int, input().split())
print((pow(9 // k + 1, r, MOD) - pow(9 // k + 1, l, MOD) + MOD) % MOD)
|
1985
|
H1
|
Maximize the Largest Component (Easy Version)
|
\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. The only difference between the two versions is the operation.}
Alex has a grid with $n$ rows and $m$ columns consisting of '.' and '#' characters. A set of '#' cells forms a connected component if from any cell in this set, it is possible to reach any other cell in this set by only moving to another cell in the set that shares a \textbf{common side}. The size of a connected component is the number of cells in the set.
In one operation, Alex selects any row $r$ ($1 \le r \le n$) \textbf{or} any column $c$ ($1 \le c \le m$), then sets every cell in row $r$ \textbf{or} column $c$ to be '#'. Help Alex find the maximum possible size of the largest connected component of '#' cells that he can achieve after performing the operation \textbf{at most once}.
|
Let's first solve the problem if we can only select and fill rows. Columns can be handled in the exact same way. For each row $r$, we need to find the size of the component formed by filling row $r$ (i.e. the size of the component containing row $r$ if we set all cells in row $r$ to be $\texttt{#}$). The size of the component containing row $r$ if we set all cells in row $r$ to be $\texttt{#}$ will be the sum of: The number of $\texttt{.}$ in row $r$ since these cells will be set to $\texttt{#}$. Let $F_r$ denote this value for some row $r$. The sum of sizes of components containing a cell in either row $r-1$, $r$, or $r+1$ (i.e. components that are touching row $r$). This is since these components will be part of the component containing row $r$. Let $R_r$ denote this value for some row $r$. The challenge is computing the second term quickly. For some component, let $s$ be the size of the component and let $r_{min}$ and $r_{max}$ denote the minimum and maximum row of a cell in the component. This means that the component will contain cells with rows $r_{min},r_{min+1},...,r_{max}$. Note that we can find these values with a dfs. Since the component will contribute $s$ to rows in $[r_{min}-1,r_{min},\ldots r_{max}+1]$, we add $s$ to $R_{r_{min}-1},R_{r_{min}},\ldots,R_{r_{max}+1}$. This can be done naively or with prefix sums. We find the maximum $F_r+R_r$ and then handle columns in the same way. This solution runs in $\mathcal{O}(nm)$ time.
|
[
"brute force",
"data structures",
"dfs and similar",
"dsu",
"graphs",
"implementation"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int n, m, minR, maxR, minC, maxC, sz, ans; vector<int> R, C, freeR, freeC;
vector<vector<bool>> vis; vector<vector<char>> A;
void dfs(int i, int j){
if (i <= 0 or i > n or j <= 0 or j > m or vis[i][j] or A[i][j] == '.')
return;
vis[i][j] = true;
sz++;
minR = min(minR, i);
maxR = max(maxR, i);
minC = min(minC, j);
maxC = max(maxC, j);
dfs(i - 1, j);
dfs(i + 1, j);
dfs(i, j - 1);
dfs(i, j + 1);
}
void solve(){
cin >> n >> m;
R.assign(n + 5, 0);
C.assign(m + 5, 0);
freeR.assign(n + 5, 0);
freeC.assign(m + 5, 0);
vis.assign(n + 5, vector<bool>(m + 5, false));
A.assign(n + 5, vector<char>(m + 5, ' '));
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cin >> A[i][j];
if (A[i][j] == '.'){
freeR[i]++;
freeC[j]++;
}
}
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
if (vis[i][j] or A[i][j] == '.')
continue;
// Reset
sz = 0;
minR = 1e9;
maxR = -1e9;
minC = 1e9;
maxC = -1e9;
dfs(i, j);
// Expand by 1 since adjacent cells also connect
minR = max(minR - 1, 1);
maxR = min(maxR + 1, n);
minC = max(minC - 1, 1);
maxC = min(maxC + 1, m);
// Update prefix sums
R[minR] += sz;
R[maxR + 1] -= sz;
C[minC] += sz;
C[maxC + 1] -= sz;
}
}
ans = 0;
for (int i = 1; i <= n; i++){
R[i] += R[i - 1];
ans = max(ans, freeR[i] + R[i]);
}
for (int i = 1; i <= m; i++){
C[i] += C[i - 1];
ans = max(ans, freeC[i] + C[i]);
}
cout << ans << "\n";
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int tc;
cin >> tc;
while (tc--)
solve();
}
|
1985
|
H2
|
Maximize the Largest Component (Hard Version)
|
\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. The only difference between the two versions is the operation.}
Alex has a grid with $n$ rows and $m$ columns consisting of '.' and '#' characters. A set of '#' cells forms a connected component if from any cell in this set, it is possible to reach any other cell in this set by only moving to another cell in the set that shares a \textbf{common side}. The size of a connected component is the number of cells in the set.
In one operation, Alex selects any row $r$ ($1 \le r \le n$) \textbf{and} any column $c$ ($1 \le c \le m$), then sets every cell in row $r$ \textbf{and} column $c$ to be '#'. Help Alex find the maximum possible size of the largest connected component of '#' cells that he can achieve after performing the operation \textbf{at most once}.
|
For each row $r$ and column $c$, we need to find the size of the component formed by filling both row $r$ and column $c$ (i.e. the size of the component containing row $r$ and column $c$ if we set all cells in both row $r$ and column $c$ to be $\texttt{#}$). Extending the reasoning in H1, for some row $r$ and column $c$, consider the sum of: The number of $\texttt{.}$ in row $r$ or column $c$ since these cells will be set to $\texttt{#}$. Let $F_{r,c}$ denote this value for some row $r$ and column $c$. The sum of sizes of components containing a cell in either row $r-1$, $r$, or $r+1$ (i.e. components that are touching row $r$). This is since these components will be part of the component containing row $r$ and column $c$. Let $R_r$ denote this value for some row $r$. The sum of sizes of components containing a cell in either column $c-1$, $c$, or $c+1$ (i.e. components that are touching column $c$). This is since these components will be part of the component containing row $r$ and column $c$. Let $C_c$ denote this value for some column $c$. However, components that contain a cell in either row $r-1$, $r$, or $r+1$ as well as in either column $c-1$, $c$, or $c+1$ will be overcounted (since it will be counted in both terms $2$ and $3$) (you can think of it as components touching both row $r$ and column $c$). Thus, we need to subtract the sum of sizes of components that contain a cell in either row $r-1$, $r$, or $r+1$ as well as in either column $c-1$, $c$, or $c+1$. Let $B_{r,c}$ denote this for some row $r$ and column $c$. Then the size of the component formed by filling both row $r$ and column $c$ will be $F_{r,c}+R_r+C_c-B_{r,c}$ and we want to find the maximum value of this. Let's try to calculate these values efficiently. Consider some component. Let $s$ be its size. Let $r_{min}$ and $r_{max}$ denote the minimum and maximum row of a cell in the component. This means that the component contains cells with rows $r_{min},r_{min+1},...,r_{max}$. Let $c_{min}$ and $c_{max}$ denote the minimum and maximum column of a cell in the component. This means that the component contains cells with columns $c_{min},c_{min+1},...,c_{max}$. All these values can be found with a dfs. We then do the following updates: Add $s$ to $R_{r_{min}-1},R_{r_{min}},\ldots,R_{r_{max}+1}$. This can be done naively or with prefix sums. Add $s$ to $C_{c_{min}-1},C_{c_{min}},\ldots,C_{c_{max}+1}$. This can be done naively or with prefix sums. Add $s$ to the subrectangle of $B$ with top left at ($r_{min}-1,c_{min}-1$) and bottom right at ($r_{max}+1,c_{max}+1$). This can be done with 2D prefix sums. (Note that doing this naively will pass because of low constant factor and the fact that we could not cut this solution without cutting slow correct solutions.) We do this for each component. Also, calculating $F_{r,c}$ can be done by looking at the number of $\texttt{.}$ in row $r$, column $c$, and checking whether we overcounted a $\texttt{.}$ at ($r,c$). In all, this solution runs in $\mathcal{O}(nm)$ time.
|
[
"data structures",
"dfs and similar",
"dp",
"dsu",
"implementation"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
int n, m, minR, maxR, minC, maxC, sz, ans; vector<int> R, C, freeR, freeC;
vector<vector<int>> RC; vector<vector<bool>> vis; vector<vector<char>> A;
void dfs(int i, int j){
if (i <= 0 or i > n or j <= 0 or j > m or vis[i][j] or A[i][j] == '.')
return;
vis[i][j] = true;
sz++;
minR = min(minR, i);
maxR = max(maxR, i);
minC = min(minC, j);
maxC = max(maxC, j);
dfs(i - 1, j);
dfs(i + 1, j);
dfs(i, j - 1);
dfs(i, j + 1);
}
void solve(){
cin >> n >> m;
R.assign(n + 5, 0);
C.assign(m + 5, 0);
freeR.assign(n + 5, 0);
freeC.assign(m + 5, 0);
RC.assign(n + 5, vector<int>(m + 5, 0));
vis.assign(n + 5, vector<bool>(m + 5, false));
A.assign(n + 5, vector<char>(m + 5, ' '));
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cin >> A[i][j];
if (A[i][j] == '.'){
freeR[i]++;
freeC[j]++;
}
}
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
if (vis[i][j] or A[i][j] == '.')
continue;
// Reset
sz = 0;
minR = 1e9;
maxR = -1e9;
minC = 1e9;
maxC = -1e9;
dfs(i, j);
// Expand by 1 since adjacent cells also connect
minR = max(minR - 1, 1);
maxR = min(maxR + 1, n);
minC = max(minC - 1, 1);
maxC = min(maxC + 1, m);
// Update prefix sums
R[minR] += sz;
R[maxR + 1] -= sz;
C[minC] += sz;
C[maxC + 1] -= sz;
RC[minR][minC] += sz;
RC[maxR + 1][minC] -= sz;
RC[minR][maxC + 1] -= sz;
RC[maxR + 1][maxC + 1] += sz;
}
}
for (int i = 1; i <= n; i++)
R[i] += R[i - 1];
for (int i = 1; i <= m; i++)
C[i] += C[i - 1];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
RC[i][j] += RC[i - 1][j] + RC[i][j - 1] - RC[i - 1][j - 1];
ans = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
ans = max(ans, (R[i] + C[j] - RC[i][j]) + (freeR[i] + freeC[j] - (A[i][j] == '.')));
cout << ans << "\n";
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int tc;
cin >> tc;
while (tc--)
solve();
}
|
1986
|
A
|
X Axis
|
You are given three points with integer coordinates $x_1$, $x_2$, and $x_3$ on the $X$ axis ($1 \leq x_i \leq 10$). You can choose any point with an integer coordinate $a$ on the $X$ axis. Note that the point $a$ may coincide with $x_1$, $x_2$, or $x_3$. Let $f(a)$ be the total distance from the given points to the point $a$. Find the smallest value of $f(a)$.
The distance between points $a$ and $b$ is equal to $|a - b|$. For example, the distance between points $a = 5$ and $b = 2$ is $3$.
|
Let $x_1 \leq x_2 \leq x_3$. Notice that the answer is at least $x_3 - x_1$, because $|x_3 - a| + |x_1 - a| \geq |x_3 - x_1|$ for any numbers $a$, $x_1$, $x_3$. The answer is equal to $x_3 - x_1$, since we can choose $a = x_2$.
|
[
"brute force",
"geometry",
"math",
"sortings"
] | 800
| null |
1986
|
B
|
Matrix Stabilization
|
You are given a matrix of size $n \times m$, where the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The element at the intersection of the $i$-th row and the $j$-th column is denoted by $a_{ij}$.
Consider the algorithm for stabilizing matrix $a$:
- Find the cell $(i, j)$ such that its value is strictly greater than the values of all its neighboring cells. If there is no such cell, terminate the algorithm. If there are multiple such cells, choose the cell with the smallest value of $i$, and if there are still multiple cells, choose the one with the smallest value of $j$.
- Set $a_{ij} = a_{ij} - 1$.
- Go to step $1$.
In this problem, cells $(a, b)$ and $(c, d)$ are considered neighbors if they share a common side, i.e., $|a - c| + |b - d| = 1$.
Your task is to output the matrix $a$ after the stabilization algorithm has been executed. It can be shown that this algorithm cannot run for an infinite number of iterations.
|
Let's consider any two adjacent cells of the matrix. Notice that our algorithm can change at most one value of these two cells. If the values in the cells are equal, then neither of these two adjacent cells will ever change its value. If the values in the cells are not equal, then the value of the larger cell will never become smaller than the value of the smaller cell. Let $mx$ be the maximum value written in the cells adjacent to $(i, j)$. If $mx \geq a_{ij}$, then the value of the cell $(i, j)$ will not change during the execution of the algorithm; otherwise, it will eventually become equal to $mx$.
|
[
"brute force",
"data structures",
"greedy",
"sortings"
] | 1,000
| null |
1986
|
C
|
Update Queries
|
Let's consider the following simple problem. You are given a string $s$ of length $n$, consisting of lowercase Latin letters, as well as an array of indices $ind$ of length $m$ ($1 \leq ind_i \leq n$) and a string $c$ of length $m$, consisting of lowercase Latin letters. Then, in order, you perform the update operations, namely, during the $i$-th operation, you set $s_{ind_i} = c_i$. Note that you perform all $m$ operations from the first to the last.
Of course, if you change the order of indices in the array $ind$ and/or the order of letters in the string $c$, you can get different results. Find the lexicographically smallest string $s$ that can be obtained after $m$ update operations, if you can rearrange the indices in the array $ind$ and the letters in the string $c$ as you like.
A string $a$ is lexicographically less than a string $b$ if and only if one of the following conditions is met:
- $a$ is a prefix of $b$, but $a \neq b$;
- in the first position where $a$ and $b$ differ, the symbol in string $a$ is earlier in the alphabet than the corresponding symbol in string $b$.
|
Let $i_1 < i_2 < \ldots < i_k$ be the set of indices of the array $ind$. Note that the indices of the string $s$ that are not in this set will simply not change their value. Then we want to place the smallest character of the string $c$ at position $i_1$, the next smallest at position $i_2$, and so on. To achieve this, we can sort all the characters in the string $c$. This approach to obtaining the answer is possible because all other operations, except those described above, can be performed first and will not affect the answer.
|
[
"data structures",
"greedy",
"sortings"
] | 1,100
| null |
1986
|
D
|
Mathematical Problem
|
You are given a string $s$ of length $n > 1$, consisting of digits from $0$ to $9$. You must insert exactly $n - 2$ symbols $+$ (addition) or $\times$ (multiplication) into this string to form a valid arithmetic expression.
In this problem, the symbols cannot be placed before the first or after the last character of the string $s$, and two symbols cannot be written consecutively. Also, note that the order of the digits in the string cannot be changed. Let's consider $s = 987009$:
- From this string, the following arithmetic expressions can be obtained: $9 \times 8 + 70 \times 0 + 9 = 81$, $98 \times 7 \times 0 + 0 \times 9 = 0$, $9 + 8 + 7 + 0 + 09 = 9 + 8 + 7 + 0 + 9 = 33$. Note that the number $09$ is considered valid and is simply transformed into $9$.
- From this string, the following arithmetic expressions cannot be obtained: $+9 \times 8 \times 70 + 09$ (symbols should only be placed between digits), $98 \times 70 + 0 + 9$ (since there are $6$ digits, there must be exactly $4$ symbols).
The result of the arithmetic expression is calculated according to the rules of mathematics — first all multiplication operations are performed, then addition. You need to find the minimum result that can be obtained by inserting exactly $n - 2$ addition or multiplication symbols into the given string $s$.
|
First, let's iterate through the position $i$, such that we do not place a mathematical sign between the $i$-th and $(i+1)$-th elements. Next, we have the following task - we have $n - 1$ numbers and we need to place a $+$ or $\times$ sign between each pair of neighboring numbers to minimize the result. There are three possible cases: If there is at least one $0$, the answer is $0$. We can simply place all signs as $\times$. If all numbers are $1$, the answer is $1$. We can simply place all signs as $\times$. Otherwise, the answer is the sum of numbers not equal to $1$. It is not advantageous to multiply numbers greater than one with each other, and all ones can simply be multiplied by any of the neighbors.
|
[
"brute force",
"dp",
"greedy",
"implementation",
"math",
"two pointers"
] | 1,400
| null |
1986
|
E
|
Beautiful Array
|
You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $k$. You need to make it beautiful with the least amount of operations.
Before applying operations, you can shuffle the array elements as you like. For one operation, you can do the following:
- Choose an index $1 \leq i \leq n$,
- Make $a_i = a_i + k$.
The array $b_1, b_2, \ldots, b_n$ is beautiful if $b_i = b_{n - i + 1}$ for all $1 \leq i \leq n$.
Find the minimum number of operations needed to make the array beautiful, or report that it is impossible.
|
Notice that we actually want to pair the elements (in the odd case, exactly one element will not have a pair). If numbers $x \leq y$ fall into the same pair, then: These two numbers should have the same remainder when divided by $k$. This is necessary in order to obtain one from the other. To make them equal, we will need $\frac{y - x}{k} = \frac{y}{k} - \frac{x}{k}$ operations. Consider all numbers from the array $a$ with the same remainder when divided by $k$. Also, immediately divide them by the number $k$. Let these numbers be $b_1 \leq b_2 \leq \ldots \leq b_m$. There are two possible cases: If $m$ is even, we need to pair all the numbers. It is best to pair $b_1$ and $b_2$, $b_3$ and $b_4$, and so on. Consequently, we will need $b_2 - b_1 + b_4 - b_3 + \ldots + b_{n} - b_{n - 1}$ operations. If $m$ is odd, one element will remain unpaired. It can be tried and then an even number of elements will remain, and we can apply the idea for the even case. Notice that it is advantageous to remove the element with an odd index (denote it as $i$). Then, if we leave the $i$-th element unpaired, we will need $b_2 - b_1 + b_4 - b_3 + \ldots + b_{i - 1} - b_{i - 2} + b_{i + 2} - b_{i + 1} + \ldots b_n - b_{n - 1}$ operations. To quickly calculate this sum, you can use prefix/suffix sums. Also, note that if there are two different remainders for which $m$ is odd, the answer is $-1$.
|
[
"greedy",
"math",
"number theory",
"sortings"
] | 1,700
| null |
1986
|
F
|
Non-academic Problem
|
You are given a connected undirected graph, the vertices of which are numbered with integers from $1$ to $n$. Your task is to minimize the number of pairs of vertices $1 \leq u < v \leq n$ between which there exists a path in this graph. To achieve this, you can remove exactly one edge from the graph.
Find the smallest number of pairs of vertices!
|
Notice that if an edge is not a bridge, then after its removal the graph remains connected and all vertices are reachable from each other. Therefore, we would like to remove some bridge edge (if there are no bridges, the answer is $\frac{n \cdot (n - 1)}{2}$). After its removal, the graph will split into two connected components, let their sizes be $x$ and $y$ (note that $x + y = n$). Then the number of pairs of vertices reachable from each other will be equal to $\frac{x \cdot (x - 1)}{2} + \frac{y \cdot (y - 1)}{2}$. Let's find all the bridges in the graph, run a $dfs$ from an arbitrary vertex and calculate for each vertex the size of its subtree in the $dfs$ traversal tree (denote the size of the subtree of vertex $v$ as $sz_v$). Thus, for each bridge, we can find $x$ and $y$, knowing the sizes of the subtrees (if the edge $(u, v)$ is a bridge, then $x = \min(sz_x, sz_y), y = n - x$). For all bridges, output the smallest answer.
|
[
"dfs and similar",
"graphs",
"trees"
] | 1,900
| null |
1986
|
G2
|
Permutation Problem (Hard Version)
|
\textbf{This is the hard version of the problem. The only difference is that in this version $n \leq 5 \cdot 10^5$ and the sum of $n$ for all sets of input data does not exceed $5 \cdot 10^5$.}
You are given a permutation $p$ of length $n$. Calculate the number of index pairs $1 \leq i < j \leq n$ such that $p_i \cdot p_j$ is divisible by $i \cdot j$ without remainder.
A permutation is a sequence of $n$ integers, in which each integer from $1$ to $n$ occurs exactly once. For example, $[1]$, $[3,5,2,1,4]$, $[1,3,2]$ are permutations, while $[2,3,2]$, $[4,3,1]$, $[0]$ are not.
|
Let $a_i = \frac{p_i}{\gcd(i, p_i)}$, $b_i = \frac{i}{\gcd(i, p_i)}$. Notice that we want to calculate the number of index pairs $i < j$, such that: $a_j$ is divisible by $b_i$. $a_i$ is divisible by $b_j$. Let's iterate through the values of $b_i$ from $1$ to $n$ (note that we are not fixing the element $i$, but rather fixing the value of $b_i$). Now we know that we are interested in all $a_j = b_i \cdot k$, for some positive integer $k$. Let's iterate through all such possible $a_j$, and then iterate through all pairs with that value of $a_j$. Add all suitable $b_j$ to the count array. Now, for a fixed $b_i$ and the constructed count array for it, iterate through all $a_i$ that exist with this $b_i$. We can iterate through all divisors of $a_i$ and simply add their count from the count array to the answer, because: Only those pairs for which $a_j$ is divisible by $b_i$ are considered in the count array, so we have accounted for the first condition. We have accounted for the second condition when iterating through the divisors of $a_i$. If the above is implemented correctly, a solution can be obtained in $O(n \log n)$. For this, we will need to pre-calculate all divisors for each $i$ from $1$ to $n$. We can iterate through $i$ and mark it as a divisor for all numbers of the form $k \cdot i$. Also, everything written above works in $O(n \log n)$, because: the array $a$ was obtained from a permutation by dividing some elements, so the total number of divisors of all elements in $a$ (as well as the array $b$) is no more than the total number of divisors of numbers from $1$ to $n$. And the total number of divisors of numbers from $1$ to $n$ is at most $\sum\limits_{i=1}^n \frac{n}{i} = O(n \log n)$.
|
[
"brute force",
"data structures",
"hashing",
"math",
"number theory"
] | 2,500
| null |
1987
|
A
|
Upload More RAM
|
Oh no, the ForceCodes servers are running out of memory! Luckily, you can help them out by uploading some of your RAM!
You want to upload $n$ GBs of RAM. Every second, you will upload either $0$ or $1$ GB of RAM. However, there is a restriction on your network speed: in any $k$ consecutive seconds, you can upload only at most $1$ GB of RAM in total.
Find the minimum number of seconds needed to upload $n$ GBs of RAM!
|
First of all, note that you can upload $n$ GBs of RAM if you upload on the seconds $1, k + 1, 2k + 1, \ldots, (n - 1)k + 1$, taking $(n - 1)k + 1$ seconds in total. Let's show that it's impossible to do better. Suppose there is a solution where you upload on the times $t_1, t_2, \ldots t_n$, taking $t_n$ seconds to upload $n$ GBs. Then, $t_{i} + k \le t_{i + 1}$ for all $1 \le i \le n - 1$. Furthermore, $t_1 \ge 1$. Thus, we have the following inequalities: $1 \le t_1$ $t_1 + k \le t_2$ $t_2 + k \le t_3$ $\ldots$ $t_{n - 1} + k \le t_n$ Using them, we get the inequalities $1 \le t_1$ $1 + k \le t_1 + k \le t_2$ $1 + 2k \le t_2 + k \le t_3$ $\ldots$ $1 + (n - 1)k \le t_{n-1} + k \le t_n$ So, $t_n \ge (n - 1)k + 1$, so the answer is at least $(n - 1)k + 1$. Since there is always a way to upload in exactly this many seconds, this is the answer to our problem. Complexity: $\mathcal{O}(1)$
|
[
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
cout << 1 + (n - 1) * k << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1987
|
B
|
K-Sort
|
You are given an array of integers $a$ of length $n$.
You can apply the following operation any number of times (maybe, zero):
- First, choose an integer $k$ such that $1 \le k \le n$ and pay $k + 1$ coins.
- Then, choose \textbf{exactly} $k$ indices such that $1 \le i_1 < i_2 < \ldots < i_k \le n$.
- Then, for each $x$ from $1$ to $k$, increase $a_{i_x}$ by $1$.
Find the minimum number of coins needed to make $a$ non-decreasing. That is, $a_1 \le a_2 \le \ldots \le a_n$.
|
Suppose that after all of the operations, the value at index $i$ has been increased by $b_i$. Notice that our cost can be factored into two parts: $k$ is responsible for how many elements we choose, and $1$ is responsible for how many operations we apply. Since we have to apply at least $\max(b_i)$ operations, and over all operations we select a total of $\sum{b_i}$ elements, we have to pay at least $\sum{b_i} + \max(b_i)$ coins. This bound is also achievable, if on the $m$-th operation (numbered from $1$ to $\max(b_i)$) we select all indices with $b_i \ge m$. Suppose the resulting array is sorted ($a_1 + b_1 \le a_2 + b_2 \le \ldots \le a_n + b_n$). Then, $a_i + b_i \le a_j + b_j$ must hold for all $1 \le i \le j \le n$. Using $b_i \ge 0$, we get $a_j + b_j \ge a_i + b_i \ge a_i \implies b_j \ge a_i - a_j$ for all $1 \le i \le j$. If we define $p_j := max(a_1, \ldots, a_j)$, we get $b_j \ge p_j - a_j$. This gives the lower bounds $\sum{b_i} \ge \sum(p_i - a_i)$ and $\max(b_i) \ge \max(p_i - a_i)$. Setting $b_i := p_i - a_i$ achieves them, so the answer to our problem is $\sum(p_i - a_i) + \max(p_i - a_i)$ coins. Complexity: $\mathcal{O}(n)$ Note: it's possible to simulate the process on the values of $b$ (described above) in $\mathcal{O}(n \log n)$.
|
[
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
ll pref_max = 0, s = 0, mx = 0;
for (int i = 0; i < n; i++) {
pref_max = max(pref_max, (ll) a[i]);
ll d = pref_max - a[i];
s += d;
mx = max(mx, d);
}
cout << s + mx << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
solve();
}
}
|
1987
|
C
|
Basil's Garden
|
There are $n$ flowers in a row, the $i$-th of them initially has a positive height of $h_i$ meters.
Every second, the wind will blow from the left, causing the height of some flowers to decrease.
Specifically, every second, for each $i$ from $1$ to $n$, in this order, the following happens:
- If $i = n$ or $h_i > h_{i + 1}$, the value of $h_i$ changes to $\max(0, h_i - 1)$.
How many seconds will pass before $h_i=0$ for all $1 \le i \le n$ for the first time?
|
First, let's try to find when $h_{n}$ will first be equal to zero. The answer is clearly $h_{n}$. Suppose for some $2 \le i \le n$ we know that $h_{i}$ will first become equal to zero at time $t_{i}$ ($t_n = h_n$). If at some point in time, $h_{i-1}$ was equal to $h_{i}$ (at the start of the second and before they are both equal to zero), $t_{i-1}$ is equal to $t_{i} + 1$. Since after that point in time, if $h_{i}$ decreases, $h_{i-1}$ must decrease in the next second. If $h_{i-1}$ is never equal to $h_{i}$ (until they hit zero), $h_{i - 1}$ must always be strictly greater than $h_{i}$. This means that $h_{i-1}$ will keep decreasing every second until it hits zero, so $t_{i-1}$ is equal to $h_{i-1}$ in this case. Examples: The array $[2, 3, 1, 1, 1]$ changes as follows: $[2, \color{red}{3}, 1, 1, \color{red}{1}] \rightarrow [2, \color{red}{2}, 1, \color{red}{1}, 0] \rightarrow [\color{red}{2}, 1, \color{red}{1}, 0, 0] \rightarrow$ $[1, \color{red}{1}, 0, 0, 0] \rightarrow [\color{red}{1}, 0, 0, 0, 0] \rightarrow [0, 0, 0, 0, 0]$. If we focus on the first two elements, they change as follows: $[2, \color{red}{3}] \rightarrow [2, \color{red}{2}] \rightarrow [\color{red}{2}, 1] \rightarrow [1, 1] \rightarrow [1, \color{red}{1}] \rightarrow [\color{red}{1}, 0] \rightarrow [0, 0]$. The array $[4, 1, 1]$ changes as follows: $[\color{red}{4}, 1, \color{red}{1}] \rightarrow [\color{red}{3}, \color{red}{1}, 0] \rightarrow [\color{red}{2}, 0, 0] \rightarrow [\color{red}{1}, 0, 0] \rightarrow [0, 0, 0]$. Let's combine the two cases. If initially $h_{i-1} \le h_{i}$ holds, $h_{i-1}$ will become equal to $h_{i}$ at some point in time, so $t_{i-1} = t_{i} + 1$. Else, $h_{i-1} > h_{i}$, so $t_{i-1} = h_{i-1}$. Combining the two, we get $t_{i-1} = \max(h_{i-1}, t_{i} + 1)$. Since we know $t_n = h_n$, we can easily calculate all the other values of $t_i$ by iterating from $n - 1$ to $1$. The answer to the problem is $t_1$, since $t_{i-1} \ge t_{i} + 1$ for all $2 \le i \le n$. Complexity: $\mathcal{O}(n)$
|
[
"dp",
"greedy"
] | 1,200
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> h(n);
for (auto &x: h) cin >> x;
int ans = h[n - 1];
for (int i = n - 2; i >= 0; i--) {
ans = max(ans + 1, h[i]);
}
cout << ans << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) solve();
}
|
1987
|
D
|
World is Mine
|
Alice and Bob are playing a game. Initially, there are $n$ cakes, with the $i$-th cake having a tastiness value of $a_i$.
Alice and Bob take turns eating them, with Alice starting first:
- In her turn, Alice chooses and eats any remaining cake whose tastiness is \textbf{strictly greater} than the \textbf{maximum} tastiness of any of the cakes she's eaten before that. Note that on the first turn, she can choose any cake.
- In his turn, Bob chooses any remaining cake and eats it.
The game ends when the current player can't eat a suitable cake. Let $x$ be the number of cakes that Alice ate. Then, Alice wants to maximize $x$, while Bob wants to minimize $x$.
Find out how many cakes Alice will eat if both players play optimally.
|
Let's consider Alice's strategy. Notice that if both players play optimally, Alice eating a cake with a tastiness value of $t$ is equivalent to her eating all remaining cakes with $a_i \le t$. Since it is better for her to have more cakes to choose from later on, she will choose the minimum possible $t$ on each turn. Now let's consider Bob's strategy. Suppose Bob ate at least one cake with a tastiness value of $t$. Then he has to have eaten all of them, because eating only some of them does not affect Alice's possible moves, resulting in wasted turns (he might be forced to waste moves at the end of the game when there are some leftover cakes). Let $A_1, \ldots, A_m$ be the sorted unique values of $a_1, \ldots, a_n$, and let $c_i$ be the number of occurrences of $A_i$ in $a$. Then the game is reduced to Alice finding the first $c_i > 0$ and assigning $c_i := 0$, and Bob choosing any $c_i > 0$ and decreasing it by $1$. Since Bob's optimal strategy is for each $c_i$ either not to touch it or make $c_i = 0$, we can model it as him selecting some set of indices $1 \le i_1 < \ldots < i_k \le m$ and zeroing out $c_{i_1}, c_{i_2}, \ldots, c_{i_k}$ in this order. To be able to zero out $c_{i_p}$ ($1 \le p \le k$), Alice must not have gotten to the value $c_{i_p}$. In $c_{i_1} + \ldots + c_{i_p}$ turns, Alice will zero out exactly that many values. Additionally, Bob would have zeroed out $p - 1$ values before index $i_p$. So, $c_{i_1} + \ldots + c_{i_p} + p - 1$ must be less than $i_p$. Transforming this a bit, we get that the condition $\sum_{j=1}^{p}{c_{i_j}} \le i_p - p$ must hold for all $1 \le p \le k$. Bob's objective to maximize the size of the set of incides $1 \le i_1 < \ldots < i_k \le m$. Let $dp[i][k] =$ the minimum possible $\sum_{j=1}^{k}{c_{i_j}}$ over all valid sets of indices $1 \le i_1 < \ldots < i_k \le i$. Initialize $dp[0][0] = 0$, and everything else to $+\infty$. The main idea is to grow valid sets of indices one index at a time. We will iterate over all $i$ from $1$ to $m$, and then for each $k$ from $0$ to $m$. The transitions are: $dp[i][k] = \min(dp[i][k], d[i - 1][k])$, which corresponds to not using the current index in the set. Let $s := dp[i - 1][k - 1] + c_i$. If $s \le i_k - k$, update $dp[i][k] = \min(dp[i][k], s)$, which is equivalent to adding the current index to the set. We only need to check the condition on the last index because it is already satisfied for all the previous indices. The answer to the problem is $m - y$, where $y$ is the largest value where $dp[m][y] < +\infty$. Complexity: $\mathcal{O}(n^2)$ Note: it is possible to solve in $\mathcal{O}(n \log n)$ by making an additional observation.
|
[
"dp",
"games"
] | 1,800
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int inf = 1e9;
void solve() {
vector<int> a;
{
int n;
cin >> n;
map<int, int> cnt;
while (n--) {
int x;
cin >> x;
cnt[x]++;
}
for (auto const &[k, v]: cnt) {
a.push_back(v);
}
}
int n = a.size();
vector<int> dp(n + 1, inf);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
vector<int> ndp = dp;
for (int k = 1; k <= n; k++) {
int nv = dp[k - 1] + a[i - 1];
if (nv <= i - k) {
ndp[k] = min(ndp[k], nv);
}
}
dp = ndp;
}
int ans = n;
while (dp[ans] >= inf) ans--;
cout << n - ans << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) solve();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.