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
⌀ |
|---|---|---|---|---|---|---|---|
1714
|
A
|
Everyone Loves to Sleep
|
Vlad, like everyone else, loves to sleep very much.
Every day Vlad has to do $n$ things, each at a certain time. For each of these things, he has an alarm clock set, the $i$-th of them is triggered on $h_i$ hours $m_i$ minutes every day ($0 \le h_i < 24, 0 \le m_i < 60$). Vlad uses the $24$-hour time format, so after $h=12, m=59$ comes $h=13, m=0$ and after $h=23, m=59$ comes $h=0, m=0$.
This time Vlad went to bed at $H$ hours $M$ minutes ($0 \le H < 24, 0 \le M < 60$) and asks you to answer: how much he will be able to sleep until the next alarm clock.
If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $0$.
|
To begin with, let's learn how to determine how much time must pass before the $i$ alarm to trigger. If the alarm time is later than the current one, then obviously $60*(h_i - H) + m_i - M$ minutes should pass. Otherwise, this value will be negative and then it should pass $24*60 + 60* (h_i - H) + m_i - M$ since a full day must pass, not including the time from the alarm to the current time. We just need to find the minimum number of minutes among all the alarm clocks. Due to small constrains, the problem can also be solved by stimulating the sleep process: increase the answer by $1$ and check whether any alarm will work after this time.
|
[
"implementation",
"math"
] | 900
|
#include <bits/stdc++.h>
#define int long long
#define pb emplace_back
#define mp make_pair
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
mt19937 rnd(143);
const int inf = 1e15;
const int M = 1e9 + 7;
const ld pi = atan2(0, -1);
const ld eps = 1e-6;
void solve(){
int n;
cin >> n;
int time, h, m;
cin >> h >> m;
time = 60 * h + m;
int ans = 24 * 60;
for(int i = 0; i < n; ++i){
cin >> h >> m;
int t = 60 * h + m - time;
if(t < 0) t += 24 * 60;
ans = min(ans, t);
}
cout << ans / 60 << " " << ans % 60;
}
bool multi = true;
signed main() {
int t = 1;
if (multi)cin >> t;
for (; t; --t) {
solve();
cout << endl;
}
return 0;
}
|
1714
|
B
|
Remove Prefix
|
Polycarp was presented with some sequence of integers $a$ of length $n$ ($1 \le a_i \le n$). A sequence can make Polycarp happy only if it consists of \textbf{different} numbers (i.e. distinct numbers).
In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.
In one move, he can:
- remove the first (leftmost) element of the sequence.
For example, in one move, the sequence $[3, 1, 4, 3]$ will produce the sequence $[1, 4, 3]$, which consists of different numbers.
Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $a$, after removing which all values in the sequence will be unique.
|
Let's turn the problem around: we'll look for the longest suffix that will make Polycarp happy, since it's the same thing. Let's create an array $cnt$, in which we will mark the numbers already encountered. Let's go along $a$ from right to left and check if $a_i$ does not occur to the right (in this case it is marked in $cnt$), if it occurs to the right, then removing any prefix that does not include $i$, we get an array where $a_i$ occurs twice, so we have to delete prefix of length $i$.
|
[
"data structures",
"greedy",
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n;
cin >> n;
vector<int> a(n);
forn(i, n)
cin >> a[i];
bool yes = false;
set<int> c;
for (int i = n - 1; i >= 0; i--) {
if (c.count(a[i])) {
cout << i + 1 << endl;
yes = true;
break;
}
c.insert(a[i]);
}
if (!yes)
cout << 0 << endl;
}
}
|
1714
|
C
|
Minimum Varied Number
|
Find the minimum number with the given sum of digits $s$ such that \textbf{all} digits in it are distinct (i.e. all digits are unique).
For example, if $s=20$, then the answer is $389$. This is the minimum number in which all digits are different and the sum of the digits is $20$ ($3+8+9=20$).
For the given $s$ print the required number.
|
Let's use the greedy solution: we will go through the digits in decreasing order. If the sum of $s$ we need to dial is greater than the current digit, we add the current digit to the end of the line with the answer. Note that in this way we will always get an answer consisting of the minimum possible number of digits, because we are going through the digits in descending order. Suppose that the resulting number is not optimal. Then some digit can be reduced, and some digit that comes after it can be increased, in order to save the sum (we can not increase the digit before it, as then we get a number greater than the current one). Two variants are possible. We want to increase the digit $x$ to $x+1$, but then it becomes equal to the digit following it, or exceeds the value $9$. Then we can't increment that digit. Otherwise, in the first step, we can get $x+1$ instead of $x$, but since we are going through the digits in decreasing order, we cannot get the value of $x$ in that case. Contradiction.
|
[
"greedy"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int s;
cin >> s;
string result;
for (int d = 9; d >= 1; d--)
if (s >= d) {
result = char('0' + d) + result;
s -= d;
}
cout << result << endl;
}
}
|
1714
|
D
|
Color with Occurrences
|
You are given some text $t$ and a set of $n$ strings $s_1, s_2, \dots, s_n$.
In one step, you can choose any occurrence of any string $s_i$ in the text $t$ and color the corresponding characters of the text in red. For example, if $t=bababa$ and $s_1=ba$, $s_2=aba$, you can get $t=\textcolor{red}{ba}baba$, $t=b\textcolor{red}{aba}ba$ or $t=bab\textcolor{red}{aba}$ in one step.
You want to color all the letters of the text $t$ in red. When you color a letter in red again, it stays red.
In the example above, three steps are enough:
- Let's color $t[2 \dots 4]=s_2=aba$ in red, we get $t=b\textcolor{red}{aba}ba$;
- Let's color $t[1 \dots 2]=s_1=ba$ in red, we get $t=\textcolor{red}{baba}ba$;
- Let's color $t[4 \dots 6]=s_2=aba$ in red, we get $t=\textcolor{red}{bababa}$.
Each string $s_i$ can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily.
Determine the minimum number of steps needed to color all letters $t$ in red and how to do it. If it is impossible to color all letters of the text $t$ in red, output -1.
|
The first step is to find the word that covers the maximum length prefix. If there is no such word, we cannot color the string. Then go through the positions inside the found prefix and find the next word, which is a tweak of $t$, has the maximal length, and ends not earlier than the previous found word, and not later than the text $t$. If there is no such word, it is impossible to color $t$. After the second word is found, similarly continue looking for the next ones.
|
[
"brute force",
"data structures",
"dp",
"greedy",
"strings"
] | 1,600
|
#include<bits/stdc++.h>
#define len(s) (int)s.size()
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int ans = 0;
bool ok = true;
void Find(int a, int b, string &t, vector<string>&str, vector<pair<int, int>>&match){
int Max = 0, id = -1, pos = -1;
for(int i = a; i <= b; i++){
for(int j = 0; j < len(str); j++){
string s = str[j];
if(i + len(s) > len(t) || i + len(s) <= b) continue;
if(t.substr(i, len(s)) == s) {
if(i + len(s) > Max){
Max = i + len(s);
id = j;
pos = i;
}
}
}
}
if(id == -1) {
ok = false;
return;
}
else{
match.emplace_back(id, pos);
ans++;
if(Max == len(t)) return;
else Find(max(pos + 1, b +1), Max, t, str, match);
}
}
void solve(){
ans = 0;
ok = true;
string t;
cin >> t;
int n;
cin >> n;
vector<string>s(n);
vector<pair<int, int>>match;
forn(i, n) {
cin >> s[i];
}
Find(0, 0, t, s, match);
if(!ok) cout << "-1\n";
else{
cout << ans << endl;
for(auto &p : match) cout << p.first + 1 << ' ' << p.second + 1 << endl;
}
}
int main(){
int q;
cin >> q;
while(q--){
solve();
}
return 0;
}
|
1714
|
E
|
Add Modulo 10
|
You are given an array of $n$ integers $a_1, a_2, \dots, a_n$
You can apply the following operation an arbitrary number of times:
- select an index $i$ ($1 \le i \le n$) and replace the value of the element $a_i$ with the value $a_i + (a_i \bmod 10)$, where $a_i \bmod 10$ is the remainder of the integer dividing $a_i$ by $10$.
For a single index (value $i$), this operation can be applied multiple times. If the operation is applied repeatedly to the same index, then the current value of $a_i$ is taken into account each time. For example, if $a_i=47$ then after the first operation we get $a_i=47+7=54$, and after the second operation we get $a_i=54+4=58$.
Check if it is possible to make \textbf{all} array elements equal by applying multiple (possibly zero) operations.
For example, you have an array $[6, 11]$.
- Let's apply this operation to the first element of the array. Let's replace $a_1 = 6$ with $a_1 + (a_1 \bmod 10) = 6 + (6 \bmod 10) = 6 + 6 = 12$. We get the array $[12, 11]$.
- Then apply this operation to the second element of the array. Let's replace $a_2 = 11$ with $a_2 + (a_2 \bmod 10) = 11 + (11 \bmod 10) = 11 + 1 = 12$. We get the array $[12, 12]$.
Thus, by applying $2$ operations, you can make all elements of an array equal.
|
Let's see which remainders modulo $10$ change into which ones. If the array contains a number divisible by $10$, then it cannot be changed. If there is a number that has a remainder of $5$ modulo $10$, then it can only be replaced once. Thus, if the array contains a number divisible by $5$, then we apply this operation to all elements of the array once and check that all its elements are equal. The remaining odd balances ($1, 3, 7, 9$) immediately turn into even ones. The even remainders ($2, 4, 6, 8$) change in a cycle, while the array element increases by $20$ in $4$ operations. Thus, we will apply the operation to each element of the array until its remainder modulo $10$ becomes, for example, $2$, and then check that the array does not contain both remainders $2$ and $12$ modulo $20$.
|
[
"brute force",
"math",
"number theory"
] | 1,400
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
int next(int x) {
return x + x % 10;
}
void solve() {
int n;
cin >> n;
vector<int> a(n);
bool flag = false;
for (int i = 0; i < n; ++i) {
cin >> a[i];
if (a[i] % 5 == 0) {
flag = true;
a[i] = next(a[i]);
}
}
if (flag) {
cout << (*min_element(a.begin(), a.end()) == *max_element(a.begin(), a.end()) ? "Yes": "No") << '\n';
} else {
bool flag2 = false, flag12 = false;
for (int i = 0; i < n; ++i) {
int x = a[i];
while (x % 10 != 2) {
x = next(x);
}
if (x % 20 == 2) {
flag2 = true;
} else {
flag12 = true;
}
}
cout << ((flag2 & flag12) ? "No" : "Yes") << '\n';
}
}
int main() {
int t = 1;
cin >> t;
for (int it = 0; it < t; ++it) {
solve();
}
return 0;
}
|
1714
|
F
|
Build a Tree and That Is It
|
A tree is a connected undirected graph without cycles. Note that in this problem, we are talking about not rooted trees.
You are given four positive integers $n, d_{12}, d_{23}$ and $d_{31}$. Construct a tree such that:
- it contains $n$ vertices numbered from $1$ to $n$,
- the distance (length of the shortest path) from vertex $1$ to vertex $2$ is $d_{12}$,
- distance from vertex $2$ to vertex $3$ is $d_{23}$,
- the distance from vertex $3$ to vertex $1$ is $d_{31}$.
Output any tree that satisfies all the requirements above, or determine that no such tree exists.
|
If the answer exists, you can hang the tree by some vertex such that the distances $d_{12}, d_{23}$ and $d_{31}$ can be expressed through the sums of distances to vertices $1,2$ and $3$. Then from the system of equations we express the required values of distances to vertices $1,2,3$ and construct a suitable tree. If the distance to a vertex is $0$, then that vertex is the root. There cannot be two roots, nor can there be negative distances. If none of the vertices of $1,2,3$ is the root, then make vertex $4$ the root. Next we build the required tree: add the required number of unique vertices on the path from the root to vertices $1,2,3$. Note also that if the sum of distances is greater than or equal to $n$, then we cannot build the tree either. The remaining vertices can be simply joined to the root.
|
[
"constructive algorithms",
"implementation",
"trees"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
int t;
cin >> t;
forn(tt, t) {
int n;
cin >> n;
vector<int> d(3);
forn(i, 3)
cin >> d[i];
int sum = d[0] + d[1] + d[2];
if (sum % 2 == 0) {
vector<int> w(3);
forn(i, 3)
w[i] = sum / 2 - d[(i + 1) % 3];
vector<int> sw(w.begin(), w.end());
sort(sw.begin(), sw.end());
if (sw[0] >= 0 && sw[1] >= 1) {
vector<pair<int,int>> edges;
int num = 3;
int center;
if (sw[0] == 0)
center = min_element(w.begin(), w.end()) - w.begin();
else
center = num++;
forn(i, 3) {
int before = center;
forn(j, w[i] - 1) {
edges.push_back({before, num});
before = num++;
}
if (w[i] > 0)
edges.push_back({before, i});
}
if (num <= n) {
while (num < n)
edges.push_back({center, num++});
cout << "YES" << endl;
for (auto& [u, v]: edges)
cout << u + 1 << " " << v + 1 << endl;
continue;
}
}
}
cout << "NO" << endl;
}
}
|
1714
|
G
|
Path Prefixes
|
You are given a rooted tree. It contains $n$ vertices, which are numbered from $1$ to $n$. The root is the vertex $1$.
Each edge has two positive integer values. Thus, two positive integers $a_j$ and $b_j$ are given for each edge.
Output $n-1$ numbers $r_2, r_3, \dots, r_n$, where $r_i$ is defined as follows.
Consider the path from the root (vertex $1$) to $i$ ($2 \le i \le n$). Let the sum of the costs of $a_j$ along this path be $A_i$. Then $r_i$ is equal to the length of the maximum prefix of this path such that the sum of $b_j$ along this prefix does not exceed $A_i$.
\begin{center}
{\small Example for $n=9$. The blue color shows the costs of $a_j$, and the red color shows the costs of $b_j$.}
\end{center}
Consider an example. In this case:
- $r_2=0$, since the path to $2$ has an amount of $a_j$ equal to $5$, only the prefix of this path of length $0$ has a smaller or equal amount of $b_j$;
- $r_3=3$, since the path to $3$ has an amount of $a_j$ equal to $5+9+5=19$, the prefix of length $3$ of this path has a sum of $b_j$ equal to $6+10+1=17$ ( the number is $17 \le 19$);
- $r_4=1$, since the path to $4$ has an amount of $a_j$ equal to $5+9=14$, the prefix of length $1$ of this path has an amount of $b_j$ equal to $6$ (this is the longest suitable prefix, since the prefix of length $2$ already has an amount of $b_j$ equal to $6+10=16$, which is more than $14$);
- $r_5=2$, since the path to $5$ has an amount of $a_j$ equal to $5+9+2=16$, the prefix of length $2$ of this path has a sum of $b_j$ equal to $6+10=16$ (this is the longest suitable prefix, since the prefix of length $3$ already has an amount of $b_j$ equal to $6+10+1=17$, what is more than $16$);
- $r_6=1$, since the path up to $6$ has an amount of $a_j$ equal to $2$, the prefix of length $1$ of this path has an amount of $b_j$ equal to $1$;
- $r_7=1$, since the path to $7$ has an amount of $a_j$ equal to $5+3=8$, the prefix of length $1$ of this path has an amount of $b_j$ equal to $6$ (this is the longest suitable prefix, since the prefix of length $2$ already has an amount of $b_j$ equal to $6+3=9$, which is more than $8$);
- $r_8=2$, since the path up to $8$ has an amount of $a_j$ equal to $2+4=6$, the prefix of length $2$ of this path has an amount of $b_j$ equal to $1+3=4$;
- $r_9=3$, since the path to $9$ has an amount of $a_j$ equal to $2+4+1=7$, the prefix of length $3$ of this path has a sum of $b_j$ equal to $1+3+3=7$.
|
Note that all $b_j$ are positive, which means that the amount on the prefix only increases. This allows us to use binary search to find the answer for the vertex. It remains only to learn how to quickly find the sum of $b_j$ on the path prefix. Let's run a depth-first search and store the prefix sums of the current path in stack: going to the vertex, add the sum to the end of the path and delete it when exiting.
|
[
"binary search",
"data structures",
"dfs and similar",
"trees"
] | 1,700
|
#pragma GCC optimize("O3","unroll-loops")
#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=2e5+5;
vector<int> ch[maxn];
int a[maxn];
int b[maxn];
int ans[maxn];
vector<int> vb;
int curb=0;
int cura=0;
void dfs(int x){
curb+=b[x];
cura+=a[x];
vb.push_back(curb);
ans[x]=upper_bound(vb.begin(),vb.end(),cura)-vb.begin();
for(int v:ch[x]){
dfs(v);
}
curb-=b[x];
cura-=a[x];
vb.pop_back();
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--){
int n;cin>>n;
for(int i=0;i<n;++i) ch[i].clear();
for(int i=1;i<n;++i){
int pr,a1,b1;
cin>>pr>>a1>>b1;
--pr;
ch[pr].push_back(i);
a[i]=a1;
b[i]=b1;
}
dfs(0);
for(int i=1;i<n;++i) cout<<ans[i]-1<<' ';
cout<<'\n';
}
return 0;
}
|
1715
|
A
|
Crossmarket
|
Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $n$ rows and $m$ columns.
Stanley and Megan can move to an adjacent cell using $1$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $1$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.
They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $(1, 1)$) to the lower-right cell (cell with coordinates $(n, m)$), whilst Megan needs to get from the lower-left cell (cell with coordinates $(n, 1)$) to the upper-right cell (cell with coordinates $(1, m)$).
What is the minimum total energy needed for them both to do that?
Note that they can choose the time they move. Time does not affect energy.
|
For convenience let's define going upward as decreasing $x$ coordinate, downward - increasing $x$, left - decreasing $y$, right - increasing y. One of the optimal solutions is the following: Megan goes upward to Stanley, she spends $(n - 1)$ units of energy for that. Then she goes right to her final destination by spending $(m - 1)$ more units of energy. Stanley now has a choice: he obviously has to teleport from his starting position either all the way down, or right. He chooses what will save him the most energy, so he teleports along the greater wall of the shop for the 1 unit of power. Then Stanley has to finish his route: he walks along the smaller side and spends $min(n, m) - 1$ more energy. If at least one of the dimensions is not $1$, then the answer is $(n - 1) + (m - 1) + 1 + (min(n, m) - 1) = min(n, m) + n + m - 2$. In case where $(n, m) = (1, 1)$ answer is $0$. Obviously, except for 1 case, it is always beneficial for Stanley to use teleportation. Let the first portal he visited be $A$, and the last is $B$. It is also obvious, that teleporting for more than 1 time makes no sense, so that's why we consider, that he always teleports from $A$ to $B$ and that's it. For the sake of convenience let's define manhattan distance between two points as $dist(P_1, P_2) = |{P_1}_x - {P_2}_x| + |{P_1}_y - {P_2}_y|$. Consider the next few cases for the relative position of those two portals: $A_x \le B_x$ and $Ay > By$ Megan must make at least $(n-1) + (m-1)$ moves. The portal does not help Stanley in the $y$ direction, so he must make at least $(m-1)$ moves. $A_x > B_x$ and $A_y \le B_y$ Megan must make at least $(n-1) + (m-1)$ moves. The portal does not help Stanley in the $x$ direction, so he must make at least $(n-1)$ moves. $A_x \le Bx$ and $Ay \le By$ Megan must make at least $dist(A,B)$ moves between $A$ and $B$. Going between A and B either undoes Megan's progress in the $x$ direction or $y$ direction (depending on which is visited first), so she must make at least an additional $(n-1) or (m-1)$ moves. Stanley must make at least $(n-1) + (m-1) - dist(A,B)$ moves. $Ax > Bx$ and $Ay > By$ Megan must make at least $(n-1) + (m-1)$ moves. Using the portal undoes Stanley's progress in both the x and y directions, so he must make at least $(n-1) + (m-1)$ moves. In all cases, the total number of moves is at least (n-1) + (m-1) + min(n-1, m-1). Proof: To start with, Stanley and Megan can complete their steps in any order. So, again, for our convenience let's reorder their moves in such a way, that firstly Megan finishes her route and places portals, and then Stanley does what he needs to do. What is always the optimal route for Stanley? He goes to the nearest cell with the teleport and then teleports to the nearest possible cell to his finish. It is obvious, that Stanley can always complete his route without going left or up (except for the teleportations). Let's try to prove a similar statement for Megan: she can always plan her route avoiding moves left or down. These two cases are almost equivalent, so we will consider the first one. Let's assume that teleportations are free for Megan. Consider any cell, from which she made her move to the left. Then it is possible to "shift" a segment of the route to the right in order to decrease its length at least by one in conjunction with getting rid of at least one move to the left. More formally we need to construct a new route for her, so the following conditions are met: for each cell in the previous route either itself, or her right neighbor is included in the new route. This can be done by the following algorithm: we will consider cells from the original route $A$ in order of installation of the portals, and build the new route $B$ in parallel. If we cannot include the cell $(x, y)$ from $A$ to the route $B$ because it does not have adjacent sides to any of the cells from $B$. Then we can include the cell $(x, y + 1)$ to $B$ (it cannot be out of bounds). Let there be a cell $(x_1, y_1)$ in $A$ with a portal, that was installed earlier than in our current cell, and that is adjacent to our current cell. If we could not include cell $(x, y)$ to the route $B$, that it means that we also did not include the cell $(x_1, y_1)$ there, thus cell $(x_1, y_1 + 1)$ is in $B$, that also also allows us to include cell $(x, y + 1)$. After such an operation Stanley's energy consumption could increase at most by 1. Though energy spent by Megan decreased at least by one. That means that our new route is not more energy-consuming. That way Megan will never go left or down, so she will spend at least $(n - 1) + (m - 1) = n + m - 2$ units of power. If, when all the operations are applied, Stanley teleports from the cell $(x_1, y_1)$ to $(x_2, y_2)$, then $\left[ \begin{array}{c} x_1 \le x_2, y_1 \ge y_2 \\ x_1 \ge x_2, y_1 \le y_2 \\ \end{array} \right.$. In the first case he teleports along Megan's route and approaches his finish by $(x_2 - x_1) - (y_1 - y2)$, and in the second case he teleports across Megan's route and approaches his destination by $(y_2 - y_1) - (x_1 - x2)$. As you can easily notice, first's expression maximum is $n - 1$, and second's is $m - 1$. Hence Stanley will spend at least $(n - 1) + (m - 1) - max(n - 1, m - 1) = n + m - max(n, m) - 1$ units of power. After adding only teleportation we get $n + m - max(n, m)$ We got two lower bounds, that in sum are $n + m - 2 + n + m - max(n, m) = 2n + 2m - max(n, m) - 2 = n + m + min(n, m) - 2$, which is not better, than our solution's answer, even though we did not consider Megan's teleportations.
|
[
"constructive algorithms",
"greedy",
"math"
] | 800
|
import kotlin.math.*
fun main() {
var t = readLine()!!.toInt()
for (test in 0 until t) {
val (n, m) = readLine()!!.split(" ").map { it -> it.toInt() }
print("${n + m - 3 + min(n, m) + min(max(n, m) - 1, 1)}\n")
}
}
|
1715
|
B
|
Beautiful Array
|
Stanley defines the beauty of an array $a$ of length $n$, which contains \textbf{non-negative integers}, as follows: $$\sum\limits_{i = 1}^{n} \left \lfloor \frac{a_{i}}{k} \right \rfloor,$$ which means that we divide each element by $k$, round it down, and sum up the resulting values.
Stanley told Sam the integer $k$ and asked him to find an array $a$ of $n$ non-negative integers, such that the beauty is equal to $b$ and the sum of elements is equal to $s$. Help Sam — find any of the arrays satisfying the conditions above.
|
To start with, the sum of the numbers in the array $s$ cannot be less, than $k \cdot b$ (where $k$ is the number by which we divide, and $b$ is beauty ($s \ge k \cdot b$)) It is important, that $s \le k \cdot b + (k - 1) \cdot n$. Let's assume that is not true. Consider the sum of divisible parts of numbers in the array: it obviously does not exceed $k \cdot b$, thus the sum of remainders is at least $(k - 1) \cdot n + 1$, which means, that at least one of the numbers' remainders is $k$, which is impossible by definition of the remainder. That way we got the criteria for the existence of the answer: $k \cdot b \le s \le k \cdot b + (k - 1) \cdot n$. If there does exist an answer, then we can use the following algorithm: Assign $k \cdot b$ to any of the $n$ cells of the array. Iterate over all the cells (including the cell from the previous item) and add $min(s - sum, k - 1)$ to the current cell, where $sum$ is the current sum of the elements.
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,000
|
t = int(input())
for i in range(t):
n, x, s, q = map(int, input().split())
q0 = q
a = [0 for i in range(n)]
for i in range(n):
a[i] = min(x - 1, q)
q -= a[i]
a[-1] += q
q = q0
curr = sum(i // x for i in a)
if (curr <= s <= q // x):
j = 0
while curr != s:
curr -= a[-1] // x
a[-1] += a[j]
curr += a[-1] // x
a[j] = 0
j += 1
print(*a)
else:
print(-1)
|
1715
|
C
|
Monoblock
|
Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.
The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array
- $[1, 1, 1]$ is $1$;
- $[5, 7]$ is $2$, as it could be split into blocks $[5]$ and $[7]$;
- $[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$ is 3, as it could be split into blocks $[1]$, $[7, 7, 7, 7, 7, 7, 7]$, and $[9, 9, 9, 9, 9, 9, 9, 9, 9]$.
You are given an array $a$ of length $n$. There are $m$ queries of two integers $i$, $x$. A query $i$, $x$ means that from now on the $i$-th element of the array $a$ is equal to $x$.
After each query print the sum of awesomeness values among all subsegments of array $a$. In other words, after each query you need to calculate $$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$ where $g(l, r)$ is the awesomeness of the array $b = [a_l, a_{l + 1}, \ldots, a_r]$.
|
Let us introduce another definition for the beauty - beauty of the array $a$ is a number of such positions (indexes) $i < n$, that $a_i \neq a_{i + 1}$, plus $1$. Let's call "joints" places where two adjacent different numbers exist in the array. Now consider the problem from the angle of these joints: if $f(joint)$ is equal to the number of segments, that overlap this joint, then the sum of beauty over all subsegments is equal to the sum of $f(joint)$ over all joints. To get a clearer understanding, consider the following example: $[1, 7, 7, 9, 9, 9] = [1] + [7, 7] + [9, 9, 9]$ ("$+$" is basically a joint). There are 5 segments, which contain first joint ($[1:2], [1:3], [1:4], [1:5], [1:6]$), and there are 9 such for the second joint ($[1:4], [1:5], [1, 6], [2:4], [2:5], [2:6], [3:4], [3:5], [3:6]$), $14$ in total. After adding the number of subsegments, we get the answer: $\frac{6 \cdot 7}{2} = 21, 21 + 14 = 35$. From this the solution is derived, apart from change requests: iterate over the array, find "joints", comparing adjacent numbers, if $a_i$ is different from $a_{i + 1}$, that we must add $i \cdot (n - i)$ to the answer, that is how many possible beginnings of subsegments from the left multiplied by the number of possible ends from the right. How we should apply changes? In fact, it's worth just checking if there are any neighboring joints for the position of the changing number, subtracting the number of subsegments, that overlap these joints, and then doing similar operations after setting a new value for the number. For a better understanding and more details, we suggest you look over the authors' solutions.
|
[
"combinatorics",
"data structures",
"implementation",
"math"
] | 1,700
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <chrono>
#include <deque>
#include <iomanip>
#include <queue>
#include <functional>
using namespace std;
#define int long long
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<int> a(n + 2, 0);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
int ans = 0;
for (int i = 1; i <= n; ++i) {
ans += (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i;
}
while (m--) {
int i, x;
cin >> i >> x;
ans -= (a[i] != a[i - 1]) * (n - i + 1) * (i - 1);
ans -= (a[i + 1] != a[i]) * (n - (i + 1) + 1) * i;
a[i] = x;
ans += (a[i] != a[i - 1]) * (n - i + 1) * (i - 1);
ans += (a[i + 1] != a[i]) * (n - (i + 1) + 1) * i;
cout << ans + n * (n + 1) / 2 << '\n';
}
}
|
1715
|
D
|
2+ doors
|
The Narrator has an integer array $a$ of length $n$, but he will only tell you the size $n$ and $q$ statements, each of them being three integers $i, j, x$, which means that $a_i \mid a_j = x$, where $|$ denotes the bitwise OR operation.
Find the lexicographically smallest array $a$ that satisfies all the statements.
An array $a$ is lexicographically smaller than an array $b$ of the same length if and only if the following holds:
- in the first position where $a$ and $b$ differ, the array $a$ has a smaller element than the corresponding element in $b$.
|
The first observation is that we can solve the task separately bit by bit, because of bitwise or operation is "bit-independent": bits of one particular power don't affect other bits to gen a lexicographically minimal solution, we can combine solutions for each bit separately This makes it possible for us to create a solution for a boolean array, and then run it $30$ times for all numbers and statements, considering only $i$-th bit in each run. For ease of understanding let's speak in a language of graphs: we have an undirected graph with $n$ vertices, on each vertex, there is either $0$ or $1$, and on each edge, there is a bitwise or of numbers, that are written on vertices connected by that edge. We have to recover the numbers on the vertices after they were somehow lost, knowing, that numbers on the vertices create a lexicographically minimal sequence possible. Initially, let's write $1$ on each of the vertices. Then walk through them and consider incidental edges. If any of the edges contain $0$, we must also write $0$ on our current vertex and the neighbor by that edge. After zeroing all the required vertices, let's try to make our sequence lexicographically minimal. Walk through the vertices again and try to write $0$ on each: to check if everything is ok, iterate over the incidental edges again. If any of them contains $1$ and connects us with a vertex with $0$, then we cannot make our vertex $0$. Such solution works in $\mathcal{O}(\log(\max(a_i)) \cdot (n + m))$ time. For a better understanding and more details, we suggest you look over the authors' solutions.
|
[
"2-sat",
"bitmasks",
"graphs",
"greedy"
] | 1,900
|
#include <iostream>
#include <vector>
using namespace std;
inline bool get_bit(uint32_t &x, uint32_t &bt) { return (x >> bt) & 1; }
inline void make_one(uint32_t &x, uint32_t &bt) { x |= (1 << bt); }
inline void make_null(uint32_t &x, uint32_t &bt) { x &= (~(1 << bt)); }
inline bool solve_bit(vector<uint32_t> &ans,
vector<vector<pair<uint32_t, uint32_t>>> &g,
uint32_t &bt) {
for (uint32_t i = 0; i < (uint32_t)ans.size(); ++i)
for (auto &it : g[i])
if (!get_bit(it.second, bt))
make_null(ans[i], bt);
else if (!get_bit(ans[i], bt) && !get_bit(ans[it.first], bt))
return false;
for (uint32_t i = 0; i < (uint32_t)ans.size(); ++i)
if (get_bit(ans[i], bt)) {
make_null(ans[i], bt);
for (auto &it : g[i])
if (!get_bit(ans[it.first], bt) && get_bit(it.second, bt)) {
make_one(ans[i], bt);
break;
}
}
return true;
}
inline void solve() {
uint32_t n, m;
cin >> n >> m;
vector<vector<pair<uint32_t, uint32_t>>> g(n);
while (m--) {
uint32_t a, b, c;
cin >> a >> b >> c;
a--;
b--;
g[a].emplace_back(b, c);
g[b].emplace_back(a, c);
if (a > b)
swap(a, b);
}
const int pt = 31;
vector<uint32_t> ans(n, ~(1 << pt));
for (uint32_t i = 0; i < pt; ++i)
if (!solve_bit(ans, g, i)) {
cout << "-1\n";
return;
}
for (auto &it : ans)
cout << it << " ";
cout << "\n";
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}
|
1715
|
E
|
Long Way Home
|
Stanley lives in a country that consists of $n$ cities (he lives in city $1$). There are bidirectional roads between some of the cities, and you know how long it takes to ride through each of them. Additionally, there is a flight between each pair of cities, the flight between cities $u$ and $v$ takes $(u - v)^2$ time.
Stanley is quite afraid of flying because of watching "Sully: Miracle on the Hudson" recently, so he can take at most $k$ flights. Stanley wants to know the minimum time of a journey to each of the $n$ cities from the city $1$.
|
Let's assume we know the shortest distances from the first vertex to each, if we have added no more than $k$ edges (air travels). Let's learn to recalculate the answer for $(k + 1)$ edges. First, let's update the answer for all the paths ending in an air travel. Then we can run Dijkstra to take into account all the paths ending with a usual edge. In order to add an air travel, we need to update the distance to $v$, with all the paths ending with an air travel to $v$. To do so, we can use Convex Hull Trick, since the recalculation formula has the following form ($d_{old}$ - array of distances for $k$ edges, $d_{new}$ - array of distances if $k+1$ the flight goes exactly to the $i$-th vertex): $d_{new}[v] = \min\limits_{u} \ d_{old}[u] + (u - v)^2$ After that, we need to run Dijkstra to update the distances with all the paths not ending with an air travel. The resulting asymptotics is $O(k(m \log n + n))$
|
[
"data structures",
"divide and conquer",
"dp",
"geometry",
"graphs",
"greedy",
"shortest paths"
] | 2,400
|
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define int long long
const int inf = 1e18;
const int inf1 = 1e15;
struct CHT {
struct line {
int k, b;
line() {}
line(int k, int b): k(k), b(b) {}
double intersect(line l) {
double db = l.b - b;
double dk = k - l.k;
return db / dk;
}
long long operator () (long long x) {
return k * x + b;
}
};
vector<double> x;
vector<line> ll;
void init(line l) {
x.push_back(-inf);
ll.push_back(l);
}
void addLine(line l) {
while (ll.size() >= 2 && l.intersect(ll[ll.size() - 2]) <= x.back()) {
x.pop_back();
ll.pop_back();
}
if (!ll.empty()) {
x.push_back(l.intersect(ll.back()));
}
ll.push_back(l);
}
long long query(long long qx) {
int id = upper_bound(x.begin(), x.end(), qx) - x.begin();
--id;
return ll[id](qx);
}
};
void dijkstra(vector<vector<pair<int, int>>> &g, vector<int> &dist) {
const int n = g.size();
vector<bool> used(n, false);
priority_queue<pair<int, int>> q;
for (int i = 0; i < n; ++i) {
q.push({ -dist[i], i });
}
while (!q.empty()) {
int v = q.top().second;
q.pop();
if (used[v]) {
continue;
}
used[v] = true;
for (auto [u, w] : g[v]) {
if (dist[u] > dist[v] + w) {
dist[u] = dist[v] + w;
q.push({ -dist[u], u });
}
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m, k;
cin >> n >> m >> k;
vector<vector<pair<int, int>>> g(n);
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
--u; --v;
g[u].push_back({ v, w });
g[v].push_back({ u, w });
}
vector<int> dist(n, inf1);
dist[0] = 0;
dijkstra(g, dist);
for (int i = 0; i < k; ++i) {
CHT cht;
cht.init(CHT::line(0, 0));
for (int i = 1; i < n; ++i) {
cht.addLine(CHT::line(-i * 2, dist[i] + i * i));
}
for (int i = 0; i < n; ++i) {
dist[i] = cht.query(i) + i * i;
}
dijkstra(g, dist);
}
for (int i : dist) {
cout << i << ' ';
}
}
|
1715
|
F
|
Crop Squares
|
This is an interactive problem.
Farmer Stanley grows corn on a rectangular field of size $ n \times m $ meters with corners in points $(0, 0)$, $(0, m)$, $(n, 0)$, $(n, m)$. This year the harvest was plentiful and corn covered the whole field.
The night before harvest aliens arrived and poisoned the corn in a single $1 \times 1$ square with sides parallel to field borders. The corn inside the square must not be eaten, but you cannot distinguish it from ordinary corn by sight. Stanley can only collect a sample of corn from an arbitrary polygon and bring it to the laboratory, where it will be analyzed and Stanley will be told the amount of corn in the sample that was poisoned. Since the harvest will soon deteriorate, such a study can be carried out no more than $5$ times.
More formally, it is allowed to make no more than $5$ queries, each of them calculates the area of intersection of a chosen polygon with a square of poisoned corn. It is necessary to find out the coordinates of the lower-left corner of the drawn square (the vertex of the square with the smallest $x$ and $y$ coordinates).
|
In fact, two queries are enough. The first query is to find out the area of intersection of the polygon with $2n + 2$ vertices at the points with coordinates $(0, m + 1),\:(0, 0),\:(1, m),\:(1, 0),\; \dots ,\;(n - 1, m),\:(n - 1, 0),\:(n, m),\:(n, m + 1)$ with a filled square. Such a polygon is periodic over $x$ axis with period $1$, hence the $x$-coordinate of the lower left corner of the filled square does not affect the intersection area. Denote the intersection area - $s$, then the $y$-coordinate of the lower left corner of the square is calculated by the formula $y=ms-\frac{1}{2}$. An example of such a polygon for the field $5 \times 4$ and a filled square with the lower left corner at the point $(3.5, 2.5)$: With the second query, we find out the area of intersection of a similar polygon with $2m + 2$ vertices at points with coordinates $(n + 1, m),\:(0, m),\:(n, m - 1),\:(0, m - 1),\; \dots ,\;(n, 1),\:(0, 1),\:(n, 0),\:(n + 1, 0)$ with a filled square. Such a polygon is periodic over $y$ axis with period $1$, hence the $y$-coordinate of the lower left corner of the filled square does not affect the intersection area. Denote the intersection area - $s$, then the $x$-coordinate of the lower left corner of the square is calculated by the formula $x=ns-\frac{1}{2}$. An example of such a polygon for the field $5 \times 4$ and a filled square with the lower left corner at the point $(3.5, 2.5)$:
|
[
"constructive algorithms",
"geometry",
"interactive",
"math"
] | 2,700
|
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
using ld = long double;
template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
return out << x.first << ' ' << x.second;
}
ld query(const vector<pair<int, int>>& vert) {
cout << "? " << vert.size() << '\n';
for (const auto& x : vert) {
cout << x << '\n';
}
cout.flush();
ld reply;
cin >> reply;
return reply;
}
void answer(ld x, ld y) {
cout << setprecision(10) << fixed;
cout << "! " << x << ' ' << y << endl;
}
int main() {
int n, m;
cin >> n >> m;
vector<pair<int, int>> poly;
poly.emplace_back(0, m + 1);
poly.emplace_back(0, 0);
for (int i = 1; i < n; ++i) {
poly.emplace_back(i, m);
poly.emplace_back(i, 0);
}
poly.emplace_back(n, m);
poly.emplace_back(n, m + 1);
ld y = m * query(poly) - 0.5L;
poly.clear();
poly.emplace_back(n + 1, 0);
poly.emplace_back(0, 0);
for (int i = 1; i < m; ++i) {
poly.emplace_back(n, i);
poly.emplace_back(0, i);
}
poly.emplace_back(n, m);
poly.emplace_back(n + 1, m);
ld x = n * query(poly) - 0.5L;
answer(x, y);
return 0;
}
|
1716
|
A
|
2-3 Moves
|
You are standing at the point $0$ on a coordinate line. Your goal is to reach the point $n$. In one minute, you can move by $2$ or by $3$ to the left or to the right (i. e., if your current coordinate is $x$, it can become $x-3$, $x-2$, $x+2$ or $x+3$). Note that the new coordinate can become negative.
Your task is to find the \textbf{minimum} number of minutes required to get from the point $0$ to the point $n$.
You have to answer $t$ independent test cases.
|
If $n = 1$, the answer is $2$ (we can't get $1$, so we can move by $3$ to the right and by $2$ to the left). If $n = 2$ or $n = 3$, the answer is obviously $1$. Otherwise, the answer is always $\lceil\frac{n}{3}\rceil$. We can't get the answer less than this value (because we need at least $\lceil\frac{n}{3}\rceil$ moves to get to the point greater than or equal to $n$) and we can always get this answer by the recurrence.
|
[
"greedy",
"math"
] | 800
|
for _ in range(int(input())):
n = int(input())
print(1 + (n == 1) if n <= 3 else (n + 2) // 3)
|
1716
|
B
|
Permutation Chain
|
A permutation of length $n$ is a sequence of integers from $1$ to $n$ such that each integer appears in it exactly once.
Let the fixedness of a permutation $p$ be the number of fixed points in it — the number of positions $j$ such that $p_j = j$, where $p_j$ is the $j$-th element of the permutation $p$.
You are asked to build a sequence of permutations $a_1, a_2, \dots$, starting from the identity permutation (permutation $a_1 = [1, 2, \dots, n]$). Let's call it a permutation chain. Thus, $a_i$ is the $i$-th permutation of length $n$.
For every $i$ from $2$ onwards, the permutation $a_i$ should be obtained from the permutation $a_{i-1}$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $a_i$ should be strictly lower than the fixedness of the permutation $a_{i-1}$.
Consider some chains for $n = 3$:
- $a_1 = [1, 2, 3]$, $a_2 = [1, 3, 2]$ — that is a valid chain of length $2$. From $a_1$ to $a_2$, the elements on positions $2$ and $3$ get swapped, the fixedness decrease from $3$ to $1$.
- $a_1 = [2, 1, 3]$, $a_2 = [3, 1, 2]$ — that is not a valid chain. The first permutation should always be $[1, 2, 3]$ for $n = 3$.
- $a_1 = [1, 2, 3]$, $a_2 = [1, 3, 2]$, $a_3 = [1, 2, 3]$ — that is not a valid chain. From $a_2$ to $a_3$, the elements on positions $2$ and $3$ get swapped but the fixedness increase from $1$ to $3$.
- $a_1 = [1, 2, 3]$, $a_2 = [3, 2, 1]$, $a_3 = [3, 1, 2]$ — that is a valid chain of length $3$. From $a_1$ to $a_2$, the elements on positions $1$ and $3$ get swapped, the fixedness decrease from $3$ to $1$. From $a_2$ to $a_3$, the elements on positions $2$ and $3$ get swapped, the fixedness decrease from $1$ to $0$.
Find the longest permutation chain. If there are multiple longest answers, print any of them.
|
Ideally, we would want the fixedness values to be $n, n - 1, n - 2, \dots, 0$. That would make a chain of length $n + 1$. However, it's impossible to have fixedness of $n - 1$ after one swap. The first swap always makes a permutation with fixedness $n - 2$. Okay, how about $n, n - 2, n - 3, \dots, 0$ then? That turns out to always be achievable. For example, swap elements $1$ and $2$, then elements $2$ and $3$, then $3$ and $4$ and so on. Overall complexity: $O(n^2)$ per testcase.
|
[
"constructive algorithms",
"math"
] | 800
|
for _ in range(int(input())):
n = int(input())
p = [i + 1 for i in range(n)]
print(n)
for i in range(n):
print(*p)
if i < n - 1:
p[i], p[i + 1] = p[i + 1], p[i]
|
1716
|
C
|
Robot in a Hallway
|
There is a grid, consisting of $2$ rows and $m$ columns. The rows are numbered from $1$ to $2$ from top to bottom. The columns are numbered from $1$ to $m$ from left to right.
The robot starts in a cell $(1, 1)$. In one second, it can perform either of two actions:
- move into a cell adjacent by a side: up, right, down or left;
- remain in the same cell.
The robot is not allowed to move outside the grid.
Initially, all cells, except for the cell $(1, 1)$, are locked. Each cell $(i, j)$ contains a value $a_{i,j}$ — the moment that this cell gets unlocked. The robot can only move into a cell $(i, j)$ if at least $a_{i,j}$ seconds have passed before the move.
The robot should visit all cells \textbf{without entering any cell twice or more} (cell $(1, 1)$ is considered entered at the start). It can finish in any cell.
What is the fastest the robot can achieve that?
|
Let's first consider the possible paths across the grid that visit all cells. You can immediately think of two of them. The first one is: go right to the wall, turn into the other row and return. Let's call it a hook. The second one is: go down, go right, go up, go right and so on. Let's call it a snake. Turns out, these two are basically the two extremes of all paths. You can start with a snake and turn into a hook when you wish. You can see that once you move right twice in a row, you can only continue with a hook. And as long as you didn't move right twice, you are just doing a snake. Let's fix some path across the grid. What will its minimum time be? Calculate it iteratively. If you want to enter the next cell, and it's still locked, wait until it isn't. So there are some seconds of waiting (possibly, zero) before each cell. However, why not instead do the following. Let's calculate the sum of waiting time required and wait for that amount of seconds before starting to move. All cells will be visited at the same time as before or even later. Thus, they will surely be unlocked if they were in the original plan. So the goal is to calculate the minimum amount of time required to wait in the start, then add the movement time to it. Once again, the path is fixed. Let the $k$-th cell of the path be $(x_k, y_k)$. If you start after waiting for $t$ seconds, then you reach the $k$-th cell at time $t + k$ ($k$ is $1$-indexed). Thus, the $k$-th cell should have $a_{x_k, y_k} \le t + k - 1$. If all cells satisfy this condition, then the path can be done after waiting for $t$ seconds at the start. Let's rewrite it into $t \ge a_{x_k, y_k} - k + 1$. So, the condition tells us that $t$ should be greater or equal than this value for all cells. In other words, $t$ should be greater or equal than the maximum of the values over all cells. Study the formula. Imagine we have some path with a known length and want to append a cell to it. That's pretty simple. Just update the maximum with the value with the corresponding cell and increase the length. What if we wanted to prepend a cell to it? Turns out, it's not that hard as well. Every cell in the path gets its value $k$ increased by $1$. From the formula, you can see that this actually decreases the value of each cell by $1$. So the maximum decreases by $1$ as well. The only thing left is to update the maximum with the value of the new first cell. Well, and increase the length again. Finally, let's learn how to choose the best path. We can iterate over the length of the snake part. The hook part is determined uniquely. It's easy to maintain the maximum on the snake. Just append the new cell to the path. How to glue up the hook part to that? Well, actually, realize that the formula allows us to glue up two paths into one. Let path $1$ have length $n_1$ and maximum $\mathit{mx}_1$ and path $2$ have length $n_2$ and maximum $\mathit{mx}_2$. To make path $2$ start after path $1$, we just decrease its maximum by $n_1$. The resulting path has length $n_1 + n_2$ and maximum $\max(\mathit{mx}_1, \mathit{mx}_2 - n_1)$. Let's look closer into what the hooks look like. They start in some column $j$, traverse all the way right, then left up to the same column $j$. If the snake part took both cells in its last column, then that's it. Otherwise, the hook has to take the final cell in the last column - column $j-1$. If we manage to precalculate something for hooks that start in some column $j$ and end in column $j$, then we will be able to use that. Appending the final cell is not a hard task, since we know its index in the path ($k = 2 \cdot m$). Let $\mathit{su}_{i,j}$ be the waiting time required for a hook that starts in cell $(i, j)$ and ends in a cell $(3 - i, j)$ as if the path started with the hook (cell $(i, j)$ is the first one). $\mathit{su}_{i,j}$ can be calculated from $\mathit{su}_{i,j+1}$. Prepend it with a cell $(i, j)$ and append it with a cell $(3 - i, j)$. The only thing left is to find the best answer. I found the most convenient to start with a snake of length $1$ (only cell $(1, 1)$) and progress it two steps at the time: update the answer; progress the snake to the other cell of the current column; update the answer; progress the snake into the next column. Overall complexity: $O(m)$ per testcase.
|
[
"data structures",
"dp",
"greedy",
"implementation",
"ternary search"
] | 2,000
|
INF = 2 * 10**9
for _ in range(int(input())):
m = int(input())
a = [[int(x) for x in input().split()] for i in range(2)]
su = [[-INF for j in range(m + 1)] for i in range(2)]
for i in range(2):
for j in range(m - 1, -1, -1):
su[i][j] = max(su[i][j + 1] - 1, a[i][j], a[i ^ 1][j] - (2 * (m - j) - 1))
pr = a[0][0] - 1
ans = INF
for j in range(m):
jj = j & 1
ans = min(ans, max(pr, su[jj][j + 1] - 2 * j - 1, a[jj ^ 1][j] - 2 * m + 1))
pr = max(pr, a[jj ^ 1][j] - 2 * j - 1)
ans = min(ans, max(pr, su[jj ^ 1][j + 1] - 2 * j - 2))
if j < m - 1:
pr = max(pr, a[jj ^ 1][j + 1] - 2 * j - 2)
print(ans + 2 * m)
|
1716
|
D
|
Chip Move
|
There is a chip on the coordinate line. Initially, the chip is located at the point $0$. You can perform any number of moves; each move increases the coordinate of the chip by some positive integer (which is called the length of the move). The length of the first move you make should be divisible by $k$, the length of the second move — by $k+1$, the third — by $k+2$, and so on.
For example, if $k=2$, then the sequence of moves may look like this: $0 \rightarrow 4 \rightarrow 7 \rightarrow 19 \rightarrow 44$, because $4 - 0 = 4$ is divisible by $2 = k$, $7 - 4 = 3$ is divisible by $3 = k + 1$, $19 - 7 = 12$ is divisible by $4 = k + 2$, $44 - 19 = 25$ is divisible by $5 = k + 3$.
You are given two positive integers $n$ and $k$. Your task is to count the number of ways to reach the point $x$, starting from $0$, for every $x \in [1, n]$. The number of ways can be very large, so print it modulo $998244353$. Two ways are considered different if they differ as sets of visited positions.
|
Let's calculate dynamic programming $dp_{s, i}$ - the number of ways to achieve $i$ in $s$ moves. From the state $(s, i)$, you can make a transition to the states $(s+1, j)$, where $i < j$ and $j - i$ is divisible by $k + s$. Let's try to estimate the maximum number of moves, because it seems that there can't be very many of them. For $m$ moves, the minimum distance by which a chip can be moved is $k+ (k + 1) + \dots + (k + m - 1)$ or $\frac{(k + k + m - 1) \cdot m}{2}$. From here one can see that the maximum number of transitions does not exceed $\sqrt{2n}$ (maximum at $k=1$). So it remains to make transitions in dynamic programming faster than $O(n)$ from a single state for a fast enough solution. Let's use the fact that $j \equiv i \pmod{k+s}$. Let's iterate over the value of $j$ and maintain the sum of dynamic programming values with smaller indices for each remainder modulo $k + s$ in a separate array. The final complexity of such a solution is $O(n\sqrt{n})$. It remains to solve the memory problem, because with the existing limits, it is impossible to save the entire $dp$ matrix of size $n^{\frac{3}{2}}$. However, this is easy to solve if you notice that only the previous layer is used for transitions in dp, i.e. it is enough to store $dp_s$ to calculate $dp_{s+1}$.
|
[
"brute force",
"dp",
"math"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int main() {
int n, k;
cin >> n >> k;
vector<int> dp(n + 1), ans(n + 1);
dp[0] = 1;
for (int mn = 0; mn + k <= n; mn += k++) {
vector<int> sum(k);
for (int i = mn; i <= n; ++i) {
int cur = dp[i];
dp[i] = sum[i % k];
(sum[i % k] += cur) %= MOD;
(ans[i] += dp[i]) %= MOD;
}
}
for (int i = 1; i <= n; ++i) cout << ans[i] << ' ';
}
|
1716
|
E
|
Swap and Maximum Block
|
You are given an array of length $2^n$. The elements of the array are numbered from $1$ to $2^n$.
You have to process $q$ queries to this array. In the $i$-th query, you will be given an integer $k$ ($0 \le k \le n-1$). To process the query, you should do the following:
- for every $i \in [1, 2^n-2^k]$ \textbf{in ascending order}, do the following: if the $i$-th element was already swapped with some other element \textbf{during this query}, skip it; otherwise, swap $a_i$ and $a_{i+2^k}$;
- after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment).
For example, if the array $a$ is $[-3, 5, -3, 2, 8, -20, 6, -1]$, and $k = 1$, the query is processed as follows:
- the $1$-st element wasn't swapped yet, so we swap it with the $3$-rd element;
- the $2$-nd element wasn't swapped yet, so we swap it with the $4$-th element;
- the $3$-rd element was swapped already;
- the $4$-th element was swapped already;
- the $5$-th element wasn't swapped yet, so we swap it with the $7$-th element;
- the $6$-th element wasn't swapped yet, so we swap it with the $8$-th element.
So, the array becomes $[-3, 2, -3, 5, 6, -1, 8, -20]$. The subsegment with the maximum sum is $[5, 6, -1, 8]$, and the answer to the query is $18$.
Note that the queries actually \textbf{change the array}, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array.
|
Let's carefully analyze the operation denoted in the query. Since the length of the array is always divisible by $2^{k+1}$, every element will be swapped with some other element. The elements can be split into two groups - the ones whose positions increase by $2^k$, and the ones whose positions decrease by $2^k$. Let's find some trait of the elements which will allow us to distinguish the elements of one group from the elements of the other group. The first $2^k$ elements will be shifted to the right, the next $2^k$ elements will be shifted to the left, the next $2^k$ elements will be shifted to the right, etc. If we look at the binary representations of integers $0, 1, \dots, n-1$, then we can see that the first $2^k$ elements have $0$ in the $k$-th bit, the next $2^k$ elements have $1$ in the $k$-th bit, the next $2^k$ elements have $0$ in the $k$-th bit, and so on. So, if we consider the positions of elements as $0$-indexed, then the operation can be described as follows: "Let the position of the element be $i$. If the $k$-th bit in $i$ is $0$, $i$ gets increased by $2^k$, otherwise $i$ gets decreased by $2^k$". What does it look like? Actually, it is just $i \oplus 2^k$ (where $\oplus$ denotes XOR). So, each query can be represented as "swap $a_i$ with $a_{i \oplus x}$ for some integer $x$". The combination of two queries can also be represented with a single query; in fact, the state of the array can be denoted as the XOR of all $2^k$ from the previous queries. Now, let's try to solve the following problem: for every $x \in [0, 2^n-1]$, calculate the maximum sum of subsegment if every element $a_i$ is swapped with $a_{i \oplus x}$. To solve this problem, we can use a segment tree. First of all, we need to understand how to solve the problem of finding the maximum sum on subsegment using a segment tree. To do this, we should store the following four values in each vertex of the segment tree: $\mathit{sum}$ - the sum of elements on the segment denoted by the vertex; $\mathit{pref}$ - the maximum sum of elements on the prefix of the segment denoted by the vertex; $\mathit{suff}$ - the maximum sum of elements on the suffix of the segment denoted by the vertex; $\mathit{ans}$ - the answer on the segment. If some vertex of the segment tree has two children, these values for it can be easily calculated using the values from the children. So, we can "glue" two segments represented by the vertices together, creating a new vertex representing the concatenation of these segments. Okay, but how do we apply XOR to this? For every vertex of the segment tree, let's create several versions; the $x$-th version of the vertex $v$ represents the segment corresponding to this vertex if we apply swapping query with $x$ to it. For a vertex $v$ representing the segment of length $2^k$, we can use the following relation to get all its versions (here, we denote $t(v, x)$ as the $x$-th version of $v$, and $v_l$ and $v_r$ as the children of $v$): if $x \ge 2^{k-1}$, then $t(v, x) = \mathit{combine}(t(v_r, x-2^{k-1}), t(v_l, x-2^{k-1}))$; else $t(v, x) = \mathit{combine}(t(v_l, x), t(v_r, x))$; The function $\mathit{combine}$ here denotes the "glueing together" of two vertices we described above. Now let's try to analyze how many versions of each vertex we need. For the root, we will need all $2^n$ versions. For its children, we need only $2^{n-1}$ versions. For the children of the children of the root, we need only $2^{n-2}$ versions, and so on; so, overall, the total number of versions is only $O(n 2^n)$, and each version can be constructed in $O(1)$, so the solution works in $O(n 2^n)$.
|
[
"bitmasks",
"data structures",
"dfs and similar",
"divide and conquer",
"dp"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
const int K = 18;
struct node
{
long long sum, pref, suff, ans;
node(const node& l, const node& r)
{
sum = l.sum + r.sum;
pref = max(l.pref, l.sum + r.pref);
suff = max(r.suff, r.sum + l.suff);
ans = max(max(l.ans, r.ans), l.suff + r.pref);
}
node(int x)
{
sum = x;
pref = suff = ans = max(x, 0);
}
node() {};
};
int a[1 << K];
vector<node> tree[2 << K];
void build(int v, int l, int r)
{
tree[v].resize(r - l);
if(l == r - 1)
{
tree[v][0] = node(a[l]);
}
else
{
int m = (l + r) / 2;
build(v * 2 + 1, l, m);
build(v * 2 + 2, m, r);
for(int i = 0; i < m - l; i++)
{
tree[v][i] = node(tree[v * 2 + 1][i], tree[v * 2 + 2][i]);
tree[v][i + (m - l)] = node(tree[v * 2 + 2][i], tree[v * 2 + 1][i]);
}
}
}
int main()
{
int n;
scanf("%d", &n);
int m = (1 << n);
for(int i = 0; i < m; i++)
{
scanf("%d", &a[i]);
}
build(0, 0, m);
int q;
scanf("%d", &q);
int cur = 0;
for(int i = 0; i < q; i++)
{
int x;
scanf("%d", &x);
cur ^= (1 << x);
printf("%lld\n", tree[0][cur].ans);
}
}
|
1716
|
F
|
Bags with Balls
|
There are $n$ bags, each bag contains $m$ balls with numbers from $1$ to $m$. For every $i \in [1, m]$, there is exactly one ball with number $i$ in each bag.
You have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $1$ from the first bag and the ball $2$ from the second bag is not the same as taking the ball $2$ from the first bag and the ball $1$ from the second bag). After that, you calculate the number of balls with \textbf{odd} numbers among the ones you have taken. Let the number of these balls be $F$.
Your task is to calculate the sum of $F^k$ over all possible ways to take $n$ balls, one from each bag.
|
The main idea of this problem is to use a technique similar to "contribution to the sum". We will model the value of $F^k$ as the number of tuples $(i_1, i_2, \dots, i_k)$, where each element is an index of a bag from which we have taken an odd ball. Let $G(t)$ be the number of ways to take balls from bags so that all elements from tuple $t$ are indices of bags with odd balls; then, the answer to the problem can be calculated as the sum of $G(t)$ over all possible tuples $t$. First of all, let's obtain a solution in $O(k^2)$ per test case. We need to answer the following questions while designing a solution to the problem: How do we calculate $G(t)$ for a given tuple? How do we group tuples and iterate through them? The first question is not that difficult. Every element from the tuple $(i_1, i_2, \dots, i_k)$ should be an index of a bag from which we have taken an odd ball; so, for every bag appearing in the tuple, we can take only a ball with odd number; but for every bag not appearing in the tuple, we can choose any ball. So, if the number of distinct elements in a tuple is $d$, then $G(t)$ for the tuple can be calculated as $\lceil \frac{m}{2}\rceil^d \cdot m^{n-d}$. This actually gives as a hint for the answer to the second question: since $G(t)$ depends on the number of distinct elements in the tuple, let's try to group the tuples according to the number of distinct elements in them. So, the answer will be calculated as $\sum\limits_{i=1}^{k} H(i) \lceil \frac{m}{2}\rceil^i \cdot m^{n-i}$, where $H(i)$ is the number of tuples with exactly $i$ different elements. How do we calculate $H(i)$? First of all, if $i > n$, then $H(i)$ is obviously $0$. Otherwise, we can use the following recurrence: let $dp_{i,j}$ be the number of tuples of $i$ elements with $j$ distinct ones; then: if $i = 1$ and $j = 1$, $dp_{i,j} = n$ (for a tuple with one element, there are $n$ ways to choose it); if $i = 1$ and $j \ne 1$, $dp_{i,j} = 0$; if $i > 1$ and $j = 1$, $dp_{i,j} = dp_{i-1,j}$ (there is only one distinct element, and it was already chosen); if $i > 1$ and $j > 1$, $dp_{i,j} = dp_{i-1,j} \cdot j + dp_{i-1,j-1} \cdot (n-j+1)$ (we either add an element which did not belong to the tuple, and there are $n-j+1$ ways to choose it, or we add an already existing element, and there are $j$ ways to choose it). Obviously, this recurrence can be calculated in $O(k^2)$ with dynamic programming, so we get a solution in $O(k^2)$ per test case. How do we speed this up? Let's change the way we calculate $H(i)$. Instead of considering tuples with values from $1$ to $n$, we will consider only tuples where values are from $1$ to $k$, and the first appearance of a value $i$ is only after the first appearance of the value $i-1$. So, these tuples actually represent a way to split a set of integers $\{1, 2, \dots, n\}$ into several subsets; so they are the Stirling numbers of the second kind, and we can calculate them in $O(k^2)$ with dynamic programming outside of processing the test cases. How do we calculate $H(i)$ using these values? If we use $i$ distinct integers as the elements of the tuple, there are $n$ ways to choose the first one, $n-1$ ways to choose the second one, etc. - so $H(i) = S(k,i) \cdot \prod \limits_{j=0}^{i-1} (n-j)$, where $S(k, i)$ is the Stirling number of the second kind for the parameters $k$ and $i$. We can maintain the values of $\prod \limits_{j=0}^{i-1} (n-j)$ and $\lceil \frac{m}{2}\rceil^i \cdot m^{n-i}$ while iterating on $i$ from $1$ to $k$, and that gives us a way to solve the problem in $O(k)$ per test case. Overall complexity: $O(k^2)$ for precalculation and $O(k)$ per test case.
|
[
"combinatorics",
"dp",
"math",
"number theory"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 2043;
int dp[N][N];
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int sub(int x, int y)
{
return add(x, -y);
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int binpow(int x, int y)
{
int z = 1;
while(y > 0)
{
if(y % 2 == 1) z = mul(z, x);
x = mul(x, x);
y /= 2;
}
return z;
}
int inv(int x)
{
return binpow(x, MOD - 2);
}
int divide(int x, int y)
{
return mul(x, inv(y));
}
void precalc()
{
dp[1][1] = 1;
for(int i = 1; i < N - 1; i++)
for(int j = 1; j <= i; j++)
{
dp[i + 1][j] = add(dp[i + 1][j], mul(dp[i][j], j));
dp[i + 1][j + 1] = add(dp[i + 1][j + 1], dp[i][j]);
}
}
int solve(int n, int m, int k)
{
int way1 = (m / 2) + (m % 2);
int curA = n;
int ans = 0;
int ways_chosen = way1;
int ways_other = binpow(m, n - 1);
int invm = inv(m);
for(int i = 1; i <= k; i++)
{
ans = add(ans, mul(mul(curA, dp[k][i]), mul(ways_chosen, ways_other)));
curA = mul(curA, sub(n, i));
ways_chosen = mul(way1, ways_chosen);
ways_other = mul(ways_other, invm);
}
return ans;
}
int main()
{
int t;
cin >> t;
precalc();
for(int i = 0; i < t; i++)
{
int n, m, k;
cin >> n >> m >> k;
cout << solve(n, m, k) << endl;
}
}
|
1717
|
A
|
Madoka and Strange Thoughts
|
Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $(a, b)$ exist, where $1 \leq a, b \leq n$, for which $\frac{\operatorname{lcm}(a, b)}{\operatorname{gcd}(a, b)} \leq 3$.
In this problem, $\operatorname{gcd}(a, b)$ denotes the greatest common divisor of the numbers $a$ and $b$, and $\operatorname{lcm}(a, b)$ denotes the smallest common multiple of the numbers $a$ and $b$.
|
Notice that only the following pairs of numbers are possible: $(x, x)$, $(x, 2 \cdot x)$, and $(x, 3 \cdot x)$. Proof:Let $d = gcd(a, b)$. Now notice that it's impossible that $a = k \cdot d$ for some $k > 4$, because otherwise $lcm$ will be at least $k \cdot d > 3 \cdot d$. Therefore the only possible cases are the pairs listed above and $(2 \cdot d, 3 \cdot d)$, but in the latter case we have $lcm = 6 \cdot d$. The number of the pairs of the first kind is $n$, of the second kind is $2 \cdot \lfloor \frac{n}{2} \rfloor$, and of the third kind is $2 \cdot \lfloor \frac{n}{3} \rfloor$ (the factor $2$ in the latter two formulae arises from the fact that pairs are ordered). Therefore, the answer to the problem is $n + 2 \cdot \left( \lfloor \frac{n}{2} \rfloor + \lfloor \frac{n}{3} \rfloor \right)$.
|
[
"math",
"number theory"
] | 800
| null |
1717
|
B
|
Madoka and Underground Competitions
|
Madoka decided to participate in an underground sports programming competition. And there was exactly one task in it:
A square table of size $n \times n$, where \textbf{$n$ is a multiple of $k$}, is called good if only the characters '.' and 'X' are written in it, as well as in any subtable of size $1 \times k$ or $k \times 1$, there is at least one character 'X'. In other words, among any $k$ consecutive vertical or horizontal cells, there must be at least one containing the character 'X'.
Output any good table that has the \textbf{minimum} possible number of characters 'X', and also the symbol 'X' is written in the cell $(r, c)$. Rows are numbered from $1$ to $n$ from top to bottom, columns are numbered from $1$ to $n$ from left to right.
|
Notice that the answer to the problem is at least $\frac{n^2}{k}$, because you can split the square into so many non-intersecting rectangles of dimensions $1 \times k$. So let's try to paint exactly so many cells and see if maybe it's always possible. For simplicity, let's first solve the problem without necessarily painting $(r, c)$. In this case, we're looking for something like a chess coloring, which is a diagonal coloring. Let's number the diagonals from the "lowest" to the "highest". Notice that every $1 \times k$ and $k \times 1$ subrectangle intersects exactly $k$ consecutive diagonals, so we can paint every $k$-th diagonal to obtain the required answer: every such subrectangle will contain exactly one painted cell. To add the $(r, c)$ requirement back, notice that $(r, c)$ lies on the diagonal number $r + c$. (Because if you trace any path from $(0, 0)$ to $(r, c)$ with non-decreasing coordinates, going one cell upwards or rightwards increases exactly one of the coordinates by one, and also increases the number of the diagonal by one). Therefore, all we need to do is paint the cells whose coordinates satisfy $(x + y) \% k = (r + c) \% k$
|
[
"constructive algorithms",
"implementation"
] | 1,100
| null |
1717
|
C
|
Madoka and Formal Statement
|
Given an array of integer $a_1, a_2, \ldots, a_n$. In one operation you can make $a_i := a_i + 1$ if $i < n$ and $a_i \leq a_{i + 1}$, or $i = n$ and $a_i \leq a_1$.
You need to check whether the array $a_1, a_2, \ldots, a_n$ can become equal to the array $b_1, b_2, \ldots, b_n$ in some number of operations (possibly, zero). Two arrays $a$ and $b$ of length $n$ are called equal if $a_i = b_i$ for all integers $i$ from $1$ to $n$.
|
Firstly, we obviously require $a_i \le b_i$ to hold for all $i$. With that out of our way, let's consider non-trivial cases. Also let $a_{n+1} = a_1, b_{n+1} = b_1$ cyclically. For each $i$, we require that either $a_i = b_i$ or $b_i \leq b_{i + 1} + 1$ holds. That's because if we increment $a_i$ at least once, we had $a_i = b_i - 1$ and $a_{i + 1} \le b_{i + 1}$ before the last increment of $a_i$, and from here it's just a matter of simple algebraic transformations. Now let's prove these two conditions are enough. Let $i$ be the index of the minimal element of $a$ such that $a_i < b_i$ (i.e. the smallest element that's not ready yet). Notice that in this case we can, in fact, assign $a_i := a_i+1$, because $a_i \leq b_i \leq b_{i + 1} + 1$ holds, and now we're one step closer to the required array. It's easy to continue this proof by induction.
|
[
"greedy"
] | 1,300
| null |
1717
|
D
|
Madoka and The Corruption Scheme
|
Madoka decided to entrust the organization of a major computer game tournament "OSU"!
In this tournament, matches are held according to the "Olympic system". In other words, there are $2^n$ participants in the tournament, numbered with integers from $1$ to $2^n$. There are $n$ rounds in total in the tournament. In the $i$-th round there are $2^{n - i}$ matches between two players (one of whom is right, the other is left), after which the winners go further along the tournament grid, and the losing participants are eliminated from the tournament. Herewith, the relative order in the next round does not change. And the winner of the tournament — is the last remaining participant.
But the smaller the participant's number, the more he will pay Madoka if he wins, so Madoka wants the participant with the lowest number to win. To do this, she can arrange the participants in the first round as she likes, and also determine for each match who will win — the participant on the left or right.
But Madoka knows that tournament sponsors can change the winner in matches no more than $k$ times. (That is, if the participant on the left won before the change, then the participant on the right will win after the change, and if the participant on the right won, then the participant on the left will win after the change).
\begin{center}
{\small So, the first image shows the tournament grid that Madoka made, where the red lines denote who should win the match. And the second one shows the tournament grid, after one change in the outcome of the match by sponsors (a match between $1$ and $3$ players).}
\end{center}
Print the minimum possible number of the winner in the tournament, which Madoka can get regardless of changes in sponsors. But since the answer can be very large, output it modulo $10^9 + 7$. Note that we need to minimize the answer, and only then take it modulo.
|
The problem can be reformulated as follows. We've got a complete binary tree with $2^n$ leaves. There's a marked edge from each intermediate node to one of its children. The winner is the leaf reachable from the root via marked edges. Changes modify the outgoing marked edge of a node. Now it should be fairly obvious that there's no reason to change more than one node per level, because only one node matters per level--the one on the path from the root to the answer node. So, the winner only depends on the subset of levels we perform changes on, and vice versa: different subsets always yield different winners. Sponsors can change exactly $i$ nodes in $\binom{n}{i}$ ways. Summing this over $i$, we get $\sum_{i=0}^{\min(n, k)} \binom{n}{i}$. Call this number $m$. $m$ is the number of winners the sponsors choose between--let's call them candidates for brevity. It's easy to see that $m$ is the answer to the problem, because a) sponsors can guarantee the winner is at least $m$, as, independent of the list of candidate winners "provided" by Madoka, at least one of them must be at least $m$, and b) Madoka can guarantee the winner is at most $m$ by firstly marking edges arbitrarily, then computing the list of candidate nodes, and only then fill them with numbers from $1$ to $m$ (and the other nodes arbitrarily).
|
[
"combinatorics",
"constructive algorithms",
"greedy",
"math"
] | 1,900
| null |
1717
|
E
|
Madoka and The Best University
|
Madoka wants to enter to "Novosibirsk State University", but in the entrance exam she came across a very difficult task:
Given an integer $n$, it is required to calculate $\sum{\operatorname{lcm}(c, \gcd(a, b))}$, for all triples of positive integers $(a, b, c)$, where $a + b + c = n$.
In this problem $\gcd(x, y)$ denotes the greatest common divisor of $x$ and $y$, and $\operatorname{lcm}(x, y)$ denotes the least common multiple of $x$ and $y$.
Solve this problem for Madoka and help her to enter to the best university!
|
Let's bruteforce $c$, then we have $gcd(a, b) = gcd(a, a + b) = gcd(a, n - c)$. This means that $gcd(a, b)$ divides $n - c$, so let's just go through all divisors of $n - c$. For every factor $d$, the count of pairs $(a, b)$ satisfying $a + b = n - c$ and $gcd(a, b) = d$ is $\phi (\frac{n - c}{d})$, because we need $d$ to divide $a$ and be coprime with $\frac{n - c}{d}$, so that the $gcd$ is equal to $d$. Therefore, the answer to the problem is $\sum{lcm(c, d) * \phi{\frac{n - c}{d}}}$, where $1 \leq c \leq n - 2$ and $d$ is a factor of $n - c$.
|
[
"math",
"number theory"
] | 2,200
| null |
1717
|
F
|
Madoka and The First Session
|
Oh no, on the first exam Madoka got this hard problem:
Given integer $n$ and $m$ pairs of integers ($v_i, u_i$). Also there is an array $b_1, b_2, \ldots, b_n$, \textbf{initially filled with zeros}.
Then for each index $i$, where $1 \leq i \leq m$, perform either $b_{v_i} := b_{v_i} - 1$ and $b_{u_i} := b_{u_i} + 1$, or $b_{v_i} := b_{v_i} + 1$ and $b_{u_i} := b_{u_i} - 1$. Note that exactly one of these operations should be performed for every $i$.
Also there is an array $s$ of length $n$ consisting of $0$ and $1$. And there is an array $a_1, a_2, \ldots, a_n$, where it is guaranteed, that if $s_i = 0$ holds, then $a_i = 0$.
Help Madoka and determine whenever it is possible to perform operations in such way that for every $i$, where $s_i = 1$ it holds that $a_i = b_i$. If it possible you should also provide Madoka with a way to perform operations.
|
Let's reformulate the problem in terms of graphs. We are given an undirected graph and we are asked to determine edge directions, subject to fixed indegree minus outdegree (hereinafter balance) values for some vertices. It is tempting to think of this as a flow problem: edges indicate pipes with capacity of 1, vertices are producers or consumers of flow, and vertices with fixed differencies produce or consume an exact amount of flow. Except that's not quite an equivalent problem: a maxflow algorithm will find a flow, i.e. an orientation of edges, but it might just ignore some edges if it feels like it. We need to overcome this somehow by introducing incentive to use all edges. To do this, forget about the "edges are edges, vertices are vertices" idea for a while. Create an imaginary source and add a pipe with capacity 1 to every edge of the original graph. Technically, this is interpreting edges of the original graph as vertices of the flow graph. Non-technically, I like to interpret this like magically spawning flow into the middle of the edge. Now, the flow appearing in the edge has to actually go somewhere if we want the maxflow algorithm to treat it like a treasure it wants to increase. Let's just add two pipes: from the edge to vertex $u_i$ and from the edge to vertex $v_i$, because where else would it go? (technically, any capacity works, but let's use 1 for simplicity) This has a nice side effect of determining the orientation of the edge: if the flow from the edge goes into $u_i$, it's as if it was oriented from $v_i$ to $u_i$, and vice versa. A small problem is that this changes the semantics of the edge orientation somewhat. In the original problem, $u_i \to v_i$ incremented $v_i$ and decremented $u_i$. In the new formulation, only $v_i$ is incremented, so we need to transform the requirements $a_v$ on balances into requirements $b_v$ on indegrees: $b_v = \frac{a_v + \mathrm{deg} v}{2}$ (and we need to check that the numerator is even and non-negative, otherwise the answer is NO). How do we enforce the indegree requirements? For all vertices with $s_v = 1$, add a pipe from the vertex $v$ to an imaginary sink with capacity $b_v$. We expect all these pipes to be satiated. What about vertices with $s_v = 0$? Unfortunately, we can't just add a pipe from the vertex $v$ to an imaginary sink with capacity $\infty$, because if you have an edge with $s_v = 0$ and $s_u = 1$, the maxflow algorithm doesn't have any incentive to let the flow go to $u$ instead of $v$, so the pipe from $u$ to the sink might not get satiated and we might erroneously report a negative answer. How do we require certain pipes to be satiated? We could theoretically use a push-relabel algorithm, but in this case we can use something much simpler. The sum of capacities of all pipes from the imaginary source is $m$. We expect them all to be satiated, so this is the total flow we're expecting. The sum of capacities of all pipes to the imaginary sink we want to satiate is $\sum_v b_v$. Therefore, there's a surplus of flow of exactly $\Delta = m - \sum_v b_v$ (if it's negative, the answer is NO). So: create an intermediate vertex, add a pipe of capacity $\infty$ from each vertex with $s_v = 0$ to this intermediate vertex, and a pipe from this intermediate vertex to the imaginary sink with capacity $\Delta$. This will stop the algorithm from relying too much on non-fixed vertices. Run a maxflow algorithm. Check that every pipe from the source to an edge and every pipe from a vertex to the sink is satiated, or, alternatively, the maxflow is exactly $m$. If this does not hold, the answer is NO. If this holds, the answer is YES and the edge orientation can be restored by checking which of the two pipes from an edge is satiated. Is this fast? That depends on the algorithm heavily. Firstly, you can use the Edmonds-Karp algorithm. It works in $\mathcal{O}(FM)$, where $F$ is the maxflow and $M$ is the number of pipes. The former is $m$ and the latter is $n + m$, so we've got $\mathcal{O}((n + m) m)$, which is just fine. Secondly, you can use Dinic's algorithm, which is typically considered an improved version of Edmonds-Karp's, but is worse in some cases. It improves the number of rounds from $F$ to $\mathcal{O}(N)$, where $N$ is the number of vertices in the network, which doesn't help in this particular problem, sacrificing the complexity of a single phase, increasing it to $\mathcal{O}(NM)$, which is a disaster waiting to happen. Lots of people submitted Dinic's instead of Edmonds-Karp's. I don't know why, perhaps they just trained themselves to use Dinic's everywhere and didn't notice the unfunny joke here. Luckily for them, Dinic's algorithm still works. You might've heard it works in $\mathcal{O}(M N^{2/3})$ for unit-capacity networks, where $M$ is the number of pipes and $N$ is the number of vertices, which translates to $\mathcal{O}((n + m) n^{2/3})$ in our case, which would be good enough if the analysis held. Our network is not unitary, but it's easy to see how to make it into one. We use non-unit capacities in three cases: When we enforce the indegree, we add a pipe with capacity $b_v$ from the vertex to the sink. We can replace it with $b_v$ pipes of capacity 1. As $\sum_v b_v \le m$, this will not increase the number of pipes by more than $m$, so the complexity holds. Due to how Dinic's algorithm works, replacing a pipe with several pipes of the same total capacity does not slow the algorithm down. Similarly, the pipe from the intermediate vertex to the sink has capacity $\Delta \le m$, so we could theoretically replace it with $\Delta$ unit pipes and the complexity would hold. Finally, when we handle vertices with $s_v = 0$, we add pipes from such vertices to the intermediate vertex with capacity $\infty$. However, for each such vertex, the maximum used capacity is actually the count $k$ of edges incident with $v$, so the capacity of such pipes could be replaced with $k$. This would obviously have the same effect, and would not slow Dinic down: even if it tries to push more than $k$ through the corresponding backedge, it will quickly rollback, which affects the time taken by a single phase (non-asymptotically), but not the count of phases. As the sum of $k$ is $\mathcal{O}(m)$, we're fine again.
|
[
"constructive algorithms",
"flows",
"graph matchings",
"graphs",
"implementation"
] | 2,500
| null |
1718
|
A2
|
Burenka and Traditions (hard version)
|
\textbf{This is the hard version of this problem. The difference between easy and hard versions is only the constraints on $a_i$ and on $n$. You can make hacks only if both versions of the problem are solved.}
Burenka is the crown princess of Buryatia, and soon she will become the $n$-th queen of the country. There is an ancient tradition in Buryatia — before the coronation, the ruler must show their strength to the inhabitants. To determine the strength of the $n$-th ruler, the inhabitants of the country give them an array of $a$ of exactly $n$ numbers, after which the ruler must turn all the elements of the array into zeros in the shortest time. The ruler can do the following two-step operation any number of times:
- select two indices $l$ and $r$, so that $1 \le l \le r \le n$ and a non-negative integer $x$, then
- for all $l \leq i \leq r$ assign $a_i := a_i \oplus x$, where $\oplus$ denotes the bitwise XOR operation. It takes $\left\lceil \frac{r-l+1}{2} \right\rceil$ seconds to do this operation, where $\lceil y \rceil$ denotes $y$ rounded up to the nearest integer.
Help Burenka calculate how much time she will need.
|
Segments of length greater than 2 are not needed. For A1 you can use dynamic programming Dynamic programming where dp[i][v] means the minimum time to make $a_j = 0$ for $j < i$ and $a_i = v$. (Notice that v can be any number from 0 to 8191) There is an answer in which segments of length $2$ does not intersect with segments of length $1$. If $a_l\oplus a_{l + 1} \oplus \ldots \oplus a_{r} = 0$ is executed for $l, r$, then we can fill this segment with zeros in $r-l$ seconds using only segments of length 2. There is an answer where the time spent is minimal and the lengths of all the segments taken are 1 and 2. because of the segment $l, r, x$ can be replaced to $\lceil\frac{r-l+1}{2}\rceil$ of segments of length 2 and 1, or rather $[l, l + 1, x], [l+ 2, l + 3, x], \ldots, [r, r, x]$(or $[r-1, r, x]$ if $(l - r + 1)$ even). Note that if $a_l\oplus a_{l + 1} \oplus \ldots \oplus a_{r} = 0$ is executed for $l, r$, then we can fill the $l, r$ subsections with zeros for $r-l$ seconds with queries $[l, l+1, a_l], [l+1, l+2, a_l \oplus a_{l+1}], ... [r-1, r, a_l\oplus a_{l+1} \oplus \ldots \oplus a_r]$. Note that if a segment of length 2 intersects with a segment of length 1, they can be changed to 2 segments of length 1. It follows from all this that the answer consists of segments of length 1 and cover with segments of length 2. Then it is easy to see that the answer is ($n$ minus (the maximum number of disjoint sub-segments with a xor of 0)), because in every sub-segments with a xor of 0 we can spend 1 second less as I waited before. this amount can be calculated by dynamic programming or greedily. Our solution goes greedy with a set and if it finds two equal prefix xors($prefix_l = prefix_r$ means that $a_{l + 1} \oplus a_{l+2} \oplus \ldots \oplus a_{r} = 0$), it clears the set. 168724728 The complexity of the solution is $O(n \operatorname{log}(n))$.
|
[
"data structures",
"dp",
"greedy"
] | 1,900
|
t = int(input())
for i in range(t):
n = int(input())
lst = list(map(int, input().split()))
res = n
for i in range(1, n):
lst[i] ^= lst[i - 1]
st = set()
st.add(0)
for i in lst:
if i in st:
res -= 1
st.clear()
st.add(i)
print(res)
|
1718
|
B
|
Fibonacci Strings
|
In all schools in Buryatia, in the $1$ class, everyone is told the theory of Fibonacci strings.
"A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci string if, when it is divided into blocks, their lengths in the order they appear in the string form the Fibonacci sequence ($f_0 = f_1 = 1$, $f_i = f_{i-2} + f_{i-1}$), starting from the zeroth member of this sequence. A string is called semi-Fibonacci if it possible to reorder its letters to get a Fibonacci string."
Burenka decided to enter the Buryat State University, but at the entrance exam she was given a difficult task. She was given a string consisting of the letters of the Buryat alphabet (which contains exactly $k$ letters), and was asked if the given string is semi-Fibonacci. The string can be very long, so instead of the string, she was given the number of appearances of each letter ($c_i$ for the $i$-th letter) in that string. Unfortunately, Burenka no longer remembers the theory of Fibonacci strings, so without your help she will not pass the exam.
|
Try to express $n$(the sum of all $c_i$) as $F_1 + F_2 + \ldots + F_m = n$. Let, $n = F_1 + F_2 + \ldots + F_m$, then try to find the minimum $x$ starting from which if there is $c_i=x$ there is no answer. $x$ is (the maximum sum of the Fibonacci numbers, among which there are no neighbors) + 1. $x$ is $F_1 + F_3 + F_5 + \ldots + F_{m} + 1$ for odd $m$ and $F_2 + F_4 + F_6 + \ldots + F_{m} + 1$ for even. $x$ is $F_{m+1} + 1$ for odd $m$ and $F_{m+1}$ for even. Try to understand if it can happen that there are two different answers in which the letter forming the block of length $F_{m}$ differs. The correct answer is: yes if there is $c_i = F_m$ and $c_j = F_m$ and this is only way. Now, using everything you have understood, write a greedy solution. Try to write a greedy solution. The programmer does not need a second hint, he wrote a greedy solution after the first one. At the beginning, let's check that the number $n$ (the sum of all $c_i$) is representable as the sum of some prefix of Fibonacci numbers, otherwise we will output the answer NO. Let's try to type the answer greedily, going from large Fibonacci numbers to smaller ones. For the next Fibonacci number, let's take the letter with the largest number of occurrences in the string from among those that are not equal to the previous letter taken (to avoid the appearance of two adjacent blocks from the same letter, which cannot be). If there are fewer occurrences of this letter than this number, then the answer is NO. Otherwise, we will put the letter on this Fibonacci number and subtract it from the number of occurrences of this letter.If we were able to dial all the Fibonacci numbers, then the answer is YES. Why does the greedy solution work? Suppose at this step you need to take $F_i$ (I will say take a number from $c_t$, this will mean taking $F_i$ letters $t$ from string), let's look at the maximum $c_x$ now, if it cannot be represented as the sum of Fibonacci numbers up to $F_i$ among which there are no neighbors, then the answer is no. It can be proved that if $c_x > F_{i+1}$, then it is impossible to represent $c_x$. If there is exactly one number greater than or equal to $F_i$ at the step, then there is only one option to take a number, so the greedy solution works. If there are two such numbers and they are equal, then the option to take a number is exactly one, up to the permutation of letters. the greedy solution works again. If there are $c_j \geq F_i, c_x \geq F_i, j \ne x$, then we note that the larger of the numbers $c_j, c_x$ will be greater than $F_i$, if we don't take it, then at the next step this number will be greater than $F_{i+1}$ ($i$ will be 1 less), according to the above proven answer will not be, so, taking the larger of the numbers is always optimal. The complexity of the solution is $O(k \operatorname{log}(n)\operatorname{log}(k))$.
|
[
"greedy",
"implementation",
"math",
"number theory"
] | 2,000
| null |
1718
|
C
|
Tonya and Burenka-179
|
Tonya was given an array of $a$ of length $n$ written on a postcard for his birthday. For some reason, the postcard turned out to be a \textbf{cyclic array}, so the index of the element located strictly to the right of the $n$-th is $1$. Tonya wanted to study it better, so he bought a robot "Burenka-179".
A program for Burenka is a pair of numbers $(s, k)$, where $1 \leq s \leq n$, $1 \leq k \leq n-1$. Note that $k$ \textbf{cannot} be equal to $n$. Initially, Tonya puts the robot in the position of the array $s$. After that, Burenka makes \textbf{exactly} $n$ steps through the array. If at the beginning of a step Burenka stands in the position $i$, then the following happens:
- The number $a_{i}$ is added to the usefulness of the program.
- "Burenka" moves $k$ positions to the right ($i := i + k$ is executed, if $i$ becomes greater than $n$, then $i := i - n$).
Help Tonya find the maximum possible usefulness of a program for "Burenka" if the initial usefulness of any program is $0$.
Also, Tony's friend Ilyusha asks him to change the array $q$ times. Each time he wants to assign $a_p := x$ for a given index $p$ and a value $x$. You need to find the maximum possible usefulness of the program after each of these changes.
|
The answer for $k=x$ and $k=\gcd(x,n)$ is the same. In this problem, a general statement is useful: for any array $c$ of length $m$, $m\cdot\operatorname{max}(c_1, c_2, \ldots, c_m) \geq c_1 +c_2 +\ldots+c_m$ is true. Try applying the second hint for $k_1$ and $k_2$ divisible by $k_1$, where $k_1, k_2$ are divisors of $n$. We can consider only $k$ which equals to $\frac{n}{p}$, where $p$ is a simple divisor of $n$. Let's note that the answer for $k=x$ and $k=\gcd(x,n)$ is the same. Indeed, for the number $k$, we will visit numbers with indices $s + ik \mod n$ for $i$ from $0$ to $n-1$ inclusive, from this we can see that the index of the $i$-th number coincides with the index of $i + \frac{n}{\gcd(k,n)}$, and if we look at two indexes, the difference between which is $l$ and $l<\frac{n}{\gcd(k,n)}$, then they are different, since $k\cdot l \mod n \neq 0$, therefore, the answer is (the sum of numbers with indices $s + ik \mod n$ for $i$ from $0$ to $\frac{n}{\gcd(k,n)}-1$) $\cdot\gcd(k,n)$. Now let's prove that the first $\gcd(k,n)$ numbers are the same for $(s,x)$ and $(s,\gcd(x,n))$, note that only those indices that have the same remainder as $s$ when divided by $\gcd(x,n)$ are suitable, but there are only $\frac{n}{\gcd(k,n)}$ of such indices, and we proved that we should have $\frac{n}{\gcd(k,n)}$ of different indices, so they are all represented once, therefore the answer for $k=x$ and $k=\gcd(x, n)$ is the same, because the sum consists of the same numbers. So, we need to consider only $k$ being divisors of $n$, this is already passes tests if we write, for example, a segment tree, but we don't want to write a segment tree, so we go further, prove that for $k_1 = x$, the answer is less or equal than for $k_2 = x \cdot y$ if $k_1$ and $k_2$ are divisors of $n$, why is this so? Note that for the number $k$, the answer beats for $\gcd(k,n)$ groups of numbers, so that in each group there is exactly $\frac{n}{\gcd(k,n)}$ and each number is in exactly one group, and for different $s$ the answer will be (the sum in the group that $s$ belongs to) $\cdot\gcd(k,n)$. Let's look at the answer for the optimal $s$ for $k_1$, let's call the set at which it is reached $t$, note that in $k_2$ for different $s$ there are $m$ independent sets that are subsets of $t$. Let $m_i$ be the sum in the $i$-th set. Now note that we need to prove $max(m_1, m_2, \ldots, m_y) * y\geq m_1 +m_2 +\ldots m_y$ this is true for any $m_i$, easy to see. So you need to iterate the divisors which equals to $\frac{n}{p}$ where $p$ is prime, now it can be passed with a set. Hurray! For the divisor $d$, it is proposed to store answers for all pairs $(s, d)$, where $s\le\frac{n}{d}$ and the maximum among them, they can be counted initially for $O(n log n)$ for one $d$, each request is changing one of the values, this can be done for $O(log n)$. The complexity of the author's solution is $O(6\cdot n\operatorname{log}(n))$, where 6 is the maximum number of different prime divisors of the number $n$.
|
[
"data structures",
"greedy",
"math",
"number theory"
] | 2,400
| null |
1718
|
D
|
Permutation for Burenka
|
We call an array $a$ pure if all elements in it are pairwise distinct. For example, an array $[1, 7, 9]$ is pure, $[1, 3, 3, 7]$ isn't, because $3$ occurs twice in it.
A pure array $b$ is similar to a pure array $c$ if their lengths $n$ are the same and for all pairs of indices $l$, $r$, such that $1 \le l \le r \le n$, it's true that $$\operatorname{argmax}([b_l, b_{l + 1}, \ldots, b_r]) = \operatorname{argmax}([c_l, c_{l + 1}, \ldots, c_r]),$$ where $\operatorname{argmax}(x)$ is defined as the index of the largest element in $x$ (which is unique for pure arrays). For example, $\operatorname{argmax}([3, 4, 2]) = 2$, $\operatorname{argmax}([1337, 179, 57]) = 1$.
Recently, Tonya found out that Burenka really likes a permutation $p$ of length $n$. Tonya decided to please her and give her an array $a$ similar to $p$. He already fixed some elements of $a$, but exactly $k$ elements are missing (in these positions temporarily $a_i = 0$). It is guaranteed that $k \ge 2$. Also, he has a set $S$ of $k - 1$ numbers.
Tonya realized that he was missing one number to fill the empty places of $a$, so he decided to buy it. He has $q$ options to buy. Tonya thinks that the number $d$ suits him, if it is possible to replace all zeros in $a$ with numbers from $S$ and the number $d$, so that $a$ becomes a pure array similar to $p$. For each option of $d$, output whether this number is suitable for him or not.
|
Try to reduce the task to a single array and tree. Try to reduce the tree to a match of bipartite graph. The first part: For each $a_i=0$, a segment of suitable values. The second part: The set $S$ and the number $d$. There exist $L$ and $R$ such that the answer to the query is ''YES'' if and only if $L \le d \le R$. Let's build a tree recursively starting from the segment $[1, n]$, at each step we will choose the root of the subtree $v = \operatorname{argmax}([p_l, p_{l+1}\ldots, p_r]) +l - 1$, then recursively construct trees for subtrees $[l, v-1], [v+1, r]$ if they are not empty, then create edges from the root to the roots of these subtrees. What we got is called a Cartesian tree by array. This Cartesian tree will be mentioned further in the analysis. It is easy to see that Cartesian trees by arrays coincide if and only if these arrays are similar. Then the necessary and sufficient condition for the array $a$ to be similar to $p$ is that for any pair $u, v$ such that $u$ is in the subtree $v$, $a_v > a_u$ is satisfied, in other words $a_v$ is the maximum among the numbers in the subtree of the vertex $v$. Let's call the position $i$ initially empty if initially $a_i = 0$. Let's call an array $a$ almost similar to $p$ if for any pair $u, v$ such that $u$ is in the subtree $v$, $a_v > a_u$ is executed, or both positions $u$, $v$ are initially empty. Let's prove that if there is a way to fill in the gaps in $a$ to get an array almost similar to $p$, then there is also a way to fill in the gaps to get a similar to $p$ array $a$. Indeed, let's look at the $a$ array almost similar to $p$. let's walk through the tree recursively starting from the root. At the step with the vertex $v$, we first start recursively from all the children of $v$, now it is true for them that the maxima of their subtrees are in them, let's look at the maximum child $v$, let it be $u$, then if $a_v > a_u$, then everything is fine, otherwise $a_v < a_u$ note that $v$ is initially an empty position, because for all initially non-empty positions it is true that they are maximums in their subtrees (this is easy to see in the definition), but $v$ is not. Note that $u$ is initially an empty position. Otherwise, we have never changed $a_v$ and $a_u$, therefore, in the original array $a$ almost similar to $p$, $a_v > a_u$ contradiction was executed, it is contradiction. so $v, u$ are initially empty, we can perform $swap(a_v, a_u)$ and everything will be executed. After executing this algorithm, we changed only the initially empty elements and got $a$ similar to $p$. Q.E.D. How to check the existence of an array almost similar to $p$? Let's call the number $r_i$ the minimum among all the numbers $a_v$ such that $i$ is in the subtree of $v$. Let's call the number $l_i$ the maximum among all the numbers $a_v$ such that $v$ is in the subtree of $i$. it is easy to see that $a$ is almost similar to $p$ if and only if for all $i$, $l_i < a_i < r_i$ is satisfied. That sounds incredibly good. So, all we need is to find a matching of the set $S$ and number $d$ and segments $[l_i, r_i]$ for $i$ that are initially empty. Now it is easy to prove that the suitable $d$ is a continuous segment (let's say the answer is yes for $d_1$, we don't know the answer for $d_2$, try looking at the alternating path from $d_1$ to $d_2$ in good matching for $d_1$, it's easy to see that if there is such a path, then for $d_2$ the answer is yes, otherwise, no. If you look at the structure of the matching of points with segments, you can see that an alternating path exists for a continuous segment of values $d_2$). the boundaries can be found by binary search or by typing greedily twice. Final complexity is $O(n \operatorname{log} n)$ or $O(n \operatorname{log}^2 n)$
|
[
"data structures",
"graph matchings",
"greedy",
"math",
"trees"
] | 3,300
| null |
1718
|
E
|
Impressionism
|
Burenka has two pictures $a$ and $b$, which are tables of the same size $n \times m$. Each cell of each painting has a color — a number from $0$ to $2 \cdot 10^5$, and there are no repeating colors in any row or column of each of the two paintings, except color $0$.
Burenka wants to get a picture $b$ from the picture $a$. To achieve her goal, Burenka can perform one of $2$ operations: swap any two rows of $a$ or any two of its columns. Tell Burenka if she can fulfill what she wants, and if so, tell her the sequence of actions.
The rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $m$ from left to right.
|
you can notice that a pair of operations $1\, i\, j$, $2\, k\, t$ and $2\, k\, t$, $1\, i\, j$ lead to the same result, what does this mean? This means that operations can be represented as two permutations describing which swaps will occur with rows and which swaps will occur with columns. Try to reduce this problem to a graph isomorphism problem. Let's have two permutations: $p$ of length $n$ and $q$ of length $m$. Initially, both permutations are identical. For operation $1\, i\, j$, we will execute $\operatorname{swap}(p_i, p_j)$, for operation $2\, i\, j$ we will execute $\operatorname{swap}(q_i, q_j)$. It is easy to see that after performing all operations in the position $i, j$ will be $a_{p_i,q_j}$. Now we need to find permutations of $p, q$ so that $a_{p_i,q_j} = b_{i, j}$. Let's look at a bipartite graph where the first part is rows and the second is columns. Let if $a_{i,j}\ne 0$, then from $i$ there is an undirected edge in $j$ of the color $a_{i, j}$. if we construct the same graph for $b$, then we need to check for isomorphism two bipartite graphs, each edge of which has a color, and as we remember, by the condition of the vertex, 2 edges of the same color cannot be Incidence. Let's call them graph $a$ and graph $b$. This problem is largely for implementation, therefore, starting from this moment, the actions that you can observe in the author's solution are described 168728958. Let $n < m$ otherwise let's swap $n$ and $m$ in places. Let's try to match the elements of the array $a$ to the elements of the array $b$. Let's go through the indices from $1$ to $n$. Let's now choose which pair of $b$ to choose for the $i$-th vertex of the first fraction of the graph $a$. If we have already found a pair earlier, skip the step, otherwise let's sort out the appropriate option for the pair among all the vertices of the first component $b$ that do not yet have a pair, there are no more than $n$, after the vertices are matched, the edges are also uniquely matched (because there are no 2 edges of different colors), let's then run the substitution recursively for edges (if we have mapped the vertex $v$ to the vertex $u$ and from $v$ there is an edge of color $x$ in $i$, and from $u$ there is an edge $x$ in $j$, then it is easy to prove that in the answer $i$ will be mapped to $j$), which means we will restore the entire component. Let the sum of the number of vertices and the number of edges in the component be $k$, then we will perform no more than $n \cdot k$ actions to restore the component. by permutations, getting a sequence of swaps is a matter of technique, I will not explain it, but this is a separate function in the author's solution you will understand. in total, our solution works for $O(n(n\cdot m + n + m))$ or $O(min(n, m)(n\cdot m + n + m))$, where $n\cdot m + n +m$ is the total number of vertices and edges in all components. feel free to ask any questions
|
[
"constructive algorithms",
"graphs",
"implementation",
"math"
] | 3,500
|
#include <iostream>
#include "vector"
#include "algorithm"
#include "numeric"
#include "climits"
#include "iomanip"
#include "bitset"
#include "cmath"
#include "map"
#include "deque"
#include "array"
#include "set"
#include "random"
#define all(x) x.begin(), x.end()
using namespace std;
int swp = 0;
vector<vector<pair<int, int>>> havenumsN, havenumsM;
vector<vector<pair<int, int>>> havenumsN2, havenumsM2;
bool operator==(vector<pair<int, int>> &a, vector<pair<int, int>> &b) {
if (a.size() != b.size())
return 0;
for (int i = 0; i < a.size(); ++i) {
if (a[i].first != b[i].first)
return 0;
}
return 1;
}
bool operator!=(vector<pair<int, int>> &a, vector<pair<int, int>> &b) {
if (a.size() != b.size())
return 1;
for (int i = 0; i < a.size(); ++i) {
if (a[i].first != b[i].first)
return 1;
}
return 0;
}
void NO() {
cout << "-1\n";
exit(0);
}
vector<pair<int, int>> getswops(vector<int> a) {
map<int, int> mp;
vector<pair<int, int>> ans;
int n = a.size();
for (int i = 0; i < n; ++i) {
mp[a[i]] = i;
}
for (int i = 0; i < n; ++i) {
if (mp[i] != i) {
int i1 = i, i2 = mp[i];
ans.push_back({i1, i2});
swap(a[i1], a[i2]);
mp[a[i1]] = i1;
mp[a[i2]] = i2;
}
}
reverse(all(ans));
return ans;
}
struct inform {
bool good = 0;
int chpos = 0;
vector<int> deln;
vector<int> chansN, chansM;
inform(bool good1 = 0, int chpos1 = 0, vector<int> deln1 = {}, vector<int> chansN1 = {}, vector<int> chansM1 = {}) {
chpos = chpos1;
good = good1;
deln = deln1;
chansN = chansN1;
chansM = chansM1;
}
};
inform trysolve(int i, int ind, vector<int> goodn, vector<int> goodm) {
vector<array<int, 3>> que;
que.push_back({0, i, ind});
vector<int> nowina;
int chpos = 0;
while (!que.empty()) {
auto [typem, in2, in1] = que.back();
que.pop_back();
if (typem == 0) {
if (goodn[in2] != -1 and goodn[in2] != in1)
return {};
if (goodn[in2] != -1)
continue;
if (havenumsN[in1] != havenumsN2[in2]) {
return {};
}
goodn[in2] = in1;
if (in2 != in1)
chpos++;
nowina.push_back(in1);
for (int j = 0; j < havenumsN[in1].size(); ++j) {
que.push_back({1, havenumsN2[in2][j].second, havenumsN[in1][j].second});
}
} else {
if (goodm[in2] != -1 and goodm[in2] != in1)
return {};
if (goodm[in2] != -1)
continue;
if (havenumsM[in1] != havenumsM2[in2]) {
return {};
}
if (in2 != in1)
chpos++;
goodm[in2] = in1;
for (int j = 0; j < havenumsM[in1].size(); ++j) {
que.push_back({0, havenumsM2[in2][j].second, havenumsM[in1][j].second});
}
}
}
return {1, chpos, nowina, goodn, goodm};
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> pole(n, vector<int>(m)), pole2(n, vector<int>(m));
if (n > m) {
swp = 1;
swap(n, m);
pole.assign(n, vector<int>(m));
pole2.assign(n, vector<int>(m));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cin >> pole[j][i];
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cin >> pole2[j][i];
}
}
} else {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> pole[i][j];
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> pole2[i][j];
}
}
}
havenumsN.assign(n, {}), havenumsM.assign(m, {});
havenumsN2.assign(n, {}), havenumsM2.assign(m, {});
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (pole[i][j] != 0) {
havenumsN[i].push_back({pole[i][j], j});
havenumsM[j].push_back({pole[i][j], i});
}
if (pole2[i][j] != 0) {
havenumsN2[i].push_back({pole2[i][j], j});
havenumsM2[j].push_back({pole2[i][j], i});
}
}
}
for (int i = 0; i < n; ++i) {
sort(all(havenumsN[i]));
sort(all(havenumsN2[i]));
}
for (int i = 0; i < m; ++i) {
sort(all(havenumsM[i]));
sort(all(havenumsM2[i]));
}
set<int> nopt;
for (int i = 0; i < n; ++i) {
nopt.insert(i);
}
vector<int> goodn(n, -1), goodm(m, -1);
for (int i = 0; i < n; ++i) {
if (goodn[i] == -1) {
bool gd = 0;
int chp = 0;
vector<int> nn, nansn, nansm;
for (auto ind : nopt) {
if (havenumsN[ind] == havenumsN2[i]) {
inform a = trysolve(i, ind, goodn, goodm);
if (a.good) {
if (gd == 0) {
chp = a.chpos + 1;
}
gd = 1;
if (a.chpos < chp) {
nn = a.deln;
nansn = a.chansN;
nansm = a.chansM;
}
}
}
}
if (gd == 0) {
NO();
}
goodn = nansn;
goodm = nansm;
for (auto k : nn)
nopt.erase(k);
}
}
set<int> who;
for (int i = 0; i < m; ++i) {
who.insert(i);
}
for (int i = 0; i < m; ++i) {
who.erase(goodm[i]);
}
for (int i = 0; i < m; ++i) {
if (goodm[i] == -1) {
goodm[i] = *who.begin();
who.erase(who.begin());
}
}
cout << getswops(goodn).size() + getswops(goodm).size() << '\n';
if (swp)
swap(goodn, goodm);
for (auto i : getswops(goodn)) {
cout << "1 " << 1+i.first << ' ' << 1+i.second << '\n';
}
for (auto i : getswops(goodm)) {
cout << "2 " << 1+i.first << ' ' << 1+i.second << '\n';
}
}
|
1718
|
F
|
Burenka, an Array and Queries
|
Eugene got Burenka an array $a$ of length $n$ of integers from $1$ to $m$ for her birthday. Burenka knows that Eugene really likes coprime integers (integers $x$ and $y$ such that they have only one common factor (equal to $1$)) so she wants to to ask Eugene $q$ questions about the present.
Each time Burenka will choose a subsegment $a_l, a_{l + 1}, \ldots, a_r$ of array $a$, and compute the product of these numbers $p = a_l \cdot a_{l + 1} \cdot \ldots \cdot a_r$. Then she will ask Eugene to count the number of integers between $1$ and $C$ inclusive which are coprime with $p$.
Help Eugene answer all the questions!
|
The only one hint to this problem is don't try to solve, it's not worth it. In order to find the number of numbers from $1$ to $C$ that are mutually prime with $x$, we write out its prime divisors (various). Let these be prime numbers $a_{1}, a_{2}, \ldots, a_{k}$. Then you can find the answer for $2^{k}$ using the inclusion-exclusion formula. Because $\left\lfloor\frac{a}{b\cdot c}\right\rfloor = \left\lfloor\frac{\left\lfloor\frac{a}{b}\right\rfloor}{c}\right\rfloor$, a similar statement is made for $k$ numbers (you can divide completely in any order). Let's split the primes up to $2\times 10^4$ into 2 classes - small ($\leq 42$) and large (the rest). There are 13 small numbers, and 2249 large ones. Separately, we will write down pairs of large numbers that in the product give a number not exceeding $10 ^ 5$. There will be 4904 such pairs. Let's match each set of small primes with a mask. Let's write $dp[mask]$ - alternating sum over the $mask$ submasks of numbers $\left\lfloor\frac{C}{a_{1}\cdot a_{2}\cdot\ldots \cdot a_{k}} \right\rfloor$, where $a_{1}, \ldots, a_{k}$ - prime numbers from the submask. Similarly, we define $dp[mask][big]$ (in addition to the mask, there is a large prime $big$) and $dp[mask][case]$ (in addition to the mask, there are a pair of primes from a pair of large primes $case$). Each $dp$ can be counted for $states\times bits$, where $states$ - is the number of states in $dp$, and $bits$ - is the mask size (number of bits). If we write out all the large primes on the segment for which $mask$ - mask of small primes, the answer for this segment will be the sum of $dp[mask] + \sum dp[mask][big_{i}] + \sum dp[mask][case_{i}]$ (for $big$ and $case$ lying on the segment). Thus, the request can be answered in 7000 calls to $dp$. In order to find a set of prime numbers on a segment, you can use the MO algorithm. Final complexity is $O(n\sqrt{n} + q\times(\pi(m)+casesCount(C)))$ It is worth noting that (with a very strong desire) it is possible to further optimize the solution using avx, to speed up the calculation of the amount by submasks in dynamics by 16 times, to speed up the calculation of the amount of $dp[mask][big]$ by 8 times, which will allow you to answer the request in ~5000 (instead of 7000) calls to $dp$, and the pre-calculation for $4\cdot 10^7$ instead of $7\cdot 10^8$ (in fact, the pre-calculation works much faster due to compiler optimizations).
|
[
"data structures",
"math",
"number theory"
] | 3,300
| null |
1719
|
A
|
Chip Game
|
Burenka and Tonya are playing an old Buryat game with a chip on a board of $n \times m$ cells.
At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any \textbf{odd} number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.
Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way).
\begin{center}
{\small Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.}
\end{center}
|
Try to look at the parity of $n, m$. The player who wins does not depend on player's strategy. The only thing that the winning player depends on is the parity of $n, m$. Note that the game will end only when the chip is in the upper right corner (otherwise you can move it $1$ square to the right or up). For all moves, the chip will move $n - 1$ to the right and $m - 1$ up, which means that the total length of all moves is $n + m - 2$ (the length of the move is how much the chip moved per turn). Since the length of any move is odd, then after any move of Burenka, the sum of the lengths will be odd, and after any move of Tonya is even. So we can find out who made the last move in the game by looking at $(n + m - 2) \operatorname{mod} 2 = (n + m) \operatorname{mod} 2$. With $(n + m) \operatorname{mod} 2 = 0$, Tonya wins, otherwise Burenka. The complexity of the solution is $O(1)$.
|
[
"games",
"math"
] | 800
| null |
1719
|
B
|
Mathematical Circus
|
A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $n$ and $k$, \textbf{where $n$ is even}. Next, he takes all the integers from $1$ to $n$, and splits them all into pairs $(a, b)$ (each integer must be in exactly one pair) so that for each pair the integer $(a + k) \cdot b$ is divisible by $4$ (\textbf{note that the order of the numbers in the pair matters}), or reports that, unfortunately for viewers, such a split is impossible.
Burenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers $n$ and $k$.
Tonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it.
|
Instead of $k$, we can consider the remainder of dividing $k$ by 4. There is no answer for the remainder 0. For all other remainders, there is an answer. Note that from the number $k$ we only need the remainder modulo $4$, so we take $k$ modulo and assume that $0 \leq k \leq 3$. If $k = 0$, then there is no answer, because the product of the numbers in each pair must be divisible by $4 = 2^2$, that is, the product of all numbers from $1$ to $n$ must be divisible by $2^{\frac{n}{2} \cdot 2} = 2^n$, but the degree of occurrence of $2$ in this sum is $\lfloor\frac{n}{2}\rfloor +\lfloor\frac{n}{4}\rfloor$, which is less than $n$. If $k = 1$ or $k = 3$, then we will make all pairs of the form $(i, i + 1)$, where $i$ is odd. Then $a + k$ will be even in each pair, since $a$ and $k$ are odd, and since $b$ is also even, the product will be divisible by $4$. If $k = 2$, then we will do the same splitting into pairs, but in all pairs where $i + 1$ is not divisible by $4$, we will swap the numbers (that is, we will make $a = i + 1$ and $b = i$). Then in pairs where $i + 1 \operatorname{mod} 4 = 0$, $b$ is divisible by $4$ (therefore the product too), and in the rest $a + k$ is divisible by $4$ (since $a$ and $k$ have a remainder $2$ modulo $4$). The complexity of the solution is $O(n)$.
|
[
"constructive algorithms",
"math"
] | 800
| null |
1719
|
C
|
Fighting Tournament
|
Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya.
$n$ athletes participate in the tournament, numbered from $1$ to $n$. Burenka determined the strength of the $i$-th athlete as an integer $a_i$, where $1 \leq a_i \leq n$. All the strength values are different, that is, the array $a$ is a permutation of length $n$. We know that in a fight, if $a_i > a_j$, then the $i$-th participant always wins the $j$-th.
The tournament goes like this: initially, all $n$ athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.
Burenka decided to ask Tonya $q$ questions. In each question, Burenka asks how many victories the $i$-th participant gets in the first $k$ rounds of the competition for some given numbers $i$ and $k$. Tonya is not very good at analytics, so he asks you to help him answer all the questions.
|
Who would win duels if the strongest athlete was the first in queue? After what number of rounds is the strongest athlete guaranteed to be at the front of the queue? Simulate the first $n$ rounds and write down their winners so that for each person you can quickly find out the number of wins in rounds with numbers no more than a given number. Note that after the strongest athlete is at the beginning of the queue, only he will win. The strongest athlete will be at the beginning of the queue no more than after the $n$-th round. Let's simulate the first $n$ rounds, if the $j$-th athlete won in the $i$-th round, then we will write down the $i$ number for him. Now, to answer the query $(i, k)$, it is enough to find the number of wins of the $i$ athlete in rounds with numbers $j \leq k$, and if $k > n$, and the strength of the $i$ athlete is equal to $n$, then add to the answer another $k - n$. The complexity of the solution is $O(n + q \operatorname{log}(n))$.
|
[
"binary search",
"data structures",
"implementation",
"two pointers"
] | 1,400
| null |
1720
|
A
|
Burenka Plays with Fractions
|
Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($\frac{a}{b}$ and $\frac{c}{d}$) with integer numerators and denominators. Then children are commanded to play with their fractions.
Burenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by $0$). Now she wants know the minimal number of claps to make her fractions equal (by \textbf{value}). Please help her and find the required number of claps!
|
Note that we always can make fractions equal in two operations: Multiply first fraction's enumerator by $bc$, the first fraction is equal to $\frac{abc}{b} = ac$, Multiply second fraction's enumerator by $ad$, the second fraction is equal to $\frac{acd}{d} = ac$. That means that the answer does not exceed 2. If fractions are equal from input, the answer is 0. Otherwise, it can't be 0. Now we have to check if the answer is 1. Let's assume that for making fractions equal in 1 operation we have to multiply first fraction's enumerator by $x$. Then $\frac{ax}{b} = \frac{c}{d}$ must be true. From this we can see that $x = \frac{bc}{ad}$. $x$ must be integer, so $bc$ must be divisible by $ad$. If we assume that we multiplied first fraction's denumerator by $x$, we can do the same calculations and see that $ad$ must be divisible by $bc$. So, for checking if the answer is $1$ we need to check if one of $ad$ and $bc$ is divisible by another one. If we multiply second fraction's enumerator or denumerator by $x$ we will get the same conditions for answer being equla to 1. If the answer is not 0 or 1, it's 2. Complexity: $O(1)$
|
[
"math",
"number theory"
] | 900
|
#include <bits/extc++.h>
using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define sfor(i, l, r) for (int i = l; i <= r; ++i)
#define bfor(i, r, l) for (int i = r; i >= l; --i)
#define all(a) a.begin(), a.end()
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using vi = vector<int>;
using oset = tree<int, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update>;
void solve() {
ll a, b, c, d;
cin >> a >> b >> c >> d;
ll x = a * d, y = b * c;
if (x == y)
cout << "0\n";
else if (y != 0 && x % y == 0 || x != 0 && y % x == 0)
cout << "1\n";
else
cout << "2\n";
}
int main() {
fast;
int t;
cin >> t;
while (t--)
solve();
}
|
1720
|
B
|
Interesting Sum
|
You are given an array $a$ that contains $n$ integers. You can choose any proper subsegment $a_l, a_{l + 1}, \ldots, a_r$ of this array, meaning you can choose any two integers $1 \le l \le r \le n$, where $r - l + 1 < n$. We define the beauty of a given subsegment as the value of the following expression:
$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$
Please find the maximum beauty among all proper subsegments.
|
Obviously, answer does not exceed $max_{1} + max_{2} - min_{1} - min_{2}$, where $max_{1}, max_{2}$ are two maximum values in the array, and $min_{1}, min_{2}$ are two minimum values. Let's find a segment, such as this is true. For that we will look at all positions containing $max_{1}$ or $max_{2}$ ($S_{1}$) and all positions containing $min_{1}$ or $min_{2}$ ($S_2$). After that we choose a pair $l \in S_1$, $r \in S_2$, such as $abs(r - l)$ is minimum possible. Complexity: $O(n\log n)$
|
[
"brute force",
"data structures",
"greedy",
"math",
"sortings"
] | 800
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef long double ld;
#define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);
vector<ll> vec;
ll n;
int main() {
fastInp;
ll t;
cin >> t;
while (t--) {
cin >> n;
vec.resize(n);
for (auto& c : vec) cin >> c;
sort(vec.begin(), vec.end());
cout << vec[n - 1] + vec[n - 2] - vec[0] - vec[1] << "\n";
}
return 0;
}
|
1720
|
C
|
Corners
|
You are given a matrix consisting of $n$ rows and $m$ columns. Each cell of this matrix contains $0$ or $1$.
Let's call a square of size $2 \times 2$ without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing $1$ and replace all numbers in it with zeroes.
Find the \textbf{maximum} number of operations that you can do with the given matrix.
|
Let's say that $cnt_1$ is the number of ones in the table. Note that if there is a connected area of zeros in the table of size at least 2, then we can add one $0$ to this area by replacing only one 1 in the table. That means that if we have such area we can fill the table with zeros in $cnt_1$ operations (we can't make more opertions because we need to replace at least one 1 by operation). There can be no such area in the beginning, but after first operation it will appear. So, for finding the answer we just need to find an angle with minimal number of 1 in it, and which we can replace. Complexity: $O(nm)$
|
[
"greedy",
"implementation"
] | 1,200
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <array>
#include <cassert>
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <random>
#include <iomanip>
#include <chrono>
#include <bitset>
#include <queue>
#include <complex>
#include <functional>
using namespace std;
const int INF = 1e9;
const int MAXN = 2000;
int a[MAXN][MAXN];
inline void solve1() {
int n, m, sum = 0;
cin >> n >> m;
string s;
for (int i = 0; i < n; ++i) {
cin >> s;
for (int j = 0; j < m; ++j) {
a[i][j] = s[j] - '0';
sum += a[i][j];
}
}
int minn = INF;
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < m - 1; ++j) {
int cnt = a[i][j] + a[i + 1][j] + a[i][j + 1] + a[i + 1][j + 1];
if (cnt == 0) continue;
minn = min(minn, max(1, cnt - 1));
}
}
if (sum == 0) cout << "0\n";
else cout << 1 + sum - minn << "\n";
}
signed main() {
int t = 1;
cin >> t;
while (t--) {
solve1();
}
}
|
1720
|
D1
|
Xor-Subsequence (easy version)
|
\textbf{It is the easy version of the problem. The only difference is that in this version $a_i \le 200$.}
You are given an array of $n$ integers $a_0, a_1, a_2, \ldots a_{n - 1}$. Bryap wants to find the longest \textbf{beautiful} subsequence in the array.
An array $b = [b_0, b_1, \ldots, b_{m-1}]$, where $0 \le b_0 < b_1 < \ldots < b_{m - 1} < n$, is a subsequence of length $m$ of the array $a$.
Subsequence $b = [b_0, b_1, \ldots, b_{m-1}]$ of length $m$ is called \textbf{beautiful}, if the following condition holds:
- For any $p$ ($0 \le p < m - 1$) holds: $a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p$.
Here $a \oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \oplus 4 = 6$ and $3 \oplus 1=2$.
Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.
|
Let's use dynamic programming to solve this task. $dp_i$ -- maximum length of good subsequence, that ends int $i$-th element of $a$, than naive solution is $dp_i = \max_{\substack{j = 0 \\ a_j \oplus i < a_i \oplus j}}^i dp_j + 1$ Let's observe that $a_j \oplus i$ changes $i$ not more than by $200$. This way we can relax $dp_i$ not from $j = 0$, but $j = i - 512$, because xor operation changes only last 8 bits, so for $j' < i - 512$, definitely $a_{j'} \oplus j > a_{j} \oplus j'$. Additional idea: It not so hard to proove that we can try $j$ from $i - 256$ to $i - 1$.
|
[
"bitmasks",
"brute force",
"dp",
"strings",
"trees",
"two pointers"
] | 1,800
|
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
typedef long double ld;
#define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);
vector<ll> vec;
ll n;
const ll CHECK = 512;
int solve() {
cin >> n;
vec.resize(n);
for (auto& c : vec) cin >> c;
vector<ll> dp(1);
ll bst = 0;
for (int i = 0; i < n; i++) {
ll cur = 0;
dp.push_back(1);
for (int j = i - 1; j >= max(0ll, i - CHECK); j--) {
if ((vec[i] ^ j) > (vec[j] ^ i)) {
dp.back() = max(dp.back(), dp[j + 1] + 1);
}
}
bst = max(bst, dp.back());
}
cout << bst << "\n";
return 0;
}
int main(){
fastInp;
int t;
cin >> t;
while(t--) solve();
}
|
1720
|
D2
|
Xor-Subsequence (hard version)
|
\textbf{It is the hard version of the problem. The only difference is that in this version $a_i \le 10^9$.}
You are given an array of $n$ integers $a_0, a_1, a_2, \ldots a_{n - 1}$. Bryap wants to find the longest \textbf{beautiful} subsequence in the array.
An array $b = [b_0, b_1, \ldots, b_{m-1}]$, where $0 \le b_0 < b_1 < \ldots < b_{m - 1} < n$, is a subsequence of length $m$ of the array $a$.
Subsequence $b = [b_0, b_1, \ldots, b_{m-1}]$ of length $m$ is called \textbf{beautiful}, if the following condition holds:
- For any $p$ ($0 \le p < m - 1$) holds: $a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p$.
Here $a \oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \oplus 4 = 6$ and $3 \oplus 1=2$.
Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.
|
Let's calculate answer for each prefix. Let's find answer if the last number in our subsequence is number with index $i$. Let there be such $j$ that $a[j] \oplus i < a[i] \oplus j$. That means that there are $k$ bits in numbers $a[j] \oplus i$ and $a[i] \oplus j$ which are the same, and after that $a[j] \oplus i$ has different $k + 1$-th bit. Let's notice that if first $k$ bits are the same in $a[j] \oplus i$ and $a[i] \oplus j$, then these bits are the same in $a[j] \oplus j$ and $a[i] \oplus i$ Let's keep our answer in bit trie. We will add numbers $a[j] \oplus j$ for our prefix. To find dp value for index $i$, we will descend in our trie with pair of integers $a_i \oplus i$ and $i$. Each time we descend with bit $l$(0 or 1), in the opposite subtree there might be numbers which we can use to recalculate our answer. If in that subtree exists indexc $j$, then $k+1$-th bit of $a[j] \cdot i$ to $0$. Let's keep such dp for every subtree: maximum value of $dp[j]$ for every $j$, such that $j$ lies in the subtree (but we need to keep answer if $k$-th bit of $j$ is 0, and if it's equals 1). We should try to improve our answer using $j$ if we descend to the opposite subtree. Then we can easily find answer for current $i$. After that we only need to add our number in the trie and recalculate the dp. Complexity: O(n * logC) where C its max value
|
[
"bitmasks",
"data structures",
"dp",
"strings",
"trees"
] | 2,400
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxlog = 30;
const int maxn = 300000;
int nodes[maxn * maxlog + maxlog][2];
int nodev[maxn * maxlog + maxlog][2];
int last;
inline int f() {
nodes[last][0] = 0;
nodes[last][1] = 0;
nodev[last][0] = 0;
nodev[last][1] = 0;
return last++;
}
int solve() {
int n;
cin >> n;
vector <int> v(n);
for (auto& i : v) cin >> i;
int ans = 0;
last = 0;
f();
for (int i = 0; i < n; i++) {
int a = 0;
int b = v[i] ^ i;
int c = i;
int getmax = 0;
for (int j = maxlog; j >= 0; j--) {
if (nodes[a][((b >> j) & 1) ^ 1]) getmax = max(getmax, nodev[nodes[a][((b >> j) & 1) ^ 1]][(((b ^ c) >> j) & 1) ^ 1]);
if (!nodes[a][(b >> j) & 1]) break;
a = nodes[a][(b >> j) & 1];
}
ans = max(ans, getmax + 1);
a = 0;
b = v[i] ^ i;
c = i;
int d = getmax + 1;
for (int j = maxlog; j >= 0; j--) {
if (!nodes[a][(b >> j) & 1]) nodes[a][(b >> j) & 1] = f();
nodev[nodes[a][(b >> j) & 1]][(c >> j) & 1] = max(nodev[nodes[a][(b >> j) & 1]][(c >> j) & 1], d);
a = nodes[a][(b >> j) & 1];
}
}
cout << ans << "\n";
return 0;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while (t--) solve();
}
|
1720
|
E
|
Misha and Paintings
|
Misha has a \textbf{square} $n \times n$ matrix, where the number in row $i$ and column $j$ is equal to $a_{i, j}$. Misha wants to modify the matrix to contain \textbf{exactly} $k$ distinct integers. To achieve this goal, Misha can perform the following operation zero or more times:
- choose any \textbf{square} submatrix of the matrix (you choose $(x_1,y_1)$, $(x_2,y_2)$, such that $x_1 \leq x_2$, $y_1 \leq y_2$, $x_2 - x_1 = y_2 - y_1$, then submatrix is a set of cells with coordinates $(x, y)$, such that $x_1 \leq x \leq x_2$, $y_1 \leq y \leq y_2$),
- choose an integer $k$, where $1 \leq k \leq n^2$,
- replace all integers in the submatrix with $k$.
Please find the minimum number of operations that Misha needs to achieve his goal.
|
If $k$ is greater than the number of different numbers in the matrix, then the answer is $k$ minus the number of different elements. Otherwise the answer does not exceed 2. Let's proof that: choose the maximum square (let its side be equal to $L$), containing the top left corner of the matrix, such as recolouring it to some new colour makes the number of different colours in the table at least $k$. If the number of different colours after recolouring is greater than $k$, then choose a square with bottom right corner in $(L + 1, L + 1)$, such as recolouring it makes the number of different colours at least $k$. If we got exactly $k$ colours then we are done. Otherwise let's extend the square by one. We got $k$ or $k - 1$ different colours. This way, by choosing the correct colour of the square we can get exactly $k$ colours. Otherwise we are done. It remains to learn how to check whether the answer is equal to 1. We will iterate over length of the side of the square of the answer. Now we need $O(n^2)$ to check whether the required square with such a side exists. To do this, we calculate for each square in the table with such a side length (there are $n^2$ such squares), how many numbers this square completely covers (all appeareances of this numbers are in thsi square). To do this, let's iterate over the number $c$. Having considered its occurrences, it is easy to understand that the upper left corners of all squares with our side length, covering all cells with the number $c$, lie in some subrectangle of the table, so you can simply add 1 on this subrectangle using offline prefix sums. Having processed all the numbers in this way, we can count for each square how many numbers it covers completely, and therefore check whether it fits the requirements. Complexity: $O(n^3)$
|
[
"constructive algorithms",
"data structures",
"greedy",
"implementation",
"math"
] | 2,700
|
#include <iostream>
#include <vector>
#include <cmath>
#include <array>
using namespace std;
const int INF = 1e9;
inline int min(int a, int b) {
if (a < b) return a;
return b;
}
inline int max(int a, int b) {
if (a > b) return a;
return b;
}
inline void solve1() {
int n, k, cnt = 0;
cin >> n >> k;
vector <vector <int>> a(n, vector <int>(n)), pref(n + 1, vector <int>(n + 1));
vector <array <int, 4>> all(n * n, { INF, -INF, INF, -INF });
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> a[i][j]; --a[i][j];
all[a[i][j]][0] = min(all[a[i][j]][0], i);
all[a[i][j]][1] = max(all[a[i][j]][1], i);
all[a[i][j]][2] = min(all[a[i][j]][2], j);
all[a[i][j]][3] = max(all[a[i][j]][3], j);
}
}
for (auto& i : all) {
if (i[0] != INF) ++cnt;
}
if (cnt <= k) {
cout << k - cnt;
return;
}
for (int len = 1; len <= n; ++len) {
for (auto& i : all) {
if (i[0] == INF) continue;
int mn_x = i[0], mx_x = i[1], mn_y = i[2], mx_y = i[3];
mx_x = max(0, mx_x - len + 1);
mx_y = max(0, mx_y - len + 1);
mn_x = min(mn_x, n - len);
mn_y = min(mn_y, n - len);
if (mx_x <= mn_x && mx_y <= mn_y) {
++pref[mx_x][mx_y];
--pref[mx_x][mn_y + 1];
--pref[mn_x + 1][mx_y];
++pref[mn_x + 1][mn_y + 1];
}
}
for (int x = 0; x < n; ++x) {
for (int y = 0; y < n; ++y) {
if (x == 0 && y == 0) continue;
else if (x == 0) pref[x][y] += pref[x][y - 1];
else if (y == 0) pref[x][y] += pref[x - 1][y];
else pref[x][y] += pref[x - 1][y] + pref[x][y - 1] - pref[x - 1][y - 1];
}
}
for (int x = 0; x < n; ++x) {
for (int y = 0; y < n; ++y) {
if (cnt - pref[x][y] == k || cnt - pref[x][y] + 1 == k) {
cout << 1;
return;
}
}
}
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
pref[i][j] = 0;
}
}
}
cout << 2;
}
int main() {
if (1) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
if (1) {
int t = 1;
// cin >> t;
while (t--) {
solve1();
}
}
return 0;
}
|
1721
|
A
|
Image
|
You have an image file of size $2 \times 2$, consisting of $4$ pixels. Each pixel can have one of $26$ different colors, denoted by lowercase Latin letters.
You want to recolor some of the pixels of the image \textbf{so that all $4$ pixels have the same color}. In one move, you can choose \textbf{no more than two} pixels \textbf{of the same color} and paint them into some other color \textbf{(if you choose two pixels, both should be painted into the same color)}.
What is the minimum number of moves you have to make in order to fulfill your goal?
|
There are some solutions based on case analysis, but in my opinion, the most elegant one is the following: Let's pick a color with the maximum possible number of pixels and repaint all other pixels into it. We will try to pick all pixels of some other color and repaint them in one operation, and we can ignore the constraint that we can repaint no more than $2$ pixels, since we will never need to repaint $3$ or $4$ pixels in one operation. So, the number of operations is just the number of colors other than the one we chosen, or just $d - 1$, where $d$ is the number of different colors in the image. To calculate this, we can use a set or an array of size $26$, where we mark which colors are present.
|
[
"greedy",
"implementation"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
string s1, s2;
cin >> s1 >> s2;
s1 += s2;
cout << set<char>(s1.begin(), s1.end()).size() - 1 << endl;
}
}
|
1721
|
B
|
Deadly Laser
|
The robot is placed in the top left corner of a grid, consisting of $n$ rows and $m$ columns, in a cell $(1, 1)$.
In one step, it can move into a cell, adjacent by a side to the current one:
- $(x, y) \rightarrow (x, y + 1)$;
- $(x, y) \rightarrow (x + 1, y)$;
- $(x, y) \rightarrow (x, y - 1)$;
- $(x, y) \rightarrow (x - 1, y)$.
The robot can't move outside the grid.
The cell $(s_x, s_y)$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $d$ to the laser, it gets evaporated. The distance between two cells $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$.
Print the smallest number of steps that the robot can take to reach the cell $(n, m)$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $(n, m)$, print -1.
The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $d$ to the laser.
|
First, let's determine if it's possible to reach the end at all. If the laser's field doesn't span until any wall, then it's surely possible - just stick to the wall yourself. If it touches at most one wall, it's still possible. If it's the bottom wall or the left wall, then take the path close to the top and the right wall. Vice versa, if it's the top wall or the right wall, then take the path close to the bottom and the left wall. What if both of these paths are locked? That means that the laser touches at least two walls at the same time: the top one and the left one, or the bottom one and the right one. Turns out, it's completely impossible to reach the end in either of these two cases. Just draw a picture and see for yourself. Thus, we can always take at least one of the path sticking to the walls. The distance from the start to the end is $|n - 1| + |m - 1|$, and both of these paths are exactly this long. So the answer is always either -1 or $n + m - 2$. To check if the laser touches a wall with its field, you can either use a formula or check every cell adjacent to a wall. Overall complexity: $O(1)$ or $O(n + m)$ per testcase.
|
[
"implementation"
] | 1,000
|
for _ in range(int(input())):
n, m, sx, sy, d = map(int, input().split())
if min(sx - 1, m - sy) <= d and min(n - sx, sy - 1) <= d:
print(-1)
else:
print(n + m - 2)
|
1721
|
C
|
Min-Max Array Transformation
|
You are given an array $a_1, a_2, \dots, a_n$, which is sorted in non-descending order. You decided to perform the following steps to create array $b_1, b_2, \dots, b_n$:
- Create an array $d$ consisting of $n$ arbitrary \textbf{non-negative} integers.
- Set $b_i = a_i + d_i$ for each $b_i$.
- Sort the array $b$ in non-descending order.
You are given the resulting array $b$. For each index $i$, calculate what is the minimum and maximum possible value of $d_i$ you can choose in order to get the given array $b$.
Note that the minimum (maximum) $d_i$-s are \textbf{independent} of each other, i. e. they can be obtained from different possible arrays $d$.
|
For the start, let's note that $a_i \le b_i$ for each $i$. Otherwise, there is no way to get $b$ from $a$. Firstly, let's calculate $d_i^{min}$ for each $i$. Since all $d_i \ge 0$ then $b_j$ is always greater or equal than $a_i$ you get it from. So, the minimum $d_i$ would come from lowest $b_j$ that still $\ge a_i$. Since $b$ is sorted, we can find such $b_j$ with lower_bound in $O(\log{n})$. Let's prove that we can build such $d$ that transforms $a_i$ to $b_j$ we found earlier. Let's just make $d_k = b_k - a_k$ for $k \in [1..j) \cup (i..n]$; $d_k = b_{k+1} - a_k$ for $k \in [j..i)$ and $d_i = b_j - a_i$. It's easy to see that all $d_i$ are non-negative, so such $d$ is valid. Now, let's calculate $d_i^{max}$. Suppose, we transform $a_i$ to $b_j$ for some $j \ge i$. It's not hard to prove that the "proving" array $d$ may be constructed in the similar way: $d_k = b_k - a_k$ for $k \in [1..i) \cup (j..n]$; $d_k = b_{k-1} - a_k$ for $k \in (i..j]$ and $d_i = b_j - a_i$. In order to build such array $d$, you need $b_{k-1} \ge a_k$ for each $i \in (i..j]$. In other words, if there is some position $l$ such that $l > i$ and $b_{l - 1} < a_l$ you can't choose $j$ such that $j \ge l$. It means that we can iterate $i$ in descending order and just keep track of leftmost $l \ge i$ with $b_{l - 1} < a_l$. Then, $d_i^{max}$ is equal to $b[l - 1] - a[i]$ (or $b[n] - a[i]$ if there are no such $l$). The resulting complexity is $O(n \log n)$ because of the first part. But it can be optimized to $O(n)$ if we use two pointers instead of lower_bound.
|
[
"binary search",
"greedy",
"two pointers"
] | 1,400
|
fun main() {
repeat(readLine()!!.toInt()) {
val n = readLine()!!.toInt()
val a = readLine()!!.split(' ').map { it.toInt() }
val b = readLine()!!.split(' ').map { it.toInt() }
val indices = (0 until n).sortedBy { a[it] }
val mn = Array(n) { 0 }
val mx = Array(n) { 0 }
var lst = n
for (i in n - 1 downTo 0) {
val pos = indices[i]
mn[pos] = lowerBound(b, a[pos])
mx[pos] = lst - 1;
if (i == mn[pos])
lst = i
mn[pos] = b[mn[pos]] - a[pos]
mx[pos] = b[mx[pos]] - a[pos]
}
println(mn.joinToString(" "))
println(mx.joinToString(" "))
}
}
fun lowerBound(a: List<Int>, v: Int): Int {
var l = -1; var r = a.size
while (r - l > 1) {
val m = (l + r) / 2
if (a[m] < v)
l = m
else
r = m
}
return r
}
|
1721
|
D
|
Maximum AND
|
You are given two arrays $a$ and $b$, consisting of $n$ integers each.
Let's define a function $f(a, b)$ as follows:
- let's define an array $c$ of size $n$, where $c_i = a_i \oplus b_i$ ($\oplus$ denotes bitwise XOR);
- the value of the function is $c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n$ (i.e. bitwise AND of the entire array $c$).
Find the maximum value of the function $f(a, b)$ if you can reorder the array $b$ in an arbitrary way (leaving the initial order is also an option).
|
We will build the answer greedily, from the highest significant bit to the lowest one. Let's analyze how to check if the answer can have the highest bit equal to $1$. It means that every value in $c$ should have its highest bit equal to $1$, so for every $i$, exactly one of the numbers $\{a_i, b_i\}$ should have this bit equal to $1$. For both of the given arrays, we can calculate how many elements have which value of this bit, and then the number of elements with $1$ in this bit in the array $a$ should be equal to the number of elements with $0$ in the array $b$ (and the same for elements with $0$ in $a$ and elements with $1$ in $b$). If these values are equal, it means that the elements of $a$ and $b$ can be matched in such a way that in every pair, the XOR of them has $1$ in this bit. If it is so, then the highest bit of the answer is $1$, otherwise it is $0$. Okay, then let's proceed to the next bit. Should we just do the same to check if this bit can be equal to $1$ in the answer? Unfortunately, that's not enough. Let's look at the case: $a = [3, 0]$, $b = [2, 1]$. We can get the value $1$ in the $0$-th bit or in the $1$-st bit, but not in both simultaneously. So, for the next bit, we need to make sure that not only we can get $1$ in the result, but we can also do this without transforming some of the $1$-s to $0$-s in the higher bits. If it is impossible, it doesn't matter if we can get $1$ in the current bit since it will be suboptimal, so we have to use an ordering that gets $0$ in this bit. In general case, it means that we have to solve the following subproblem: check if we can obtain $1$ in several bits of the answer; let these bits be $\{x_1, x_2, \dots, x_k\}$ ($x_1$ to $x_{k-1}$ are the bits that we have already checked; $x_k$ is the new bit we are trying to check). Let $mask$ be the number that has $1$ in every bit $x_i$ and $0$ in every other bit. The elements should be matched in such a way that $(a_i \& mask) \oplus (b_i \& mask) = mask$. If we group all numbers from $a$ and from $b$ according to the value of $a_i \& mask$ (or $b_i \& mask$), then for every group of elements from $a$, there is a corresponding group in $b$ such that we can match the elements from the first group only with the elements from the second group. So, if for every such group, its size in $a$ is equal to the size of the corresponding group in $b$, then we can set all bits from $\{x_1, x_2, \dots, x_k\}$ to $1$ simultaneously. Some implementation notes: if the number of bits we need to check is big, the number of groups can become too large to handle all of them (since it is $2^k$). So, to store the number of elements in each group, we should use some associative data structure, like, for example, std::map in C++. If you use a map, splitting elements into groups will be done in $O(n \log n)$, so in total, you will get complexity of $O(n \log n \log A)$, where $A$ is the maximum possible value in the input.
|
[
"bitmasks",
"dfs and similar",
"divide and conquer",
"greedy",
"sortings"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n), b(n);
for (int& x : a) cin >> x;
for (int& x : b) cin >> x;
auto check = [&](int ans) {
map<int, int> cnt;
for (int x : a) ++cnt[x & ans];
for (int x : b) --cnt[~x & ans];
bool ok = true;
for (auto it : cnt) ok &= it.second == 0;
return ok;
};
int ans = 0;
for (int bit = 29; bit >= 0; --bit)
if (check(ans | (1 << bit)))
ans |= 1 << bit;
cout << ans << '\n';
}
}
|
1721
|
E
|
Prefix Function Queries
|
You are given a string $s$, consisting of lowercase Latin letters.
You are asked $q$ queries about it: given another string $t$, consisting of lowercase Latin letters, perform the following steps:
- concatenate $s$ and $t$;
- calculate the prefix function of the resulting string $s+t$;
- print the values of the prefix function on positions $|s|+1, |s|+2, \dots, |s|+|t|$ ($|s|$ and $|t|$ denote the lengths of strings $s$ and $t$, respectively);
- revert the string back to $s$.
The prefix function of a string $a$ is a sequence $p_1, p_2, \dots, p_{|a|}$, where $p_i$ is the maximum value of $k$ such that $k < i$ and $a[1..k]=a[i-k+1..i]$ ($a[l..r]$ denotes a contiguous substring of a string $a$ from a position $l$ to a position $r$, inclusive). In other words, it's the longest proper prefix of the string $a[1..i]$ that is equal to its suffix of the same length.
|
What's the issue with calculating the prefix function on the string $s$ and then appending the string $t$ with an extra $|t|$ recalculations? Calculating prefix function is linear anyway. Well, it's linear, but it's also amortized. So while it will make $O(n)$ operations for a string in total, it can take up to $O(n)$ on every particular letter. These particular letters can appear in string $t$, making the algorithm work in $O(q \cdot (|s| + |t|))$. Let's analyze the classic way to calculate the prefix function. To append a character to the string and calculate the new value of the prefix function, you have to do the following: take the longest proper prefix of a string before appending the letter, which is also a suffix; if the letter right after it is the same as the new one, then the new value is length of it plus one; if it's empty, then the new value is $0$; otherwise, take its longest proper prefix and return to step $2$. Basically, from having the value of the prefix function of the string and the new letter, you can determine the new value of the prefix function. If $|t|$ was always equal to $1$, then you would only want to try all options for the next letter after a string. That should remind you of a structure known as prefix function automaton. Its states are the values of the prefix function, and the transitions are appending a letter to a string with a certain value of the prefix function. So you can append a letter in $O(1)$ if you have an automaton built on the string $s$. However, you can't just append more letters after one - you don't have the automaton built this far. You can follow two paths. The first one is to jump with a regular way of calculating the prefix function until you reach the state of the automaton which exists. The second one is to continue building the automaton onto the string $t$, calculating the prefix function along the way. Appending a layer to the automaton takes $O(\mathit{AL})$ non-amortized. After you calculated everything you needed, pop the states back to the original. Overall complexity: $O(|s| \cdot \mathit{AL} + q \cdot |t|)$ or $O(|s| \cdot \mathit{AL} + q \cdot |t| \cdot \mathit{AL})$.
|
[
"dfs and similar",
"dp",
"hashing",
"string suffix structures",
"strings",
"trees"
] | 2,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int AL = 26;
vector<int> prefix_function(const string &s){
int n = s.size();
vector<int> p(n);
for (int i = 1; i < n; ++i){
int k = p[i - 1];
while (k > 0 && s[i] != s[k])
k = p[k - 1];
k += (s[i] == s[k]);
p[i] = k;
}
return p;
}
int main() {
cin.tie(0);
iostream::sync_with_stdio(false);
string s;
cin >> s;
int n = s.size();
auto p = prefix_function(s);
vector<vector<int>> A(n, vector<int>(AL));
forn(i, n) forn(j, AL){
if (i > 0 && j != s[i] - 'a')
A[i][j] = A[p[i - 1]][j];
else
A[i][j] = i + (j == s[i] - 'a');
}
int q;
cin >> q;
vector<vector<int>> ans(q);
forn(z, q){
string t;
cin >> t;
int m = t.size();
s += t;
for (int i = n; i < n + m; ++i){
A.push_back(vector<int>(AL));
forn(j, AL){
if (j != s[i] - 'a')
A[i][j] = A[p[i - 1]][j];
else
A[i][j] = i + (j == s[i] - 'a');
}
p.push_back(A[p[i - 1]][s[i] - 'a']);
ans[z].push_back(p[i]);
}
forn(_, m){
p.pop_back();
s.pop_back();
A.pop_back();
}
}
for (auto &it : ans){
for (int x : it)
cout << x << ' ';
cout << '\n';
}
return 0;
}
|
1721
|
F
|
Matching Reduction
|
You are given a bipartite graph with $n_1$ vertices in the first part, $n_2$ vertices in the second part, and $m$ edges. The maximum matching in this graph is the maximum possible (by size) subset of edges of this graph such that no vertex is incident to more than one chosen edge.
You have to process two types of queries to this graph:
- $1$ — remove the \textbf{minimum possible} number of vertices from this graph so that the size of the maximum matching gets reduced \textbf{exactly by $1$}, and print the vertices that you have removed. Then, find any maximum matching in this graph and print the sum of indices of edges belonging to this matching;
- $2$ — query of this type will be asked only after a query of type $1$. As the answer to this query, you have to print the edges forming the maximum matching you have chosen in the previous query.
Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
|
Let's start by finding the maximum matching in the given graph. Since the constraints are pretty big, you need something fast. The model solution converts the matching problem into a flow network and uses Dinic to find the matching in $O(m^{1.5})$, but something like heavily optimized Kuhn's algorithm can also work. Okay, then what about finding the minimum possible number of vertices to delete in order to reduce the maximum matching? We claim that it is always enough to remove one vertex, and the proof will also provide a way to quickly search for such vertices. Let's recall that the size of the maximum matching is equal to the size of the minimum vertex cover (this only works in bipartite graphs). So, we will try to find a way to reduce the minimum vertex cover by $1$, and it's actually pretty easy - just remove any vertex belonging to the vertex cover; it's obvious that it reduces the vertex cover by $1$, and the maximum matching by $1$ as well. So, we can find the minimum vertex cover in the graph using the standard algorithm to convert the MM into MVC (or, if you're using Dinic to find the maximum matching, you can represent the minimum vertex cover as the minimum cut problem), and for each query of type $1$, just take a vertex from the vertex cover we found. Now the only thing that's left is discussing how to maintain the structure of the maximum matching in the graph. In fact, it's quite easy: on the one hand, since we remove the vertices belonging to the minimum vertex cover, every edge (including the edges from the matching) will be incident to one of the vertices we will remove; on the other hand, due to the definition of the maximum matching, there is no vertex that is incident to two or more edges from the maximum matching; so, every vertex from the vertex cover has exactly one edge from the maximum matching that is incident to it, and when we remove a vertex, we can simply remove the corresponding edge from the maximum matching. So, the only thing we need to do is to maintain which edge from the matching corresponds to which vertex from the minimum vertex cover, and it will allow us to maintain the structure of the maximum matching - and since these "pairs" don't change when we remove a vertex, it is enough to get this information right after we have constructed the maximum matching in the given graph; we won't need to rebuild it.
|
[
"brute force",
"constructive algorithms",
"dfs and similar",
"flows",
"graph matchings",
"graphs",
"interactive"
] | 2,800
|
#include<bits/stdc++.h>
using namespace std;
const int N = 400043;
const int INF = int(1e9);
struct edge
{
int y, c, f;
edge() {};
edge(int y, int c, int f) : y(y), c(c), f(f) {};
};
vector<edge> e;
vector<int> g[N];
int S, T, V;
int d[N], lst[N];
int n1, n2, m, q;
map<pair<int, int>, int> es;
void add_edge(int x, int y, int c)
{
g[x].push_back(e.size());
e.push_back(edge(y, c, 0));
g[y].push_back(e.size());
e.push_back(edge(x, 0, 0));
}
int rem(int x)
{
return e[x].c - e[x].f;
}
bool bfs()
{
for (int i = 0; i < V; i++)
d[i] = INF;
d[S] = 0;
queue<int> q;
q.push(S);
while (!q.empty())
{
int k = q.front();
q.pop();
for (auto y : g[k])
{
if (rem(y) == 0)
continue;
int to = e[y].y;
if (d[to] > d[k] + 1)
{
q.push(to);
d[to] = d[k] + 1;
}
}
}
return d[T] < INF;
}
int dfs(int x, int mx)
{
if (x == T || mx == 0)
return mx;
int sum = 0;
for (; lst[x] < g[x].size(); lst[x]++)
{
int num = g[x][lst[x]];
int r = rem(num);
if (r == 0)
continue;
int to = e[num].y;
if (d[to] != d[x] + 1)
continue;
int pushed = dfs(to, min(r, mx));
if (pushed > 0)
{
e[num].f += pushed;
e[num ^ 1].f -= pushed;
sum += pushed;
mx -= pushed;
if (mx == 0)
return sum;
}
}
return sum;
}
int Dinic()
{
int ans = 0;
while (bfs())
{
for (int i = 0; i < V; i++)
lst[i] = 0;
int f = 0;
do
{
f = dfs(S, INF);
ans += f;
} while (f > 0);
}
return ans;
}
int main()
{
scanf("%d %d %d %d", &n1, &n2, &m, &q);
S = n1 + n2;
T = S + 1;
V = T + 1;
for (int i = 0; i < m; i++)
{
int x, y;
scanf("%d %d", &x, &y);
--x;
--y;
es[make_pair(x, y)] = i + 1;
add_edge(x, n1 + y, 1);
}
for (int i = 0; i < n1; i++)
add_edge(S, i, 1);
for (int i = 0; i < n2; i++)
add_edge(i + n1, T, 1);
Dinic();
bfs();
vector<int> vertex_cover;
map<int, int> index;
set<int> matched;
long long sum = 0;
for (int i = 0; i < n1; i++)
if (d[i] == INF)
{
vertex_cover.push_back(i + 1);
for (auto ei : g[i])
if (e[ei].f == 1)
{
int idx = es[make_pair(i, e[ei].y - n1)];
index[i + 1] = idx;
sum += idx;
matched.insert(idx);
}
}
for (int i = 0; i < n2; i++)
if (d[i + n1] != INF)
{
vertex_cover.push_back(-(i + 1));
for (auto ei : g[i + n1])
if (e[ei].f == -1)
{
int idx = es[make_pair(e[ei].y, i)];
index[-(i + 1)] = idx;
sum += idx;
matched.insert(idx);
}
}
for (int i = 0; i < q; i++)
{
int s;
scanf("%d", &s);
if (s == 1)
{
puts("1");
int v = vertex_cover.back();
vertex_cover.pop_back();
printf("%d\n", v);
sum -= index[v];
matched.erase(index[v]);
printf("%lld\n", sum);
}
else
{
printf("%d\n", (int)matched.size());
for(auto x : matched) printf("%d ", x);
puts("");
}
fflush(stdout);
}
}
|
1722
|
A
|
Spell Check
|
Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.
Today he wrote string $s$ of length $n$ consisting only of uppercase or lowercase Latin letters. He asks you to check if $s$ is the correct spelling of his name.
|
Check if the string has length 5 and if it has the characters $\texttt{T}, \texttt{i}, \texttt{m}, \texttt{u}, \texttt{r}$. The complexity is $\mathcal{O}(n)$. You can also sort the string, and check if it is $\texttt{Timur}$ when sorted (which is $\texttt{Timru}$).
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int main() {
string name = "Timur";
sort(name.begin(), name.end());
int n;
cin >> n;
forn(i, n) {
int m;
cin >> m;
string s;
cin >> s;
sort(s.begin(), s.end());
cout << (s == name ? "YES" : "NO") << endl;
}
}
|
1722
|
B
|
Colourblindness
|
Vasya has a grid with $2$ rows and $n$ columns. He colours each cell red, green, or blue.
Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.
|
Here are two solutions. Solution 1. Iterate through the string character by character. If $s_i=\texttt{R}$, then $t_i=\texttt{R}$; otherwise, if $s_i=\texttt{G}$ or $\texttt{B}$, then $t_i=\texttt{G}$ or $\texttt{B}$. If the statement is false for any $i$, the answer is NO. Otherwise it is YES. Solution 2. Replace all $\texttt{B}$ with $\texttt{G}$, since they are the same anyway. Then just check if the two strings are equal. In either case the complexity is $\mathcal{O}(n)$ per testcase.
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
string s, t;
cin >> s >> t;
for (int i = 0; i < n; i++) {
if (s[i] == 'R') {
if (t[i] != 'R') {cout << "NO\n"; return;}
}
else {
if (t[i] == 'R') {cout << "NO\n"; return;}
}
}
cout << "YES\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1722
|
C
|
Word Game
|
Three guys play a game: first, each person writes down $n$ distinct words of length $3$. Then, they total up the number of points as follows:
- if a word was written by one person — that person gets 3 points,
- if a word was written by two people — each of the two gets 1 point,
- if a word was written by all — nobody gets any points.
In the end, how many points does each player have?
|
You need to implement what is written in the statement. To quickly check if a word is written by another guy, you should store some map<string, int> or Python dictionary, and increment every time you see a new string in the input. Then, you should iterate through each guy, find the number of times their word appears, and update their score. The complexity is $\mathcal{O}(n \log n)$ per testcase.
|
[
"data structures",
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
map<string, int> mp;
string a[3][n];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
mp[a[i][j]]++;
}
}
for (int i = 0; i < 3; i++) {
int tot = 0;
for (int j = 0; j < n; j++) {
if (mp[a[i][j]] == 1) {tot += 3;}
else if (mp[a[i][j]] == 2) {tot++;}
}
cout << tot << ' ';
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1722
|
D
|
Line
|
There are $n$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The \textbf{value} of the line is the sum of each person's count.
For example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are $[0, 3, 2, 3, 4]$, and the value is $0+3+2+3+4=12$.
You are given the initial arrangement of people in the line. For each $k$ from $1$ to $n$, determine the maximum value of the line if you can change the direction of \textbf{at most} $k$ people.
|
For each person, let's calculate how much the value will change if they turn around. For example, in the line LRRLL, if the $i$-th person turns around, then the value of the line will change by $+4$, $-2$, $0$, $-2$, $-4$, respectively. (For instance, if the second person turns around, they see $3$ people before and $1$ person after, so the value of the line changes by $-2$ if they turn around.) Now note that if a person turns around, it doesn't affect anyone else's value. So the solution is a greedy one: let's sort the array of values in increasing order. Afterwards, we should go from the left to the right, and see if the value will increase if this person turns around; if it does, we should add it to the current total and continue. The time complexity of this solution is $\mathcal{O}(n \log n)$ per testcase.
|
[
"greedy",
"sortings"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
string s;
cin >> s;
long long tot = 0;
vector<long long> v;
for (int i = 0; i < n; i++) {
if (s[i] == 'L') {
v.push_back((n - 1 - i) - i);
tot += i;
}
else {
v.push_back(i - (n - 1 - i));
tot += n - 1 - i;
}
}
sort(v.begin(), v.end(), greater<int>());
for (int i = 0; i < n; i++) {
if (v[i] > 0) {tot += v[i];}
cout << tot << ' ';
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1722
|
E
|
Counting Rectangles
|
You have $n$ rectangles, the $i$-th rectangle has height $h_i$ and width $w_i$.
You are asked $q$ queries of the form $h_s \ w_s \ h_b \ w_b$.
For each query output, the total area of rectangles you own that \textbf{can fit}a rectangle of height $h_s$ and width $w_s$ while also \textbf{fitting in} a rectangle of height $h_b$ and width $w_b$. In other words, print $\sum h_i \cdot w_i$ for $i$ such that $h_s < h_i < h_b$ and $w_s < w_i < w_b$.
\textbf{Please note, that if two rectangles have the same height or the same width, then they cannot fit inside each other.} Also note that you \textbf{cannot} rotate rectangles.
Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
|
Consider the 2D array with $a[x][y]=0$ for all $x,y$. Increase $a[h][w]$ by $h \times w$ if there is an $h \times w$ rectangle in the input. Now for each query, we need to find the sum of all $a[x][y]$ in a rectangle with lower-left corner at $a[h_s+1][w_s+1]$ and upper-right corner at $a[h_b-1][w_b-1]$. This is the standard problem that can be solved with 2D prefix sums. The time complexity is $\mathcal{O}(n+q+\max(h_b)\max(w_b))$ per testcase. You can read about 2D prefix sums if you haven't heard of them before.
|
[
"brute force",
"data structures",
"dp",
"implementation"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
long long a[1005][1005];
long long pref[1005][1005];
void solve()
{
long long n, q;
cin >> n >> q;
for(int i = 0; i <= 1001; i++)
{
for(int j = 0; j <= 1001; j++)
{
a[i][j] = pref[i][j] = 0;
}
}
for(int i = 0; i < n; i++)
{
long long h, w;
cin >> h >> w;
a[h][w]+=h*w;
}
for(int i = 1; i <= 1000; i++)
{
for(int j = 1; j <= 1000; j++)
{
pref[i][j] = pref[i-1][j]+pref[i][j-1]-pref[i-1][j-1]+a[i][j];
}
}
for(int i = 0; i < q; i++)
{
long long hs, ws, hb, wb;
cin >> hs >> ws >> hb >> wb;
cout << pref[hb-1][wb-1]-pref[hb-1][ws]-pref[hs][wb-1]+pref[hs][ws] << endl;
}
}
int main() {
int t = 1;
cin >> t;
while(t--)
{
solve();
}
}
|
1722
|
F
|
L-shapes
|
An L-shape is a figure on gridded paper that looks like the first four pictures below. An L-shape contains exactly three shaded cells (denoted by *), which can be rotated in any way.
You are given a rectangular grid. Determine if it contains L-shapes only, where L-shapes can't touch an edge or corner. More formally:
- Each shaded cell in the grid is part of exactly one L-shape, and
- no two L-shapes are adjacent by edge or corner.
For example, the last two grids in the picture above \textbf{do not} satisfy the condition because the two L-shapes touch by corner and edge, respectively.
|
The problem is mainly a tricky implementation problem. Let's denote the elbow of an L-shape as the square in the middle (the one that is side-adjacent to two other squares). Every elbow is part of exactly one L-shape, and every L-shape has exactly one elbow. Iterate through the grid and count the number of side-adjacent neighbors they have. If there is a cell with more than 2, or if there is a cell with exactly two neighbors on opposite sides, then the answer is NO. Otherwise, if there are exactly 2 neighbors, this cell is an elbow. Mark all three cells of this L-shape with a unique number (say, mark the first one you find with $1$, the second with $2$, and so on.) If you ever remark a cell that already has a number, then two elbows are adjacent, and you can output NO. After all elbows are marked, check if all shaded cells have a number. If some don't, then they are not part of an L-shape, so you can output NO. Finally, we should check that L-shapes don't share edge or corner. Just check, for each number, if it is only diagonally adjacent to other numbers equal to it or unshaded cells. If it is diagonally adjacent to other unequal numbers, then the answer is NO, because two L-shapes share an edge or corner then. Otherwise the answer is YES. There are many other solutions, all of which are various ways to check the conditions. The complexity is $\mathcal{O}(mn)$ per testcase.
|
[
"dfs and similar",
"implementation"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
const int dx[3] = {-1, 0, 1}, dy[3] = {-1, 0, 1};
void solve() {
int n, m;
cin >> n >> m;
char g[n][m];
int id[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> g[i][j];
id[i][j] = 0;
}
}
int curr = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '*') {
vector<pair<int, int>> adjh, adjv;
if (i > 0 && g[i - 1][j] == '*') {
adjh.emplace_back(i - 1, j);
}
if (i < n - 1 && g[i + 1][j] == '*') {
adjh.emplace_back(i + 1, j);
}
if (j > 0 && g[i][j - 1] == '*') {
adjv.emplace_back(i, j - 1);
}
if (j < m - 1 && g[i][j + 1] == '*') {
adjv.emplace_back(i, j + 1);
}
if (adjh.size() == 1 && adjv.size() == 1) {
if (id[i][j] == 0) {id[i][j] = curr;}
else {cout << "NO\n"; return;}
if (id[adjh[0].first][adjh[0].second] == 0) {id[adjh[0].first][adjh[0].second] = curr;}
else {cout << "NO\n"; return;}
if (id[adjv[0].first][adjv[0].second] == 0) {id[adjv[0].first][adjv[0].second] = curr;}
else {cout << "NO\n"; return;}
curr++;
}
else if (adjh.size() > 1 || adjv.size() > 1) {
cout << "NO\n"; return;
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '*') {
if (id[i][j] == 0) {cout << "NO\n"; return;}
else {
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (0 <= i + dx[x] && i + dx[x] < n) {
if (0 <= j + dy[y] && j + dy[y] < m) {
if (id[i + dx[x]][j + dy[y]] != id[i][j] && id[i + dx[x]][j + dy[y]] != 0) {
cout << "NO\n"; return;
}
}
}
}
}
}
}
}
}
cout << "YES\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1722
|
G
|
Even-Odd XOR
|
Given an integer $n$, find any array $a$ of $n$ \textbf{distinct} nonnegative integers less than $2^{31}$ such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.
|
There are a lot of solutions to this problem. Here I will describe one of them. First, we observe that having the XOR of even indexed numbers and odd indexed numbers equal is equivalent to having the XOR of all the elements equal to 0. Let's note with $a$ the XOR of all odd indexed numbers and $b$ the xor of all even indexed numbers. Notice that the XOR of all the array equals $0$ if and only if a = b. So how do we generate such an array with XOR of all elements $0$? Our first instinct might be to arbitrarily generate the first $n-1$ numbers, then set the last element as the XOR of the first $n-1$, ensuring that the total XOR is $0$. However, we might have problems with the condition that all elements must be distinct. Let's arbitrarily set the first $n-2$ so that they don't have the highest bit($2^30$) set, and then the $n-1$-th number can be just $2^30$. The last number can be the XOR of the first $n-2$ XOR the $n-1$-th number; you will be sure that the last number has not occurred in the first $n-2$ elements because they don't have the highest bit set while the last number must have the highest bit set. But how do we know that the $n-1$-th number and the $n$-th number will not be equal? This occurs only if the total XOR of the first $n-2$ numbers equals $0$. To fix this, we can just choose a different arbitrary number in one of the $n-2$ spots. For example, my solution checks if the XOR of the numbers $0, 1, 2 ..., n-4, n-3$ is $0$. If it is not $0$, great! We can use the simple solution without any changes. However, if the XOR is $0$ I use the numbers $1, 2, 3, ...., n-3, n-2$ in their place. These two sequences have different XORs, so it ensures that one of them always works. Output the integers from $1$ to $n-3$, then $2^{29}$, $2^{30}$, and the XOR of those $n-1$ numbers. Why does it work?
|
[
"bitmasks",
"constructive algorithms",
"greedy"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin >> n;
int case1 = 0;
int case2 = 0;
for(int i = 0; i < n-2; i++)
{
case1^=i;
case2^=(i+1);
}
long long addLast = ((long long)1<<31)-1;
if(case1 != 0)
{
for(int i = 0; i < n-2; i++)
{
cout << i << " ";
}
case1^=addLast;
cout << addLast << " " << case1 << endl;
}
else
{
for(int i = 1; i <= n-2; i++)
{
cout << i << " ";
}
case2^=addLast;
cout << addLast << " " << case2 << endl;
}
}
int main()
{
int t = 1;
cin >> t;
while(t--)
{
solve();
}
}
|
1725
|
A
|
Accumulation of Dominoes
|
Pak Chanek has a grid that has $N$ rows and $M$ columns. Each row is numbered from $1$ to $N$ from top to bottom. Each column is numbered from $1$ to $M$ from left to right.
Each tile in the grid contains a number. The numbers are arranged as follows:
- Row $1$ contains integers from $1$ to $M$ from left to right.
- Row $2$ contains integers from $M+1$ to $2 \times M$ from left to right.
- Row $3$ contains integers from $2 \times M+1$ to $3 \times M$ from left to right.
- And so on until row $N$.
A domino is defined as two different tiles in the grid that touch \textbf{by their sides}. A domino is said to be \textbf{tight} if and only if the two numbers in the domino have a difference of exactly $1$. Count the number of distinct \textbf{tight} dominoes in the grid.
Two dominoes are said to be distinct if and only if there exists at least one tile that is in one domino, but not in the other.
|
We can divide the dominoes into two types: Horizontal dominoes. A domino is horizontal if and only if it consists of tiles that are on the same row. Vertical dominoes. A domino is vertical if and only if it consists of tiles that are on the same column. For an arbitrary tile in the grid that is not on the rightmost column, the integer in it is always exactly $1$ less than the integer in the tile that is directly to the right of it. So we can see that all possible horizontal dominoes are always tight. For an arbitrary tile in the grid that is not on the bottommost row, the integer in it is always exactly $M$ less than the integer in the tile that is directly to the bottom of it. So we can see that all possible vertical dominoes are tight if and only if $M=1$. We can calculate that there are $N \times (M-1)$ horizontal dominoes and $(N-1) \times M$ vertical dominoes. Therefore, we can get the following solution: If $M > 1$, then there are $N \times (M-1)$ tight dominoes. If $M = 1$, then there are $N-1$ tight dominoes. Time complexity: $O(1)$
|
[
"math"
] | 800
| null |
1725
|
B
|
Basketball Together
|
A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $5$ players in one team for each match). There are $N$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $i$-th candidate player has a power of $P_i$.
Pak Chanek will form zero or more teams from the $N$ candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of $D$. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is \textbf{strictly greater than $D$}.
One of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.
Determine the maximum number of wins that can be achieved by Pak Chanek.
|
For a team of $c$ players with a biggest power of $b$, the total power of the team is $b \times c$. So for a team with a biggest power of $b$ to win, it needs to have at least $\lceil \frac{D+1}{b} \rceil$ players. For each player $i$, we can calculate a value $f(i)$ which means a team that has player $i$ as its biggest power needs to have at least $f(i)$ players to win. We can see that the bigger the value of $P_i$, the smaller the value of $f(i)$. We can also see that if a formed team is said to have a fixed biggest power and a fixed number of players, the powers of the players that are less than the biggest power do not affect the total power of the team. So those players can be anyone. Using the information above, we can form the teams using a greedy method. We iterate through each candidate player starting from the biggest $P_i$ and form new teams with each next biggest candidate player power as each team's biggest power. We do that while maintaining the total number of extra players required to make all formed teams win. We stop once the number of remaining players is not enough for the total number of extra players required. Time complexity: $O(N \log N)$
|
[
"binary search",
"greedy",
"sortings"
] | 1,000
| null |
1725
|
C
|
Circular Mirror
|
Pak Chanek has a mirror in the shape of a circle. There are $N$ lamps on the circumference numbered from $1$ to $N$ in clockwise order. The length of the arc from lamp $i$ to lamp $i+1$ is $D_i$ for $1 \leq i \leq N-1$. Meanwhile, the length of the arc between lamp $N$ and lamp $1$ is $D_N$.
Pak Chanek wants to colour the lamps with $M$ different colours. Each lamp can be coloured with one of the $M$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $90$ degrees).
The following are examples of lamp colouring configurations on the circular mirror.
\begin{center}
\begin{tabular}{ccc}
& & \
Figure 1. an example of an incorrect colouring because lamps $1$, $2$, and $3$ form a right triangle & Figure 2. an example of a correct colouring & Figure 3. an example of a correct colouring \
\end{tabular}
\end{center}
Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $998\,244\,353$.
|
Let's represent the mirror as a circle with $N$ points at the circumference. First, one should notice that a circumscribed triangle (triangle whose vertices lie on the circumference of a circle) is a right triangle if only if one side of the triangle is the diameter of the circle. That means, for a single colour, there exists a right triangle with this colour if and only if both of the following conditions are satisfied: There exists two diametrically opposite points with this colour. This colour occurs in $3$ or more points. Let's call a pair of diametrically opposite points as a diameter pair. From the information above, we can see that if we colour the points in a diameter pair with the same colour, all other points must not have that colour. If that condition is satisfied for all diameter pairs, there cannot be a right triangle with the same colour. Let's find the number of diameter pairs in the circle and the number of points that do not belong to a diameter pair. Let the two values be $cntPair$ and $cntAlone$. One can find $cntPair$ and $cntAlone$ with two pointers or binary search using the prefix sum of the array $D$. To find the number of colouring configurations, we can iterate $i$ from $0$ to $\min(cntPair, M)$. In each iteration, we calculate the number of configurations that have exactly $i$ diameter pairs with the same colour on both of their points. It is calculated as follows: There are $\binom{cntPair}{i}$ ways to choose which diameter pairs have the same colour. Notice that each diameter pair with the same colour must have a different colour from each other. So there are $\binom{M}{i} \times i!$ ways to choose which colour is assigned to each diameter pair with the same colour. There are only $M-i$ available colours for colouring the remaining points. Each diameter pair with different colours can be coloured in $(M-i) \times (M-i-1)$ ways and each of the remaining points can be coloured in $M-i$ ways. So the total number of ways for a single value of $i$ is: $\binom{cntPair}{i} \times \binom{M}{i} \times i! \times ((M-i) \times (M-i-1))^{cntPair-i} \times (M-i)^{cntAlone}$ $\binom{cntPair}{i} \times \binom{M}{i} \times i! \times ((M-i) \times (M-i-1))^{cntPair-i} \times (M-i)^{cntAlone}$ Time complexity: $O((N+M) \log N)$
|
[
"binary search",
"combinatorics",
"geometry",
"math",
"two pointers"
] | 2,000
| null |
1725
|
D
|
Deducing Sortability
|
Let's say Pak Chanek has an array $A$ consisting of $N$ positive integers. Pak Chanek will do a number of operations. In each operation, Pak Chanek will do the following:
- Choose an index $p$ ($1 \leq p \leq N$).
- Let $c$ be the number of operations that have been done \textbf{on index $p$} before this operation.
- Decrease the value of $A_p$ by $2^c$.
- Multiply the value of $A_p$ by $2$.
After each operation, all elements of $A$ must be \textbf{positive integers}.
An array $A$ is said to be sortable if and only if Pak Chanek can do zero or more operations so that $A_1 < A_2 < A_3 < A_4 < \ldots < A_N$.
Pak Chanek must find an array $A$ that is sortable with length $N$ such that $A_1 + A_2 + A_3 + A_4 + \ldots + A_N$ is the minimum possible. If there are more than one possibilities, Pak Chanek must choose the array that is \textbf{lexicographically minimum} among them.
Pak Chanek must solve the following things:
- Pak Chanek must print the value of $A_1 + A_2 + A_3 + A_4 + \ldots + A_N$ for that array.
- $Q$ questions will be given. For the $i$-th question, an integer $P_i$ is given. Pak Chanek must print the value of $A_{P_i}$.
Help Pak Chanek solve the problem.
Note: an array $B$ of size $N$ is said to be lexicographically smaller than an array $C$ that is also of size $N$ if and only if there exists an index $i$ such that $B_i < C_i$ and for each $j < i$, $B_j = C_j$.
|
Define an array as distinctable if and only if Pak Chanek can do zero or more operations to make the elements of the array different from each other. Finding a sortable array $A$ of size $N$ with the minimum possible sum of elements is the same as finding a distinctable array $A$ of size $N$ with the minimum possible sum and permuting its elements. Define a value $k'$ as being reachable from a value $k$ if and only if we can do zero or more operations to the value $k$ to turn it into $k'$. To construct a distinctable array of size $N$ with the minimum possible sum, we can do a greedy method. Initially, the array $A$ is empty. Then, do the following iteration multiple times sequentially for each value $k$ from $1$, $2$, $3$, and so on until $A$ has $N$ elements: Consider each value $k'$ that is reachable from $k$. Let's say there are $w$ values $k'$ that has not been used as the final value for each of the previous elements of $A$. Append $w$ new elements with value $k$ to $A$ and assign the final value for each of the new elements with each of the usable values of $k'$. In the case where appending $w$ new elements makes the size of $A$ exceed $N$, we choose only some of the usable values of $k'$ to make the size of $A$ exactly $N$. Notice that while choosing the final values for each value $k$, there is only one way to do it for each iteration except the last iteration. For the last iteration, it can be obtained that in order to get the lexicographically minimum array, we choose the usable final values that are the largest ones. It can be obtained that each value that is reachable from $k$ is in the form of $x \times 2^y$ for some positive integer $x$ and some non-negative integer $y$ satisfying $x+y=k$. For a pair $(x, y)$, if we choose an even integer for $x$, we can always find another pair $(x_2, y_2)$ such that $x_2 \times 2^{y_2} = x \times 2^y$ and $x_2+y_2 \leq x+y$. From the logic of the greedy method, we can see that choosing an even integer for $x$ is always not optimal. For two distinct pairs $(x_1, y_1)$ and $(x_2, y_2)$, if both $x_1$ and $x_2$ are odd, then $x_1 \times 2^{y_1} \neq x_2 \times 2^{y_2}$ always holds. Using the knowledge above, we can see that during the greedy method, the usable final values for a value $k$ are all the ones with odd values of $x$, which there are $\lceil \frac{k}{2} \rceil$ of them. From this, we can see that in our greedy method, we only do $O(\sqrt N)$ iterations. So, we can get the sum of elements in our constructed array $A$ in $O(\sqrt N)$. To answer each query, we need to find the $P_i$-th smallest final value in the array and find which value produces it. We can construct an array $F_0, F_1, F_2, \ldots$ of size $O(\sqrt N)$. This means for each $i$, there are $F_i$ values $x \times 2^y$ with $y=i$, namely the ones with the values of $x$ being the $F_i$ smallest positive odd integers. We can convert each value $x \times 2^y$ into $x' \times 2^{y'}$ such that all values of $x'$ have the same MSB (Most Significant Bit). After converting, sorting the values $x' \times 2^{y'}$ is the same as sorting the pairs $(y', x')$. We can construct a two-dimensional array $G$ of size $O(\sqrt N) \times O(\log N)$ with $G_{i,j}$ representing the number of final values with $y' = i$ and $y = i-j$. To find the $P_i$-th smallest final value, firstly we find its value of $y'$ with binary search using array $G$. Now, for some integer $d$, we need to find the $d$-th smallest value of $x'$ for all final values with a certain value of $y'$. To find it, we do a binary search on a value $m$ with each iteration checking whether there are at least $d$ values of $x'$ that are less than or equal to $m$. Each iteration of the binary search can be computed by iterating $O(\log N)$ values in $G$ and using simple math. To find which value produces a certain final value, we just convert it back into $x \times 2^y$ and find the value of $x+y$. Time complexity: $O(\sqrt N \log N + Q \log^2N)$ Challenge: find the solution for $N \leq 10^{18}$.
|
[
"binary search",
"bitmasks",
"math"
] | 2,900
| null |
1725
|
E
|
Electrical Efficiency
|
In the country of Dengkleknesia, there are $N$ factories numbered from $1$ to $N$. Factory $i$ has an electrical coefficient of $A_i$. There are also $N-1$ power lines with the $j$-th power line connecting factory $U_j$ and factory $V_j$. It can be guaranteed that each factory in Dengkleknesia is connected to all other factories in Dengkleknesia through one or more power lines. In other words, the collection of factories forms a tree. Each pair of different factories in Dengkleknesia can use one or more existing power lines to transfer electricity to each other. However, each power line needs to be turned on first so that electricity can pass through it.
Define $f(x, y, z)$ as the minimum number of power lines that need to be turned on so that factory $x$ can make electrical transfers to factory $y$ and factory $z$. Also define $g(x, y, z)$ as the number of \textbf{distinct prime factors} of $\text{GCD}(A_x, A_y, A_z)$.
To measure the electrical efficiency, you must find the sum of $f(x, y, z) \times g(x, y, z)$ for all combinations of $(x, y, z)$ such that $1 \leq x < y < z \leq N$. Because the answer can be very large, you just need to output the answer modulo $998\,244\,353$.
Note: $\text{GCD}(k_1, k_2, k_3)$ is the greatest common divisor of $k_1$, $k_2$, and $k_3$, which is the biggest integer that simultaneously divides $k_1$, $k_2$, and $k_3$.
|
Note that $\sum_x \sum_y \sum_z f(x,y,z) \times g(x,y,z)$ can be alternatively expressed as the following: Iterate through every edge $e$ and every prime $p$. In each iteration, consider the set of vertices $S = \{x \mid A_x \text{ is divisible by } p\}$. Count how many triplets $a,b,c \in S$ such that each of the two components separated by $e$ contains at least one of $a,b,c$. Calculate the sum of those values for all possible $e$ and $p$. Note that if we root the tree and consider the edge $(x,y)$ where $x$ is the parent of $y$ in the rooted tree, then the number of triplets we count in one iteration is equivalent to $\binom{|S|}{3} - \binom{s}{3} - \binom{|S|-s}{3}$, where $s$ is the number of vertices in $S$ in the subtree of $y$. To calculate the answer, we can iterate through each prime $p$. For each prime, we only consider the vertices in $S$. We can build a sparse representation of a tree containing the vertices in $S$ (i.e. a virtual/auxiliary tree). More precisely, we only consider a set of vertices $S'$, where $x \in S'$ if and only if $x \in S$ or there exists $y,z \in S$ such that $\text{LCA}(y,z) = x$ (here, $\text{LCA}$ denotes the lowest common ancestor). It can be shown that $|S'| \leq 2|S|$. Each edge in the sparse tree connecting two vertices in $S'$ is a simple ancestor-descendant path consisting of one or more edges of the original tree. Notice that the number of triplets we count for each edge in the original tree that is not used in the sparse tree is always $0$. Also, for the edges in the original tree that make up a single edge of the sparse tree, the number of triplets we count for each of them is the same. Therefore, using the sparse tree we built, we can run a simple dynamic programming to count the answer for a single prime $p$ in $O(|S|)$ time. Notice that there are at most $\log A_x$ distinct prime factors of $A_x$, so the sum of $|S|$ for all primes is $O(N \log \max(A))$. Time complexity: $O(N \log N \log \max(A))$ or $O(N (\log N + \log \max(A)))$
|
[
"combinatorics",
"data structures",
"dp",
"math",
"number theory",
"trees"
] | 2,500
| null |
1725
|
E
|
Electrical Efficiency
|
In the country of Dengkleknesia, there are $N$ factories numbered from $1$ to $N$. Factory $i$ has an electrical coefficient of $A_i$. There are also $N-1$ power lines with the $j$-th power line connecting factory $U_j$ and factory $V_j$. It can be guaranteed that each factory in Dengkleknesia is connected to all other factories in Dengkleknesia through one or more power lines. In other words, the collection of factories forms a tree. Each pair of different factories in Dengkleknesia can use one or more existing power lines to transfer electricity to each other. However, each power line needs to be turned on first so that electricity can pass through it.
Define $f(x, y, z)$ as the minimum number of power lines that need to be turned on so that factory $x$ can make electrical transfers to factory $y$ and factory $z$. Also define $g(x, y, z)$ as the number of \textbf{distinct prime factors} of $\text{GCD}(A_x, A_y, A_z)$.
To measure the electrical efficiency, you must find the sum of $f(x, y, z) \times g(x, y, z)$ for all combinations of $(x, y, z)$ such that $1 \leq x < y < z \leq N$. Because the answer can be very large, you just need to output the answer modulo $998\,244\,353$.
Note: $\text{GCD}(k_1, k_2, k_3)$ is the greatest common divisor of $k_1$, $k_2$, and $k_3$, which is the biggest integer that simultaneously divides $k_1$, $k_2$, and $k_3$.
|
Special thanks to Um_nik for sharing this solution! Let's call $(i)$ as type $1$ cycles, $(i,j)$ as type $2$ cycles and $(i,j,i+1,j+1)$ as type $3$ cycles. What we will do, is we will fix the number of type $3$ and type $2$ cycles and come up with a formula. Let's say there are $s$ type $3$ cycles. We need to pick $2s$ numbers from $[1,n-1]$ such that no two are adjacent. The number of ways to do this is $\binom{n-2s}{2s}$. Then we can permute these numbers in $(2s)!$ ways and group the numbers in pairs of two, but these $s$ pairs can be permuted to get something equivalent, so we need to divide by $s!$. Hence we get: $\begin{aligned}\binom{n - 2s}{2s} \frac{(2s)!}{s!} \end{aligned}$Now, for the remaining $(n - 4s)$ elements, we know that only cycles will be of length $2$ or $1$. Let $I_k$ denote the number of permutations with cycles only of length $2$ and $1$. Then the final answer would be $\begin{aligned} \sum_{s=0}^{\lfloor \frac{n}{4} \rfloor}{\binom{n - 2s}{2s} \frac{(2s)!}{s!} I_{n - 4s}} \end{aligned}$Now, we would be done if we found out $I_k$ for all $k \in {1, 2, ... n}$. Observe that $I_1 = 1$ and $I_2 = 2$. Further for $k > 2$, the $k$-th element can appear in a cycle of length $1$, where there are $I_{k - 1}$ ways to do it; and the $k$-th element can appear in a cycle of length two, which can be done in $(k - 1) \cdot I_{k - 2}$ ways. Therefore we finally have: $\begin{aligned} I_k = I_{k - 1} + (k - 1) \cdot I_{k - 2}\end{aligned}$This completes the solution. Time complexity: $\mathcal{O}(n)$. Solution 2: the hard wayUsing the observations in Solution 1 this can be reduced to a counting problem using generating functions. Details follow. Now, from the remaining $n-4s$ numbers, let's pick $2k$ numbers to form $k$ type $2$ cycles. We can do this in $\binom{n-4s}{2k}$ ways. Like before, we can permute them in $(2k)!$ ways, but we can shuffle these $k$ pairs around so we have to divide by $k!$. Also, $(i,j)$ and $(j,i)$ are the same cycle, so we also need to divide by $2^k$ because we can flip the pairs and get the same thing. Finally, we have the following formula: $\begin{aligned} \sum_{s=0}^{\lfloor \frac{n}{4} \rfloor}{\sum_{k=0}^{\lfloor \frac{n-4s}{2} \rfloor}{\frac{(2s)!}{s!}\binom{n-2s}{2s}\binom{n-4s}{2k}\frac{(2k)!}{2^k k!}}} \end{aligned}$We can simplify this to get, $\begin{aligned} \sum_{s=0}^{\lfloor \frac{n}{4} \rfloor}{\frac{(n-2s)!}{s!}\sum_{k=0}^{\lfloor \frac{n-4s}{2} \rfloor}{\frac{1}{2^k (n-4s-2k)! k!}}} \end{aligned}$Now, observe that the answer is in the form of two nested summations. Let us focus on precomputing the inner summation using generating functions. We define the following generating function: $\begin{aligned} P(x) &= \sum_{r \ge 0}{ \Bigg( \sum_{k=0}^{\lfloor \frac{r}{2} \rfloor}{\frac{1}{2^k (r-2k)! k!}} \Bigg) } x^r \\ &= \sum_{r \ge 0}{ \Bigg( \sum_{k=0}^{\lfloor \frac{r}{2} \rfloor}{\frac{x^r}{2^k (r-2k)! k!}} \Bigg) } \\ &=\sum_{r \ge 0}{ \Bigg( \sum_{k=0}^{\lfloor \frac{r}{2} \rfloor}{\frac{x^{(r - 2k)}}{(r-2k)!} \cdot \frac{x^{2k}}{2^k k!}} \Bigg) } \\ &= \sum_{r \ge 0}{ \Bigg( \sum_{k=0}^{\lfloor \frac{r}{2} \rfloor}{\frac{x^{(r - 2k)}}{(r-2k)!} \cdot \frac{\big(\frac {x^2}{2} \big)^k}{k!}} \Bigg) } \\ &= \Bigg(\sum_{i \ge 0}{\frac{x^{i}}{i!} \Bigg)} \cdot \Bigg( \sum_{j \ge 0}{ \frac{\big(\frac {x^2}{2} \big)^j}{j!}} \Bigg) \\ P(x) &= \big(e^x \big) \cdot \big( e^{\frac {x^2}{2}} \big) = e^{x + \frac{x^2}{2}} \end{aligned}$We can compute the first few terms of $e^x = \sum_{i \ge 0}{\frac{x^{i}}{i!}}$ and $e^{\frac {x^2}{2}} = \sum_{j \ge 0}{ \frac{x^{2j}}{2^j j!}}$; and using FFT, we can multiply these (in $\mathcal O(n \log n)$ time) to get the first few terms of $P(x) = e^{x + \frac{x^2}{2}}$. Finally, we can get the answer (in $\mathcal O(n)$ time) as, $\begin{aligned} \sum_{s=0}^{\lfloor \frac{n}{4} \rfloor}{\frac{(n-2s)!}{s!} \Big([x^{n-4s}] P(x) \Big)} \end{aligned}$where $[x^m]F(x)$ is the coefficient of $x^m$ in the Taylor expansion of $F(x)$. Time complexity: $\mathcal{O}(\max{(t_i)}\log{\max{(t_i)}} + \sum{t_i})$, where $t_i$ is the value of $n$ in the $i$-th test case.
|
[
"combinatorics",
"data structures",
"dp",
"math",
"number theory",
"trees"
] | 2,500
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MAXN = 300005;
/* PARTS OF CODE for fft taken from https://cp-algorithms.com/algebra/fft.html */
const ll mod = 998244353;
const ll root = 15311432; // which is basically 3 ^ 119
const ll root_1 = 469870224;
const ll root_pw = (1 << 23);
ll fact[MAXN + 1], ifact[MAXN + 1], sum_pow[MAXN + 1];
vector<ll> P(MAXN); // this will be the first few terms of e^(x + (x^2)/2).
ll fxp(ll a, ll n){ // returns a ^ n modulo mod in O(log(mod)) time
if(!n){
return 1;
}else if(n & 1){
return a * fxp(a, n ^ 1) % mod;
}else{
ll v = fxp(a, n >> 1);
return v * v % mod;
}
}
inline ll inverse(ll a){ // returns the modular inverse of
return fxp(a % mod, mod -2);
}
void init_fact(){ // initializes fact[ ] and ifact[ ]
fact[0] = ifact[0] = 1;
for(int i = 1; i <= MAXN; ++i){
fact[i] = fact[i - 1] * i% mod;
ifact[i] = inverse(fact[i]);
}
}
ll C(ll n, ll r){ // returns nCr in O(1) time
return (r > n || r < 0) ? 0 : (ifact[r] * ifact[n - r] % mod * fact[n] % mod);
}
// code for fft in O(nlogn)
void fft(vector<ll>& a, bool invert){
int n = a.size();
/// this does the bit inversion
for(int i = 1, j = 0; i < n; ++i){
int bit = n >> 1;
for(; j & bit; bit >>= 1){
j ^= bit;
}
j ^= bit;
if(i < j){
swap(a[i], a[j]);
}
}
for(int len = 2; len <= n; len <<= 1){
ll wlen = invert ? root_1: root;
for(int i = len; i < root_pw; i <<= 1){
wlen = wlen * wlen % mod;
}
for(int i = 0; i < n; i += len){
ll w = 1;
for(int j = 0; j < len / 2; ++j){
ll u = a[i + j], v = a[i + j + len / 2] * w % mod;
a[i + j] = u + v < mod ? u + v : u + v - mod;
a[i + j + len / 2] = u - v >= 0 ? u - v : u - v + mod;
w = w * wlen % mod;
}
}
}
if(invert){
ll n_1 = inverse(n);
for(ll& x : a){
x = x * n_1 % mod;
}
}
}
//multiplying two polynomials a and b using ntt in O(max(A, B)log(max(A, B))), where A, B are degrees of a, b respectively
vector<ll> mul(vector<ll> const& a, vector<ll> const& b){
vector<ll> fa(a.begin(), a.end()), fb(b.begin(), b.end());
int n = 1;
while(n < (int)a.size() + (int)b.size()){
n <<= 1;
}
fa.resize(n);
fb.resize(n);
fft(fa, false);
fft(fb, false);
for(int i = 0; i < n; ++i){
fa[i] = fa[i] * fb[i] % mod;
}
fft(fa, true);
while(fa.size() > 1 && fa[fa.size() - 1] == 0){
fa.pop_back();
}
return fa;
}
/* End of FFT Template */
inline void init(){ // precomputes the first few terms of P(x) = e^(x + (x ^ 2) / 2)
init_fact();
vector<ll> e_x(MAXN), e_x2_by2(MAXN);
ll modular_inverse_of_2 = (mod + 1) / 2;
for(int i = 0; i < MAXN; ++i){
e_x[i] = ifact[i]; // e^x = sum{x^k / k!}
e_x2_by2[i] = ((i & 1)) ? 0 : ifact[i / 2] * fxp(modular_inverse_of_2, i / 2) % mod; // e^((x^2)/2) = sum{(x^2k)/(k!.(2^k))}
}
P = mul(e_x, e_x2_by2); // P(x) = e^(x + (x ^ 2) / 2) = (e ^ x) . (e ^ ((x ^ 2) / 2))
}
void test_case(){
int N;
cin >> N;
ll ans = 0;
for(int s = 0; s <= N / 4; ++s){ // computing the answer for N using the precomputed P(x) polynomial
ans = (ans + fact[N - 2 * s] * ifact[s] % mod * P[N - 4 * s]) % mod;
}
cout << ans << '
';
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
init();
int test_case_number;
cin>>test_case_number;
while(test_case_number--)
test_case();
return 0;
}
|
1725
|
F
|
Field Photography
|
Pak Chanek is traveling to Manado. It turns out that OSN (Indonesian National Scientific Olympiad) 2019 is being held. The contestants of OSN 2019 are currently lining up in a field to be photographed. The field is shaped like a grid of size $N \times 10^{100}$ with $N$ rows and $10^{100}$ columns. The rows are numbered from $1$ to $N$ from north to south, the columns are numbered from $1$ to $10^{100}$ from west to east. The tile in row $r$ and column $c$ is denoted as $(r,c)$.
There are $N$ provinces that participate in OSN 2019. Initially, each contestant who represents province $i$ stands in tile $(i, p)$ for each $p$ satisfying $L_i \leq p \leq R_i$. So, we can see that there are $R_i-L_i+1$ contestants who represent province $i$.
Pak Chanek has a variable $Z$ that is initially equal to $0$. In one operation, Pak Chanek can choose a row $i$ and a positive integer $k$. Then, Pak Chanek will do one of the two following possibilities:
- Move all contestants in row $i$ exactly $k$ tiles to the west. In other words, a contestant who is in $(i, p)$ is moved to $(i, p-k)$.
- Move all contestants in row $i$ exactly $k$ tiles to the east. In other words, a contestant who is in $(i, p)$ is moved to $(i, p+k)$.
After each operation, the value of $Z$ will change into $Z \text{ OR } k$, with $\text{OR}$ being the bitwise OR operation. Note that Pak Chanek can do operations to the same row more than once. Also note that Pak Chanek is not allowed to move contestants out of the grid.
There are $Q$ questions. For the $j$-th question, you are given a positive integer $W_j$, Pak Chanek must do zero or more operations so that the final value of $Z$ is \textbf{exactly} $W_j$. Define $M$ as the biggest number such that after all operations, there is at least one \textbf{column} that contains exactly $M$ contestants. For each question, you must find the biggest possible $M$ for all sequences of operations that can be done by Pak Chanek. Note that the operations done by Pak Chanek for one question do not carry over to other questions.
|
Let's consider some value of $W_j$. Let $b$ be the LSB (Least Significant Bit) of $W_j$. Which means $b$ is the minimum number such that the bit in index $b$ in the binary representation of $W_j$ is active. Note: the bits are indexed from $0$ from the right. For a sequence of operations, define $\text{dis}(i)$ as how many tiles to the east the final positions of the contestants in row $i$ compared to their initial position. Specifically, if their final positions are more to the west, then $\text{dis}(i)$ is negative. Notice that each move we make must be a distance that is a multiple of $2^b$. Because if we move a distance that is not a multiple of $2^b$, at least one of the bits with indices smaller than $b$ will be activated, which we do not want. This means $\text{dis}(i)$ must be a multiple of $2^b$. However, we can make each $\text{dis}(i)$ to be any integer that is a multiple of $2^b$ while making $Z = W_j$ by doing the following strategy: Only do moves with distances of exactly $2^b$ to move the contestants in each row to their final positions. Move one row with a distance of $W_j$ to the east, then to the west. Using the knowledge above, we can see that for each row $i$, there are three cases: If $R_i-L_i+1 \geq 2^b$, then each column can be occupied. Else, if $(L_i \mod 2^b) \leq (R_i \mod 2^b)$, then only each column $c$ such that $(L_i \mod 2^b) \leq (c \mod 2^b) \leq (R_i \mod 2^b)$ can be occupied. Else, then only each column $c$ such that $(L_i \mod 2^b) \leq (c \mod 2^b)$ or $(c \mod 2^b) \leq (R_i \mod 2^b)$ can be occupied. We can see that each row has at most two subsegments of the segment $[0, 2^b-1]$ denoting the occupiable columns modulo $2^b$. Now we just need to find the position that intersects the most subsegments. To solve this, we can use line sweep. To handle the $Q$ queries, notice that the number of possible distinct values for the LSB of $W_j$ are only $\lfloor \log_2 10^9 \rfloor + 1 = 30$. So we can precompute the answer for each of the $30$ possible LSB, then answer the queries using the precomputed answers. Time complexity: $O(N\log N \log \max(W) + Q \log \max(W))$
|
[
"bitmasks",
"data structures",
"sortings"
] | 2,100
| null |
1725
|
G
|
Garage
|
Pak Chanek plans to build a garage. He wants the garage to consist of a square and a right triangle that are arranged like the following illustration.
Define $a$ and $b$ as the lengths of two of the sides in the right triangle as shown in the illustration. An integer $x$ is suitable if and only if we can construct a garage with assigning \textbf{positive integer} values for the lengths $a$ and $b$ ($a<b$) so that the area of the square at the bottom is exactly $x$. As a good friend of Pak Chanek, you are asked to help him find the $N$-th smallest suitable number.
|
Let $c$ be the bottom side of the right triangle (the side that is not $a$ or $b$). From Pythagorean theorem, we know that $a^2+c^2 = b^2$, so $c^2 =b^2-a^2$. We can see that the area of the square at the bottom is $c^2$. So an integer is suitable if and only if it can be expressed as $b^2-a^2$ for some positive integers $a$ and $b$ ($a<b$). Consider the case if $b=a+1$. Then $b^2-a^2 = (a+1)^2-a^2 = a^2+2a+1-a^2 = 2a+1$. Since $a$ must be a positive integer, then all possible results for this case are all odd integers that are greater than or equal to $3$. Consider the case if $b=a+2$. Then $b^2-a^2 = (a+2)^2-a^2 = a^2+4a+4-a^2 = 4a+4$. Since $a$ must be a positive integer, then all possible results for this case are all integers that are multiples of $4$ that are greater than or equal to $8$. Let's consider an integer that has a remainder of $2$ when divided by $4$. We can get that such an integer can never be expressed as $b^2-a^2$. This is because of the fact that any square number when divided by $4$ must have a remainder of either $0$ or $1$. Using a simple brute force, we can get that $1$ and $4$ cannot be expressed as $b^2-a^2$. Using all of the information above, we can see that all suitable numbers are only all odd integers that are greater than or equal to $3$ and all integers that are multiples of $4$ that are greater than or equal to $8$. In order to find the $N$-th smallest suitable number, we can do a binary search on a value $d$. In each iteration of the binary search, we check whether there are at least $N$ suitable numbers that are less than or equal to $d$. Alternatively, we can use a mathematical formula to find the $N$-th smallest suitable number in $O(1)$ time complexity. Time Complexity: $O(\log N)$ or $O(1)$
|
[
"binary search",
"geometry",
"math"
] | 1,500
| null |
1725
|
H
|
Hot Black Hot White
|
One day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones.
Dr. Chanek has $N$ magical stones with $N$ being an even number. Those magical stones are numbered from $1$ to $N$. Magical stone $i$ has a strength of $A_i$. A magical stone can be painted with two colours, namely the colour black or the colour white. You are tasked to paint the magical stones with the colour black or white and store the magical stones into a magic box with a magic coefficient $Z$ ($0 \leq Z \leq 2$). The painting of the magical stones must be done in a way such that there are $\frac{N}{2}$ black magical stones and $\frac{N}{2}$ white magical stones.
Define $\text{concat}(x, y)$ for two integers $x$ and $y$ as the result of concatenating the digits of $x$ to the left of $y$ in their decimal representation without changing the order. As an example, $\text{concat}(10, 24)$ will result in $1024$.
For a magic box with a magic coefficient $Z$, magical stone $i$ will react with magical stone $j$ if the colours of both stones are different and $\text{concat}(A_i, A_j) \times \text{concat}(A_j, A_i) + A_i \times A_j \equiv Z \mod 3$. A magical stone that is reacting will be very hot and dangerous. Because of that, you must colour the magical stones and determine the magic coefficient $Z$ of the magic box in a way such that there is no magical stone that reacts, or report if it is impossible.
|
Notice that $10 \equiv 1 \mod 3$. Hence, if $k$ denotes the number of digits in $A_j$, $\text{concat}(A_i, A_j) \mod 3= (A_i \times 10^k + A_j) \mod 3 = (A_i \times 1^k + A_j) \mod 3 = (A_i + A_j) \mod 3$. Then one can simplify the equation that determines the reaction of stone $i$ and stone $j$ as follows. $\begin{align} \text{concat}(A_i, A_j) \times \text{concat}(A_j, A_i) + A_i A_j & \equiv Z \mod 3 \\ (A_i + A_j) (A_i + A_j) + A_i A_j & \equiv Z \mod 3 \\ A_i^2 + 2 A_i A_j + A_j^2 + A_i A_j & \equiv Z \mod 3 \\ A_i^2 + A_j^2 + 3 A_i A_j & \equiv Z \mod 3 \\ A_i^2 + A_j^2 & \equiv Z \mod 3 \\ \end{align}$ $0^2 = 0 \equiv 0 \mod 3$. $1^2 = 1 \equiv 1 \mod 3$. $2^2 = 4 \equiv 1 \mod 3$. So the value of $A_i^2 \mod 3$ is either $0$ or $1$. We can get a construction that consists of the two following cases: If there are at least $\frac{N}{2}$ stones having $A_i^2 \equiv 0 \mod 3$, then we can colour the stones such that one of the colours only occurs in all stones with $A_i^2 \equiv 0 \mod 3$. In this construction, there is no pair of stones with different colours that both have $A_i^2 \equiv 1 \mod 3$. So we can assign $Z=2$. If there are less than $\frac{N}{2}$ stones having $A_i^2 \equiv 0 \mod 3$, then there are at least $\frac{N}{2}$ stones having $A_i^2 \equiv 1 \mod 3$, so we can colour the stones such that one of the colours only occurs in all stones with $A_i^2 \equiv 1 \mod 3$. In this construction, there is no pair of stones with different colours that both have $A_i^2 \equiv 0 \mod 3$. So we can assign $Z=0$. Time complexity: $O(N)$
|
[
"constructive algorithms",
"math"
] | 1,800
| null |
1725
|
I
|
Imitating the Key Tree
|
Pak Chanek has a tree called the key tree. This tree consists of $N$ vertices and $N-1$ edges. The edges of the tree are numbered from $1$ to $N-1$ with edge $i$ connecting vertices $U_i$ and $V_i$. Initially, each edge of the key tree does not have a weight.
Formally, a path with length $k$ in a graph is a sequence $[v_1, e_1, v_2, e_2, v_3, e_3, \ldots, v_k, e_k, v_{k+1}]$ such that:
- For each $i$, $v_i$ is a vertex and $e_i$ is an edge.
- For each $i$, $e_i$ connects vertices $v_i$ and $v_{i+1}$.
A circuit is a path that starts and ends on the same vertex.
A path in a graph is said to be simple if and only if the path does not use the same edge more than once. Note that a simple path can use the same vertex more than once.
The cost of a simple path in a weighted graph is defined as the \textbf{maximum weight} of all edges it traverses.
Count the number of distinct undirected weighted graphs that satisfy the following conditions:
- The graph has $N$ vertices and $2N-2$ edges.
- For each pair of different vertices $(x, y)$, there exists a simple circuit that goes through vertices $x$ and $y$ in the graph.
- The weight of each edge in the graph is an integer between $1$ and $2N-2$ inclusive. Each edge has \textbf{distinct} weights.
- The graph is formed in a way such that there is a way to assign a weight $W_i$ to each edge $i$ in the key tree that satisfies the following conditions:
- For each pair of edges $(i, j)$, if $i<j$, then $W_i<W_j$.
- For each pair of different vertex indices $(x, y)$, the cost of the only simple path from vertex $x$ to $y$ in the key tree is equal to the \textbf{minimum cost} of a simple circuit that goes through vertices $x$ and $y$ in the graph.
- Note that the graph is allowed to have multi-edges, but is not allowed to have self-loops.
Print the answer modulo $998\,244\,353$.
Two graphs are considered distinct if and only if there exists a triple $(a, b, c)$ such that there exists an edge that connects vertices $a$ and $b$ with weight $c$ in one graph, but not in the other.
|
Let's say we have two graphs, each having $N$ vertices. Initially, there are no edges. We want to make the first graph into a graph that satisfies the condition of the problem and make the second graph into the key tree with a weight assignment that corresponds to the first graph. Sequentially for each $k$ from $1$ to $2N-2$, do all of the following: Add an edge with weight $k$ to the first graph. Choose one of the following: Add an edge with weight $k$ to the second graph. Do nothing. Add an edge with weight $k$ to the second graph. Do nothing. In order to make the second graph into the key tree, we must add exactly $N-1$ edges to it throughout the process and the $i$-th edge added is edge $i$ of the key tree. In an iteration, if we choose to not add an edge to the second graph, it can be obtained that the edge added to the first graph must not merge any biconnected components. Let's call this type of edge in the first graph an idle edge. Otherwise, if we choose to add an edge to the second graph, it can be obtained that the following must be satisfied: Let $c_1$ and $c_2$ be the connected components of the second graph that are merged by adding the new edge. The edge added to the first graph must merge exactly two biconnected components, each of them containing vertices with the same indices as the ones in each of $c_1$ and $c_2$. Let's call this type of edge in the first graph a connector edge. We can see that there must be exactly $N-1$ connector edges in the first graph. The only way to make it such that adding an edge connects exactly two biconnected components is to already have exactly one existing edge connecting the two biconnected components. Let's call this type of existing edge a helper edge. It can be obtained that an edge cannot be a helper edge of more than one connector edge. Because we only have $2N-2$ edges for the first graph, those edges must only consist of $N-1$ connector edges and $N-1$ helper edges. This means all helper edges must be idle edges. But it can be obtained that each helper edge in our construction is always an idle edge. The $i$-th connector edge and its corresponding helper edge must connect the two biconnected components that correspond to the two connected components merged using edge $i$ of the key tree. If the sizes of the connected components are $s_1$ and $s_2$, then there are $(s_1 \times s_2)^2$ possible pairs of connector and helper edges. The number of ways to choose which edge to add in each iteration is the same as the number of ways to colour a sequence of $2N-2$ elements with $N-1$ colours (numbered from $1$ to $N-1$) such that: Each colour occurs in exactly $2$ elements. For each pair of colours $(i, j)$, if $i<j$, then the latest element with colour $i$ must occur earlier than the latest element with colour $j$. We can see that the number of ways is $\frac{(2N-2)!}{(2!)^{N-1}\times (N-1)!}$. To get the answer to the problem, we just multiply this value by each of the $(s_1 \times s_2)^2$ for each merged pair of connected components in the key tree. Time complexity: $O(N)$
|
[
"combinatorics",
"dsu",
"trees"
] | 2,800
| null |
1725
|
J
|
Journey
|
One day, Pak Chanek who is already bored of being alone at home decided to go traveling. While looking for an appropriate place, he found that Londonesia has an interesting structure.
According to the information gathered by Pak Chanek, there are $N$ cities numbered from $1$ to $N$. The cities are connected to each other with $N-1$ two-directional roads, with the $i$-th road connecting cities $U_i$ and $V_i$, and taking a time of $W_i$ hours to be traversed. In other words, Londonesia's structure forms a tree.
Pak Chanek wants to go on a journey in Londonesia starting and ending in any city (not necessarily the same city) such that each city is visited \textbf{at least once} with the least time possible. In order for the journey to end quicker, Pak Chanek also carries an instant teleportation device for moving from one city to any city that can only be used at most once. Help Pak Chanek for finding the minimum time needed.
Notes:
- Pak Chanek only needs to visit each city at least once. Pak Chanek does not have to traverse each road.
- In the journey, a city or a road can be visited more than once.
|
For a journey, define $\text{cnt}(i)$ as a non-negative integer representing the number of times Pak Chanek traverses road $i$ throughout the journey. First, let's solve the simpler problem where we cannot teleport. It can be obtained that the configuration of $\text{cnt}(i)$ for an optimal journey in this version of the problem is as follows: The roads with $\text{cnt}(i)=1$ form a simple path. Every other road outside of the path has $\text{cnt}(i)=2$. If we add the ability to teleport at most once, the configuration of $\text{cnt}(i)$ is similar, but the roads with $\text{cnt}(i)=1$ form two distinct simple paths, with both paths not containing any common roads. Let's denote these two paths as $P_1$ and $P_2$. Notice that $P_1$ and $P_2$ can only have either one common city or no common cities at all. It can be obtained that the optimal configuration for each case is as follows: If $P_1$ and $P_2$ have one common city, every other road outside of $P_1$ and $P_2$ must have $\text{cnt}(i)=2$. If $P_1$ and $P_2$ have no common cities, we have the opportunity to pick one road in the path between $P_1$ and $P_2$ and assign $\text{cnt}(i)=0$. Then, every other road must have $\text{cnt}(i)=2$. It can be shown that for any configuration of $\text{cnt}(i)$ satisfying the constraints above, there always exists a valid journey that corresponds to that configuration. So we must find the configuration that results in the minimum time for each case. For the first case, we can precompute a tree DP with rerooting and try each possible common city to get the optimal answer. For the second case, we can also precompute a tree DP with rerooting and try each possible road with $\text{cnt}(i)=0$ to get the optimal answer.
|
[
"dp",
"trees"
] | 2,500
| null |
1725
|
K
|
Kingdom of Criticism
|
Pak Chanek is visiting a kingdom that earned a nickname "Kingdom of Criticism" because of how often its residents criticise each aspect of the kingdom. One aspect that is often criticised is the heights of the buildings. The kingdom has $N$ buildings. Initially, building $i$ has a height of $A_i$ units.
At any point in time, the residents can give a new criticism, namely they currently do not like buildings with heights between $l$ and $r$ units inclusive for some two integers $l$ and $r$. It is known that $r-l$ is always odd.
In $1$ minute, the kingdom's construction team can increase or decrease the height of any building by $1$ unit as long as the height still becomes a positive number. Each time they receive the current criticism from the residents, the kingdom's construction team makes it so that there are no buildings with heights between $l$ and $r$ units inclusive in the \textbf{minimum time possible}. It can be obtained that there is only one way to do this.
Note that the construction team only cares about the current criticism from the residents. All previous criticisms are forgotten.
There will be $Q$ queries that you must solve. Each query is one of the three following possibilities:
- 1 k w: The kingdom's construction team changes the height of building $k$ to be $w$ units ($1 \leq k \leq N$, $1 \leq w \leq 10^9$).
- 2 k: The kingdom's construction team wants you to find the height of building $k$ ($1 \leq k \leq N$).
- 3 l r: The residents currently do not like buildings with heights between $l$ and $r$ units inclusive ($2 \leq l \leq r \leq 10^9-1$, $r-l$ is odd).
Note that each change in height still persists to the next queries.
|
We can see that the changes in height for a single query of type $3$ are as follows: Each building with height $x$ such that $l \leq x \leq \frac{l+r}{2}$ is changed to have a height of $l-1$. Each building with height $x$ such that $\frac{l+r}{2} \leq x \leq r$ is changed to have a height of $r+1$. Note: since $r-l$ is odd, $\frac{l+r}{2}$ is not an integer. So there is no uncertainty here. We can group the buildings into their heights, so buildings with the same height belong in the same group. We can maintain all the different groups in a set such that the groups are sorted by their heights. We can see that using this set, we can perform a type $3$ query by merging several groups into a single group with a certain height. Note that each time we merge $k$ groups, the number of groups decreases by $k-1$. For each building, to maintain its height while doing all the merging of several groups and the changing of height of an entire group, we can use a simple disjoint-set data structure to make it such that we can request the height of any building quickly. More specifically, each group is represented as a single connected component. The merging of several groups is equivalent to the merging of several connected components. The changing of height of an entire group can be done by changing the height of the representative building in a connected component. However, a query of type $1$ can break our structure. Changing the height of a single building can make it leave its current group and join another group or make a new group. In order to not break our disjoint-set data structure, each time there is a type $1$ query, we can just leave the old building with the old height alone and make a new building with the new height. After this, each request for this building's height is referred to the new representation we just created. Each query of type $1$ creates one new building representation and can create at most one new group. Using this solution, we can see that: A type $1$ query is done in $O(\log(N+Q))$ time because we have to make changes to the set. This query creates one new building representation and can create at most one new group. A type $2$ query is done in $O(1)$ time. A type $3$ query is done in $O(k\log(N+Q))$ time with $k$ being the number of groups we merge. This query decreases the number of groups by $k-1$. Time complexity: $O((N+Q)\log(N+Q))$ Note: there is also an unintended solution using small-to-large with time complexity of $O((N+Q)\log^2(N+Q))$, but it needs optimisations in order to pass the time limit.
|
[
"data structures",
"dsu"
] | 2,500
| null |
1725
|
L
|
Lemper Cooking Competition
|
Pak Chanek is participating in a lemper cooking competition. In the competition, Pak Chanek has to cook lempers with $N$ stoves that are arranged sequentially from stove $1$ to stove $N$. Initially, stove $i$ has a temperature of $A_i$ degrees. A stove can have a negative temperature.
Pak Chanek realises that, in order for his lempers to be cooked, he needs to keep the temperature of each stove at a non-negative value. To make it happen, Pak Chanek can do zero or more operations. In one operation, Pak Chanek chooses one stove $i$ with $2 \leq i \leq N-1$, then:
- changes the temperature of stove $i-1$ into $A_{i-1} := A_{i-1} + A_{i}$,
- changes the temperature of stove $i+1$ into $A_{i+1} := A_{i+1} + A_{i}$, and
- changes the temperature of stove $i$ into $A_i := -A_i$.
Pak Chanek wants to know the minimum number of operations he needs to do such that the temperatures of all stoves are at non-negative values. Help Pak Chanek by telling him the minimum number of operations needed or by reporting if it is not possible to do.
|
Note that an operation is identical to choosing an index $p$ ($1 < p < N$) and doing the following things simultaneously: Increase $A_{p-1}$ by $A_p$. Increase $A_p$ by $-2 A_p$. Increase $A_{p+1}$ by $A_p$. Let's maintain array $A$ using its prefix sum $B_0, B_1, B_2, \ldots, B_N$. Formally, define $B_i = A_1 + A_2 + \ldots + A_i$. In particular, $B_0 = 0$. We can see that an operation at index $p$ changes $B$ as follows: For each index $i$ such that $0 \leq i \leq p-2$, $B_i$ does not change. $B_{p-1}$ increases by $A_p$. So, $B_{p-1}$ increases by $B_p - B_{p-1}$. Therefore, $B_{p-1}$ changes into $B_p$. $B_p$ increases by $A_p - 2 A_p = -A_p$. So, $B_p$ increases by $B_{p-1} - B_p$. Therefore, $B_p$ changes into $B_{p-1}$. For each index $i$ such that $p+1 \leq i \leq N$, $B_i$ increases by $A_p - 2 A_p + A_p = 0$. So $B_i$ does not change. Note that all of the above happen simultaneously. Therefore, an operation at index $p$ only swaps the values of $B_p$ and $B_{p-1}$. So, in one operation, we can swap two adjacent values of $B$ other than $B_0$ or $B_N$. Making every $A_i$ non-negative is equivalent to making it such that $B_0 \leq B_1 \leq B_2 \leq \ldots \leq B_N$. So, if there is a value of $B_i$ ($1 \leq i \leq N-1$) such that $B_i < B_0$ or $B_i > B_N$, then it is impossible. Otherwise, it is always possible. To count the number of adjacent swaps to sort $B$, we can just count the number of inversions in $B$. This can be done using Fenwick Tree or other methods. Time complexity: $O(N \log N)$
|
[
"data structures"
] | 2,400
| null |
1725
|
M
|
Moving Both Hands
|
Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $N$ vertices and $M$ edges. In the graph, edge $i$ connects two different vertices $U_i$ and $V_i$ with a length of $W_i$. By using the $i$-th edge, something can move from $U_i$ to $V_i$, but not from $V_i$ to $U_i$.
To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $U_i$ to vertex $V_i$, Pak Chanek needs a time of $W_i$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.
Pak Chanek has several questions. For each $p$ satisfying $2 \leq p \leq N$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $1$ and vertex $p$, or report if it is impossible.
|
Suppose we are trying to find out the minimum time to get the hands from vertices $1$ and $k$ to the same vertex. If both hands end up on some vertex $v$, then the time required is $d(1,v) + d(k,v)$, with $d(x,y)$ being the minimum distance to go from vertex $x$ to $y$. Suppose $d'(x,y)$ is the minimum distance to go from vertex $x$ to $y$ in the reversed graph (i.e. all edges' directions are reversed). Then $d(1,v) + d(k,v) = d(1,v) + d'(v,k)$. The minimum time if both hands are initially on vertices $1$ and $k$ is the minimum value of $d(1,v) + d'(v,k)$ for all vertices $v$. This is the same as the minimum distance to go from vertex $1$ to $k$ where in the middle of our path, we can reverse the graph at most once. Therefore we can set up a graph like the following: Each vertex is a pair $(x,b)$, where $x$ is a vertex in the original graph and $b$ is a boolean determining whether we have already reversed the graph or not. For each edge $i$ in the original graph, there is an edge from $(U_i, 0)$ to $(V_i, 0)$ and an edge from $(V_i, 1)$ to $(U_i, 1)$, both with weight $W_i$. For each vertex $x$ in the original graph, there is a edge from $(x,0)$ to $(x,1)$ with weight $0$. After this, we do the Dijkstra algorithm once on the new graph from vertex $(1, 0)$. Then, the optimal time if both hands start from vertices $1$ and $k$ in the original graph is equal to $d((1,0), (k,1))$ in the new graph. Time complexity: $O(N+M \log M)$
|
[
"dp",
"graphs",
"shortest paths"
] | 1,800
| null |
1726
|
A
|
Mainak and Array
|
Mainak has an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. He will do the following operation to this array \textbf{exactly once}:
- Pick a subsegment of this array and cyclically rotate it by any amount.
Formally, he can do the following exactly once:
- Pick two integers $l$ and $r$, such that $1 \le l \le r \le n$, and any positive integer $k$.
- Repeat this $k$ times: set $a_l=a_{l+1}, a_{l+1}=a_{l+2}, \ldots, a_{r-1}=a_r, a_r=a_l$ (all changes happen at the same time).
Mainak wants to \textbf{maximize} the value of $(a_n - a_1)$ after exactly one such operation. Determine the maximum value of $(a_n - a_1)$ that he can obtain.
|
There are four candidates of the maximum value of $a_n - a_1$ achievable, each of which can be found in $\mathcal O(n)$ time. No subarray is chosen: Answer would be $a_n - a_1$ in this case. Chosen subarray contains $a_n$ and $a_1$ : Answer would be $\max\limits_{i = 1}^n\{ a_{(i - 1)} - a_i\}$ where $a_0$ is same as $a_n$ (notice that the previous case is included in this case as well). Chosen subarray doesn't contain $a_n$ : Answer would be $\max\limits_{i = 1}^{n - 1}\{a_n - a_i\}$. Chosen subarray doesn't contain $a_1$ : Answer would be $\max\limits_{i = 2}^n\{a_i - a_1\}$. Finally we report the maximum of all of these four values in total time $\mathcal O(n)$.
|
[
"greedy",
"math"
] | 900
|
t=int(input())
for _ in range(t):
n=int(input())
a=[int(x) for x in input().split()]
ans=max(a[-1]-min(a),max(a)-a[0])
for i in range(n):
ans=max(ans,a[i-1]-a[i])
print(ans)
|
1726
|
B
|
Mainak and Interesting Sequence
|
Mainak has two positive integers $n$ and $m$.
Mainak finds a sequence $a_1, a_2, \ldots, a_n$ of $n$ positive integers interesting, if \textbf{for all} integers $i$ ($1 \le i \le n$), the bitwise XOR of all elements in $a$ which are \textbf{strictly less} than $a_i$ is $0$. Formally if $p_i$ is the bitwise XOR of all elements in $a$ which are strictly less than $a_i$, then $a$ is an interesting sequence if $p_1 = p_2 = \ldots = p_n = 0$.
For example, sequences $[1,3,2,3,1,2,3]$, $[4,4,4,4]$, $[25]$ are interesting, whereas $[1,2,3,4]$ ($p_2 = 1 \ne 0$), $[4,1,1,2,4]$ ($p_1 = 1 \oplus 1 \oplus 2 = 2 \ne 0$), $[29,30,30]$ ($p_2 = 29 \ne 0$) aren't interesting.
Here $a \oplus b$ denotes bitwise XOR of integers $a$ and $b$.
Find any interesting sequence $a_1, a_2, \ldots, a_n$ (or report that there exists no such sequence) such that the sum of the elements in the sequence $a$ is equal to $m$, i.e. $a_1 + a_2 \ldots + a_n = m$.
As a reminder, the bitwise XOR of an empty sequence is considered to be $0$.
|
Lemma: In an interesting sequence $a_1, a_2, \ldots, a_n$, every element other than the largest must have even occurrences. Proof: For the sake of contradiction, assume that for some $x$ ($x > 0$), such than $x \ne \max\limits_{i = 1}^n\{a_i\}$, $x$ appears an odd number of times. Let $P(z)$ denote the bitwise XOR of all elements in $a$ that are less than $z$. By assumption $P(x) = 0$. Now, since $x$ is not maximum of the sequence $a$, there exists $y$ in $a$, such that $x < y$ and there are no other elements $t$ such that $x < t < y$ (in other words, $y$ is the immediate larger element of $x$ in $a$). Again, $P(y) = 0$ as well by assumption. However, since $x$ appears an odd number of times, we have: $0 = P(y) = P(x) \oplus x = 0 \oplus x = x$, which is a contradiction as $x$ must be positive. This gives us an $\mathcal O(n)$ solution as follows: Case - I: If $n > m$ - It is clearly impossible to construct an interesting sequence with sum equal to $m$ (as integers must be positive). Case - II: $n$ is odd - Create $(n - 1)$ occurrences of $1$, and a single occurrence of $(m-n+1)$. Case - III: $n$ is even, $m$ is even - Create $(n - 2)$ occurrences of $1$ and two occurrences of $(m - n + 2)/2$. Case - IV: $n$ is even, $m$ is odd - No such interesting sequences exist. Proof: For the sake of contradiction assume that such an interesting sequence, $a$, exists. Since $m$ is odd, there must be an odd number $x$ that occurs an odd number of times in $a$. Again since $n$ is even there must be another integer $y$ (different from $x$) that occurs an also odd number of times. Hence either $x$ or $y$ (whichever is lower) violates the lemma. Proof: For the sake of contradiction assume that such an interesting sequence, $a$, exists. Since $m$ is odd, there must be an odd number $x$ that occurs an odd number of times in $a$. Again since $n$ is even there must be another integer $y$ (different from $x$) that occurs an also odd number of times. Hence either $x$ or $y$ (whichever is lower) violates the lemma.
|
[
"bitmasks",
"constructive algorithms",
"math"
] | 1,100
|
import sys
input = sys.stdin.readline
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
if n>m or (n%2==0 and m%2==1):
print("NO")
else:
print("YES")
ans=[]
if n%2==1:
ans.extend([1]*(n-1)+[m-n+1])
else:
ans.extend([1]*(n-2)+[(m-n+2)//2]*2)
print(*ans,sep=' ')
|
1726
|
C
|
Jatayu's Balanced Bracket Sequence
|
Last summer, Feluda gifted Lalmohan-Babu a \textbf{balanced} bracket sequence $s$ of length $2 n$.
Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $2 n$ vertices using the \underline{balanced bracket sequence} $s$. For any two distinct vertices $i$ and $j$ ($1 \le i < j \le 2 n$), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the \underline{subsegment} $s[i \ldots j]$ forms a balanced bracket sequence.
Determine the number of \underline{connected components} in Topshe's graph.
See the Notes section for definitions of the underlined terms.
|
Claim: The answer is one more than the number of occurrences of the substring "((" in the balanced bracket sequence given (considering overlapping occurrences as well). Proof: Observe the behavior of the lowest index $k$ of any connected component. The properties that would hold true are: $s_k =$ '('. This is because for all edges connecting indices $i$ and $j$ such that $i < j$, $s_i =$ '(' and $s_j =$ ')'. $k = 1$ is the lowest index for its connected component. For $k > 1$, $k$ is a lowest index for a connected component if and only if $s_{k - 1} =$ '('. This is because: if $s_{k - 1} =$ ')', then for any matching bracket $s_{j_1}$ of $s_{k - 1}$ ($j_1 < k - 1$) and for any matching bracket $s_{j_2}$ of $s_{k}$ ($j_2 > k$), there must be edges $(j_1, j_2)$ and $(k, j_2)$. This means that $j_1$ (which is less than $k$) is in the connected component of $k$. [Contradiction] if $s_{k - 1} =$ '(', then we can prove that there cannot be a smaller index in the connected component of $k$. For the sake of contradiction, assume that there exists a smaller index $a$ in the same connected component. This means, there is an edge $(a, b)$, such that $a < k$ and $b > k$ is in the connected component of $k$. Let $p_i$ be the number of '(' minus the the number of ')' in the prefix $s[1 \ldots i]$ (consider $p_0 = 0$ for the empty prefix). Observe that for all edges $(i, j)$, ($i < j$), it holds that $p_j = p_i - 1$ and for all $i'$, $i \le i' \le j$, we must have $p_{i'} \ge p_j$. This means that for a connected component $\mathcal C$, for all $i \in \mathcal C$, $s_i =$ '(', $p_i$ is constant. Hence $p_k = p_a$. Further we have $p_b = p_a - 1$ and $p_{k - 2} = p_{k - 1} - 1 = p_k - 2 = p_b - 1$. This implies $a < (k - 1)$, hence $a \le (k - 2) \le b$, however, $p_{k - 2} = p_b - 1 < p_b$. [Contradiction] if $s_{k - 1} =$ ')', then for any matching bracket $s_{j_1}$ of $s_{k - 1}$ ($j_1 < k - 1$) and for any matching bracket $s_{j_2}$ of $s_{k}$ ($j_2 > k$), there must be edges $(j_1, j_2)$ and $(k, j_2)$. This means that $j_1$ (which is less than $k$) is in the connected component of $k$. [Contradiction] if $s_{k - 1} =$ '(', then we can prove that there cannot be a smaller index in the connected component of $k$. For the sake of contradiction, assume that there exists a smaller index $a$ in the same connected component. This means, there is an edge $(a, b)$, such that $a < k$ and $b > k$ is in the connected component of $k$. Let $p_i$ be the number of '(' minus the the number of ')' in the prefix $s[1 \ldots i]$ (consider $p_0 = 0$ for the empty prefix). Observe that for all edges $(i, j)$, ($i < j$), it holds that $p_j = p_i - 1$ and for all $i'$, $i \le i' \le j$, we must have $p_{i'} \ge p_j$. This means that for a connected component $\mathcal C$, for all $i \in \mathcal C$, $s_i =$ '(', $p_i$ is constant. Hence $p_k = p_a$. Further we have $p_b = p_a - 1$ and $p_{k - 2} = p_{k - 1} - 1 = p_k - 2 = p_b - 1$. This implies $a < (k - 1)$, hence $a \le (k - 2) \le b$, however, $p_{k - 2} = p_b - 1 < p_b$. [Contradiction] Therefore for each '(' preceded by another '(', we have one such connected component (so we add the occurrences of the substring "((" to our answer). However, we missed the connected component of node $1$ (so we add $1$ to our answer). [Proved] Hence we can solve it in $\mathcal O(n)$.
|
[
"data structures",
"dsu",
"graphs",
"greedy"
] | 1,300
|
t=int(input())
for _ in range(t):
n=int(input())
s=input()
print(1+s.count("(")-s.count("()"))
|
1726
|
D
|
Edge Split
|
You are given a connected, undirected and unweighted graph with $n$ vertices and $m$ edges. Notice \textbf{the limit on the number of edges}: $m \le n + 2$.
Let's say we color some of the edges red and the remaining edges blue. Now consider only the red edges and count the number of connected components in the graph. Let this value be $c_1$. Similarly, consider only the blue edges and count the number of connected components in the graph. Let this value be $c_2$.
Find an assignment of colors to the edges such that the quantity $c_1+c_2$ is \textbf{minimised}.
|
Let's say for convenience that the set of red edges is called $R$ and the set of blue edges is called $B$. Fact: In at least one optimal configuration, $R$ or $B$ forms a spanning tree. Proof: Let's say that $R$ is not a spanning tree in some optimal configuration. If we move an edge connecting two disconnected vertices in $R$ from $B$ to $R$ (this edge must exist since the input is a connected graph), $c_2$ will increase by at most $1$, and $c_1$ will decrease by $1$. Also, if we have a cycle in $R$, we can move this edge from $R$ to $B$ and $c_1$ won't change. But $c_2$ may decrease by $1$. So making $R$ a spanning tree never makes the answer worse. We can swap $R$ and $B$ in this proof, it doesn't matter. If $R$ is a spanning tree then $c_1=1$ and we want to minimise $c_2$. Clearly, it would be best if there was no cycle in $B$. It turns out that we can ensure this. Notice that $m \leq (n-1)+3$, so the number of extra edges is very small. Let us build a spanning tree using DFS. A DFS tree will only have back edges and no cross edges. If there is no cycle taking these back edges in $B$, we are done. However, if there is a cycle (and there can be at most $1$ cycle, since you need at least $5$ edges for $2$ cycles), it looks like edges $u-v$ $v-w$ $u-w$ where $u$ is an ancestor of $v$ and $v$ is an ancestor of $w$. It is easy to get rid of this cycle by dropping one back edge ending at $w$ and taking the span edge connecting $w$ with its parent in the DFS tree. Note that $R$ remains a spanning tree. Hence we are done. Time complexity: $\mathcal{O}(n)$
|
[
"brute force",
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs",
"probabilities",
"trees"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
using lol=long long int;
#define endl "\n"
void dfs(int u,const vector<vector<pair<int,int>>>& g,vector<bool>& vis,vector<int>& dep,vector<int>& par,string& s)
{
vis[u]=true;
for(auto [v,idx]:g[u])
{
if(vis[v]) continue;
dep[v]=dep[u]+1;
par[v]=u;
s[idx]='1';
dfs(v,g,vis,dep,par,s);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int _=1;
cin>>_;
while(_--)
{
int n,m;
cin>>n>>m;
vector<vector<pair<int,int>>> g(n+1);
vector<pair<int,int>> edges(m);
string s(m,'0');
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
edges[i]={u,v};
g[u].push_back({v,i});
g[v].push_back({u,i});
}
vector<bool> vis(n+1,false);
vector<int> dep(n+1,0),par(n+1,-1);
dfs(1,g,vis,dep,par,s);
map<int,int> cnt;
for(int i=0;i<m;i++)
{
if(s[i]=='0')
{
cnt[edges[i].first]++;
cnt[edges[i].second]++;
}
}
if(cnt.size()==3)
{
int mn=2*n+5,mx=0;
for(auto [_,c]:cnt)
{
mn=min(mn,c);
mx=max(mx,c);
}
if(mn==mx && mn==2)
{
vector<pair<int,int>> can;
for(auto [v,_]:cnt) can.push_back({dep[v],v});
sort(can.rbegin(),can.rend());
int u=can[0].second;
int i,j; //replace edge i with edge j
for(auto [v,idx]:g[u])
{
if(s[idx]=='0') i=idx;
else if(v==par[u]) j=idx;
}
s[i]='1';
s[j]='0';
}
}
cout<<s<<endl;
}
return 0;
}
|
1726
|
F
|
Late For Work (submissions are not allowed)
|
\textbf{This problem was copied by the author from another online platform. Codeforces strongly condemns this action and therefore further submissions to this problem are not accepted.}
Debajyoti has a very important meeting to attend and he is already very late. Harsh, his driver, needs to take Debajyoti to the destination for the meeting as fast as possible.
Harsh needs to pick up Debajyoti from his home and take him to the destination so that Debajyoti can attend the meeting in time. A straight road with $n$ traffic lights connects the home and the destination for the interview. The traffic lights are numbered in order from $1$ to $n$.
Each traffic light cycles after $t$ seconds. The $i$-th traffic light is $\textcolor{green}{\text{green}}$ (in which case Harsh can cross the traffic light) for the first $g_i$ seconds, and $\textcolor{red}{\text{red}}$ (in which case Harsh must wait for the light to turn $\textcolor{green}{\text{green}}$) for the remaining $(t−g_i)$ seconds, after which the pattern repeats. Each light's cycle repeats indefinitely and initially, the $i$-th light is $c_i$ seconds into its cycle (a light with $c_i=0$ has just turned $\textcolor{green}{\text{green}}$). In the case that Harsh arrives at a light at the same time it changes colour, he will obey the new colour. Formally, the $i$-th traffic light is $\textcolor{green}{\text{green}}$ from $[0,g_i)$ and $\textcolor{red}{\text{red}}$ from $[g_i,t)$ (after which it repeats the cycle). The $i$-th traffic light is initially at the $c_i$-th second of its cycle.
From the $i$-th traffic light, \textbf{exactly} $d_i$ seconds are required to travel to the next traffic light (that is to the $(i+1)$-th light). Debajyoti's home is located just before the first light and Debajyoti drops for the interview as soon as he passes the $n$-th light. In other words, no time is required to reach the first light from Debajyoti's home or to reach the interview centre from the $n$-th light.
Harsh does not know how much longer it will take for Debajyoti to get ready. While waiting, he wonders what is the minimum possible amount of time he will spend driving provided he starts the moment Debajyoti arrives, which can be anywhere between $0$ to $\infty$ seconds from now. Can you tell Harsh the minimum possible amount of time he needs to spend on the road?
\textbf{Please note that Harsh can only start or stop driving at integer moments of time.}
|
The $d_i$ are irrelevant. Take partial sums and add them to each $c_i$ modulo $T$. If your start time is fixed, it is never beneficial to wait at a green light. Drive whenever you can. Visualise the problem as $n$ parallel lines, each coloured with a red and green interval. Now imagine the car moving up (and looping back at $T$) whenever it has to wait at a red light, and shooting to the right immediately when the lights are green. You can model this as a shortest paths problem. There are solutions to this problem using lazy segment trees, or say, sets and maps. I'll describe my own solution here, which converts the problem to a shortest paths problem. First of all, the $d_i$ are irrelevant, since we can take partial sums and add them to $c_i$. In the final answer, just add the sum of all $d_i$. Now, we can offset the green (or red) intervals by the modified $c_i$ to get new red and green intervals modulo $T$. Imagine $n$ parallel lines of length $T$, with the corresponding intervals coloured red and green. Now, consider the intervals to be static. In this picture, the car can be visualised to be moving upwards along the line (looping back at $T$) when on red intervals and shooting to the right when it reaches a green interval. Notice that for a fixed starting time, it is always optimal to drive whenever you can. So essentially, fixing your start time also fixes your answer. Now let's convert this to a graph. Notice that only the endpoints of green intervals matter, so overall, we'll have $2n$ nodes in our graph, plus a dummy node representing the start of the journey that connects to all endpoints that can be reached without being blocked by a red interval, and a dummy node representing the end of the journey that connects to all endpoints from which you can reach the end without being blocked by a red interval. So in total, $2n+2$ nodes. We'll add an edge between two nodes with a weight equal to the amount of time we'll have to spend waiting for the red light to turn green. We can achieve this with a multiset storing all currently visible endpoints, and then doing a little casework to add edges from nodes blocked by the current red interval and then deleting them, and adding new ones. We'll do this only $\mathcal{O}(n)$ times. In the end, whatever is left in the multiset are all the visible endpoints and we can connect them to the dummy node for the end. We can repeat this in the backward direction to get the endpoints for the dummy node for the start, though in my code, I elected to do this with an interval union data structure. Finally, just run Dijkstra's algorithm on this graph. The answer is the sum of all $d_i$ plus the shortest path between the dummy node for the start and the dummy node for the end. Time complexity: $\mathcal{O}(n \log n)$
|
[
"data structures",
"greedy",
"schedules",
"shortest paths"
] | 2,900
|
#include<bits/stdc++.h>
using namespace std;
using lol=long long int;
const lol inf=1e18+8;
struct IntervalUnion{
set<int> lf,ri;
map<int,int> lr,rl;
void add(int l,int r)
{
if(!ri.empty())
{
auto it=ri.lower_bound(r);
if(it!=ri.end() && rl[*it]<=l) return;
}
while(!lf.empty())
{
auto it=lf.lower_bound(l);
if(it==lf.end() || r<*it) break;
int nl=*it;
r=max(r,lr[nl]);
rl.erase(lr[nl]);
ri.erase(lr[nl]);
lr.erase(nl);
lf.erase(nl);
}
while(!ri.empty())
{
auto it=ri.lower_bound(l);
if(it==ri.end() || r<rl[*it]) break;
int nl=rl[*it];
l=min(l,nl);
rl.erase(lr[nl]);
ri.erase(lr[nl]);
lr.erase(nl);
lf.erase(nl);
}
lf.insert(l);
ri.insert(r);
lr[l]=r;
rl[r]=l;
}
bool contains(int x)
{
auto it=ri.upper_bound(x);
if(it==ri.end()) return false;
return rl[*it]<=x;
}
};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,t;
cin>>n>>t;
vector<pair<int,int>> gc(n);
for(auto& [g,c]:gc) cin>>g>>c;
lol sum=0;
for(int i=1;i<n;i++)
{
int d;
cin>>d;
sum+=d;
gc[i].second=(gc[i].second+(sum%t))%t;
}
vector<vector<pair<int,int>>> gr(2*n+2);
multiset<pair<int,int>> ms;
IntervalUnion iu;
for(int i=0;i<n;i++)
{
auto [g,c]=gc[i];
int l=(g-c+t)%t,r=t-c;
if(l<r)
{
while(!ms.empty())
{
auto it=ms.lower_bound({l,-1});
if(it==ms.end() || it->first>=r) break;
gr[2*i].push_back({it->second,r-it->first});
ms.erase(it);
}
}else
{
while(!ms.empty())
{
auto it=ms.lower_bound({l,-1});
if(it==ms.end() || it->first>=t) break;
gr[2*i].push_back({it->second,r+t-it->first});
ms.erase(it);
}
while(!ms.empty())
{
auto it=ms.lower_bound({0,-1});
if(it==ms.end() || it->first>=r) break;
gr[2*i].push_back({it->second,r-it->first});
ms.erase(it);
}
}
ms.insert({r%t,2*i});
ms.insert({(l-1+t)%t,2*i+1});
if(!iu.contains(r%t)) gr[2*i].push_back({2*n+1,0});
if(!iu.contains((l-1+t)%t)) gr[2*i+1].push_back({2*n+1,0});
if(l<r) iu.add(l,r);
else
{
iu.add(l,t);
iu.add(0,r);
}
}
while(!ms.empty())
{
auto it=ms.begin();
gr[2*n].push_back({it->second,0});
ms.erase(it);
}
//do dijkstra on this graph
vector<lol> sp(2*n+2,inf);
priority_queue<pair<lol,int>,vector<pair<lol,int>>,greater<pair<lol,int>>> pq;
pq.push({0,2*n});
sp[2*n]=0;
while(!pq.empty())
{
auto [dist,u]=pq.top();
pq.pop();
if(dist>sp[u]) continue;
for(auto [v,w]:gr[u])
{
if(dist+w<sp[v])
{
sp[v]=dist+w;
pq.push({sp[v],v});
}
}
}
cout<<sum+sp[2*n+1];
return 0;
}
|
1726
|
G
|
A Certain Magical Party
|
There are $n$ people at a party. The $i$-th person has an amount of happiness $a_i$.
Every person has a certain kind of personality which can be represented as a binary integer $b$. If $b = 0$, it means the happiness of the person will increase if he tells the story to someone \textbf{strictly less} happy than them. If $b = 1$, it means the happiness of the person will increase if he tells the story to someone \textbf{strictly more} happy than them.
Let us define a speaking order as an ordering of the people from left to right. Now the following process occurs. We go from left to right. The current person tells the story to all people other than himself. Note that \textbf{all happiness values stay constant} while this happens. After the person is done, he counts the number of people who currently have strictly less/more happiness than him as per his kind of personality, and his happiness increases by that value. Note that only the current person's happiness value increases.
As the organizer of the party, you don't want anyone to leave sad. Therefore, you want to count the number of speaking orders such that at the end of the process \textbf{all} $n$ people have \textbf{equal} happiness.
Two speaking orders are considered different if there exists at least one person who does not have the same position in the two speaking orders.
|
First of all, if there is only $1$ distinct value of happiness, any ordering is fine since no one has strictly greater or lesser happiness, and the answer is $n!$. From here on, we assume that there are at least $2$ distinct values of happiness. Note: The notation $<u,v>$ refers to elements with happiness $u$ and behaviour $v$. Observation 1: The happiness of a person can never decrease. It is obvious. Let's call the final happiness value all elements will be equal to as the target value $T$. Also, let the smallest happiness value of the array be $m$, and the largest be $M$. Note that $T \geq M$, otherwise, it is impossible for a valid order to exist, from observation $1$. Observation 2: For all $x<T$, there can be at most one occurrence of $<x,1>$ in the array. Proof: Let's say there is more than one occurrence of $<x,1>$. Let's say at some point, we can place one occurrence of it in our order, and we place it. But then for the remaining occurrences, it immediately becomes impossible to place them anymore, because the number of strictly greater values increases by $1$, and can only increase from there. Hence, contradiction. ----- Observation 3: There is only one possible $T$, given by $m+n-1$. Proof: Let's say we have $<m,0>$. Then no matter what we do, its final happiness value will still be $m$, since there will never be a value strictly lesser than it. This means $T=m$. This however, breaks our assumption of $2$ distinct values. So only $<m,1>$ can exist. But if that exists, from observation $2$, exactly one such occurrence exists. The number of values strictly greater than $m$ will always be constant. So, no matter when we place it, the final happiness value is going to be $m+n-1$. ----- Observation 4: If it is possible to place multiple numbers in the order at a certain point ( i.e. if there are multiple possible $<u,v>$ place which will all yield $<T,v>$ ), it is always better to prefer the larger number, and to place a number with behaviour $1$ over one with behaviour $0$ in case of a tie. Proof: Let's say you pick something smaller than the larger number. Now this number becomes $T$, which is $\geq M$. Now consider the larger number. If it had a $0$, now it is impossible to place it anymore, because the number of numbers strictly lesser has reduced by $1$, and it can only reduce. A similar argument follows for $1$. In the same group, you have to prefer $1$s over $0$s. Let's say you placed the $0$ first. Now the number of numbers strictly greater has increased by $1$, and can only increase. Therefore you can never place the $1$ now. Placing the $1$ first does not affect the viability of placing the $0$s. Important: If $T=M$, the $<M,1>$ group is special, since it doesn't matter when you place it since the final happiness value will still be $M$, and it won't affect any other group's viability either. But the observation still holds. In fact, except the $<M,1>$ group in the case of $T=M$, you have to follow this order. This means the order is unique upto considering equal elements as indistinguishable. This means, we can only choose the order of placing equal values. We cannot choose the occupied positions in the final order. Hence the count is going to be the product of the number of possible permutations for each group. $\begin{aligned}P=\prod_{\text{all }<u,v>} {cnt_{<u,v>}!}\end{aligned}$ ----- Observation 5: For a valid ordering (if exists), the $0$ behaving people would be sorted in non-decreasing order of initial happiness. Proof: We assume the contrary: Suppose for $x > y$, $<x, 0>$ speaks before $<y, 0>$ in some valid order. Since it is known that both finally become $<T, 0>$, it must be the case that there were $(T - x)$ people with a smaller happiness than $x$, when $x$ speaks and $(T - y)$ people with a smaller happiness than $y$, when $y$ speaks. As $x > y$, everyone having a happiness less than $y$ must also have a happiness less than $x$. Therefore when $y$ speaks at least $(T - y)$ people had a happiness smaller than $x$. Now $(T - x) < (T - y)$; which means the number of people having a value less than $x$ increased. But the happiness of each person can only increase, and hence the number of poeple with a happiness less than $x$ cannot increase; contradiction. ----- Observation 6: For a valid ordering (if exists) and at any intermediate step, for all $1$ behaving people $<u, 1>$ yet to speak, the number of people with a larger happiness than $u$ cannot exceed $(T - u)$. In other words, if we placed $<u, 1>$ at any intermediate step, its final happiness would not exceed $T$. Proof: The happiness of everyone can only increase. So if the number of people with happiness greater than $<u, 1>$ exceeds $(T - u)$ before $<u, 1>$ has spoken, the number of people with a happiness greater than $u$ would not decrease when $u$ subsequently speaks. This means the final happiness of this person would be greater than $T$, which cannot happen. ----- As mentioned before, in the case of the group $<M,1>$ if $T=M$, it doesn't matter where we place them in the order, but the order of the remaining elements is fixed. If there are $S$ occurrences of this group, then we have $n$ spots we can choose to place these values of the group in, and then the rest of the elements will follow the order in the remaining positions. The count $P$ is going to be multiplied by $\binom{n}{S}$. However, it may be the case that no such ordering exists. We thus try to find an order using Observation 4 and speed it up using Observation 5 and Observation 6. We notice that we can have a brute force simulation of Observation 4 to find the order in $\mathcal{O}(n^2)$ time. However, we can do the following: Place all occurrences of $<T, 1>$ at the beginning as their positions don't matter. Keep a sorted (non-decreasing) list of all the $0$ behaving people who are yet to speak. From Observation 5 the only candidate who can be placed from this list at a given step is the least happy candidate. Keep a sorted (increasing) list of all $1$ behaving people who are yet to speak where we keep track of the maximum of the final happiness reached if they were to speak now (i.e. their initial happiness + the number of people with a strictly greater happiness at present) among all people in this list. From Observation 6, we know that if this maximum exceeds $T$, there is no possible ordering and we output $0$. Hence from now we will assume that the maximum happiness reached if they were to talk now to be at most $T$. At each step, there are only two potential speakers that we need to check (since we are breaking ties using Observation 4): The least happy $0$ behaving person (if its happiness reached currently is $T$) and the maximum stored in the last step (if it is equal to $T$). If neither is valid, we report no answer. Otherwise, we break ties using Observation 4 and make that person speak. We change their happiness to $T$ and the final happiness values if they speak now, of all the $1$ behaving people that had a greater happiness (handled in step $3$) than the current person would increase by $1$. If we can complete the entire process, we have a valid ordering. This can be done quickly using two segment trees: One for keeping the happiness reached values of $1$ behaving people yet to speak and storing their maximum (so that steps $3$ and $5$ become max query and range updates); and another for keeping the count of people having a particular happiness value (to speed up finding the current happiness value if they speak now for the least happy $0$ behaving person in step $4$). Time complexity: $\mathcal{O}(n\log n)$
|
[
"combinatorics",
"data structures",
"greedy",
"sortings"
] | 3,300
|
#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define pll pair<ll, ll>
#define ff first
#define ss second
#define vi vector<int>
#define vl vector<ll>
#define vii vector<pii>
#define vll vector<pll>
#define FOR(i,N) for(i=0;i<(N);++i)
#define FORe(i,N) for(i=1;i<=(N);++i)
#define FORr(i,a,b) for(i=(a);i<(b);++i)
#define FORrev(i,N) for(i=(N);i>=0;--i)
#define F0R(i,N) for(int i=0;i<(N);++i)
#define F0Re(i,N) for(int i=1;i<=(N);++i)
#define F0Rr(i,a,b) for(ll i=(a);i<(b);++i)
#define F0Rrev(i,N) for(int i=(N);i>=0;--i)
#define all(v) (v).begin(),(v).end()
#define dbgLine cerr<<" LINE : "<<__LINE__<<"\n"
#define ldd long double
using namespace std;
const int Alp = 26;
const int __PRECISION = 9;
const int inf = 1e9 + 8;
const ldd PI = acos(-1);
const ldd EPS = 1e-7;
const ll MOD = 998244353;
const ll MAXN = 260007;
const ll ROOTN = 320;
const ll LOGN = 18;
const ll INF = 1e18 + 1022;
int N;
int A[MAXN];
bool B[MAXN];
vi a[2];
pii people[MAXN];
ll fact[MAXN + 1], ifact[MAXN + 1];
ll fxp(ll a, ll n){
if(n == 0) return 1;
if(n % 2 == 1) return a * fxp(a, n - 1) % MOD;
return fxp(a * a % MOD, n / 2);
}
ll inv(ll a){
return fxp(a % MOD, MOD - 2);
}
void init(){
fact[0] = ifact[0] = 1;
F0Re(i, MAXN){
fact[i] = fact[i - 1] * i % MOD;
ifact[i] = inv(fact[i]);
}
}
struct SegTree_sum{
int st[4*MAXN];
void upd(int node, int ss, int se, int i, int val){
if(ss > i or se < i) return;
if(ss == se) {st[node] += val; return;}
int mid = (ss + se) / 2;
upd(node*2+1, ss, mid, i, val);
upd(node*2+2, mid+1, se, i, val);
st[node] = st[node*2+1] + st[node*2+2];
}
int quer(int node,int ss, int se, int l, int r){
if(ss > r or se < l) return 0;
if(ss >= l and se <= r) return st[node];
int mid = (ss + se)/2;
return quer(node*2+1, ss, mid, l ,r) + quer(node*2+2, mid + 1, se, l,r);
}
SegTree_sum() {F0R(i, MAXN*4) st[i] = 0;}
inline void update(int i, int val) {upd(0, 0, 2 * MAXN, i, val);}
inline int query(int l, int r) {return quer(0, 0, 2 * MAXN, l, r);}
}S_sum;
struct Segtree_max{
int st[4 * MAXN], lz[4 * MAXN];
inline void push(int node, int ss, int se){
if(lz[node] == 0) return;
st[node] += lz[node];
if(ss != se) lz[node * 2 + 1] += lz[node], lz[node * 2 + 2] += lz[node];
lz[node] = 0;
}
void upd(int node, int ss, int se, int l, int r, int val){
push(node, ss, se);
if(ss > r or se < l) return;
if(ss >= l and se <= r) {lz[node] += val; push(node, ss, se); return;}
int mid = (ss + se)/2;
upd(node * 2 + 1, ss, mid, l, r, val);
upd(node * 2 + 2, 1 + mid, se, l, r, val);
st[node] = max(st[node * 2 + 1], st[node * 2 + 2]);
}
int quer(int node, int ss, int se, int tar){
push(node, ss, se);
if(st[node] < tar || st[node] > tar){
return -1;
}
if(ss == se){
return ss;
}
int mid = (ss + se) / 2;
push(node * 2 + 1, ss, mid);
push(node * 2 + 2, mid + 1, se);
return (st[node * 2 + 2] < tar) ? quer(node * 2 + 1, ss, mid, tar) : quer(node * 2 + 2, mid + 1, se, tar);
}
Segtree_max() {F0R(i,MAXN * 4) st[i] = - 10 * MAXN, lz[i] = 0;}
inline void update(int l, int r, ll val) {if(l <= r) upd(0, 0, 2 * MAXN, l, r, val);}
inline ll query(int v) {return quer(0, 0, 2 * MAXN, v);}
}S_max;
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
init();
cin >> N;
F0R(i, N){
cin >> A[i];
}
F0R(i, N){
cin >> B[i];
}
F0R(i, N){
a[B[i]].pb(A[i]);
people[i] = {A[i], B[i]};
S_sum.update(A[i], 1);
}
sort(all(a[0]));
sort(all(a[1]));
sort(people, people + N);
int m = people[0].ff;
int M = people[N - 1].ff;
int T = people[0].ff + N - 1;
if(m == M){
cout << fact[N] << '\n';
return 0;
}else if(people[0].ss == 0){
cout << "0\n";
return 0;
}else if(M > T){
cout << "0\n";
return 0;
}
int T_cnt = 0;
F0R(i, (int)a[1].size()){
if(a[1][i] == T){
++T_cnt;
}else if(i + 1 < (int)a[1].size() && a[1][i] == a[1][i + 1]){
cout << "0\n";
return 0;
}
}
ll ans = fact[N] * ifact[N - T_cnt] % MOD;
int p = -1, t = 0;
for(int x : a[0]){
if(p != x){
ans = ans * fact[t] % MOD;
t = 0;
}
++t;
p = x;
}
ans = ans * fact[t] % MOD;
int ptr = 0;
for(int x : a[1]){
if(x == T){
break;
}
int y = x + S_sum.query(x + 1, 2 * MAXN);
S_max.update(x, x, y + 10 * MAXN);
}
vii sequence(T_cnt, mp(T, 1));
F0R(i, N - T_cnt){
int zero = T + 1, one = T + 1;
if(ptr < (int)a[0].size() && S_sum.query(1, a[0][ptr] - 1) + a[0][ptr] == T){
zero = a[0][ptr];
}
one = S_max.query(T);
if(one == -1 && zero == T + 1){
cout << "0\n";
return 0;
}
if(zero == T + 1 || one >= zero){
sequence.pb({one, 1});
S_max.update(one, one, - 10 * N);
S_max.update(one + 1, T - 1, 1);
S_sum.update(one, -1);
S_sum.update(T, 1);
}else{
sequence.pb({zero, 0});
S_sum.update(zero, -1);
S_sum.update(T, 1);
S_max.update(zero, T - 1, 1);
++ptr;
}
}
cout << ans << '\n';
return 0;
}
|
1726
|
H
|
Mainak and the Bleeding Polygon
|
Mainak has a convex polygon $\mathcal P$ with $n$ vertices labelled as $A_1, A_2, \ldots, A_n$ in a counter-clockwise fashion. The coordinates of the $i$-th point $A_i$ are given by $(x_i, y_i)$, where $x_i$ and $y_i$ are both integers.
Further, it is known that the interior angle at $A_i$ is either a right angle or a proper obtuse angle. Formally it is known that:
- $90 ^ \circ \le \angle A_{i - 1}A_{i}A_{i + 1} < 180 ^ \circ$, $\forall i \in \{1, 2, \ldots, n\}$ where we conventionally consider $A_0 = A_n$ and $A_{n + 1} = A_1$.
Mainak's friend insisted that all points $Q$ such that there exists a chord of the polygon $\mathcal P$ passing through $Q$ with length \textbf{not exceeding} $1$, must be coloured $\textcolor{red}{\text{red}}$.
Mainak wants you to find the area of the coloured region formed by the $\textcolor{red}{\text{red}}$ points.
Formally, determine the area of the region $\mathcal S = \{Q \in \mathcal{P}$ | $Q \text{ is coloured } \textcolor{red}{\text{red}}\}$.
Recall that a chord of a polygon is a line segment between two points lying on the boundary (i.e. vertices or points on edges) of the polygon.
|
Clearly, the unsafe area is bounded by the envelope of the curve you get if you slide a rod of length $1$ around the interior of the polygon and pressed against the edges at all times. Observation 1: The length of each side of the polygon is $\geq 1$. This one is obvious. Further, it implies that (almost always) we only need to consider unsafe areas formed by adjacent pairs of edges (there is one exception to this which is a rectangle with a side of length $1$, in which case the whole rectangle is unsafe). The proof is left as an exercise to the reader (our proof required some casework and induction on the angle and number of edges). The unsafe area for the whole polygon is the union of the unsafe areas formed by each pair of adjacent edges. Two adjacent edges can be viewed as a pair of lines $y=0$ and $y=x \cdot \tan{( \alpha )}$ where $\alpha$ is the angle between the edges (which is $\geq \frac{\pi}{2}$). As it turns out, the envelope of the unsafe area is given by the parametric equations $\begin{aligned} x&=f(\theta,\alpha)=\frac{\sin\left(\theta-\alpha\right)}{\sin \alpha}+\frac{\cos\left(\theta-\alpha\right)\sin\left(\theta\right)\cos\left(\theta\right)}{\sin \alpha} \\ y&=g(\theta,\alpha)=\frac{\cos\left(\theta-\alpha\right)\sin^{2}\left(\theta\right)}{\sin \alpha} \\ \alpha & < \theta < \pi \end{aligned}$ A sketch of the area for $\alpha=\frac{2\pi}{3}$: Also, the area is given by the formula $\begin{aligned} \frac{\cot{(\alpha)}+(\pi-\alpha) \cdot (\csc^2{(\alpha)}+2)}{16} \end{aligned}$ We can easily just add up these values for each pair of adjacent edges. However, we are overestimating the area. We need to subtract out the intersecting parts of the individual unsafe areas. Observation 2: At most $2$ individual unsafe areas cover any given point. If $2$ unsafe areas intersect, they are the areas made by $3$ successive edges. If say, $3$ unsafe areas covered a point, then one of them must be between non-adjacent edges, which is not possible by the implications of observation 1. Furthermore, if the intersection of the unsafe areas is non-empty, the length of the common edge must be $< 2$, otherwise it will definitely be empty (this fact should be intuitively obvious). However, since the polygon has vertices has integer coordinates, if the length of an edge is $< 2$, it must be $1$ (it is parallel to one axis) or $\sqrt{2}$ (it is diagonal). Note that each possibility of edges with such lengths in an oriented fashion can occur at most once. Which gives us observation 3. Observation 3: The number of sides of length $< 2$ is $\leq 8$. What this basically means is that we will have to compute the area of the intersection of two unsafe areas only $\mathcal{O}(1)$ times. Coming back to the curve, its area can be given by the integral $\begin{aligned} \int{y(\theta) \cdot \frac{\mathrm{d} x(\theta)}{\mathrm{d}\theta}\text{ }\mathrm{d}\theta}=\frac{1}{\sin^2{\alpha}}\int{[2\cos^2{(\theta-\alpha)}\cos^2{\theta}\sin^2{\theta}-\sin{(\theta-\alpha)}\cos{(\theta-\alpha)}\sin^3{\theta}\cos{\theta}]\text{ }\mathrm{d}\theta} \end{aligned}$ This indefinite integral evaluates to $\begin{aligned} \frac{1}{64\sin^2{\alpha}}(\sin{(2 (\alpha - 3 \theta))} - \sin{(2 (\alpha - 2 \theta))} - 4 \sin{(2 (\alpha - \theta))} - \sin{(2 (\alpha + \theta))} - 4 \theta \cos{(2 \alpha)} + 8 \theta - 2 \sin{(4 \theta)}) + C \end{aligned}$ Now, all we need to do is find the bounds of integration by finding the point at which the curves cross. Now, for an edge of length $L$, where $L$ is either $1$ or $\sqrt 2$, we need to find the area of overlap and subtract it from our overestimated value. if we place the edge on the $x$-axis starting from origin, then the adjacent edges which were at an angle $\alpha_1$ and $\alpha_2$, now are straight lines, one at an angle $\alpha_1$ passing from the origin, whereas other is another straight line at an angle $\pi - \alpha_2$ passing through $(L, 0)$. Clearly, the parametric equations of the two envelopes would be $(f(\theta, \alpha_1), g(\theta, \alpha_1))$ for $\alpha_1 \le \theta \le \pi$ and $(L - f(\phi, \alpha2), g(\phi, \alpha_2))$ for $\alpha_2 \le \phi \le \pi$. Observation 4: $g(\theta, \alpha)$, for a fixed $\alpha \in [\frac \pi 2, \pi)$, is a decreasing function of $\theta$, $\alpha \le \theta \le \pi$. This fact can be easily verified from the equation of $g(\alpha, \theta)$ as $\cos(x)$ is decreasing in the range of $(\theta - \alpha)$ i.e. $[0, \pi - \alpha] \subset [0, \frac \pi 2]$, and $\sin^2(x)$ is decreasing in the range of $\theta$, i.e. $[\alpha, \pi] \subset [\frac \pi 2, \pi]$. This means for a given value, $y = \lambda$, we can binary search in $\mathcal O(\log(\frac 1 \varepsilon))$, the value of $\theta$, such that $g(\alpha, \theta) = \lambda$. Once we get $\theta$, we can further get the $x$-coordinate just by plugging $\theta$ in $f(\theta, \alpha)$. Consequently, for both the parametric equations, we can evaluate $x$ as a function of $y$, in $\mathcal O(\log(\frac 1 \varepsilon))$ time. Observation 5: If the coordinates of the intersection of $(f(\theta, \alpha_1), g(\theta, \alpha_1))$ for $\alpha_1 \le \theta \le \pi$ and $(L - f(\phi, \alpha2), g(\phi, \alpha_2))$ for $\alpha_2 \le \phi \le \pi$ is $(h, k)$, then we can can binary search on $k$ in $\mathcal O(\log(\frac 1 \varepsilon))$ function evaluations of $x$ as a function of $y$. Observe that $0 < k < \sin(\max(\alpha_1, \alpha_2))$. Now, for a given guess $\lambda$ of the $y$-coordinate of the intersection point, let's say the first parametric function provides an $x$-coordinate of $x_1$ and the second parametric curve gives $x_2$. In other words, $(x_1, \lambda)$ and $(x_2, \lambda)$ are points on the first and the second curves respectively. Now, if $\lambda > k$, then we must have $x_1 < x_2$, whereas if $\lambda < k$, we have $x_1 > x_2$; and thus we can find the value of $k$ in $\mathcal O(log(\frac 1 \varepsilon))$ evaluations of $x_1$ and $x_2$ using a binary search. Therefore we can find the intersection point (and therefore the corresponding $\theta$ and $\phi$ values) in $\mathcal O(\log^2(\frac 1 \varepsilon))$ time. Once we have the $\theta$ and the $\phi$ values, we get the bounds of the indefinite integral after which we just plug in the values $\theta$ and $\phi$ to the indefinite integral to get the overlap area. Since we are doing this only for edges of length $< 2$, by observation 3, the final time complexity is $\mathcal{O}(n+\log^2{\varepsilon^{-1}})$. However, a solution doing this for every edge would run in $\mathcal{O}(n\log^2{\varepsilon^{-1}})$ time. For the given constraints, this optimization was not necessary to pass.
|
[
"binary search",
"geometry",
"implementation",
"math"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
using lol=long long int;
using ldd=long double;
#define endl "\n"
const ldd PI=acos(-1.0);
const int ITERATIONS = 60;
const int PRECISION = 11;
struct Point{
lol x,y;
Point& operator-=(const Point& rhs){
x-=rhs.x,y-=rhs.y;
return *this;
}
friend Point operator-(Point lhs,const Point& rhs){
lhs -= rhs;
return lhs;
}
};
std::istream& operator>>(std::istream& is, Point& obj){
is>>obj.x>>obj.y;
return is;
}
ldd norm(Point p){
return p.x*p.x+p.y*p.y;
}
ldd cross_product(Point a,Point b){
return a.x*b.y-a.y*b.x;
}
ldd dot_product(Point a,Point b){
return a.x*b.x+a.y*b.y;
}
ldd getalpha(Point a,Point b,Point c){
return atan2l(cross_product(c-b,a-b),dot_product(c-b,a-b));
}
ldd getarea(Point a,Point b,Point c){
Point l1=c-b,l2=a-b;
return (dot_product(l1,l2)/cross_product(l1,l2)+atan2l(cross_product(l1,l2),-dot_product(l1,l2))*((norm(l1)*norm(l2))/(cross_product(l1,l2)*cross_product(l1,l2))+2.0))/16.0;
}
ldd f(ldd theta, ldd alpha){
return -cos(theta)+(1.0/tan(alpha))*sin(theta) + (cos(theta)*(1.0/tan(alpha))+sin(theta)) * (sin(2*theta)/2.0);
}
ldd g(ldd theta, ldd alpha){
return (cos(theta)*(1.0/tan(alpha))+sin(theta)) * (1.0 - cos(2*theta))/2.0;
}
ldd get_x(ldd y, ldd alpha, ldd & theta){
ldd lo = alpha, hi = PI;
for(int it = 0; it < ITERATIONS; ++it){
theta = (lo + hi) / 2.0;
ldd y_guess = g(theta, alpha);
if(y > y_guess){
hi = theta;
}else{
lo = theta;
}
}
return f(theta, alpha);
}
ldd A(ldd theta, ldd alpha){
return (sin(2 * (alpha - 3 * theta)) - sin(2 * (alpha - 2 * theta)) - 4 * sin(2 * (alpha - theta)) - sin(2 * (alpha + theta))
- 4 * theta * cos(2 * alpha) + 8 * theta - 2 * sin(4 * theta)) / (64.0 * sin(alpha) * sin(alpha));
}
ldd find_overlap_area(ldd alpha_1, ldd alpha_2, ldd L){
ldd lo = 0, hi = sin(max(alpha_1, alpha_2));
ldd theta_1 = PI, theta_2 = PI;
for(int it = 0; it < ITERATIONS; ++it){
ldd mid_y = (lo + hi) / 2;
ldd x1 = get_x(mid_y, alpha_1, theta_1);
ldd x2 = L - get_x(mid_y, alpha_2, theta_2);
if(x1 < x2){
hi = mid_y;
}else{
lo = mid_y;
}
}
return (A(PI, alpha_1) + A(PI, alpha_2)) - (A(theta_1, alpha_1) + A(theta_2, alpha_2));
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
vector<Point> v(n);
for(auto& p:v) cin>>p;
if(n == 4){
int MY = max({v[0].y, v[1].y, v[2].y, v[3].y});
int my = min({v[0].y, v[1].y, v[2].y, v[3].y});
int MX = max({v[0].x, v[1].x, v[2].x, v[3].x});
int mx = min({v[0].x, v[1].x, v[2].x, v[3].x});
if(MY - my == 1 || MX - mx == 1){
cout << fixed << setprecision(PRECISION) << 1.0 * (MY - my) * (MX - mx) << endl;
exit(0);
}
}
double ans=0.0;
for(int i=0;i<n;i++){
ans+=getarea(v[(i-1+n)%n],v[i],v[(i+1)%n]);
}
for(int i=0;i<n;i++){
Point a=v[(i-1+n)%n],b=v[i],c=v[(i+1)%n],d=v[(i+2)%n];
if(norm(c-b)<3){
ans-=find_overlap_area(getalpha(a,b,c),getalpha(b,c,d),sqrt(norm(c-b)));
}
}
cout<<fixed<<setprecision(PRECISION)<<ans;
return 0;
}
|
1728
|
A
|
Colored Balls: Revisited
|
The title is a reference to the very first Educational Round from our writers team, Educational Round 18.
There is a bag, containing colored balls. There are $n$ different colors of balls, numbered from $1$ to $n$. There are $\mathit{cnt}_i$ balls of color $i$ in the bag. The total amount of balls in the bag is odd (e. g. $\mathit{cnt}_1 + \mathit{cnt}_2 + \dots + \mathit{cnt}_n$ is odd).
In one move, you can choose two balls \textbf{with different colors} and take them out of the bag.
At some point, all the remaining balls in the bag will have the same color. That's when you can't make moves anymore.
Find any possible color of the remaining balls.
|
Let's prove that the color with the maximum value of $cnt$ is one of the possible answers. Let the color $x$ have the maximum value of $cnt$; if there are several such colors, choose any of them. Let's keep taking the balls of two different colors out of the bag without touching the balls of color $x$ for as long as possible. After such operations, two cases exist. In one case, only balls of color $x$ are left - then everything is fine. In other case, there are balls of color $x$ and some color $y$ (let $cnt_y$ be the remaining number of balls of this color). Since initially $cnt_x$ was one of the maximums, $cnt_y \le cnt_x$. However, the number of remaining balls is odd, which means $cnt_y \ne cnt_x$ and $cnt_y < cnt_x$. Therefore, we can keep taking the balls of colors $y$ and $x$ until only balls of color $x$ are left.
|
[
"brute force",
"greedy",
"implementation",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) cin >> x;
cout << max_element(a.begin(), a.end()) - a.begin() + 1 << '\n';
}
}
|
1728
|
B
|
Best Permutation
|
Let's define the value of the permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once) as follows:
- initially, an integer variable $x$ is equal to $0$;
- if $x < p_1$, then add $p_1$ to $x$ (set $x = x + p_1$), otherwise assign $0$ to $x$;
- if $x < p_2$, then add $p_2$ to $x$ (set $x = x + p_2$), otherwise assign $0$ to $x$;
- ...
- if $x < p_n$, then add $p_n$ to $x$ (set $x = x + p_n$), otherwise assign $0$ to $x$;
- the value of the permutation is $x$ at the end of this process.
For example, for $p = [4, 5, 1, 2, 3, 6]$, the value of $x$ changes as follows: $0, 4, 9, 0, 2, 5, 11$, so the value of the permutation is $11$.
You are given an integer $n$. Find a permutation $p$ of size $n$ with the maximum possible value among all permutations of size $n$. If there are several such permutations, you can print any of them.
|
Let $x_i$ be the value of the variable $x$ after $i$ steps. Note that $x_{n-1}$ should be less than $p_n$ for $x_n$ to be not equal to $0$. It means that $x_n$ does not exceed $2p_n - 1$. It turns out that for $n \ge 4$ there is always a permutation such that $x_n$ is equal to $2n - 1$. The only thing left is to find out how to build such a permutation. There are many suitable permutations, let's consider one of the possible options. For an even $n$, a suitable permutation is $[2, 1, 4, 3, \ dots, n - 2, n - 3, n - 1, n]$. You can see that $x$ in such a permutation changes as follows: $[0, 2, 0, 4, 0, \dots, n - 2, 0, n - 1, 2n - 1]$. For an odd $n$, there is a similar permutation $[1, 3, 2, 5, 4, \dots, n - 2, n - 3, n - 1, n]$, where $x$ changes as follows: $[0, 1, 4, 0, 5, 0, \dots, n-2, 0, n - 1, 2n - 1]$.
|
[
"constructive algorithms",
"greedy"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> p(n);
iota(p.begin(), p.end(), 1);
for (int i = n & 1; i < n - 2; i += 2) swap(p[i], p[i + 1]);
for (int &x : p) cout << x << ' ';
cout << '\n';
}
}
|
1728
|
C
|
Digital Logarithm
|
Let's define $f(x)$ for a positive integer $x$ as the length of the base-10 representation of $x$ without leading zeros. I like to call it a digital logarithm. Similar to a digital root, if you are familiar with that.
You are given two arrays $a$ and $b$, each containing $n$ positive integers. In one operation, you do the following:
- pick some integer $i$ from $1$ to $n$;
- assign either $f(a_i)$ to $a_i$ or $f(b_i)$ to $b_i$.
Two arrays are considered similar to each other if you can rearrange the elements in both of them, so that they are equal (e. g. $a_i = b_i$ for all $i$ from $1$ to $n$).
What's the smallest number of operations required to make $a$ and $b$ similar to each other?
|
First, why can you always make the arrays similar? Applying a digital logarithm to any number will eventually make it equal to $1$. Thus, you can at least make all numbers into $1$s in both arrays. Then notice the most improtant thing - applying the digital logarithm to a number greater than $1$ always makes this number smaller. Thus, if a number appears in only one of the arrays, you will have to do one of the followings two things: decrease some greater number to make it equal to this one; decrease this number. What if there is no greater number at all? This is the case for the largest number in both arrays altogether. If it appears in only one of the arrays, you must always decrease. If it appears in both, though, why decrease it further? Worst case, you will decrease it in one array, then you'll have to decrease it in the other array as well. This is never more optimal than just matching one occurrence in both arrays to each other and removing them from the arrays. So, the proposed solution is the following. Consider the largest element in each array. If they are equal, remove both. If not, apply digital logarithm to the larger of them. Continue until the arrays are empty. What's the estimated complexity of this algorithm? Each number in the first array will be considered at most the number of times you can decrease it with a digital logarithm operation plus one. That is at most $2+1$ - a number greater than $9$ always becomes a single digit and a single digit always becomes $1$. Same goes for the second array. So the complexity is basically linear. To implement it efficiently, you will have to use some data structure that provides three operations: peek at the maximum; remove the maximum; insert a new element. The perfect one is a heap - priority_queue in C++. Overall complexity: $O(n \log n)$ per testcase.
|
[
"data structures",
"greedy",
"sortings"
] | 1,400
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int t;
scanf("%d", &t);
forn(_, t){
int n;
scanf("%d", &n);
vector<int> a(n), b(n);
forn(i, n) scanf("%d", &a[i]);
forn(i, n) scanf("%d", &b[i]);
priority_queue<int> qa(a.begin(), a.end());
priority_queue<int> qb(b.begin(), b.end());
int ans = 0;
while (!qa.empty()){
if (qa.top() == qb.top()){
qa.pop();
qb.pop();
continue;
}
++ans;
if (qa.top() > qb.top()){
qa.push(to_string(qa.top()).size());
qa.pop();
}
else{
qb.push(to_string(qb.top()).size());
qb.pop();
}
}
printf("%d\n", ans);
}
return 0;
}
|
1728
|
D
|
Letter Picking
|
Alice and Bob are playing a game. Initially, they are given a non-empty string $s$, consisting of lowercase Latin letters. The length of the string is even. Each player also has a string of their own, initially empty.
Alice starts, then they alternate moves. In one move, a player takes either the first or the last letter of the string $s$, removes it from $s$ and \textbf{prepends} (adds to the beginning) it to their own string.
The game ends when the string $s$ becomes empty. The winner is the player with a lexicographically smaller string. If the players' strings are equal, then it's a draw.
A string $a$ is lexicographically smaller than a string $b$ if there exists such position $i$ that $a_j = b_j$ for all $j < i$ and $a_i < b_i$.
What is the result of the game if both players play optimally (e. g. both players try to win; if they can't, then try to draw)?
|
What do we do, when the array loses elements only from the left or from the right and the constraints obviously imply some quadratic solution? Well, apply dynamic programming, of course. The classic $dp[l][r]$ - what is the outcome if only the letters from positions $l$ to $r$ (non-inclusive) are left. $dp[0][n]$ is the answer. $dp[i][i]$ is the base case - the draw (both strings are empty). Let $-1$ mean that Alice wins, $0$ be a draw and $1$ mean that Bob wins. How to recalculate it? Let's consider a move of both players at the same time. From some state $[l; r)$, first, Alice goes, then Bob. The new state becomes $[l', r')$, Alice picked some letter $c$, Bob picked some letter $d$. What's that pick exactly? So, they both got a letter, prepended it to their own string. Then continued the game on a smaller string $s$ and prepended even more letters to the string. Thus, if we want to calculate $[l, r)$ from $[l', r')$, we say that we append letters $c$ and $d$. Now it's easy. If $dp[l'][r']$ is not a draw, then the new letters change nothing - the result is still the same. Otherwise, the result of the game is the same as the comparison of letters $c$ and $d$. How to perform both moves at once? First, we iterate over the Alice's move: whether she picks from $l$ or from $r$. After that we iterate over the Bob's move: whether he picks from $l$ or from $r$. Since we want $dp[l][r]$ to be the best outcome for Alice, we do the following. For any Alice move, we choose the worse of the Bob moves - the maximum of $dp[l'][r']$. Among the Alice's moves we choose the better one - the minimum one. Overall complexity: $O(n^2)$ per testcase.
|
[
"constructive algorithms",
"dp",
"games",
"two pointers"
] | 1,800
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int comp(char c, char d){
return c < d ? -1 : (c > d ? 1 : 0);
}
int main() {
int t;
cin >> t;
forn(_, t){
string s;
cin >> s;
int n = s.size();
vector<vector<int>> dp(n + 1, vector<int>(n + 1));
for (int len = 2; len <= n; len += 2) forn(l, n - len + 1){
int r = l + len;
dp[l][r] = 1;
{
int res = -1;
if (dp[l + 1][r - 1] != 0)
res = max(res, dp[l + 1][r - 1]);
else
res = max(res, comp(s[l], s[r - 1]));
if (dp[l + 2][r] != 0)
res = max(res, dp[l + 2][r]);
else
res = max(res, comp(s[l], s[l + 1]));
dp[l][r] = min(dp[l][r], res);
}
{
int res = -1;
if (dp[l + 1][r - 1] != 0)
res = max(res, dp[l + 1][r - 1]);
else
res = max(res, comp(s[r - 1], s[l]));
if (dp[l][r - 2] != 0)
res = max(res, dp[l][r - 2]);
else
res = max(res, comp(s[r - 1], s[r - 2]));
dp[l][r] = min(dp[l][r], res);
}
}
if (dp[0][n] == -1)
cout << "Alice\n";
else if (dp[0][n] == 0)
cout << "Draw\n";
else
cout << "Bob\n";
}
return 0;
}
|
1728
|
E
|
Red-Black Pepper
|
Monocarp is going to host a party for his friends. He prepared $n$ dishes and is about to serve them. First, he has to add some powdered pepper to each of them — otherwise, the dishes will be pretty tasteless.
The $i$-th dish has two values $a_i$ and $b_i$ — its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.
Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $m$ shops in his local area. The $j$-th of them has packages of red pepper sufficient for $x_j$ servings and packages of black pepper sufficient for $y_j$ servings.
Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that \textbf{each dish will get the pepper added once, and no pepper is left}. More formally, if he purchases $x$ red pepper packages and $y$ black pepper packages, then $x$ and $y$ should be non-negative and $x \cdot x_j + y \cdot y_j$ should be equal to $n$.
For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
|
Let's start by learning how to answer a query $(1, 1)$ - all red pepper and black pepper options are available. Let's iterate over all options to put the peppers and choose the maximum of them. First, let's use the red pepper for all dishes. Now we want to select some $k$ of them to use black pepper instead of red pepper. Which ones do we choose? When we switch from the red pepper to the black pepper, the total tastiness changes by $-a_i + b_i$ for the $i$-th dish. They are completely independent of each other, so we want to choose $k$ largest of these values. Let $d_1, d_2, \dots, d_n$ be the sequence of values of $-a_i + b_i$ in a non-increasing order. Thus, $k$ black peppers will yield the result of $\sum \limits_{i=1}^{n} a_i + \sum \limits_{i=1}^{k} d_i$. We can answer a query $(1, 1)$ by looking for a maximum in the sequence. Now consider an arbitrary query. Let $p_1, p_2, \dots, p_t$ be all options for the amount of available black peppers for the query. Naively, we could iterate over all of them and choose the maximum one. However, notice an interesting thing about the sequence of the answers. By definition, it is non-strictly convex. In particular, one idea that can be extracted from this is the following. Find the position of an arbitrary maximum in this sequence. Then everything to the left of is is non-increasing. Everything to the right of it is non-increasing. Thus, for a query, it's enough to consider only two options: the one closest to the maximum from the left and from the right. Now we only have to learn how to get these options fast enough. For a query $(x, y)$ we want to solve what's called a diophantine equation $ax + by = n$. An arbitrary solution can be obtained by using extended Euclid algorithm. Let it be some $(a, b)$. Then we would want to check the answer for $ax$ black peppers. The amount of solutions to the equation is either infinite or zero. If it's infinite, all solutions will be of the form $ax + k \cdot \mathit{lcm}(x, y)$ for any integer $k$. Remember that not all the solutions will be in a range $[0, n]$. Finally, find the two solutions that are the closest to the maximum, check that they are in the range $[0, n]$ and print the best answer of them. Overall complexity: $O(n \log n + q \log X)$.
|
[
"brute force",
"data structures",
"greedy",
"math",
"number theory"
] | 2,300
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
long long gcd(long long a, long long b, long long& x, long long& y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
long long x1, y1;
long long d = gcd(b, a % b, x1, y1);
x = y1;
y = x1 - y1 * (a / b);
return d;
}
bool find_any_solution(long long a, long long b, long long c, long long &x0, long long &y0, long long &g) {
g = gcd(abs(a), abs(b), x0, y0);
if (c % g) {
return false;
}
x0 *= c / g;
y0 *= c / g;
if (a < 0) x0 = -x0;
if (b < 0) y0 = -y0;
return true;
}
int main() {
int n;
scanf("%d", &n);
vector<int> a(n), b(n);
forn(i, n) scanf("%d%d", &a[i], &b[i]);
long long cur = accumulate(b.begin(), b.end(), 0ll);
vector<int> difs(n);
forn(i, n) difs[i] = a[i] - b[i];
sort(difs.begin(), difs.end(), greater<int>());
vector<long long> bst(n + 1);
forn(i, n + 1){
bst[i] = cur;
if (i < n)
cur += difs[i];
}
int mx = max_element(bst.begin(), bst.end()) - bst.begin();
int m;
scanf("%d", &m);
forn(_, m){
int x, y;
scanf("%d%d", &x, &y);
long long x0, y0, g;
if (!find_any_solution(x, y, n, x0, y0, g)){
puts("-1");
continue;
}
long long l = x * 1ll * y / g;
long long red = x0 * 1ll * x;
red = red + (max(0ll, mx - red) + l - 1) / l * l;
red = red - max(0ll, red - mx) / l * l;
long long ans = -1;
if (red <= n) ans = max(ans, bst[red]);
red -= l;
if (red >= 0) ans = max(ans, bst[red]);
printf("%lld\n", ans);
}
return 0;
}
|
1728
|
F
|
Fishermen
|
There are $n$ fishermen who have just returned from a fishing trip. The $i$-th fisherman has caught a fish of size $a_i$.
The fishermen will choose some order in which they are going to tell the size of the fish they caught (the order is just a permutation of size $n$). However, they are not entirely honest, and they may "increase" the size of the fish they have caught.
Formally, suppose the chosen order of the fishermen is $[p_1, p_2, p_3, \dots, p_n]$. Let $b_i$ be the value which the $i$-th fisherman in the order will tell to the other fishermen. The values $b_i$ are chosen as follows:
- the first fisherman in the order just honestly tells the actual size of the fish he has caught, so $b_1 = a_{p_1}$;
- every other fisherman wants to tell a value that is \textbf{strictly greater} than the value told by the previous fisherman, and is divisible by the size of the fish that the fisherman has caught. So, for $i > 1$, $b_i$ is the smallest integer that is both \textbf{strictly greater} than $b_{i-1}$ and \textbf{divisible by} $a_{p_i}$.
For example, let $n = 7$, $a = [1, 8, 2, 3, 2, 2, 3]$. If the chosen order is $p = [1, 6, 7, 5, 3, 2, 4]$, then:
- $b_1 = a_{p_1} = 1$;
- $b_2$ is the smallest integer divisible by $2$ and greater than $1$, which is $2$;
- $b_3$ is the smallest integer divisible by $3$ and greater than $2$, which is $3$;
- $b_4$ is the smallest integer divisible by $2$ and greater than $3$, which is $4$;
- $b_5$ is the smallest integer divisible by $2$ and greater than $4$, which is $6$;
- $b_6$ is the smallest integer divisible by $8$ and greater than $6$, which is $8$;
- $b_7$ is the smallest integer divisible by $3$ and greater than $8$, which is $9$.
You have to choose the order of fishermen in a way that yields the minimum possible $\sum\limits_{i=1}^{n} b_i$.
|
Suppose we have fixed some order of fishermen and calculated the values of $b_i$. Then, we have the following constraints on $b_i$: all values of $b_i$ are pairwise distinct; for every $i$, $a_i$ divides $b_i$. Not every possible array $b$ meeting these constraints can be achieved with some order of fishermen, but we can show that if we choose an array $b$ with the minimum possible sum among the arrays meeting these two constraints, there exists an ordering of fishermen which yields this array $b$. The proof is simple - suppose the ordering of fishermen is the following one: the first fisherman is the one with minimum $b_i$, the second one - the one with the second minimum $b_i$, and so on. It's obvious that if we generate the values of $b$ according to this order, they won't be greater than the values in the array we have chosen. And if some value is less than the value in the chosen array $b$, it means that we haven't chosen the array with the minimum possible sum. So, we can rephrase the problem as the following one: for each $a_i$, choose the value of $b_i$ so that it is divisible by $a_i$, all $b_i$ are distinct, and their sum is minimized. Using the pigeonhole principle, we can show that for every $a_i$, we need to consider only the values of $b_i$ among $[a_i, 2 \cdot a_i, 3 \cdot a_i, \dots, n \cdot a_i]$. So, we can formulate the problem as an instance of the weighted bipartite matching: build a graph with two parts, where the left part contains $n$ nodes representing the values of $a_i$, the right part represents the values of the form $k \cdot a_i$ where $1 \le k \le n$, and there exists an edge between a vertex in the left part representing the number $x$ and a vertex in the right part representing the number $y$ with cost $y$ if and only if $y = k \cdot x$ for some integer $k \in [1, n]$. Note that we don't add the edge if $k > n$ because we need to ensure that the size of the graph is $O(n^2)$. Okay, now we need to solve this weighted matching problem, but how? The number of vertices is $O(n^2)$, and the number of edges is $O(n^2)$ as well, so mincost flow will run in $O(n^4)$ or $O(n^3 \log n)$, which is too much. Instead, we can notice that the cost of the edges incident to the same vertex in the right part is the same, so we can swap the parts of the graph, sort the vertices of the new left part (representing the numbers $k \cdot a_i$) according to their costs, and run the classical Kuhn's algorithm in sorted order. Kuhn's algorithm in its original implementation will always match a vertex if it is possible, so it obtains the minimum total cost for the matching if we do it in sorted order. But this is still $O(n^4)$! What should we do? Well, there are some implementations of Kuhn's algorithm which can run on graphs of size about $10^5$ (sometimes even $10^6$). Why can't we use one of these? Unfortunately, not all optimizations that can be used in Kuhn's algorithm go together well with the fact that the vertices of the left part have their weights. For example, greedy initialization of matching won't work. So we need to choose optimizations carefully. The model solution uses the following optimization of Kuhn's algorithm: if you haven't found an augmenting path, don't reset the values representing which vertices were visited by the algorithm. With this optimization, Kuhn's algorithm works in $O(M(E + V))$, where $M$ is the size of the maximum matching, $E$ is the number of edges, and $V$ is the number of vertices. So, this results in a solution with complexity of $O(n^3)$. I think it's possible to show that some other optimizations of Kuhn can also work, but the one I described is enough.
|
[
"flows",
"graph matchings",
"greedy"
] | 3,100
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1003;
int n;
int a[N];
vector<int> g[N * N];
int mt[N];
bool used[N * N];
vector<int> val;
bool kuhn(int x)
{
if(used[x]) return false;
used[x] = true;
for(auto y : g[x])
if(mt[y] == -1 || kuhn(mt[y]))
{
mt[y] = x;
return true;
}
return false;
}
int main()
{
cin >> n;
for(int i = 0; i < n; i++) cin >> a[i];
for(int i = 0; i < n; i++)
for(int j = 1; j <= n; j++)
val.push_back(a[i] * j);
sort(val.begin(), val.end());
val.erase(unique(val.begin(), val.end()), val.end());
int v = val.size();
long long ans = 0;
for(int i = 0; i < n; i++)
for(int j = 1; j <= n; j++)
{
int k = lower_bound(val.begin(), val.end(), a[i] * j) - val.begin();
g[k].push_back(i);
}
for(int i = 0; i < n; i++) mt[i] = -1;
for(int i = 0; i < v; i++)
{
if(kuhn(i))
{
ans += val[i];
for(int j = 0; j < v; j++) used[j] = false;
}
}
cout << ans << endl;
}
|
1728
|
G
|
Illumination
|
Consider a segment $[0, d]$ of the coordinate line. There are $n$ lanterns and $m$ points of interest in this segment.
For each lantern, you can choose its power — an integer between $0$ and $d$ (inclusive). A lantern with coordinate $x$ illuminates the point of interest with coordinate $y$ if $|x - y|$ is less than or equal to the power of the lantern.
A way to choose the power values for all lanterns is considered \textbf{valid} if every point of interest is illuminated by at least one lantern.
You have to process $q$ queries. Each query is represented by one integer $f_i$. To answer the $i$-th query, you have to:
- add a lantern on coordinate $f_i$;
- calculate the number of valid ways to assign power values to all lanterns, and print it modulo $998244353$;
- remove the lantern you just added.
|
Let's start without the queries. How to calculate the number of ways for the given $n$ lanterns? First, it's much easier to calculate the number of bad ways - some point of interest is not illuminated. If at least one point of interest is not illuminated, then all lanterns have power lower than the distance from them to this point of interest. More importantly, it's less than $d$. Thus, the number of good ways is $(d+1)^n$ minus the number of bad ways. Let's use inclusion-exclusion. For a mask of non-illuminated points of interest, let's calculate the number of ways to assign the powers to the lanterns in such a way that at least these points of interest are not illuminated. All other points can be either illuminated or not. Let's call it $\mathit{ways}[\mathit{mask}]$. With the values for all masks, the answer is the sum of $\mathit{ways}[\mathit{mask}] \cdot (-1)^{\mathit{popcount(mask)}}$ over all masks. How to calculate the value for the mask? First, let's do it in $O(nm)$ for each mask. Each lantern can have any power from $0$ to the distance to the closest point of interest inside the mask non-inclusive. Thus, we can iterate over the lanterns and find the closest point to each of them, then multiply the number of ways for all lanterns. Let's calculate it the other way around. Initialize the answers for the masks with $1$. Then iterate over the lantern and the point of interest that will be the closest non-illuminated one to this lantern. Let the distance between them be some value $d$. Which masks will this pair affect? Let the lantern be to the right of that point of interest. The opposite can be handled similarly. All points to the left of the chosen point can be in either state. All points between the chosen one and the lantern must be illuminated. All points to the right of the lantern and with distance smaller than $d$ must also be illumunated. All point to the right of these can be in either state. Thus, the masks look like "**..**1000..000**..**", where 1 denotes the chosen non-illuminated point. All masks that correspond to this template will be multiplied by $d$. You have to be careful when there are two points of interest with the same distance $d$ to some lantern - one to the left of it and one to the right of it. In particular, in one case, you should force illumination on all points with distance $<d$. In another case, you should force illumination on all points with distance $\le d$. How to multiply fast enough? We'll use a technique called sum-over-subsets. Let's express the template in terms of submasks. For a template "***100000***", all submasks of "111100000111" will be multiplied by $d$. However, we accidentally multiplied masks of form "***000000***" too. Let's cancel them by dividing the submasks of "111000000111" by $d$. Record all multiplications for all pairs, them force push them into submasks with sum-over-subsets (well, product-over-subsets in this case :)). Now we have the values of $\mathit{ways}[\mathit{mask}]$ for all masks in basically $O(nm + 2^m \cdot m)$, give or take the time to find the points that must be forced illuminated (extra $O(\log m)$ from lower_bound or two pointers, which is not really faster). Now for the queries. How does the answer change after an extra lantern is added? Again, let's iterate over the closest point of interest and find the mask template. All masks corresponding to this template will get multiplied by $d$. Thus, the answer will change by the sum of values of these masks, multiplied by $d$, including the inclusion-exclusion coefficient. How to handle that? Well, yet another sum-over-subsets. Just collect the sum of values over the submasks beforehand and use these during the query. That gives us an $O(m)$ per query. Overall complexity: $O(nm + qm + 2^m \cdot m)$.
|
[
"binary search",
"bitmasks",
"brute force",
"combinatorics",
"dp",
"math",
"two pointers"
] | 2,700
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = 998244353;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
return a;
}
int mul(int a, int b){
return a * 1ll * b % MOD;
}
int binpow(int a, int b){
int res = 1;
while (b){
if (b & 1)
res = mul(res, a);
a = mul(a, a);
b >>= 1;
}
return res;
}
int main() {
int D, n, m;
scanf("%d%d%d", &D, &n, &m);
vector<int> inv(D + 1);
forn(i, D + 1) inv[i] = binpow(i, MOD - 2);
vector<int> b(n);
forn(i, n) scanf("%d", &b[i]);
vector<int> a(m);
forn(i, m) scanf("%d", &a[i]);
sort(a.begin(), a.end());
int fl = (1 << m) - 1;
vector<int> ways(1 << m, 1);
forn(i, m) forn(j, n){
int d = abs(b[j] - a[i]);
int mask;
if (b[j] > a[i]){
int r = lower_bound(a.begin(), a.end(), b[j] + d) - a.begin();
mask = fl ^ ((1 << r) - 1) ^ ((1 << (i + 1)) - 1);
}
else{
int l = lower_bound(a.begin(), a.end(), b[j] - d) - a.begin();
mask = fl ^ ((1 << i) - 1) ^ ((1 << l) - 1);
}
ways[mask] = mul(ways[mask], d);
mask ^= (1 << i);
ways[mask] = mul(ways[mask], inv[d]);
}
forn(i, m) for (int mask = fl; mask >= 0; --mask) if ((mask >> i) & 1){
ways[mask ^ (1 << i)] = mul(ways[mask ^ (1 << i)], ways[mask]);
}
ways[0] = binpow(D + 1, n);
forn(mask, 1 << m){
ways[mask] = mul(ways[mask], __builtin_popcount(mask) & 1 ? MOD - 1 : 1);
}
forn(i, m) forn(mask, 1 << m) if (!((mask >> i) & 1)){
ways[mask ^ (1 << i)] = add(ways[mask ^ (1 << i)], ways[mask]);
}
int q;
scanf("%d", &q);
forn(_, q){
int x;
scanf("%d", &x);
int ans = binpow(D + 1, n + 1);
forn(i, m){
int d = abs(x - a[i]);
int mask;
if (x > a[i]){
int r = lower_bound(a.begin(), a.end(), x + d) - a.begin();
mask = fl ^ ((1 << r) - 1) ^ ((1 << (i + 1)) - 1);
}
else{
int l = lower_bound(a.begin(), a.end(), x - d) - a.begin();
mask = fl ^ ((1 << i) - 1) ^ ((1 << l) - 1);
}
ans = add(ans, mul(add(ways[mask], -ways[mask ^ (1 << i)]), d));
}
printf("%d\n", ans);
}
return 0;
}
|
1729
|
A
|
Two Elevators
|
Vlad went into his appartment house entrance, now he is on the $1$-th floor. He was going to call the elevator to go up to his apartment.
There are only two elevators in his house. Vlad knows for sure that:
- the first elevator is currently on the floor $a$ (it is currently motionless),
- the second elevator is located on floor $b$ and goes to floor $c$ ($b \ne c$). Please note, if $b=1$, then the elevator is already leaving the floor $1$ and Vlad does not have time to enter it.
If you call the first elevator, it will immediately start to go to the floor $1$. If you call the second one, then first it will reach the floor $c$ and only then it will go to the floor $1$. It takes $|x - y|$ seconds for each elevator to move from floor $x$ to floor $y$.
Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.
|
You had to to calculate the time that each elevator would need and compare them. Let the time required by the first elevator be $d_1 = |a - 1|$, and the time required by the second one be $d_2 = |b - c| + |c - 1|$. Then the answer is $1$ if $d_1 < d_2$, $2$ if $d_1 > d_2$ and $3$ if $d_1 = d_2$
|
[
"math"
] | 800
|
t = int(input())
for _ in range(t):
a, b, c = map(int, input().split())
d1 = a - 1
d2 = abs(b - c) + c - 1
ans = 0
if d1 <= d2:
ans += 1
if d1 >= d2:
ans += 2
print(ans)
|
1729
|
B
|
Decode String
|
Polycarp has a string $s$ consisting of lowercase Latin letters.
He encodes it using the following algorithm.
He goes through the letters of the string $s$ from left to right and for each letter Polycarp considers its number in the alphabet:
- if the letter number is single-digit number (less than $10$), then just writes it out;
- if the letter number is a two-digit number (greater than or equal to $10$), then it writes it out and adds the number 0 after.
For example, if the string $s$ is code, then Polycarp will encode this string as follows:
- 'c' — is the $3$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3);
- 'o' — is the $15$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150);
- 'd' — is the $4$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504);
- 'e' — is the $5$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045).
Thus, code of string code is 315045.
You are given a string $t$ resulting from encoding the string $s$. Your task is to decode it (get the original string $s$ by $t$).
|
The idea is as follows: we will go from the end of the string $t$ and get the original string $s$. Note that if the current digit is $0$, then a letter with a two-digit number has been encoded. Then we take a substring of length three from the end, discard $0$ and get the number of the original letter. Otherwise, the current number $\neq 0$, then a letter with a one-digit number was encoded. We easily reconstruct the original letter. Next, discard the already processed characters and repeat the process until the encoded string is complete.
|
[
"greedy",
"strings"
] | 800
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
char get(int i) {
return 'a' + i - 1;
}
void solve() {
int n;
string s;
cin >> n >> s;
int i = n - 1;
string res;
while (i >= 0) {
if (s[i] != '0') {
res += get(s[i] - '0');
i--;
} else {
res += get(stoi(s.substr(i - 2, 2)));
i -= 3;
}
}
reverse(res.begin(), res.end());
cout << res << '\n';
}
int main() {
int t = 1;
cin >> t;
for (int it = 0; it < t; ++it) {
solve();
}
return 0;
}
|
1729
|
C
|
Jumping on Tiles
|
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $s$.
In other words, you are given a string $s$ consisting of lowercase Latin letters.
Initially, Polycarp is on the \textbf{first} tile of the row and wants to get to the \textbf{last} tile by jumping on the tiles. Jumping from $i$-th tile to $j$-th tile has a cost equal to $|index(s_i) - index(s_j)|$, where $index(c)$ is the index of the letter $c$ in the alphabet (for example, $index($'a'$)=1$, $index($'b'$)=2$, ..., $index($'z'$)=26$) .
Polycarp wants to get to the $n$-th tile for the minimum total cost, but at the same time make \textbf{maximum} number of jumps.
In other words, among all possible ways to get to the last tile for the \textbf{minimum} total cost, he will choose the one with the \textbf{maximum} number of jumps.
Polycarp can visit each tile \textbf{at most once}.
Polycarp asks you to help — print the sequence of indices of string $s$ on which he should jump.
|
It's worth knowing that ways like ('a' -> 'e') and ('a' -> 'c' -> 'e') have the same cost. That is, first you need to understand the letter on the first tile and the last one (conditionally, the letters $first$ and $last$). Then you just need to find all such tiles on which the letters are between the letters $first$ and $last$ inclusive. We go through each letter from $first$ to $last$ and for each letter we visit every tile that has a given letter (but we must not forget to start exactly at tile $1$ and end at tile $n$).
|
[
"constructive algorithms",
"strings"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define forn(i, n) for (int i = 0; i < int(n); i++)
void solve() {
string s;
cin >> s;
int n = s.size();
map<char, vector<int>> let_to_ind;
for (int i = 0; i < n; ++i) {
let_to_ind[s[i]].push_back(i);
}
int direction = (s[0] < s[n - 1]) ? 1 : -1;
vector<int> ans;
for (char c = s[0]; c != s[n - 1] + direction; c += direction) {
for (auto now : let_to_ind[c]) {
ans.push_back(now);
}
}
int cost = 0;
for (int i = 1; i < ans.size(); i++)
cost += abs(s[ans[i]] - s[ans[i - 1]]);
cout << cost << " " << ans.size() << '\n';
for (auto now : ans) {
cout << now + 1 << " ";
}
cout << '\n';
}
int main() {
int tests;
cin >> tests;
forn(tt, tests) {
solve();
}
}
|
1729
|
D
|
Friends and the Restaurant
|
A group of $n$ friends decide to go to a restaurant. Each of the friends plans to order meals for $x_i$ burles and has a total of $y_i$ burles ($1 \le i \le n$).
The friends decide to split their visit to the restaurant into several days. Each day, some group of \textbf{at least two} friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be \textbf{not less} than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $x_i$ values in the group must not exceed the sum of $y_i$ values in the group.
What is the maximum number of days friends can visit the restaurant?
For example, let there be $n = 6$ friends for whom $x$ = [$8, 3, 9, 2, 4, 5$] and $y$ = [$5, 3, 1, 4, 5, 10$]. Then:
- first and sixth friends can go to the restaurant on the first day. They will spend $8+5=13$ burles at the restaurant, and their total budget is $5+10=15$ burles. Since $15 \ge 13$, they can actually form a group.
- friends with indices $2, 4, 5$ can form a second group. They will spend $3+2+4=9$ burles at the restaurant, and their total budget will be $3+4+5=12$ burles ($12 \ge 9$).
It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.
So, the maximum number of groups the friends can split into is $2$. Friends will visit the restaurant for a maximum of two days. Note that the $3$-rd friend will not visit the restaurant at all.
Output the maximum number of days the friends can visit the restaurant for given $n$, $x$ and $y$.
|
First, we sort the friends in descending order of $y_i - x_i$. Now for each friend we know the amount of money he lacks, or vice versa, which he has in excess. In order to maximize the number of days, it is most advantageous for friends to break into pairs. It is the number of groups that matters, not the number of people in the group, so adding a third person to the pair won't improve the answer in any way. Let's solve the problem using two pointers: for the richest friend, find the first friend from the end such that the sum of their values $y$ exceeds the sum of their values $x$. Then repeat this for all subsequent friends until the pointers meet. If no pair could be formed, or none of the friends has a value $x$ greater than $y$, then the answer is -1. Otherwise, print the number of pairs formed.
|
[
"greedy",
"sortings",
"two pointers"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve(){
int n;
cin >> n;
vector<ll>x(n), y(n);
vector<pair<ll, int>>dif(n);
for(auto &i : x) cin >> i;
for(auto &i: y) cin >> i;
for(int i = 0; i < n; i++){
dif[i].first = y[i] - x[i];
dif[i].second = i;
}
sort(dif.begin(), dif.end());
reverse(dif.begin(), dif.end());
int j = n - 1, cnt = 0;
for(int i = 0; i < n; i++){
while(j > i && dif[i].first + dif[j].first < 0) j--;
if(j <= i) break;
cnt++; j--;
}
cout << cnt << endl;
}
int main() {
int t;
cin >> t;
while(t--){
solve();
}
}
|
1729
|
E
|
Guess the Cycle Size
|
\textbf{This is an interactive problem}.
I want to play a game with you...
We hid from you a cyclic graph of $n$ vertices ($3 \le n \le 10^{18}$). A cyclic graph is an undirected graph of $n$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $n$. The order of the vertices in the cycle is arbitrary.
You can make queries in the following way:
- "? a b" where $1 \le a, b \le 10^{18}$ and $a \neq b$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $a$ to vertex $b$, or -1 if $\max(a, b) > n$. The interactor chooses one of the two paths with \textbf{equal probability}. The length of the path —is the number of edges in it.
You win if you guess the number of vertices in the hidden graph (number $n$) by making no more than $50$ queries.
Note that the interactor is implemented in such a way that for any ordered pair $(a, b)$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.
The vertices in the graph are randomly placed, and their positions are fixed in advance.
Hacks are forbidden in this problem. The number of tests the jury has is $50$.
|
The implication was that the solution works correctly with some high probability. So we tried to give such constraints so that the solution probability is very high. The idea: we will output queries of the form $(1, n)$ and $(n, 1)$, gradually increasing $n$ from $2$. If we get an answer to query $-1$ the first time, then the size of the graph is exactly $n-1$. Otherwise, let the answer to the first query be $x$ and the answer to the second query be $y$. With probability $\frac{1}{2}, x \neq y$. In this case, we can output the answer: $x+y$, since there are a total of two different paths from vertex $1$ to $n$ and we recognized them. Accordingly the total length of paths will be the size of the cyclic graph. But with probability $\frac{1}{2}, x = y$. In this case we must continue the algorithm. At most we can make $25$ of such attempts. Let's calculate the probability of finding the correct graph size: $p = 1 - (\frac{1}{2})^{25}$. That is, we "lucky" on one test with probability $p \approx 0.99999997$. But we should have "lucky" on $50$ tests. We get: $P = p^{50} \approx 0.99999851$.
|
[
"interactive",
"probabilities"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define sz(v) (int)v.size()
#define all(v) v.begin(),v.end()
#define eb emplace_back
long long ask(int a, int b) {
cout << "? " << a << ' ' << b << endl;
long long x; cin >> x;
return x;
}
long long solve() {
for (int i = 2; i <= 26; i++) {
long long x = ask(1, i);
long long y = ask(i, 1);
if (x == -1) return i-1;
if (x != y) return x + y;
}
assert(false);
}
int main() {
long long ans = solve();
cout << "! " << ans << endl;
}
|
1729
|
F
|
Kirei and the Linear Function
|
Given the string $s$ of decimal digits (0-9) of length $n$.
A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($l, r$), where $1 \le l \le r \le n$, corresponds to a substring of the string $s$. We will define as $v(l,r)$ the numeric value of the corresponding substring (leading zeros are allowed in it).
For example, if $n=7$, $s=$"1003004", then $v(1,3)=100$, $v(2,3)=0$ and $v(2,7)=3004$.
You are given $n$, $s$ and an integer $w$ ($1 \le w < n$).
You need to process $m$ queries, each of which is characterized by $3$ numbers $l_i, r_i, k_i$ ($1 \le l_i \le r_i \le n; 0 \le k_i \le 8$).
The answer to the $i$th query is such a pair of substrings of length $w$ that if we denote them as $(L_1, L_1+w-1)$ and $(L_2, L_2+w-1)$, then:
- $L_1 \ne L_2$, that is, the substrings are different;
- the remainder of dividing a number $v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$ by $9$ is equal to $k_i$.
If there are many matching substring pairs, then find a pair where $L_1$ is as small as possible. If there are many matching pairs in this case, then minimize $L_2$.
Note that the answer may not exist.
|
Note that the remainder of dividing a number by $9$ is equal to the remainder of dividing its sum of digits by $9$. This is easy to check, because the number $a$ of $n$ digits is representable as a polynomial $a_0 + a_1\cdot 10 + a_2\cdot 100 + \dots + a_{n-1}\cdot 10^{n-1} + a_n\cdot 10^n$, and $10^k$ gives a remainder of $1$ when divided by $9$ for any $k$. Let's count an array of prefix sums of digits for the string $s$. Now, knowing $w$, we can pre-calculate for each remainder modulo $9$ all possible $L$. Also, for each query, we can easily find the remainder of dividing $v(l,r)$ by $9$ using all the same prefix sums. Let's iterate over the remainder of the number $a$ when dividing by $9$. Knowing it, we can easily find the remainder of the number $b$ when divided by $9$, as $k - a\cdot v(l,r)$ modulo $9$. Now, using each pair of remainers $(a, b)$, let's try to update the answer: $a = b$, then the minimum index from the pre-calculated array will act as $L_1$, and the next largest will act as $L_2$ (if such exist); $a\neq b$, then the minimum indexes from the pre-calculated array will act as $L_1$ and $L_2$. This solution works for $9\cdot(n+m)$ or for $O(n + m)$.
|
[
"hashing",
"math"
] | 1,900
|
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef pair<int, int> ipair;
const int MAXSZ = 200200;
const int INF = 2e9;
inline int add(int a, int b) {
return (a + b >= 9 ? a + b - 9 : a + b);
}
inline int sub(int a, int b) {
return (a < b ? a + 9 - b : a - b);
}
inline int mul(int a, int b) {
return a * b % 9;
}
int sz, n, m;
string s;
int ps[MAXSZ];
vector<int> D[9];
void build() {
sz = s.size();
for (int md = 0; md < 9; ++md)
D[md].clear();
for (int i = 0; i < sz; ++i)
ps[i + 1] = ps[i] + (s[i] - '0');
for (int i = 0; i + n <= sz; ++i)
D[(ps[i + n] - ps[i]) % 9].push_back(i);
}
ipair solve(int l, int r, int k) {
int x = (ps[r] - ps[l]) % 9;
ipair ans {INF, INF};
for (int a = 0; a < 9; ++a) {
int b = sub(k, mul(a, x));
if (D[a].empty() || D[b].empty()) continue;
if (a != b)
ans = min(ans, make_pair(D[a].front(), D[b].front()));
else if (D[a].size() >= 2)
ans = min(ans, make_pair(D[a].front(), D[a][1]));
}
if (ans == make_pair(INF, INF))
return {-2, -2};
return ans;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
int t; cin >> t;
while (t--) {
cin >> s >> n >> m;
build();
for (int i = 0; i < m; ++i) {
int l, r, k; cin >> l >> r >> k, --l;
auto [ans1, ans2] = solve(l, r, k);
cout << ++ans1 << ' ' << ++ans2 << endl;
}
}
}
|
1729
|
G
|
Cut Substrings
|
You are given two non-empty strings $s$ and $t$, consisting of Latin letters.
In one move, you can choose an occurrence of the string $t$ in the string $s$ and replace it with dots.
Your task is to remove all occurrences of the string $t$ in the string $s$ in the minimum number of moves, and also calculate how many \textbf{different} sequences of moves of the minimum length exist.
Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $t$ in $s$ begin differ. For example, the sets $\{1, 2, 3\}$ and $\{1, 2, 4\}$ are considered different, the sets $\{2, 4, 6\}$ and $\{2, 6\}$ — too, but sets $\{3, 5\}$ and $\{5, 3\}$ — not.
For example, let the string $s =$ "abababacababa" and the string $t =$ "aba". We can remove all occurrences of the string $t$ in $2$ moves by cutting out the occurrences of the string $t$ at the $3$th and $9$th positions. In this case, the string $s$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $t$ at the $3$th and $11$th positions. There are two different sequences of minimum length moves.
Since the answer can be large, output it modulo $10^9 + 7$.
|
First, find all occurrences of $t$ in $s$ as substrings. This can be done using the prefix function. To find the minimum number of times we need to cut substrings, consider all indexes of occurrences. Having considered the index of the occurrence, we cut out the rightmost occurrence that intersects with it. After that, we find the leftmost occurrence that does not intersect with the cut one. If it doesn't, we end the loop. The number of optimal sequences of moves will be calculated using dynamic programming. For each occurrence, we can count how many ways we can cut out all occurrences of $t$ in the suffix $s$ starting with this occurrence in the minimum number of moves. Considering the occurrence, we find the leftmost occurrence that does not intersect with it, and then iterate over the occurrences with which we can remove it.
|
[
"combinatorics",
"dp",
"hashing",
"strings",
"two pointers"
] | 2,100
|
#include<cstdio>
#include<cstring>
const int N=505;
const int Mod=1e9+7;
char s[N],t[N];
int n,m;
int f[N],g[N];
int p[N],tot;
inline void Init(){
scanf("%s",s+1);
scanf("%s",t+1);
n=strlen(s+1);
m=strlen(t+1);
tot=0;
for(int i=1;i+m-1<=n;i++){
bool flg=1;
for(int j=1;j<=m;j++)
if(s[i+j-1]!=t[j]) flg=0;
if(flg) p[++tot]=i;
}
return ;
}
inline int addv(int x,int y){
int s=x+y;
if(s>=Mod) s-=Mod;
return s;
}
inline int subv(int x,int y){
int s=x-y;
if(s<0) s+=Mod;
return s;
}
inline void add(int&x,int y){
x=addv(x,y);
return ;
}
inline void sub(int&x,int y){
x=subv(x,y);
return ;
}
inline void Solve(){
memset(f,0x3f,sizeof(f));
memset(g,0,sizeof(g));
p[0]=-N;
f[0]=0;
g[0]=1;
p[++tot]=n+m;
for(int i=0;i<tot;i++){
int j=i+1;
while(j<=tot&&p[j]<=p[i]+m-1) j++;
for(int k=j;p[j]+m-1>=p[k]&&k<=tot;k++){
if(f[i]+1<f[k]){
f[k]=f[i]+1;
g[k]=g[i];
}
else if(f[i]+1==f[k]) add(g[k],g[i]);
}
}
printf("%d %d\n",f[tot]-1,g[tot]);
return ;
}
int T;
int main(){
for(scanf("%d",&T);T;T--){
Init();
Solve();
}
return 0;
}
|
1730
|
A
|
Planets
|
One day, Vogons wanted to build a new hyperspace highway through a distant system with $n$ planets. The $i$-th planet is on the orbit $a_i$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.
Vogons have two machines to do that.
- The first machine in one operation can destroy any planet at cost of $1$ Triganic Pu.
- The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $c$ Triganic Pus.
Vogons can use each machine as many times as they want.
Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?
|
To solve the problem, it was enough to count the number of planets with the same orbits $cnt_i$ and sum up the answers for the orbits separately. For one orbit, it is advantageous either to use the second machine once and get the cost $c$, or to use only the first one and get the cost equal to $cnt_i$.
|
[
"data structures",
"greedy",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, c;
cin >> n >> c;
vector<int> a(n);
map<int, int> mp;
int ans = 0;
for(int i = 0; i < n; i++){
cin >> a[i];
mp[a[i]]++;
if(mp[a[i]] <= c){
ans++;
}
}
cout << ans << endl;
}
int main() {
int t;
cin >> t;
while(t--)
solve();
}
|
1730
|
B
|
Meeting on the Line
|
$n$ people live on the coordinate line, the $i$-th one lives at the point $x_i$ ($1 \le i \le n$). They want to choose a position $x_0$ to meet. The $i$-th person will spend $|x_i - x_0|$ minutes to get to the meeting place. Also, the $i$-th person needs $t_i$ minutes to get dressed, so in total he or she needs $t_i + |x_i - x_0|$ minutes.
Here $|y|$ denotes the absolute value of $y$.
These people ask you to find a position $x_0$ that minimizes the time in which all $n$ people can gather at the meeting place.
|
There are many solutions to this problem, here are 2 of them. 1) Let people be able to meet in time $T$, then they could meet in time $T + \varepsilon$, where $\varepsilon > 0$. So we can find $T$ by binary search. It remains to learn how to check whether people can meet for a specific time $T$. To do this, for the $i$-th person, find a segment of positions that he can get to in time $T$: if $T < t_i$ then this segment is empty, otherwise it is $[x_i - (T - t_i), x_i + (T - t_i)]$. Then people will be able to meet only if these segments intersect, that is, the minimum of the right borders is greater than or equal to the maximum of the left borders. In order to find the answer by the minimum $T$, you need to intersect these segments in the same way (should get a point, but due to accuracy, most likely, a segment of a very small length will turn out) and take any point of this intersection. Asymptotics is $O(n \log n)$. 2) If all $t_i$ were equal to $0$, then this would be a classical problem, the solution of which would be to find the average of the minimum and maximum coordinates of people. We can reduce our problem to this one if we replace the person ($x_i$, $t_i$) with two people: ($x_i - t_i$, $0$) and ($x_i + t_i$, $0$). Proof. Let the meeting be at the point $y$. Let $x_i \le y$. Then this person will need $t_i + y - x_i$ of time to get to her, and the two we want to replace him with - $y - x_i + t_i$ and $y - x_i - t_i$. it is easy to see that the first value is equal to the initial value, and the second is not greater than the initial value, then the maximum of these two values is equal to the initial value. The proof is similar for the case $y \le x_i$. Then for any meeting point, the time in the original problem and after the replacement does not differ, which means that such a replacement will not change the answer and it can be done. Asymptotics is $O(n)$.
|
[
"binary search",
"geometry",
"greedy",
"implementation",
"math",
"ternary search"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> x(n), t(n);
for(int i = 0; i < n; i++)
cin >> x[i];
for(int i = 0; i < n; i++)
cin >> t[i];
vector<int> a;
for(int i = 0; i < n; i++) {
a.push_back(x[i] + t[i]);
a.push_back(x[i] - t[i]);
}
int mn = a[0], mx = a[0];
for(int val : a) {
mn = min(mn, val);
mx = max(mx, val);
}
int sum = mn + mx;
cout << sum / 2;
if(sum % 2 != 0)
cout << ".5";
cout << '\n';
}
int main() {
int t;
cin >> t;
while(t--)
solve();
}
|
1730
|
C
|
Minimum Notation
|
You have a string $s$ consisting of digits from $0$ to $9$ inclusive. You can perform the following operation any (possibly zero) number of times:
- You can choose a position $i$ and delete a digit $d$ on the $i$-th position. Then insert the digit $\min{(d + 1, 9)}$ on any position (at the beginning, at the end or in between any two adjacent digits).
What is the lexicographically smallest string you can get by performing these operations?
A string $a$ is lexicographically smaller than a string $b$ of the same length if and only if the following holds:
- in the first position where $a$ and $b$ differ, the string $a$ has a smaller digit than the corresponding digit in $b$.
|
We leave all suffix minimums by the digits $mn_i$ (digits less than or equal to the minimum among the digits to the right of them), remove the rest and replace them with $\min{(d + 1, 9)}$ (using the described operations) and add to lexicographically minimum order on the right (due to the appropriate order of operations, this is possible). The suffix minimums $mn_i$ should be left, because no matter what digit we leave after $mn_i$, it will be no less than $mn_i$, and therefore will not improve the answer. The rest must be removed at the end with operations, since there is a number to the right less than this one, i.e. if you remove everything before it (put $mn_i$ at the current position), the answer will become less than if you leave another digit at this position.
|
[
"data structures",
"greedy",
"math",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
string s;
cin >> s;
int n = s.size();
vector<int> a(n);
vector<int> mn(n + 1, 9);
for(int i = 0; i < n; i++){
a[i] = int(s[i] - '0');
}
for(int i = n - 1; i >= 0; i--){
mn[i] = min(mn[i + 1], a[i]);
}
vector<int> buff(10, 0);
string ans = "";
string t = "0123456789";
for(int i = 0; i < n; i++){
for(int j = 0; j < mn[i]; j++){
while(buff[j]){
buff[j]--;
ans += t[j];
}
}
if(a[i] == mn[i]){
ans += t[a[i]];
}
else{
buff[min(9, a[i] + 1)]++;
}
}
for(int j = 0; j < 10; j++){
while(buff[j]){
buff[j]--;
ans += t[j];
}
}
cout << ans << endl;
}
int main() {
int t;
cin >> t;
while(t--){
solve();
}
}
|
1730
|
D
|
Prefixes and Suffixes
|
You have two strings $s_1$ and $s_2$ of length $n$, consisting of lowercase English letters. You can perform the following operation any (possibly zero) number of times:
- Choose a positive integer $1 \leq k \leq n$.
- Swap the prefix of the string $s_1$ and the suffix of the string $s_2$ of length $k$.
Is it possible to make these two strings equal by doing described operations?
|
If you reflect the second string and see what happens, it is easy to see that the elements at the same positions in both strings after any action remain at the same positions relative to each other. Let's combine them into unsorted pairs and treat these pairs as single objects. Now we need to compose a palindrome from these objects. This is always possible with the help of these actions, if there is a palindrome consisting of these objects (pay attention to odd palindromes, there must be a pair of the form (a, a) in the center). Proof of possibility: Let's make an array of pairs, in one action we expand some prefix of this array and the elements in the pairs of this prefix are swapped. Let's prove that we can change the order of the pairs in the array as we like. We will build from the end. Let all the pairs after position $i$ already stand as we want, and now the pair that we want to place in position $i$ at position $j \leq i$. Let's do the following: $1.$ $k = j$ - will move the pair from position $j$ to the beginning. $2*.$ $k = 1$ - swap elements within a pair if needed (so pairs are considered unsorted). $3.$ $k = i$ - move the pair from the beginning to position $i$. (* the $2$ action is optional if you don't want to change the order of the elements in the pair) With this construction, we can get any permutation of these pairs and a palindrome, if it is possible. If you divide the final palindrome into two strings and expand the second one back, you get the first string. Example: From the test suite from the condition: $s_1 = \mathtt{bbcaa}$, $s_2 = \mathtt{cbaab}$, expanded $s_2 = \mathtt{baabc}$. Couples: $\mathtt{(b, b)}$, $\mathtt{(b, a)}$, $\mathtt{(c, a)}$, $\mathtt{(a, b)}$, $\ mathtt{(a, c)}$. Pairs unordered: $\mathtt{(b, b)}$, $\mathtt{(a, b)} \cdot 2$, $\mathtt{(a, c)} \cdot 2$. Pairs in a palindrome: $\mathtt{(a, b)}$, $\mathtt{(a, c)}$, $\mathtt{(b, b)}$, $\mathtt{(a, c)}$, $\mathtt{(a, b)}$. Real couples: $\mathtt{(a, b)}$, $\mathtt{(a, c)}$, $\mathtt{(b, b)}$, $\mathtt{(c, a)}$, $\mathtt{(b, a)}$. Strings: $s_1 = \mathtt{aabcb}$ expanded $s_2 = \mathtt{bcbaa}$, $s_2 = \mathtt{aabcb}$. !!! The pair $\mathtt{(b, b)}$ !!!
|
[
"constructive algorithms",
"strings",
"two pointers"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
string s1, s2;
cin >> s1 >> s2;
map<pair<int, int>, int> mp;
set<pair<int, int>> st;
int cnt_odd_simmetric = 0;
int cnt_odd = 0;
for(int i = 0; i < n; i++){
pair<int, int> p = {s1[i], s2[n - i - 1]};
if(p.first > p.second){
p = {p.second, p.first};
}
if(st.count(p) != 0){
mp[p]++;
if(mp[p] % 2 == 1){
cnt_odd++;
if(p.first == p.second){
cnt_odd_simmetric++;
}
}
else{
cnt_odd--;
if(p.first == p.second){
cnt_odd_simmetric--;
}
}
}
else{
st.insert(p);
mp[p] = 1;
cnt_odd++;
if(p.first == p.second){
cnt_odd_simmetric++;
}
}
}
if(n % 2 == cnt_odd_simmetric && cnt_odd == cnt_odd_simmetric){
cout << "YES\n";
}
else{
cout << "NO\n";
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--){
solve();
}
}
|
1730
|
E
|
Maximums and Minimums
|
You are given an array $a_1, a_2, \ldots, a_n$ of positive integers.
Find the number of pairs of indices $(l, r)$, where $1 \le l \le r \le n$, that pass the check. The check is performed in the following manner:
- The minimum and maximum numbers are found among $a_l, a_{l+1}, \ldots, a_r$.
- The check is passed if the maximum number is divisible by the minimum number.
|
Let's introduce some new variables: $lge_i$ - the position of the nearest left greater or equal than $a_i$($-1$ if there is none). $rg_i$ - position of the nearest right greater than $a_i$($n$ if there is none). $ll_i$ - position of the nearest left lower than $a_i$($-1$ if there is none). $rl_i$ - position of the nearest right lower than $a_i$($n$ if there is none). All this can be calculated, for example, using a stack in $O(n)$ or using binary search and sparse table in $O(n\log n)$ Let's iterate over the position $i$ of the leftmost maximum of the good segment. Then the $i$-th element will be the maximum on the segment [l, r] if $lge_i < l \le i$ and $i \le r < rg_i$ $(1)$. For the segment to pass the test, the minimum must be a divisor of the maximum. Let's iterate over this divisor $d$ and find the number of segments where the maximum is $a_i$ and the minimum is $d$. Consider positions of occurrence of $d$ $j_1$ and $j_2$ - the nearest left and right to $i$(they can be found using two pointers). Let's find the number of segments satisfying the condition $(1)$, in which the element $j_1$ is a minimum. To do this, similar conditions must be added to $(1)$: $ll_i < l \le j_1$ and $j_1 \le r < rg_i$. Intersecting these conditions, we obtain independent segments of admissible values of the left and right boundaries of the desired segment. Multiplying their lengths, we get the number of required segments. Similarly, the number of segments satisfying $(1)$, in which $j_2$ is the minimum, is found, but in order not to count 2 times one segment, one more condition must be added: $j_1 < l$. The sum of these quantities over all $i$ and divisors of $a_i$ will give the answer to the problem. To enumerate divisors, it is better to precompute the divisors of all numbers in $O(A\log A)$, where $A$ is the constraint on $a_i$. So the whole solution runs in $O(A\log A + nD)$, where $D$ is the maximum number of divisors.
|
[
"combinatorics",
"data structures",
"divide and conquer",
"number theory"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 13;
const int A = 1e6 + 13;
vector<int> divs[A];
int a[N];
int gr_lf[N], gr_rg[N];
int less_lf[N], less_rg[N];
vector<int> pos[A];
int ind[A];
void solve() {
int n;
cin >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
pos[a[i]].push_back(i);
}
{
stack<int> st;
for(int i = 0; i < n; i++) {
while(!st.empty() && a[st.top()] < a[i])
st.pop();
gr_lf[i] = (st.empty() ? -1 : st.top());
st.push(i);
}
}
{
stack<int> st;
for(int i = n - 1; i >= 0; i--) {
while(!st.empty() && a[st.top()] <= a[i])
st.pop();
gr_rg[i] = (st.empty() ? n : st.top());
st.push(i);
}
}
{
stack<int> st;
for(int i = 0; i < n; i++) {
while(!st.empty() && a[st.top()] >= a[i])
st.pop();
less_lf[i] = (st.empty() ? -1 : st.top());
st.push(i);
}
}
{
stack<int> st;
for(int i = n - 1; i >= 0; i--) {
while(!st.empty() && a[st.top()] >= a[i])
st.pop();
less_rg[i] = (st.empty() ? n : st.top());
st.push(i);
}
}
long long ans = 0;
for(int i = 0; i < n; i++) {
for(int x : divs[a[i]]) {
if(ind[x] >= 1) {
int j = pos[x][ind[x] - 1];
if(j > gr_lf[i] && less_rg[j] > i) {
ans += (j - max(gr_lf[i], less_lf[j])) * 1ll * (min(gr_rg[i], less_rg[j]) - i);
}
}
if(ind[x] < pos[x].size()) {
int j = pos[x][ind[x]];
if(j < gr_rg[i] && less_lf[j] < i) {
ans += (i - max({gr_lf[i], less_lf[j], ind[x] >= 1 ? pos[x][ind[x] - 1] : -1})) * 1ll * (min(gr_rg[i], less_rg[j]) - j);
}
}
}
ind[a[i]]++;
}
cout << ans << endl;
for(int i = 0; i < n; i++) {
pos[a[i]].erase(pos[a[i]].begin(), pos[a[i]].end());
gr_lf[i] = gr_rg[i] = less_lf[i] = less_rg[i] = 0;
ind[a[i]] = 0;
}
}
int main() {
for(int i = 1; i < A; i++) {
for(int j = i; j < A; j += i)
divs[j].push_back(i);
}
int t;
cin >> t;
while(t--)
solve();
}
|
1730
|
F
|
Almost Sorted
|
You are given a permutation $p$ of length $n$ and a positive integer $k$. Consider a permutation $q$ of length $n$ such that for any integers $i$ and $j$, where $1 \le i < j \le n$, we have $$p_{q_i} \le p_{q_j} + k.$$
Find the minimum possible number of inversions in a permutation $q$.
A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
An inversion in a permutation $a$ is a pair of indices $i$ and $j$ ($1 \le i, j \le n$) such that $i < j$, but $a_i > a_j$.
|
Let's build a permutation $q$ from left to right. If the current prefix contains the number $i$, let's call the element $p_i$ used, otherwise - unused. Consider the smallest unused element $mn = p_j$. All elements greater than $mn + k$ must also be unused, and all elements less than $mn$ must be used. Then the current state can be described by the number $mn$ and the mask, $i$-th bit of which indicates whether the element with the value $mn + i$ is used. Let's solve the problem by dynamic programming: $dp[mn][mask]$ is the minimum number of inversions. We can continue building a permutation by adding the number $i$ such that $mn \le p_i \le mn + k$ and $p_i$ hasn't been used yet. New inversions can be divided into two types: those formed with indices of elements less than $mn$ (they can be counted using Fenwick tree) and those formed with indices of elements not less than $mn$ (but their number is not more than $k$). The time complexity is $O(n \cdot 2^k \cdot k \cdot (k + \log n))$.
|
[
"bitmasks",
"data structures",
"dp"
] | 2,700
|
#include <bits/stdc++.h>
//#define int long long
#define ld long double
#define x first
#define y second
#define pb push_back
using namespace std;
const int N = 5005;
const int K = 8;
int n, k, p[N], pos[N], dp[N][1 << K], t[N];
int sum(int r)
{
int ans = 0;
for(; r >= 0; r = (r & r + 1) - 1)
ans += t[r];
return ans;
}
void inc(int i, int d)
{
for(; i < N; i |= i + 1)
t[i] += d;
}
int inv(int mn, int mask, int x)
{
int ans = 0;
for(int i = 0; i < k; i++)
if((mask & (1 << i)) && pos[x] < pos[mn + 1 + i])
ans++;
// for(int i = 0; i < mn; i++)
// if(pos[x] < pos[i])
// ans++;
ans += sum(N - 1) - sum(pos[x]);
return ans;
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for(int i = 0; i < n; i++)
{
cin >> p[i];
p[i]--;
pos[p[i]] = i;
}
for(int mn = 0; mn <= n; mn++)
for(int mask = 0; mask < (1 << k); mask++)
dp[mn][mask] = 1e9;
dp[0][0] = 0;
for(int mn = 0; mn < n; mn++)
{
for(int mask = 0; mask < (1 << min(k, n - mn - 1)); mask++)
{
for(int i = 0; i < min(k, n - mn - 1); i++)
if((mask & (1 << i)) == 0)
dp[mn][mask + (1 << i)] = min(dp[mn][mask + (1 << i)], dp[mn][mask] + inv(mn, mask, mn + 1 + i));
int mn2 = mn, mask2 = mask;
mn2++;
while(mask2 % 2)
{
mn2++;
mask2 /= 2;
}
mask2 /= 2;
dp[mn2][mask2] = min(dp[mn2][mask2], dp[mn][mask] + inv(mn, mask, mn));
}
inc(pos[mn], 1);
}
cout << dp[n][0];
}
|
1731
|
A
|
Joey Takes Money
|
Joey is low on money. His friend Chandler wants to lend Joey some money, but can't give him directly, as Joey is too proud of himself to accept it. So, in order to trick him, Chandler asks Joey to play a game.
In this game, Chandler gives Joey an array $a_1, a_2, \dots, a_n$ ($n \geq 2$) of positive integers ($a_i \ge 1$).
Joey can perform the following operation on the array any number of times:
- Take two indices $i$ and $j$ ($1 \le i < j \le n)$.
- Choose two integers $x$ and $y$ ($x, y \ge 1$) such that $x \cdot y = a_i \cdot a_j$.
- Replace $a_i$ by $x$ and $a_j$ by $y$.
In the end, Joey will get the money equal to \textbf{the sum} of elements of the final array.
Find the maximum amount of money $\mathrm{ans}$ Joey can get \textbf{but print} $2022 \cdot \mathrm{ans}$. Why multiplied by $2022$? Because we are never gonna see it again!
It is guaranteed that the product of all the elements of the array $a$ doesn't exceed $10^{12}$.
|
If we take two elements $a_1$ and $a_2$ and do the operation on it as $a_1 \cdot a_2 = x \cdot y$, then it is easy to observe that $x + y$ will attain its maximum value when one of them is equal to $1$. So, the solution for this is $x = 1$ and $y = a_1 \cdot a_2$. Let $n$ be the total number of elements and $P$ ($P = a_1 \cdot a_2 \cdot \ldots \cdot a_n$) be the product of all elements. Now if we do the above step for every pair of elements, then the maximum value of the sum is achieved when $a_1 = 1$, $a_2 = 1$, $\dots$, $a_{n-1} = 1$ and $a_n = P$. In the final array, assign $P$ to $a_1$ and assign $1$ to all the remaining elements $a_2, a_3, \dots a_n$. So, our answer is simply $P + n - 1$ multiplied by $2022$, of course. Time complexity: $O(n)$.
|
[
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
#define endl '\n'
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t=1;
cin>>t;
while(t--){
int n;
cin>>n;
int a[n];
ll k=1;
for(int i=0;i<n;i++){
cin>>a[i];
k*=a[i];
}
k+=n-1;
k*=2022;
cout<<k<<endl;
}
}
|
1731
|
B
|
Kill Demodogs
|
Demodogs from the Upside-down have attacked Hawkins again. El wants to reach Mike and also kill as many Demodogs in the way as possible.
Hawkins can be represented as an $n \times n$ grid. The number of Demodogs in a cell at the $i$-th row and the $j$-th column is $i \cdot j$. El is at position $(1, 1)$ of the grid, and she has to reach $(n, n)$ where she can find Mike.
The only directions she can move are the right (from $(i, j)$ to $(i, j + 1)$) and the down (from $(i, j)$ to $(i + 1, j)$). She can't go out of the grid, as there are doors to the Upside-down at the boundaries.
Calculate the maximum possible number of Demodogs $\mathrm{ans}$ she can kill on the way, considering that she kills all Demodogs in cells she visits (including starting and finishing cells).
Print $2022 \cdot \mathrm{ans}$ modulo $10^9 + 7$. Modulo $10^9 + 7$ because the result can be too large and multiplied by $2022$ because we are never gonna see it again!
(Note, you firstly multiply by $2022$ and \textbf{only after} that take the remainder.)
|
To kill the maximum number of demodogs, El can travel in zigzag fashion, i.e. from $(1,1)$ to $(1,2)$ to $(2,2)$ and so on. Thus the answer would be the sum of elements at $(1,1)$, $(1,2)$, $(2,2)$ $\dots$ $(n,n)$. i.e. the answer is $$\sum_{i = 1}^n{i \cdot i} + \sum_{i = 1}^{n-1}{i (i + 1)} = \frac{n(n + 1)(4n - 1)}{6}$$. And the answer you need to print is $$2022 \frac{n(n + 1)(4n - 1)}{6} = 337 \cdot n(n + 1)(4n - 1) \pmod{10^9 + 7}$$ Proof: Let $kills_{i,j}$ be the maximum number of kills of all possible paths from $(1,1)$ to $(i,j)$. $kills_{n-1,n-1} \geq kills_{i,n - 1}$ + number of demodogs from $(i + 1,n - 1)$ to $(n - 1,n - 1)$ $( \forall i \hspace{1.5mm} \in \hspace{1.5mm} [1, n - 2])$. $$kills_{n-1,n-1} \geq kills_{i,n - 1} + \sum_{j = i + 1}^{n - 1}{j \cdot (n - 1)}$$ $$kills_{n-1,n-1} \geq kills_{i,n - 1} + \frac{(n - 1 - i)((i + 1)(n - 1) + (n - 2 - i)(n - 1))}{2} \text{ (sum of A.P.)}$$ $$kills_{n-1,n-1} \geq kills_{i,n - 1} + \frac{(n - 1 - i)(n - 1)^2}{2} \text{ (1)}$$ Let $killsZ$ be the number of kills if El travels in zigzag fashion, i.e. she goes to $(n,n)$ after passing through $(n - 1,n - 1)$: $$killsZ_{n,n} = kills_{n - 1,n - 1} + n(n - 1) + n \cdot n$$ Let $killsNZ$ be the maximum number of kills If El goes to $(n,n)$ after passing through $(i,n)$ for some $i$ in range of $[1 \dots n - 1]$, i.e. El goes from $(1,1)$ to $(i,n - 1)$ to $(i,n)$ to $(n,n)$: $$killsNZ_{n,n} = kills_{i,n - 1} + \text{no of demigods from } (i,n)\text{ to }(n,n)$$ $$killsNZ_{n,n} = kills_{i,n - 1} + \sum_{j = i}^{n}{j \cdot n}$$ $$killsNZ_{n,n} = kills_{i,n - 1} + \frac{(n + 1 - i)(n + i)n}{2}$$ $$killsZ_{n,n} - killsNZ_{n,n} = kills_{n - 1,n - 1} + n(n - 1) + n \cdot n - kills_{i,n - 1} - \frac{(n + 1 - i)(n + i)n}{2} \text{ from $(1)$}$$ $$killsZ_{n,n} - killsNZ_{n,n} \geq kills_{i,n - 1} + \frac{(n - 1 - i)(n - 1)^2}{2} + n(n - 1) + n \cdot n - kills_{i,n - 1} - \frac{(n + 1 - i)(n + i)n}{2}$$ $$killsZ_{n,n} - killsNZ_{n,n} \geq \frac{2 n^2 - 3 n - n \cdot i - i - 1}{2}$$ $$killsZ_{n,n} - killsNZ_{n,n} \geq 0$$ since $2n^2 - 3 n - n \cdot i - i - 1 \geq 0$ for all $i \in \hspace{1.5mm} [1, n - 2]$. In other words, $killsZ_{n,n} \geq killsNZ_{n,n}$ Therefore zigzag path guarantees maximum number of demodog kills. Now, the last thing was taking the modulus. Modulus should always be taken after every multiply operation to avoid the overflow. You can refer to modular arithmetic for more details. And the main reason we told you to multiply the answer by $2022$ is that we needed to divide it by $6$. For division, we have to take inverse modulo in modular arithmetic. So, in order to avoid that, we gave you a multiple of $6$, which is $2022$.
|
[
"greedy",
"math"
] | 1,100
|
#include<bits/stdc++.h>
#define ll long long
const int n1=1e9+7;
using namespace std;
int solve()
{
ll n;
cin>>n;
ll ans=((((n*(n+1))%n1)*(4*n-1))%n1*337)%n1;
cout<<ans<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
solve();
}
}
|
1731
|
C
|
Even Subarrays
|
You are given an integer array $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$).
Find the number of subarrays of $a$ whose $\operatorname{XOR}$ has an even number of divisors. In other words, find all pairs of indices $(i, j)$ ($i \le j$) such that $a_i \oplus a_{i + 1} \oplus \dots \oplus a_j$ has an even number of divisors.
For example, numbers $2$, $3$, $5$ or $6$ have an even number of divisors, while $1$ and $4$ — odd. Consider that $0$ has an odd number of divisors in this task.
Here $\operatorname{XOR}$ (or $\oplus$) denotes the bitwise XOR operation.
\sout{Print the number of subarrays but multiplied by 2022...} Okay, let's stop. Just print the actual answer.
|
Let's calculate the number of subarrays whose $\operatorname{XOR}$ sum has an odd number of divisors and subtract them from total no of subarrays. Note: A number has an odd number of divisors only if it is a perfect square. So we have to calculate number of subarray having $\operatorname{XOR}$ sum a perfect square. For the given constraints for elements in the array, the maximum possible $\operatorname{XOR}$ sum of any subarray will be less than $2n$, so the number of possible elements with odd divisors $\leq \sqrt{2n}$. Number of subarrays with a given $\operatorname{XOR}$ sum can be calculated in $O(n)$. Therefore, calculate the same for each perfect square less than $2n$ and add all these to get the number of subarrays whose $\operatorname{XOR}$ sum has an odd number of divisors. Subtract from total number of subarrays to get the required answer. Time complexity : $O(n \cdot \sqrt{n})$.
|
[
"bitmasks",
"brute force",
"hashing",
"math",
"number theory"
] | 1,700
|
sq_list=[]
p=int(0)
while p*p<=400000:
sq_list.append(p*p)
p+=1
for t in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
val=int(2*n)
z=int(0)
m=[z]*val
cnt=int(0)
curr=int(0)
m[curr]+=1
j=0
while j<n:
curr^=a[j]
for i in sq_list:
if i>=val:
break
if curr^i<val:
cnt+=m[curr^i]
m[curr]+=1
j+=1
ans=((n*(n+1))//2)
ans=ans-cnt
print(ans)
|
1731
|
D
|
Valiant's New Map
|
Game studio "DbZ Games" wants to introduce another map in their popular game "Valiant". This time, the map named "Panvel" will be based on the city of Mumbai.
Mumbai can be represented as $n \times m$ cellular grid. Each cell $(i, j)$ ($1 \le i \le n$; $1 \le j \le m$) of the grid is occupied by a cuboid building of height $a_{i,j}$.
This time, DbZ Games want to make a map that has perfect vertical gameplay. That's why they want to choose an $l \times l$ square inside Mumbai, such that each building inside the square has a height of at least $l$.
Can you help DbZ Games find such a square of the maximum possible size $l$?
|
The basic brute force solution for this problem was to just iterate through all the values of sides possible. Note that the value of sides can range only from $1$ to $1000$ as product of $n \cdot m$ can't exceed $10^6$, so there can't be a cube having all sides greater than $1000$. After setting side length (let's say $s$) we look into all possible submatrices of dimensions $s \times s$ and see if we can form a cube from any one of those. This could only be possible if there exists a submatrix with its minimum $\ge s$. Now, we need to do all these operations efficiently, looking at the constraints. The main thing that we need to do is Binary search on the answer. As obviously, it is possible to make a cube with a smaller side if it is possible to make the one with the current side length. Now from here, we have two different approaches - Sparse Table - For a particular side $s$, check for all submatrices of size $s \times s$, if their minimum is greater than equal to $s$. If you find any such submatrix, then this value of side is possible. A minimum can be calculated in $O(1)$ using sparse tree. You might have tried using segment tree, which takes $\log m \cdot \log n$ time per query. But it may not to pass with these constraints. So, the time complexity to solve this problem is $O(n \cdot m \cdot \log{(\min{(n, m)})}$). It would pass these constraints. Another $O(n \cdot m \cdot \min{(n, m)}$) solution where you don't use binary search is also there but would fail with these constraints. The segment tree solution takes $O(n \cdot m \cdot \log{n} \cdot \log{m} \cdot \log{(\min{(n, m)})}$) . So, only sparse tree can be used. Prefix Sum - This is a much simpler solution. First, we create another $n\times m$ matrix, let's say $B$. Now, for a particular side length $s$, we take all the indices where the building heights are greater than equal to $s$ and set the elements of $B$ at those indices to $1$. Other elements are set to $0$. Now we precalculate the prefix sum for this matrix. Then for each index $(i, j)$ of the matrix $B$, we check if the square starting from that index has a prefix sum equal to $s^2$. If anyone of it does, then this side length for the cube is possible. Time Complexity is again $O(n \cdot m \cdot \log{(\min{(n, m)})})$.
|
[
"binary search",
"brute force",
"data structures",
"dp",
"two pointers"
] | 1,700
|
#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,
tree_order_statistics_node_update> indexed_set;
#define endl '\n'
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
int st[n][m][10];
int a[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
st[i][j][0]=a[i][j];
}
}
for(int k=1;k<=log2(min(n,m));k++){
for(int i=0;i+(1<<k)<=n;i++){
for(int j=0;j+(1<<k)<=m;j++){
st[i][j][k]=min(min(st[i][j][k-1],st[i+(1<<(k-1))][j][k-1]),min(st[i][j+(1<<(k-1))][k-1],st[i+(1<<(k-1))][j+(1<<(k-1))][k-1]));
}
}
}
int l=1;
int r=min(n,m);
while(l<r){
int x=(l+r+1)/2;
int z=0;
int p=log2(x);
for(int i=0;i+x<=n;i++){
for(int j=0;j+x<=m;j++){
if(min(min(st[i][j][p],st[i+x-(1<<p)][j+x-(1<<p)][p]),min(st[i][j+x-(1<<p)][p],st[i+x-(1<<p)][j][p]))>=x){
z=1;
}
}
}
if(z){
l=x;
}
else{
r=x-1;
}
}
cout<<l<<endl;
}
}
|
1731
|
E
|
Graph Cost
|
You are given an initially empty undirected graph with $n$ nodes, numbered from $1$ to $n$ (i. e. $n$ nodes and $0$ edges). You want to add $m$ edges to the graph, so the graph won't contain any self-loop or multiple edges.
If an edge connecting two nodes $u$ and $v$ is added, its weight must be equal to the greatest common divisor of $u$ and $v$, i. e. $\gcd(u, v)$.
In order to add edges to the graph, you can repeat the following process any number of times (possibly zero):
- choose an integer $k \ge 1$;
- add exactly $k$ edges to the graph, each having a weight equal to $k + 1$. Adding these $k$ edges costs $k + 1$ in total.
Note that you can't create self-loops or multiple edges. Also, if you can't add $k$ edges of weight $k + 1$, you can't choose such $k$.For example, if you can add $5$ more edges to the graph of weight $6$, you may add them, and it will cost $6$ for the whole pack of $5$ edges. But if you can only add $4$ edges of weight $6$ to the graph, you can't perform this operation for $k = 5$.
Given two integers $n$ and $m$, find the minimum total cost to form a graph of $n$ vertices and exactly $m$ edges using the operation above. If such a graph can't be constructed, output $-1$.
Note that the final graph may consist of several connected components.
|
In each step, adding $e$ edges to the graph with weights $e + 1$ costs one more than the number of edges added. So, the total cost of adding $m$ edges in $s$ steps will be $m + s$. Since the number of edges is given, i. e. fixed, to find the minimum cost, we need to minimize the number of steps. Firstly, let's calculate the number of pairs $(x, y)$ where $1 \le x < y \le n$ with $\gcd(x, y) = k$ for each $k \in [1..n]$ in $O(n \log n)$ time. It can be solved in a standard way using the Möbius function $\mu(x)$ or using Dynamic Programming, where $dp[k]$ is the required number that can be calculated as: $ dp[k] = \frac{1}{2} \left\lfloor \frac{n}{k} \right\rfloor ( \left\lfloor \frac{n}{k} \right\rfloor - 1) - dp[2k] - dp[3k] - \dots - dp[\left\lfloor \frac{n}{k} \right\rfloor k]$ Knowing all $dp[k]$ we can calculate the maximum number of steps $s[k]$ we can perform using edges of weight $k$. And $s[k] = \left\lfloor \frac{dp[k]}{k - 1} \right\rfloor$. Note that array $s[k]$ is non-increasing ($s[k] \ge s[k + 1]$) and if we have at least one pack of size $x$ then we have at least one pack of each size $y$ where $1 \le y < x$. So, our task is an "extension" of the task where you need to take a subset of $1, 2, \dots, n$ of minimum size with sum equal to $m$ and can be solved with the same greedy strategy. Let's just take packs greedily, starting from weight $n$ down to weight $2$. We'll take packs as many packs as possible. For a fixed weight $k$ we can calculate the maximum number of packs we can take as $\min(s[k], \frac{m'}{k - 1})$. If $m$ edges can't be constructed, then we return $-1$. Otherwise, we return $m + s$ where $s$ is the total number of packs. Time Complexity: $O(n \log n)$
|
[
"dp",
"greedy",
"math",
"number theory"
] | 2,000
|
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
#define endl '\n'
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
ll n,m;
cin>>n>>m;
vector<ll> dp(n+1);
for(ll i=n;i>=1;i--){
dp[i]=(n/i)*((n/i)-1)/2;
for(ll j=2*i;j<=n;j+=i){
dp[i]-=dp[j];
}
}
ll x=0;
for(ll i=n;i>=2;i--){
if(m<i-1){
continue;
}
ll k=m/(i-1);
ll l=dp[i]/(i-1);
m-=min(k,l)*(i-1);
x+=min(k,l)*i;
if(m==0){
break;
}
}
if(m){
cout<<-1<<endl;
}
else{
cout<<x<<endl;
}
}
}
|
1731
|
F
|
Function Sum
|
Suppose you have an integer array $a_1, a_2, \dots, a_n$.
Let $\operatorname{lsl}(i)$ be the number of indices $j$ ($1 \le j < i$) such that $a_j < a_i$.
Analogically, let $\operatorname{grr}(i)$ be the number of indices $j$ ($i < j \le n$) such that $a_j > a_i$.
Let's name position $i$ good in the array $a$ if $\operatorname{lsl}(i) < \operatorname{grr}(i)$.
Finally, let's define a function $f$ on array $a$ $f(a)$ as the \textbf{sum} of all $a_i$ such that $i$ is good in $a$.
Given two integers $n$ and $k$, find the sum of $f(a)$ over all arrays $a$ of size $n$ such that $1 \leq a_i \leq k$ for all $1 \leq i \leq n$ modulo $998\,244\,353$.
|
Let's try to write a brute force solution of this using combinatorics. Let's say that $a[i]=t$ now we will try to see that in how many permutations this is contributing towards the answer. Using combinatorics, it can be calculated as $$F(t) = t \cdot {\sum_{i=1}^n \sum_{x=0}^{i-1} \sum_{y = x+1}^{n-i} \left( \binom{i-1}{x} (t-1)^{x} (K+1-t)^{i-1-x} \cdot \binom{n-i}{y} (K-t)^{y} \cdot t^{n-i-y} \right)} $$. Here $x$ represents $\operatorname{lsl}(i)$ and y represents $\operatorname{grr}(i)$. Let $$P(u) = {\sum_{t=1}^u F(t)} $$ be a polynomial whose degree will be $\le n+2$. And now our answer will be $P(k)$. Now, we can evaluate this polynomial for smaller values (by brute force) and will use the technique of polynomial interpolation to find the answer.
|
[
"brute force",
"combinatorics",
"dp",
"fft",
"math"
] | 2,500
|
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pcc pair<char,char>
#define vi vector <int>
#define vl vector <ll>
using namespace std;
ll powmod(ll base,ll exponent,ll mod){
ll ans=1;
if(base<0) base+=mod;
while(exponent){
if(exponent&1)ans=(ans*base)%mod;
base=(base*base)%mod;
exponent/=2;
}
return ans;
}
const int N = 201;
const int mod = 998244353;
int fact[N];
int invfact[N];
int nCr(int n,int r){
int ans = fact[n];
ans = (1ll*ans*invfact[r])%mod;
ans = (1ll*ans*invfact[n-r])%mod;
return ans;
}
int interpolate(vi &y,int r,int n){
int ans=0,prod=1,temp;
for(int i = 1; i <= r; i++){
prod=(1ll*prod*(n-i))%mod;
}
for(int i = 0; i < r; i++){
temp=(1ll*prod*powmod(n-i-1,mod-2,mod))%mod;
temp=(1ll*temp*y[i])%mod;
temp=(1ll*temp*invfact[i])%mod;
temp=(1ll*temp*invfact[r-i-1])%mod;
if((r-i)%2==0) temp=mod-temp;
ans+=temp;ans%=mod;
}
return ans;
}
void brute_force(int n,int k){
vi values_of_polynomial(k);
for(int i = 1; i <= n; i++){
for(int x = 0; x < i; x++){
for(int y = x+1; y <= n-i; y++){
for(int val = 1; val <= k; val++){
ll calculation = (1ll * nCr(i-1,x) * powmod(val-1,x,mod))%mod;
calculation *= powmod(k+1-val,i-1-x,mod);
calculation %= mod;
calculation *= (1ll * nCr(n-i,y) * powmod(k-val,y,mod))%mod;
calculation %= mod;
calculation *= powmod(val,n-i-y,mod);
calculation %= mod;
calculation *= val;
calculation %= mod;
values_of_polynomial[val-1] += calculation;
values_of_polynomial[val-1] %= mod;
}
}
}
}
for(int i = 1; i < k; i++){
values_of_polynomial[i] += values_of_polynomial[i-1];
values_of_polynomial[i] %= mod;
}
cout << values_of_polynomial[k-1] << "\n";
}
int main(){
fact[0]=1;
invfact[0]=1;
for(int i = 1; i < N; i++){
fact[i] = (1ll*i*fact[i-1])%mod;
invfact[i] = powmod(fact[i],mod-2,mod);
}
int t,n,k;
t=1;
while(t--){
cin >> n >> k;
vi values_of_polynomial(n+3,0);
for(int i = 1; i <= n; i++){
for(int x = 0; x < i; x++){
for(int y = x+1; y <= n-i; y++){
for(int val = 1; val <= n+3; val++){
ll calculation = (1ll * nCr(i-1,x) * powmod(val-1,x,mod))%mod;
calculation *= powmod(k+1-val,i-1-x,mod);
calculation %= mod;
calculation *= (1ll * nCr(n-i,y) * powmod(k-val,y,mod))%mod;
calculation %= mod;
calculation *= powmod(val,n-i-y,mod);
calculation %= mod;
calculation *= val;
calculation %= mod;
values_of_polynomial[val-1] += calculation;
values_of_polynomial[val-1] %= mod;
}
}
}
}
for(int i = 1; i < n+3; i++){
values_of_polynomial[i] += values_of_polynomial[i-1];
values_of_polynomial[i] %= mod;
}
if(k <= n+3) cout << values_of_polynomial[k-1] << "\n";
else cout << interpolate(values_of_polynomial,n+3,k) << "\n";
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.