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
⌀ |
|---|---|---|---|---|---|---|---|
1338
|
D
|
Nested Rubber Bands
|
You have a tree of $n$ vertices. You are going to convert this tree into $n$ rubber bands on infinitely large plane. Conversion rule follows:
- For every pair of vertices $a$ and $b$, rubber bands $a$ and $b$ should intersect if and only if there is an edge exists between $a$ and $b$ in the tree.
- Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect.
Now let's define following things:
- Rubber band $a$ \textbf{includes} rubber band $b$, if and only if rubber band $b$ is in rubber band $a$'s area, and they don't intersect each other.
- Sequence of rubber bands $a_{1}, a_{2}, \ldots, a_{k}$ ($k \ge 2$) are \textbf{nested}, if and only if for all $i$ ($2 \le i \le k$), $a_{i-1}$ includes $a_{i}$.
\begin{center}
This is an example of conversion. Note that rubber bands $5$ and $6$ are nested.
\end{center}
It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.
What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it.
|
Observation 1. You have to generate optimal sequence which is subsequence of path between some two vertices. Neighbors of vertices in optimal sequence will be used as nested rubber bands. This is an example of conversion. Red vertices are picked sequence, and blue vertices are neighbor of red vertices which are used as nested rubber bands. The reason why black vertices can't be used as nested rubber bands is, basically you have to make a tunnel between any two blue lines, but it's impossible, because in each tunnel there is at least one red vertex which blocks complete connection on tunnel. Also, this can be described as finding maximum independent set on subtree, which consists of vertices which has at most $1$ distance from the optimal path connection of red vertices. Now your goal is to maximize number of blue vertices. Observation 2. The distances between two adjacent red vertices are at most $2$. Adjacent in this sentence means adjacent elements in generated optimal sequence. Because if there is some unused It is always optimal to take more red vertices than abandoning black vertices. Note that if there are two black vertices between two red vertices, then we cannot use both of them as blue vertices. From those two observations, construct tree DP and run for it. Time complexity is $O(n)$.
|
[
"constructive algorithms",
"dfs and similar",
"dp",
"math",
"trees"
] | 2,700
| null |
1338
|
E
|
JYPnation
|
Due to the success of TWICE, JYP Entertainment has earned countless money and emerged as the biggest entertainment firm by market capitalization. Therefore, the boss, JYP, has decided to create a new nation and has appointed you to provide a design diagram.
The new nation consists of $n$ cities and some roads between them. JYP has given some restrictions:
- To guarantee efficiency while avoiding chaos, \textbf{for any $2$ different cities $A$ and $B$, there is exactly one road between them, and it is one-directional. There are no roads connecting a city to itself}.
- The logo of rivaling companies should not appear in the plan, that is, \textbf{there does not exist} $4$ \textbf{distinct cities} $A$,$B$,$C$,$D$ \textbf{, such that the following configuration occurs.}
JYP has given criteria for your diagram. For two cities $A$,$B$, let $dis(A,B)$ be the smallest number of roads you have to go through to get from $A$ to $B$. If it is not possible to walk from $A$ to $B$, $dis(A,B) = 614n$. Then, the efficiency value is defined to be the sum of $dis(A,B)$ for all ordered pairs of distinct cities $(A,B)$.
\textbf{Note that $dis(A,B)$ doesn't have to be equal to $dis(B,A)$}.
You have drawn a design diagram that satisfies JYP's restrictions. Find the sum of $dis(A,B)$ over all ordered pairs of cities $(A,B)$ with $A\neq B$.
\textbf{Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.}
|
The solution contains several tricky observations, but its not hard to prove each of them seperately, so I will mention only the key points of the solution and proof. Firstly, we should repeatedly remove points that have no in-degree. We can calculate their contribution easily. For a node $x$, define $in(x)$ to be the set of nodes $u$ that $u \rightarrow x$ exists. Lemma 1: $in(x) \cup {x}$ has no cycles for any node $x$. Let's pick $X$ to be the node with maximum in-degree. Let $P$ = $in(X) \cup {X}$, and let $Q$ = $Z \setminus P$, where $Z$ is the set of all vertices. Lemma 2: There exist nodes $U \in Q$,$V \in P$, such that $U \rightarrow V$ exists. Let $R$ = $in(V) \cap Q$, and let $S$ = $Q \setminus R$ Lemma 3: For all nodes $A \in S$,$B \in R$, $A \rightarrow B$ exists. Lemma 4: $S$ has no cycles, $R$ has no cycles. Lemma 5: $P$ has no cycles, $Q$ has no cycles. That means we have partitioned the graph into two sets of nodes, where each set is completely ordered. Lets label the nodes in $P$ by $P_i$ where $i$ is an integer from $1$ to $|P|$, such that for two nodes $P_i$ and $P_j$, $P_j \rightarrow P_i$ exists iff $j>i$. Label nodes in $Q$ by $Q_i$ in similar manner. Define $inP(x)$ to be the set of nodes $u \in P$ that $u \rightarrow x$ exists. Define $inQ(x)$ to be the set of nodes $u \in Q$ that $u \rightarrow x$ exists. Lemma 6a: If $|inQ(P_i)| = |inQ(P_j)|$ then $inQ(P_i) = inQ(P_j)$. Lemma 6b: If $|inP(Q_i)| = |inP(Q_j)|$ then $inP(Q_i) = inP(Q_j)$. Final observations: $dis(P_i,P_j)=1$ iff $i>j$ $dis(P_i,P_j)=2$ iff $i<j$ and $|inQ(P_i)| \neq |inQ(P_j)|$ $dis(P_i,P_j)=3$ iff $i<j$ and $|inQ(P_i)| = |inQ(P_j)|$ $dis(Q_i,Q_j)=1$ iff $i>j$ $dis(Q_i,Q_j)=2$ iff $i<j$ and $|inP(Q_i)| \neq |inP(Q_j)|$ $dis(Q_i,Q_j)=3$ iff $i<j$ and $|inP(Q_i)| = |inP(Q_j)|$ $dis(P_i,Q_j)+dis(Q_j,P_i)=3$ Finally, we can count the answer in $O(N^2)$ by the above observations.
|
[
"graphs"
] | 3,500
| null |
1339
|
A
|
Filling Diamonds
|
You have integer $n$. Calculate how many ways are there to fully cover belt-like area of $4n-2$ triangles with diamond shapes.
Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.
$2$ coverings are different if some $2$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.
Please look at pictures below for better understanding.
\begin{center}
On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill.These are the figures of the area you want to fill for $n = 1, 2, 3, 4$.
\end{center}
You have to answer $t$ independent test cases.
|
The key observation of this problem is, wherever you put vertical diamond at some point, all other places are uniquely placed by horizontal diamonds like picture below. There are $n$ places you can put vertical diamond, so answer is $n$ for each test case.
|
[
"brute force",
"dp",
"implementation",
"math"
] | 900
| null |
1339
|
B
|
Sorted Adjacent Differences
|
You have array of $n$ numbers $a_{1}, a_{2}, \ldots, a_{n}$.
Rearrange these numbers to satisfy $|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$, where $|x|$ denotes absolute value of $x$. It's always possible to find such rearrangement.
Note that all numbers in $a$ are not necessarily different. In other words, some numbers of $a$ may be same.
You have to answer independent $t$ test cases.
|
Sort the list, and make an oscillation centered on middle element like picture below. In this way, you will always achieve to make $|a_{i} - a_{i+1}| \le |a_{i+1} - a_{i+2}|$ for all $i$. Time complexity is $O(n \log n)$.
|
[
"constructive algorithms",
"sortings"
] | 1,200
| null |
1340
|
A
|
Nastya and Strange Generator
|
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something.
Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.
When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $n$ steps. At the $i$-th step, a place is chosen for the number $i$ $(1 \leq i \leq n)$. The position for the number $i$ is defined as follows:
- For all $j$ from $1$ to $n$, we calculate $r_j$ — the minimum index such that $j \leq r_j \leq n$, and the position $r_j$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $r_j$ is not defined.
- For all $t$ from $1$ to $n$, we calculate $count_t$ — the number of positions $1 \leq j \leq n$ such that $r_j$ is defined and $r_j = t$.
- Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $count$ array is maximum.
- The generator selects one of these positions for the number $i$. The generator can choose \textbf{any} position.
Let's have a look at the operation of the algorithm in the following example:
Let $n = 5$ and the algorithm has already arranged the numbers $1, 2, 3$ in the permutation. Consider how the generator will choose a position for the number $4$:
- The values of $r$ will be $r = [3, 3, 3, 4, \times]$, where $\times$ means an indefinite value.
- Then the $count$ values will be $count = [0, 0, 3, 1, 0]$.
- There are only two unoccupied positions in the permutation: $3$ and $4$. The value in the $count$ array for position $3$ is $3$, for position $4$ it is $1$.
- The maximum value is reached only for position $3$, so the algorithm will uniquely select this position for number $4$.
Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $p_1, p_2, \ldots, p_n$ and decided to find out if it could be obtained as a result of the generator.
Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.
|
Consider the initial moment of time. Note that the array is $r = [1, 2, \ldots, n]$, $count = [1, 1, \ldots, 1]$. So the generator will choose a random position from the entire array - let it be the position $i_1$. In the next step, $r = [1, 2, \ldots i_1 + 1, i_1 + 1, i + 2, \ldots, n]$, $count = [1, 1, \ldots, 0, 2, 1, \ldots, 1]$. That is, now there is only one maximum and it is reached at the position $i_1 + 1$. Thus, we will fill in the entire suffix starting at position $i_1$: $a = [\times, \ldots, \times, 1, \ldots, i_1]$. After this, this procedure will be repeated for some $i_2$ ($1 \leq i_2 < i_1$) and the array will become $a = [\times, \ldots, \times, i_1 + 1, \ldots, i_1 + i_2, 1, \ldots, i_1]$ . That is, we need to check that the array consists of several ascending sequences.
|
[
"brute force",
"data structures",
"greedy",
"implementation"
] | 1,500
|
#include<bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> p(n);
for (int& i : p)
cin >> i;
vector<int> pos(n);
for (int i = 0; i < n; ++i)
pos[--p[i]] = i;
vector<bool> was(n);
for (int i = 0; i < n; ++i) {
if (was[i])
continue;
int me = pos[i];
while (me < n) {
was[me] = 1;
if (me + 1 == n) break;
if (was[me + 1]) break;
if (p[me + 1] == p[me] + 1) {
++me;
continue;
}
cout << "No\n";
return;
}
}
cout << "Yes\n";
}
int main() {
int q;
cin >> q;
while (q--)
solve();
}
|
1340
|
B
|
Nastya and Scoreboard
|
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer.
The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $7$ segments, which can be turned on or off to display different numbers. The picture shows how all $10$ decimal digits are displayed:
After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke \textbf{exactly} $k$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $k$ sticks (which are off now)?
It is \textbf{allowed} that the number includes leading zeros.
|
Let $dp[i][j] = true$, if at the suffix $i \ldots n$ you can turn on exactly $j$ sticks and get the correct sequence of digits and $false$ otherwise. It is easy to recalculate this dynamics: we will make transitions to all possible digits (the mask at position $i$ should be a submask of the digit). Asymptotic calculate of the dynamics $O(10nd)$. Now let's go in order from $1$ to $n$ and will try to eagerly set the maximum possible figure using our dynamics. It is easy to understand that in this way we get the maximum possible number of $n$ digits.
|
[
"bitmasks",
"dp",
"graphs",
"greedy"
] | 1,700
|
/**
* author: tourist
* created: 23.04.2020 17:45:43
**/
#include <bits/stdc++.h>
using namespace std;
vector<string> digits = {"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<string> s(n);
vector<vector<int>> dist(n, vector<int>(10));
for (int i = 0; i < n; i++) {
cin >> s[i];
for (int d = 0; d < 10; d++) {
for (int j = 0; j < 7; j++) {
char x = s[i][j];
char y = digits[d][j];
if (x == '1' && y == '0') {
dist[i][d] = -1;
break;
}
if (x == '0' && y == '1') {
++dist[i][d];
}
}
}
}
vector<vector<int>> dp(n + 1, vector<int>(k + 1));
dp[n][0] = 1;
for (int i = n; i > 0; i--) {
for (int j = 0; j <= k; j++) {
if (dp[i][j]) {
for (int d = 0; d < 10; d++) {
if (dist[i - 1][d] != -1 && j + dist[i - 1][d] <= k) {
dp[i - 1][j + dist[i - 1][d]] = 1;
}
}
}
}
}
if (dp[0][k] == 0) {
cout << -1 << '\n';
return 0;
}
for (int i = 0; i < n; i++) {
int now = -1;
for (int d = 9; d >= 0; d--) {
if (dist[i][d] != -1 && k >= dist[i][d] && dp[i + 1][k - dist[i][d]]) {
now = d;
k -= dist[i][d];
break;
}
}
assert(now != -1);
cout << now;
}
cout << '\n';
return 0;
}
|
1340
|
C
|
Nastya and Unexpected Guest
|
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.
Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $g$ seconds green, and then $r$ seconds red, then again $g$ seconds green and so on.
Formally, the road can be represented as a segment $[0, n]$. Initially, Denis is at point $0$. His task is to get to point $n$ in the shortest possible time.
He knows many different integers $d_1, d_2, \ldots, d_m$, where $0 \leq d_i \leq n$ — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.
Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:
- He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $\pm 1$ in $1$ second. While doing so, he must always stay inside the segment $[0, n]$.
- He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $+1$ and he walked on a safety island, then he can change his position by $\pm 1$. Otherwise, he can change his position only by $+1$. Similarly, if in the previous second he changed his position by $-1$, on a safety island he can change position by $\pm 1$, and at any other point by $-1$.
- At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.
Denis has crossed the road as soon as his coordinate becomes equal to $n$.
This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.
|
Notice the fact: if we somehow came to safety island and time $i \bmod g$ ($\bmod$ - is a remainder after dividing $i$ by $g$), we don't need anymore to come to this island at time $j$ where $i<j$ and $i\bmod g = j\bmod g$, because this will form a cycle. So that we can rephrase our task like this: we have some vertices, which are denoted as a pair $(i, t)$, $i$ - is island index, $t$ is a remainder after dividing the time we came to $i$ by $g$. So it will be enough to use only edges between vertices $(i, t) \to (i + 1, (t + a[i + 1] - a[i])\bmod g)$ and $(i, t)\to (i - 1, (t + a[i] - a[i - 1])\bmod g)$, because all remaining edges can be expressed through these ones. Now lets notice that edges, which make time $t + a > g$ can't be used due to restriction of walking on red. But vertices with $t + a = g$ are good for us. So we can say, that while green light is on, Denis can walk without restrictions, and when $t + a = g$ we add $g + r$ to time. So we can use $01$-BFS to solve this task and at the end check find vertex and position from which we can go to our final destination. Time complexity will be $O(g * m)$.
|
[
"dfs and similar",
"dp",
"graphs",
"shortest paths"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
using ll = long long int;
vector<vector<int>> dist;
vector<vector<bool>> was;
int main() {
int n, m;
cin >> n >> m;
vector<int> arr(m + 2);
for (int i = 0; i < m; ++i)
cin >> arr[i + 1];
m += 2;
arr.back() = n;
sort(arr.begin(), arr.end());
ll G, R;
cin >> G >> R;
dist.resize(m, vector<int>(G+1));
was.resize(m, vector<bool>(G+1));
deque<pair<int, int>> bfs;
bfs.push_back({0, 0});
was[0][0] = 1;
ll ans = -1;
while (bfs.size()) {
int v = bfs.front().first;
int t = bfs.front().second;
bfs.pop_front();
if (t == 0) {
int tTo = n - arr[v];
if (tTo <= G) {
ll tempAns = (R + G) * dist[v][t] + tTo;
if (ans == -1 || ans > tempAns)
ans = tempAns;
}
}
if (t == G) {
if (was[v][0] == 0) {
dist[v][0] = dist[v][t] + 1;
bfs.push_back({v, 0});
was[v][0] = 1;
}
continue;
}
if (v) {
int tTo = t + arr[v] - arr[v - 1];
if (tTo <= G && was[v-1][tTo] == 0) {
was[v-1][tTo] = 1;
dist[v-1][tTo] = dist[v][t];
bfs.push_front({v-1, tTo});
}
}
if (v < m - 1) {
int tTo = t + arr[v + 1] - arr[v];
if (tTo <= G && was[v+1][tTo] == 0) {
was[v+1][tTo] = 1;
dist[v+1][tTo] = dist[v][t];
bfs.push_front({v+1, tTo});
}
}
}
cout << ans;
}
|
1340
|
D
|
Nastya and Time Machine
|
Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him.
The map of the city where they live has a lot of squares, some of which are connected by roads. There is exactly one way between each pair of squares which does not visit any vertex twice. It turns out that the graph of the city is a tree.
Denis is located at vertex $1$ at the time $0$. He wants to visit every vertex at least once and get back as soon as possible.
Denis can walk one road in $1$ time. Unfortunately, the city is so large that it will take a very long time to visit all squares. Therefore, Denis took a desperate step. He pulled out his pocket time machine, which he constructed in his basement. With its help, Denis can change the time to any non-negative time, which is less than the current time.
But the time machine has one feature. If the hero finds himself in the same place and at the same time twice, there will be an explosion of universal proportions and Nastya will stay unhappy. Therefore, Denis asks you to find him a route using a time machine that he will get around all squares and will return to the first and at the same time the maximum time in which he visited any square will be minimal.
Formally, Denis's route can be represented as a sequence of pairs: $\{v_1, t_1\}, \{v_2, t_2\}, \{v_3, t_3\}, \ldots, \{v_k, t_k\}$, where $v_i$ is number of square, and $t_i$ is time in which the boy is now.
The following conditions must be met:
- The route starts on square $1$ at time $0$, i.e. $v_1 = 1, t_1 = 0$ and ends on the square $1$, i.e. $v_k = 1$.
- All transitions are divided into two types:
- Being in the square change the time: $\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \} : v_{i+1} = v_i, 0 \leq t_{i+1} < t_i$.
- Walk along one of the roads: $\{ v_i, t_i \} \to \{ v_{i+1}, t_{i+1} \}$. Herewith, $v_i$ and $v_{i+1}$ are connected by road, and $t_{i+1} = t_i + 1$
- All pairs $\{ v_i, t_i \}$ must be different.
- All squares are among $v_1, v_2, \ldots, v_k$.
You need to find a route such that the maximum time in any square will be minimal, that is, the route for which $\max{(t_1, t_2, \ldots, t_k)}$ will be the minimum possible.
|
Lemma: The maximum time that Denis will visit will be at least $\max\limits_{v = 1}^{n} \deg v = T$ Proof: consider an arbitrary vertex $v$. We will visit her $\deg v - 1$ times when we will bypass all her neighbors and another $1$ when we return to her ancestor. But we can't go to vertex at 0 time. So, we need $\deg v$ moments more than 0. We construct a graph traversal with a maximum time equal to $T$. Let us now stand at $v$ at a time $t$ and $v$ has an un visited son $u$. We want to go to $u$, go around its entire subtree and return to $v$ at time $t + 1$. That is, the route will be something like this: $(v, t) \to (u, t + 1) \to \ldots \to (u, t) \to (v, t + 1)$. Let $k = \deg u - 1$, for $w_i$ we denote the $i$ th son of $u$. If $t + 1 \leq T - k$, then there are no problems, we will move back in time at the very end of the route: $(v, t)$ $\to$ $(u, t + 1)$ $\to$ $(w_1, t + 2)$ $\to$ $\ldots$ $\to$ $(u, t + 2)$ $\to$ $\ldots$ $\to$ $(w_k, t + k + 1)$ $\to$ $\ldots$ $\to$ $(u, t + k)$ $\to$ $(u, t)$ $\to$ $(v, t + 1)$. Otherwise, you have to go back in time in the middle of the route (exactly when we get to T) so that after the last visit we will be in $(v, t + 1)$, that is: $(v, t)$ $\to$ $(u, t + 1)$ $\to$ $(w_1, t + 2)$ $\to$ $\ldots$ $\to$ $(u, t + 2)$ $\to$ $\ldots$ $\to$ $(u, T)$ $\to$ $(u, t')$ $\to$ $\ldots$ $(w_k, t + k + 1)$ $\to$ $\ldots$ $\to$ $(u, t + k)$ $\to$ $(u, t)$ $\to$ $(v, t + 1)$ , where $t'$ can be easily calculated by the number of not visited sons.
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"trees"
] | 2,600
|
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("O3")
#pragma optimize("SEX_ON_THE_BEACH")
#include<bits/stdc++.h>
using ll = long long int;
using ull = unsigned long long int;
using dd = double;
using ldd = long double;
namespace Hashes {
const int mod197 = 1e9 + 7;
const int mod199 = 1e9 + 9;
const int modfft = 998244353;
int MOD = mod197;
template<typename T = int>
struct Hash {
T me, mod;
Hash() {}
Hash(T _me, T _mod = MOD) { me = _me, mod = _mod; if (me >= mod) me %= mod; }
Hash operator+ (Hash to) {
to.me += me;
if (to.me >= to.mod)
to.me -= to.mod;
return to;
}
Hash operator- (Hash to) {
to.me -= me;
to.me *= -1;
if (to.me < 0)
to.me += to.mod;
return to;
}
Hash operator* (Hash to) {
to.me *= me;
to.me %= to.mod;
return to;
}
Hash& operator+= (Hash to) {
me += to.me;
if (me >= mod)
me -= mod;
return *this;
}
Hash& operator-= (Hash to) {
me -= to.me;
if (me < 0)
me += mod;
return *this;
}
Hash& operator*= (Hash to) {
me *= to.me;
me %= mod;
return *this;
}
bool operator==(Hash to) {
return me == to.me;
}
T operator*() {
return me;
}
};
}
namespace someUsefull {
template<typename T1, typename T2>
inline void checkMin(T1& a, T2 b) {
if (a > b)
a = b;
}
template<typename T1, typename T2>
inline void checkMax(T1& a, T2 b) {
if (a < b)
a = b;
}
}
//name spaces
using namespace std;
using namespace Hashes;
using namespace someUsefull;
//end of name spaces
//defines
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define NO cout << "NO" << '\n';
#define No cout << "No" << '\n';
#define YES cout << "YES" << '\n';
#define Yes cout << "Yes" << '\n';
//end of defines
//debug defines
#ifdef HOME
#define debug(x) cout << #x << " " << x << endl;
#define debug_p(x) cout << #x << " " << x.ff << " " << x.ss << endl;
#define debug_v(x) {cout << #x << " "; for (auto ioi : x) cout << ioi << " "; cout << endl;}
#define debug_vp(x) {cout << #x << " "; for (auto ioi : x) cout << '[' << ioi.ff << " " << ioi.ss << ']'; cout << endl;}
#define debug_v_v(x) {cout << #x << "/*\n"; for (auto ioi : x) { for (auto ioi2 : ioi) cout << ioi2 << " "; cout << '\n';} cout << "*/" << #x << endl;}
int jjj;
#define wait() cin >> jjj;
#define PO cout << "POMELO" << endl;
#define OL cout << "OLIVA" << endl;
#define gen_clock(x) ll x = clock(); cout << "Clock " << #x << " created" << endl;
#define check_clock(x) cout << "Time spent in " << #x << ": " << clock() - x << endl; x = clock();
#define reset_clock(x) x = clock();
#define say(x) cout << x << endl;
#else
#define debug(x) 0;
#define debug_p(x) 0;
#define debug_v(x) 0;
#define debug_vp(x) 0;
#define debug_v_v(x) 0;
#define wait() 0;
#define PO 0;
#define OL 0;
#define gen_clock(x) 0;
#define check_clock(x) 0;
#define reset_clock(x) 0;
#define say(x) 0;
#endif // HOME
//end of debug defines
vector<pair<int, int>> ans;
vector<vector<int>> gr;
int mad = 0;
void dfs(int v, int& t, int backT = -1, int p = -1) {
ans.push_back({v, t});
int cntTo = 0;
for (int to : gr[v]) {
if (to != p)
++cntTo;
}
for (int to : gr[v]) {
if (to == p)
continue;
if (t == mad) {
t = backT - 1 - cntTo;
ans.push_back({v, t});
}
t++;
dfs(to, t, t, v);
ans.push_back({v, t});
--cntTo;
}
if (p == -1)
return;
if (t >= backT) {
t = backT-1;
ans.push_back({v, t});
}
++t;
}
void solve(int test) {
int n;
cin >> n;
gr.resize(n);
for (int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
--a;
--b;
gr[a].push_back(b);
gr[b].push_back(a);
}
int t = 0;
for (int i = 0; i < n; ++i)
mad = max(mad, int(gr[i].size()));
dfs(0, t);
cout << ans.size() << '\n';
for (int i = 0; i < ans.size(); ++i) {
cout << ans[i].ff + 1 << " " << ans[i].ss << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(false);
cout.tie(0);
cin.tie(0);
int t = 1;
//cin >> t;
for (int i = 0; i < t; ++i) {
solve(i);
}
return 0;
}
/*
*/
|
1340
|
F
|
Nastya and CBS
|
Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?
A string $s$ is given. It consists of $k$ kinds of pairs of brackets. Each bracket has the form $t$ — it is an integer, such that $1 \leq |t| \leq k$. If the bracket has a form $t$, then:
- If $t > 0$, then it's an opening bracket of the type $t$.
- If $t < 0$, then it's a closing bracket of the type $-t$.
Thus, there are $k$ types of pairs of brackets in total.
The queries need to be answered:
- Replace the bracket at position $i$ with the bracket of the form $t$.
- Check if the substring from the $l$-th to $r$-th position (including) is the correct bracket sequence.
Recall the definition of the correct bracket sequence:
- An empty sequence is correct.
- If $A$ and $B$ are two correct bracket sequences, then their concatenation "$A$ $B$" is also correct bracket sequence.
- If $A$ is the correct bracket sequence, $c$ $(1 \leq c \leq k)$ is a type of brackets, then the sequence "$c$ $A$ $-c$" is also correct bracket sequence.
|
We will call the string exactly the wrong bracket sequence if we go through it with a stack and it will not be of the form $close + open$, where $close$ is the sequence of closing brackets, and $open$ is opening. Claim: if $s = a + b$ and $a$ is exactly not CBS or $b$ is exactly not CBS, then $s$ is also exactly not CBS. At the top of the Segment Tree, we will keep the line after going through it with the stack in the form $close + open$ or marking that it is exactly not CBS. How to merge $2$ segments of the form $\{close_1 + open_1 \}$ and $\{close_2 + open_2 \}$? Note that $3$ cases are possible: The suffix $open_1$ is $close_2$, then the result is $close_1 + (close_2 - \text {prefix}) + open_2$. The prefix $close_1$ is equal to $open_2$, similarly. The result is exectly not CBS. How can we quickly consider this? Let's build a segment tree, which contains treaps (which contain hashes) in each node, then we need to check for equality some prefixes, glue some strings and save all versions in order to update the ST. The resulting asymptotics of $O (n \log^2 n)$.
|
[
"brute force",
"data structures",
"hashing"
] | 3,300
|
#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
using namespace std;
mt19937 rnd(13'06'2019);
const int N = 4e5 + 1;
const int LN = 2e6 + 1;
const int mod = 1e9 + 7;
const long long div1 = 100'001;
struct dek {
int l, r, sz, key;
long long hesh;
};
int top = 0;
dek m[LN];
long long t[N];
int lft[N], righ[N], a[N];
bool open[N], bad[N];
bool use[LN];
int get_next() {
while (use[top])
++top;
use[top] = 1;
return top;
}
void recalc(int u) {
m[u].sz = m[m[u].l].sz + m[m[u].r].sz + 1;
m[u].hesh = (m[m[u].l].hesh * t[m[m[u].r].sz + 1] + t[m[m[u].r].sz] * m[u].key + m[m[u].r].hesh) % mod;
}
void copy_vert(int from, int to) {
m[to] = m[from];
}
int merg(int a, int b) {
if (a == 0)
return b;
if (b == 0)
return a;
int u = get_next();
if (rnd() % (m[a].sz + m[b].sz) < m[a].sz) {
copy_vert(a, u);
m[u].r = merg(m[a].r, b);
} else {
copy_vert(b, u);
m[u].l = merg(a, m[b].l);
}
recalc(u);
return u;
}
void split(int root, int &a, int &b, int x) {
if (root == 0) {
a = 0;
b = 0;
return;
}
int u = get_next();
copy_vert(root, u);
if (m[m[root].l].sz >= x) {
split(m[root].l, a, m[u].l, x);
b = u;
} else {
split(m[root].r, m[u].r, b, x - m[m[root].l].sz - 1);
a = u;
}
recalc(u);
}
int newv(int key) {
int u = get_next();
m[u].key = key;
m[u].l = m[u].r = 0;
m[u].sz = 1;
m[u].hesh = key;
return u;
}
void recalc_do(int v) {
if (bad[2*v + 1] || bad[2*v + 2])
bad[v] = 1;
else {
if (m[righ[2*v + 1]].sz >= m[lft[2*v + 2]].sz) {
int a, b;
split(righ[2*v + 1], a, b, m[righ[2*v + 1]].sz - m[lft[2*v + 2]].sz);
if (m[b].hesh != m[lft[2*v + 2]].hesh)
bad[v] = 1;
else {
lft[v] = lft[2*v + 1];
righ[v] = merg(a, righ[2*v + 2]);
bad[v] = 0;
}
} else {
int a, b;
split(lft[2*v + 2], a, b, m[lft[2*v + 2]].sz - m[righ[2*v + 1]].sz);
if (m[b].hesh != m[righ[2*v + 1]].hesh)
bad[v] = 1;
else {
lft[v] = merg(a, lft[2*v + 1]);
righ[v] = righ[2*v + 2];
bad[v] = 0;
}
}
}
}
void build_do(int v, int vl, int vr) {
if (vr - vl == 1) {
righ[v] = 0;
lft[v] = 0;
if (open[vl] == 1)
righ[v] = newv(a[vl]);
else
lft[v] = newv(a[vl]);
bad[v] = 0;
} else {
build_do(2*v + 1, vl, (vl + vr) / 2);
build_do(2*v + 2, (vl + vr) / 2, vr);
recalc_do(v);
}
}
void als(int v, int vl, int vr, int l, int x, bool op) {
if (vr - vl == 1) {
a[vl] = x;
open[vl] = op;
build_do(v, vl, vr);
} else {
if (l < (vl + vr) / 2)
als(2*v + 1, vl, (vl + vr) / 2, l, x, op);
else
als(2*v + 2, (vl + vr) / 2, vr, l, x, op);
recalc_do(v);
}
}
bool zpr(int v, int vl, int vr, int l, int r, int &lefq, int &rigq) {
if (l <= vl && vr <= r) {
lefq = lft[v];
rigq = righ[v];
return bad[v];
} else if (l >= vr || vl >= r) {
lefq = 0;
rigq = 0;
return 0;
} else {
bool b1, b2;
int l1, r1, l2, r2;
b1 = zpr(2*v + 1, vl, (vl + vr) / 2, l, r, l1, r1);
b2 = zpr(2*v + 2, (vl + vr) / 2, vr, l, r, l2, r2);
if (b1 || b2)
return true;
if (m[r1].sz >= m[l2].sz) {
int a, b;
split(r1, a, b, m[r1].sz - m[l2].sz);
if (m[b].hesh != m[l2].hesh)
return true;
rigq = merg(a, r2);
lefq = l1;
} else {
int a, b;
split(l2, a, b, m[l2].sz - m[r1].sz);
if (m[b].hesh != m[r1].hesh)
return true;
rigq = r2;
lefq = merg(a, l1);
}
return false;
}
}
void dfs(int u) {
if (use[u])
return;
use[u] = 1;
dfs(m[u].l);
dfs(m[u].r);
}
int main() {
int i, j, k, n, p, x, q, type;
//freopen("input.txt", "r", stdin);
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
use[0] = 1;
cin >> n >> k;
t[0] = 1;
for (i = 1; i <= n; ++i)
t[i] = (t[i - 1] * div1) % mod;
for (i = 1; i <= n; ++i) {
cin >> a[i];
if (a[i] > 0)
open[i] = 1;
else {
a[i] = -a[i];
open[i] = 0;
}
}
build_do(0, 1, n + 1);
cin >> q;
for (i = 0; i < q; ++i) {
cin >> type;
if (type == 1) {
cin >> p >> x;
bool op;
if (x > 0)
op = 1;
else {
x = -x;
op = 0;
}
als(0, 1, n + 1, p, x, op);
} else {
int l, r, lft, right;
cin >> l >> r;
bool bad = zpr(0, 1, n + 1, l, r + 1, lft, right);
if (bad || lft != 0 || right != 0)
cout << "No\n";
else
cout << "Yes\n";
}
if (top > LN - 1e4) {
memset(use, 0, sizeof(use));
for (j = 0; j < N; ++j) {
dfs(lft[j]);
dfs(righ[j]);
}
top = 0;
}
}
}
|
1341
|
A
|
Nastya and Rice
|
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped $n$ grains. Nastya read that each grain weighs some integer number of grams from $a - b$ to $a + b$, inclusive (numbers $a$ and $b$ are known), and the whole package of $n$ grains weighs from $c - d$ to $c + d$ grams, inclusive (numbers $c$ and $d$ are known). The weight of the package is the sum of the weights of all $n$ grains in it.
Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $i$-th grain weighs some integer number $x_i$ $(a - b \leq x_i \leq a + b)$, and in total they weigh from $c - d$ to $c + d$, inclusive ($c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$).
|
We can get any weight of all grains from $n(a - b)$ to $n(a + b)$, so we need to check that the segments $[n(a - b); n(a + b)]$ and $[c - d; c + d]$ intersect.
|
[
"math"
] | 900
|
#include <iostream>
using namespace std;
int main() {
int q;
cin >> q;
while (q--) {
int n, a, b, c, d;
cin >> n >> a >> b >> c >> d;
int L = n * (a - b), R = n * (a + b);
if (R < c - d || c + d < L)
cout << "No\n";
else
cout << "Yes\n";
}
}
|
1341
|
B
|
Nastya and Door
|
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $k$ ($k \ge 3$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights $a_1, a_2, \dots, a_n$ in order from left to right ($k \le n$). It is guaranteed that neighboring heights are not equal to each other (that is, $a_i \ne a_{i+1}$ for all $i$ from $1$ to $n-1$).
Peaks of mountains on the segment $[l,r]$ (from $l$ to $r$) are called indexes $i$ such that $l < i < r$, $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$. It is worth noting that the boundary indexes $l$ and $r$ for the segment \textbf{are not peaks}. For example, if $n=8$ and $a=[3,1,4,1,5,9,2,6]$, then the segment $[1,8]$ has only two peaks (with indexes $3$ and $6$), and there are no peaks on the segment $[3, 6]$.
To break the door, Nastya throws it to a segment $[l,l+k-1]$ of consecutive mountains of length $k$ ($1 \le l \le n-k+1$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $p+1$, where $p$ is the number of peaks on the segment $[l,l+k-1]$.
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $[l, l+k-1]$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $l$ is minimal.
Formally, you need to choose a segment of mountains $[l, l+k-1]$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $l$.
|
Let's make an array consisting of $0$ and $1$, such that it shows whether the position $i$ is a peak on the whole segment. To do this, we will go through the indices from $2$ to $n - 1$, and if the conditions $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$ are true, then we write $1$ in a new array at position $i$. After that, we calculate the prefix sum in the new array $pref$. Now the number of peaks in the segment $[l, l + k - 1]$ is calculated as $pref[l + k - 2] - pref[l]$, so we find out how many peaks in the desired segment, not including the boundaries of the segment. It remains only to go through all $l$ from $1$ to $n - k + 1$ and find the leftmost $l$, such that $pref[l + k - 2] - pref[l]$ as much as possible.
|
[
"greedy",
"implementation"
] | 1,300
|
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <fstream>
#include <iomanip>
#include <bitset>
#include <random>
#include <queue>
#include <cstring>
#include <cassert>
using namespace std;
#define X first
#define Y second
#define mp make_pair
#define all(x) x.begin(), x.end()
#define all_(x) x.rbegin(), x.rend()
#define multi_test 1
typedef long long ll;
typedef long long lint;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pld;
const ll INF = 1e9 + 9;
const ll INF1 = 1e18 + 19;
const ll MAXN = 1e6 + 7;
const ll MAXN1 = 300;
const ll MAXN2 = (1 << 24) + 7;
const ll MOD = 1e9 + 7;
const ll PW = 31;
const ll BLOCK = 317;
void solve();
mt19937_64 mt(1e9 + 7);
signed main() {
srand('a' + 'l' + 'e' + 'x' + 'X' + '5' + '1' + '2');
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef _DEBUG
#define MAXN 5000
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int q = 1;
if (multi_test) cin >> q;
while (q--) {
solve();
}
}
/*-----------------------------------------------------------------------------------------------------------------------------*/
bool pick(int i, vector<int>& v, int l, int r) {
if (i == l || i == r) return 0;
return v[i - 1] < v[i] && v[i] > v[i + 1];
}
void solve() {
int n, k;
cin >> n >> k;
vector<int> v(n);
for (auto &i : v) cin >> i;
int ans = -1, l = -1, r = -1, now = 0;
for (int i = 1; i + 1 < k; ++i) {
if (pick(i, v, 0, k - 1)) ++now;
}
ans = now + 1, l = 0, r = k - 1;
for (int i = k; i < n; ++i) {
if (pick(i - k + 1, v, i - k, i - 1)) --now;
if (pick(i - 1, v, i - k + 1, i)) ++now;
if (now + 1 > ans) {
ans = now + 1;
l = i - k + 1;
r = i;
}
}
cout << ans << " " << l + 1 << "\n";
}
|
1342
|
A
|
Road To Zero
|
You are given two integers $x$ and $y$. You can perform two types of operations:
- Pay $a$ dollars and increase or decrease any of these integers by $1$. For example, if $x = 0$ and $y = 7$ there are four possible outcomes after this operation:
- $x = 0$, $y = 6$;
- $x = 0$, $y = 8$;
- $x = -1$, $y = 7$;
- $x = 1$, $y = 7$.
- Pay $b$ dollars and increase or decrease both integers by $1$. For example, if $x = 0$ and $y = 7$ there are two possible outcomes after this operation:
- $x = -1$, $y = 6$;
- $x = 1$, $y = 8$.
Your goal is to make both given integers equal zero simultaneously, i.e. $x = y = 0$. There are no other requirements. In particular, it is possible to move from $x=1$, $y=0$ to $x=y=0$.
Calculate the minimum amount of dollars you have to spend on it.
|
Let's presume that $x \ge y$. Then there are two cases in the problem: If $a + a \le b$ then we have to $x + y$ times perform the first operation. So the answer is $(x + y) \cdot a$; If $a + a > b$ then we have to $y$ times perform the second operation and pass the remaining distance by performing the first operation. So the answer is $y \cdot b + (x - y) \cdot a$.
|
[
"greedy",
"math"
] | 1,000
|
for _ in range(int(input())):
x, y = map(int, input().split())
a, b = map(int, input().split())
b = min(b, a + a)
if x < y:
x, y= y, x
print(y * b + (x - y) * a)
|
1342
|
B
|
Binary Period
|
Let's say string $s$ has period $k$ if $s_i = s_{i + k}$ for all $i$ from $1$ to $|s| - k$ ($|s|$ means length of string $s$) and $k$ is the minimum positive integer with this property.
Some examples of a period: for $s$="0101" the period is $k=2$, for $s$="0000" the period is $k=1$, for $s$="010" the period is $k=2$, for $s$="0011" the period is $k=4$.
You are given string $t$ consisting only of 0's and 1's and you need to find such string $s$ that:
- String $s$ consists only of 0's and 1's;
- The length of $s$ doesn't exceed $2 \cdot |t|$;
- String $t$ is a subsequence of string $s$;
- String $s$ has smallest possible period among all strings that meet conditions 1—3.
Let us recall that $t$ is a subsequence of $s$ if $t$ can be derived from $s$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $t$="011" is a subsequence of $s$="10101".
|
Let's see how strings with periods $k = 1$ and $k = 2$ look. There are two types of strings with a period equal to $1$: 0000... and 1111.... And there are two types of strings with a period equal to $2$: 01010... and 10101.... It's easy to see if $t$ consists only of 0's (1's) then the string itself is an answer since it has period equal to $1$. Otherwise, it's also quite obvious that any string $t$ is a subsequence of 0101...01 (1010...10) of $2|t|$ length.
|
[
"constructive algorithms",
"strings"
] | 1,100
|
fun main() {
val T = readLine()!!.toInt()
for (tc in 1..T) {
val t = readLine()!!
val s = t.toCharArray().distinct().joinToString("").repeat(t.length)
println(s)
}
}
|
1342
|
C
|
Yet Another Counting Problem
|
You are given two integers $a$ and $b$, and $q$ queries. The $i$-th query consists of two numbers $l_i$ and $r_i$, and the answer to it is the number of integers $x$ such that $l_i \le x \le r_i$, and $((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$. Calculate the answer for each query.
Recall that $y \bmod z$ is the remainder of the division of $y$ by $z$. For example, $5 \bmod 3 = 2$, $7 \bmod 8 = 7$, $9 \bmod 4 = 1$, $9 \bmod 9 = 0$.
|
It's quite easy to see that $((ab + x) \bmod a) \bmod b = (x \bmod a) \bmod b$. What does it mean? The property given in the statement holds for $x$ if and only if it holds for $x \bmod ab$. It allows us to answer each testcase in $O(ab + q)$ as follows: for each number from $0$ to $ab - 1$, we may check the given property before processing the queries, and build an array of prefix sums on it to efficiently count the number of integers satisfying the property from the segment $[0, y]$, where $y < ab$. Then each query $[l, r]$ can be divided into two prefix-queries $[0, l - 1]$ and $[0, r]$. To answer a prefix query $[0, p]$ in $O(1)$, we can calculate the number of "full segments" of length $ab$ inside this prefix (that is $\lfloor \frac{p}{ab} \rfloor$) and the length of the last segment of numbers that don't belong into a full segment (that is $p \bmod ab$). To handle full segments, we multiply the number of integers satisfying the property on one segment by the number of such segments, and to handle the last part of segment, we use prefix sums.
|
[
"math",
"number theory"
] | 1,600
|
#include<bits/stdc++.h>
using namespace std;
const int N = 40043;
int len;
int p[N];
void build(int a, int b)
{
len = a * b;
p[0] = 0;
for(int i = 1; i <= len; i++)
{
p[i] = p[i - 1];
if((i % a) % b != (i % b) % a)
p[i]++;
}
}
long long query(long long l)
{
long long cnt = l / len;
int rem = l % len;
return p[len] * 1ll * cnt + p[rem];
}
long long query(long long l, long long r)
{
return query(r) - query(l - 1);
}
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
int a, b, q;
cin >> a >> b >> q;
build(a, b);
long long l, r;
for(int j = 0; j < q; j++)
{
cin >> l >> r;
cout << query(l, r) << " ";
}
cout << endl;
}
}
|
1342
|
D
|
Multiple Testcases
|
So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!
Initially, each test in that problem is just an array. The maximum size of an array is $k$. For simplicity, the contents of arrays don't matter. You have $n$ tests — the $i$-th test is an array of size $m_i$ ($1 \le m_i \le k$).
Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than $c_1$ arrays of size \textbf{greater than or equal to $1$} ($\ge 1$), no more than $c_2$ arrays of size \textbf{greater than or equal to $2$}, $\dots$, no more than $c_k$ arrays of size \textbf{greater than or equal to $k$}. Also, $c_1 \ge c_2 \ge \dots \ge c_k$.
So now your goal is to create the new testcases in such a way that:
- each of the initial arrays appears in \textbf{exactly one} testcase;
- for each testcase the given conditions hold;
- the number of testcases is minimum possible.
Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.
|
Let's estimate the smallest possible achievable answer. Let the number of the arrays of size greater than or equal to $i$ be $g_i$. The answer is maximum $\lceil \frac{g_i}{c_i} \rceil$ over all $i$ from $1$ to $k$. You can prove that you can't fit $g_i$ arrays in less than $\lceil \frac{g_i}{c_i} \rceil$ testcases with the pigeonhole principle. Let that be called $ans$. Ok, let's now construct the solution for that estimate. Sort arrays in the increasing or decreasing order and assign the $i$-th array ($0$-indexed) in that order to the $i~mod~ans$ testcase. It's easy to see that for any $i$ the number of arrays of size greater than or equal to $i$ is always restricted by $\lceil \frac{g_i}{c_i} \rceil$. Overall complexity: $O(n \log n + k)$ or $O(n + k)$ if you care enough to do counting sort.
|
[
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"sortings",
"two pointers"
] | 1,900
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int n, k;
scanf("%d%d", &n, &k);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
vector<int> c(k + 1);
forn(i, k) scanf("%d", &c[i + 1]);
sort(a.begin(), a.end(), greater<int>());
int ans = 0;
for (int i = k, g = 0; i >= 1; --i){
while (g < n && a[g] == i) ++g;
ans = max(ans, (g + c[i] - 1) / c[i]);
}
vector<vector<int>> res(ans);
forn(i, n) res[i % ans].push_back(a[i]);
printf("%d\n", ans);
forn(i, ans){
printf("%d", int(res[i].size()));
for (auto it : res[i])
printf(" %d", it);
puts("");
}
return 0;
}
|
1342
|
E
|
Placing Rooks
|
Calculate the number of ways to place $n$ rooks on $n \times n$ chessboard so that both following conditions are met:
- each empty cell is under attack;
- exactly $k$ pairs of rooks attack each other.
An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture:
\begin{center}
{\small One of the ways to place the rooks for $n = 3$ and $k = 2$}
\end{center}
Two ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way.
The answer might be large, so print it modulo $998244353$.
|
If we want to place $n$ rooks on an $n \times n$ chessboard so all empty cells are under attack, then either each row or each column should contain at least one rook. Let's suppose that each row contains at least one rook, and multiply the answer by $2$ in the end. How to ensure that there are exactly $k$ pairs of rooks attacking each other? Since each row contains exactly one rook, only the rooks in the same column attack each other - moreover, if there are $x$ rooks in a non-empty column, they create $(x - 1)$ pairs. So our goal is to distribute $n$ rooks to $n - k$ columns so that each column contains at least one rook. How to calculate the number of ways to distribute the rooks into $c$ columns? One of the options is to choose the columns we use (the number of ways to do this is ${n}\choose{c}$), and then use inclusion-exclusion to ensure that we are counting only the ways where each column contains at least one rook. The formula we will get is something like $\sum \limits_{i = 0}^{c} (-1)^i {{c}\choose{i}} (c-i)^n$: we want to fix the number of columns that will not contain rooks (that is $i$), which are these columns (that is ${c}\choose{i}$), and how many are there ways to distribute the rooks among remaining columns (that is $(c-i)^n$). Are we done? Almost. We wanted to multiply the answer by $2$ to count the ways where each column contains at least one rook, but we should not do it if $k = 0$, because in this case each placement of the rooks has exactly one rook in each row and exactly one rook in each column.
|
[
"combinatorics",
"fft",
"math"
] | 2,300
|
#include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 200043;
int add(int x, int y)
{
return (x + y) % MOD;
}
int sub(int x, int y)
{
return add(x, MOD - 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 fact[N];
int C(int n, int k)
{
return mul(fact[n], inv(mul(fact[k], fact[n - k])));
}
int main()
{
int n, k;
cin >> n >> k;
if(k > n - 1)
{
cout << 0 << endl;
return 0;
}
fact[0] = 1;
for(int i = 1; i <= n; i++)
fact[i] = mul(i, fact[i - 1]);
int ans = 0;
int c = n - k;
for(int i = c; i >= 0; i--)
if(i % 2 == c % 2)
ans = add(ans, mul(binpow(i, n), C(c, i)));
else
ans = sub(ans, mul(binpow(i, n), C(c, i)));
ans = mul(ans, C(n, c));
if(k > 0)
ans = mul(ans, 2);
cout << ans << endl;
}
|
1342
|
F
|
Make It Ascending
|
You are given an array $a$ consisting of $n$ elements. You may apply several operations (possibly zero) to it.
During each operation, you choose two indices $i$ and $j$ ($1 \le i, j \le n$; $i \ne j$), increase $a_j$ by $a_i$, and remove the $i$-th element from the array (so the indices of all elements to the right to it decrease by $1$, and $n$ also decreases by $1$).
Your goal is to make the array $a$ strictly ascending. That is, the condition $a_1 < a_2 < \dots < a_n$ should hold (where $n$ is the resulting size of the array).
Calculate the minimum number of actions required to make the array strictly ascending.
|
Suppose we don't have any constraints on the order of elements, the resulting array just should not contain any duplicates. Let's build the result one element after another in ascending order, so each element we create is strictly greater than the previous. To create an element, just use some subset of elements and merge them into new element. This process can be efficiently modeled with the following dynamic programming: $dp_{cnt, mask}$ is the minimum value of the last element, if we merged all the elements from $mask$ into $cnt$ ascending numbers. To model transitions, we simply iterate on the mask of elements that will be merged into a new one, and check if its sum is greater than the last element we created. This runs in $O(n3^n)$, if we use an efficient way to iterate on all masks that don't intersect with the given mask. Okay, how about maintaining the order? When we create an element by merging some elements of the original array, let's choose some position of an element we use in merging and state that all other elements are added to it. Then, to ensure that the result is ascending, the position of this element should be greater than the position of the element we chose while building the previous number. We can add the position we have chosen for the last element to the states of our dynamic programming, so it becomes $dp_{cnt, mask, pos}$ - the minimum value of the last element, if we merged the $mask$ of elements into $cnt$ numbers, and the last element originally had index $pos$ in the array. Using some greedy optimizations (for example, we should not iterate on the position we are choosing to merge - it can be chosen greedily as the leftmost position after the position of previous element we are taking into consideration), we can make it $O(n^2 3^n)$, yet with a small constant factor. To restore the answer, we can maintain the previous values of $mask$ and $pos$ in each state, since $cnt$ just increases by $1$ with each transition.
|
[
"bitmasks",
"brute force",
"dp"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define sz(a) int((a).size())
#define forn(i, n) for (int i = 0; i < int(n); ++i)
typedef pair<int, int> pt;
const int INF = 1e9;
const int N = 15;
int n;
int a[N];
int sum[1 << N];
int dp[N + 1][1 << N][N + 1];
pt p[N + 1][1 << N][N + 1];
void solve() {
scanf("%d", &n);
forn(i, n) scanf("%d", &a[i]);
forn(mask, 1 << n) {
sum[mask] = 0;
forn(i, n) if (mask & (1 << i))
sum[mask] += a[i];
}
forn(cnt, n + 1) forn(mask, 1 << n) forn(pos, n + 1)
dp[cnt][mask][pos] = INF;
dp[0][0][0] = 0;
forn(cnt, n) forn(mask, 1 << n) forn(pos, n) if (dp[cnt][mask][pos] < INF) {
int rmask = mask ^ ((1 << n) - 1);
for (int nmask = rmask; nmask; nmask = (nmask - 1) & rmask) {
if (sum[nmask] <= dp[cnt][mask][pos])
continue;
if ((nmask >> pos) == 0)
continue;
int npos = pos + __builtin_ctz(nmask >> pos) + 1;
if (dp[cnt + 1][mask | nmask][npos] > sum[nmask]) {
dp[cnt + 1][mask | nmask][npos] = sum[nmask];
p[cnt + 1][mask | nmask][npos] = mp(mask, pos);
}
}
}
int acnt = 0, apos = 0;
forn(cnt, n + 1) forn(pos, n + 1) if (dp[cnt][(1 << n) - 1][pos] < INF)
acnt = cnt, apos = pos;
vector<pt> ans;
int mask = (1 << n) - 1, pos = apos;
for (int cnt = acnt; cnt > 0; --cnt) {
int nmask = p[cnt][mask][pos].x;
int npos = p[cnt][mask][pos].y;
forn(i, n) if ((nmask ^ mask) & (1 << i))
if (i != pos - 1) ans.pb(mp(i, pos - 1));
mask = nmask, pos = npos;
}
printf("%d\n", sz(ans));
forn(i, sz(ans)) {
int from = ans[i].x;
forn(j, i) from -= ans[j].x < ans[i].x;
int to = ans[i].y;
forn(j, i) to -= ans[j].x < ans[i].y;
printf("%d %d\n", from + 1, to + 1);
}
}
int main() {
int tc;
scanf("%d", &tc);
forn(i, tc) solve();
}
|
1343
|
A
|
Candies
|
Recently Vova found $n$ candy wrappers. He remembers that he bought $x$ candies during the first day, $2x$ candies during the second day, $4x$ candies during the third day, $\dots$, $2^{k-1} x$ candies during the $k$-th day. But there is an issue: Vova remembers neither $x$ nor $k$ but he is sure that $x$ and $k$ are positive integers and $k > 1$.
Vova will be satisfied if you tell him \textbf{any positive} integer $x$ so there is an integer $k>1$ that $x + 2x + 4x + \dots + 2^{k-1} x = n$. It is guaranteed that at least one solution exists. \textbf{Note that $k > 1$}.
You have to answer $t$ independent test cases.
|
Notice that $\sum\limits_{i=0}^{k-1} 2^i = 2^k - 1$. Thus we can replace the initial equation with the following: $(2^k - 1) x = n$. So we can iterate over all possible $k$ in range $[2; 29]$ (because $2^{30} - 1 > 10^9$) and check if $n$ is divisible by $2^k-1$. If it is then we can print $x = \frac{n}{2^k-1}$. P.S. I know that so many participants found the formula $\sum\limits_{i=0}^{k-1} 2^i = 2^k - 1$ using geometric progression sum but there is the other way to understand this and it is a way more intuitive for me. Just take a look at the binary representation of numbers: we can notice that $2^0 = 1, 2^1 = 10, 2^2 = 100$ and so on. Thus $2^0 = 1, 2^0+2^1=11, 2^0+2^1+2^2=111$ and so on. And if we add one to this number consisting of $k$ ones then we get $2^k$.
|
[
"brute force",
"math"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int pw = 2; pw < 30; ++pw) {
int val = (1 << pw) - 1;
if (n % val == 0) {
cerr << val << endl;
cout << n / val << endl;
break;
}
}
}
return 0;
}
|
1343
|
B
|
Balanced Array
|
You are given a positive integer $n$, it is guaranteed that $n$ is even (i.e. divisible by $2$).
You want to construct the array $a$ of length $n$ such that:
- The first $\frac{n}{2}$ elements of $a$ are even (divisible by $2$);
- the second $\frac{n}{2}$ elements of $a$ are odd (not divisible by $2$);
- \textbf{all elements of $a$ are distinct and positive};
- the sum of the first half equals to the sum of the second half ($\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$).
If there are multiple answers, you can print any. It is \textbf{not guaranteed} that the answer exists.
You have to answer $t$ independent test cases.
|
Firstly, if $n$ is not divisible by $4$ then the answer is "NO" because the parities of halves won't match. Otherwise, the answer is always "YES". Let's construct it as follows: firstly, let's create the array $[2, 4, 6, \dots, n, 1, 3, 5, \dots, n - 1]$. This array is almost good except one thing: the sum in the right half is exactly $\frac{n}{2}$ less than the sum in the left half. So we can fix it easily: just add $\frac{n}{2}$ to the last element.
|
[
"constructive algorithms",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
n /= 2;
if (n & 1) {
cout << "NO" << endl;
continue;
}
cout << "YES" << endl;
for (int i = 1; i <= n; ++i) {
cout << i * 2 << " ";
}
for (int i = 1; i < n; ++i) {
cout << i * 2 - 1 << " ";
}
cout << 3 * n - 1 << endl;
}
return 0;
}
|
1343
|
C
|
Alternating Subsequence
|
Recall that the sequence $b$ is a a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For example, if $a=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.
You are given a sequence $a$ consisting of $n$ positive and negative elements (there is no zeros in the sequence).
Your task is to choose \textbf{maximum by size} (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the \textbf{maximum sum} of elements.
In other words, if the maximum length of alternating subsequence is $k$ then your task is to find the \textbf{maximum sum} of elements of some alternating subsequence of length $k$.
You have to answer $t$ independent test cases.
|
Firstly, let's extract maximum by inclusion segments of the array that consists of the numbers with the same sign. For example, if the array is $[1, 1, 2, -1, -5, 2, 1, -3]$ then these segments are $[1, 1, 2]$, $[-1, -5]$, $[2, 1]$ and $[-3]$. We can do it with any "two pointers"-like algorithm. The number of these segments is the maximum possible length of the alternating subsequence because we can take only one element from each block. And as we want to maximize the sum, we need to take the maximum element from each block. Time complexity: $O(n)$.
|
[
"dp",
"greedy",
"two pointers"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
auto sgn = [&](int x) {
if (x > 0) return 1;
else return -1;
};
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &it : a) cin >> it;
long long sum = 0;
for (int i = 0; i < n; ++i) {
int cur = a[i];
int j = i;
while (j < n && sgn(a[i]) == sgn(a[j])) {
cur = max(cur, a[j]);
++j;
}
sum += cur;
i = j - 1;
}
cout << sum << endl;
}
return 0;
}
|
1343
|
D
|
Constant Palindrome Sum
|
You are given an array $a$ consisting of $n$ integers (it is guaranteed that $n$ is even, i.e. divisible by $2$). All $a_i$ does not exceed some integer $k$.
Your task is to replace the \textbf{minimum} number of elements (replacement is the following operation: choose some index $i$ from $1$ to $n$ and replace $a_i$ with some integer in range $[1; k]$) to satisfy the following conditions:
- after all replacements, all $a_i$ are positive integers not greater than $k$;
- for all $i$ from $1$ to $\frac{n}{2}$ the following equation is true: $a_i + a_{n - i + 1} = x$, where $x$ should be \textbf{the same} for all $\frac{n}{2}$ pairs of elements.
You have to answer $t$ independent test cases.
|
It is obvious that if we fix the value of $x$ then there are three cases for the pair of elements: We don't need to change anything in this pair; we can replace one element to fix this pair; we need to replace both elements to fix this pair. The first part can be calculated easily in $O(n+k)$, we just need to create the array of frequencies $cnt$, where $cnt_x$ is the number of such pairs $(a_i, a_{n-i+1})$ that $a_i + a_{n-i+1} = x$. The second part is a bit tricky but still doable in $O(n+k)$. For each pair, let's understand the minimum and the maximum sum we can obtain using at most one replacement. For the $i$-th pair, all such sums belong to the segment $[min(a_i, a_{n-i+1})+1; max(a_i, a_{n-i+1})+k]$. Let's make $+1$ on this segment using prefix sums (make $+1$ in the left border, $-1$ in the right border plus one and then just compute prefix sums on this array). Let this array be $pref$. Then the value $pref_x$ tells the number of such pairs that we need to replace at most one element in this pair to make it sum equals $x$. And the last part can be calculated as $\frac{n}{2} - pref_x$. So, for the sum $x$ the answer is $(pref_x - cnt_x) + (\frac{n}{2} - pref_x) \cdot 2$. We just need to take the minimum such value among all possible sums from $2$ to $2k$. There is another one solution that uses scanline, not depends on $k$ and works in $O(n \log n)$ but it has no cool ideas to explain it here (anyway the main idea is almost the same as in the solution above).
|
[
"brute force",
"data structures",
"greedy",
"two pointers"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto &it : a) cin >> it;
vector<int> cnt(2 * k + 1);
for (int i = 0; i < n / 2; ++i) {
++cnt[a[i] + a[n - i - 1]];
}
vector<int> pref(2 * k + 2);
for (int i = 0; i < n / 2; ++i) {
int l1 = 1 + a[i], r1 = k + a[i];
int l2 = 1 + a[n - i - 1], r2 = k + a[n - i - 1];
assert(max(l1, l2) <= min(r1, r2));
++pref[min(l1, l2)];
--pref[max(r1, r2) + 1];
}
for (int i = 1; i <= 2 * k + 1; ++i) {
pref[i] += pref[i - 1];
}
int ans = 1e9;
for (int sum = 2; sum <= 2 * k; ++sum) {
ans = min(ans, (pref[sum] - cnt[sum]) + (n / 2 - pref[sum]) * 2);
}
cout << ans << endl;
}
return 0;
}
|
1343
|
E
|
Weights Distributing
|
You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) $a$ to the vertex (district) $b$ and then from the vertex (district) $b$ to the vertex (district) $c$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (\textbf{he pays each time he goes along the road}). The list of prices that will be used $p$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.
You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the \textbf{minimum} possible. \textbf{Note that you cannot rearrange prices after the start of the trip}.
You have to answer $t$ independent test cases.
|
If we distribute costs optimally, then this pair of paths ($a \rightarrow b$ and $b \rightarrow c$) can look like just a straight path that doesn't visit the same vertex twice or like three straight paths with one intersection point $x$. The first case is basically a subcase of the second one (with the intersection point $a, b$ or $c$). So, if we fix the intersection point $x$ then these two paths ($a \rightarrow b$ and $b \rightarrow c$) become four paths ($a \rightarrow x$, $x \rightarrow b$, $b \rightarrow x$ and $x \rightarrow c$). We can notice that each path we denoted should be the shortest possible because if it isn't the shortest one then we used some prices that we couldn't use. Let the length of the shortest path from $u$ to $v$ be $dist(u, v)$. Then it is obvious that for the fixed intersection point $x$ we don't need to use more than $dist(a, x) + dist(b, x) + dist(c, x)$ smallest costs. Now we want to distribute these costs between these three paths somehow. We can see that the path from $b$ to $x$ is used twice so it is more optimally to distribute the smallest costs along this part. So, let $pref_i$ be the sum of the first $i$ smallest costs (just prefix sums on the sorted array $p$). Then for the intersection point $x$ the answer is $pref_{dist(b, x)} + pref_{dist(a, x) + dist(b, x) + dist(c, x)}$ (if $dist(a, x) + dist(b, x) + dist(c, x) \le m$). We can calculate distances from $a$, $b$ and $c$ to each vertex with three runs of bfs. Time complexity: $O(m \log m)$.
|
[
"brute force",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
vector<vector<int>> g;
void bfs(int s, vector<int> &d) {
d[s] = 0;
queue<int> q;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto to : g[v]) {
if (d[to] == INF) {
d[to] = d[v] + 1;
q.push(to);
}
}
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n, m, a, b, c;
cin >> n >> m >> a >> b >> c;
--a, --b, --c;
vector<int> p(m);
for (auto &it : p) cin >> it;
sort(p.begin(), p.end());
vector<long long> pref(m + 1);
for (int i = 0; i < m; ++i) {
pref[i + 1] = pref[i] + p[i];
}
g = vector<vector<int>>(n);
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
--x, --y;
g[x].push_back(y);
g[y].push_back(x);
}
vector<int> da(n, INF), db(n, INF), dc(n, INF);
bfs(a, da);
bfs(b, db);
bfs(c, dc);
long long ans = 1e18;
for (int i = 0; i < n; ++i) {
if (da[i] + db[i] + dc[i] > m) continue;
ans = min(ans, pref[db[i]] + pref[da[i] + db[i] + dc[i]]);
}
cout << ans << endl;
}
return 0;
}
|
1343
|
F
|
Restore the Permutation by Sorted Segments
|
We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you.
For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \dots, p_r$ in \textbf{sorted} order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.
For example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be:
- $[2, 5, 6]$
- $[4, 6]$
- $[1, 3, 4]$
- $[1, 3]$
- $[1, 2, 4, 6]$
Your task is to find \textbf{any} suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).
You have to answer $t$ independent test cases.
|
Let's fix the first element and then try to restore permutation using this information. One interesting fact: if such permutation exists (with this first element) then it can be restored uniquely. Let's remove the first element from all segments containing it (we can use some logarithmic data structure for it). Then we just have a smaller problem but with one important condition: there is a segment consisting of one element (again, if such permutation exists). So, if the number of segments of length $1$ is zero or more than one by some reason then there is no answer for this first element. Otherwise, let's place this segment (a single element) in second place, remove it from all segments containing it and just solve a smaller problem again. If we succeed with restoring the permutation then we need to check if this permutation really satisfies the given input segments (see the first test case of the example to understand why this case appears). Let's just iterate over all $i$ from $2$ to $n$ and then over all $j$ from $i-1$ to $1$. If the segment $a_j, a_{j+1}, \dots, a_i$ is in the list, remove it and go to the next $i$. If we can't find the segment for some $i$ then this permutation is wrong. Time complexity: $O(n^3 \log n)$ (or less, maybe?)
|
[
"brute force",
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<set<int>> segs;
for (int i = 0; i < n - 1; ++i) {
set<int> cur;
int k;
cin >> k;
for (int j = 0; j < k; ++j) {
int x;
cin >> x;
cur.insert(x);
}
segs.push_back(cur);
}
for (int fst = 1; fst <= n; ++fst) {
vector<int> ans;
bool ok = true;
vector<set<int>> cur = segs;
for (auto &it : cur) if (it.count(fst)) it.erase(fst);
ans.push_back(fst);
for (int i = 1; i < n; ++i) {
int cnt1 = 0;
int nxt = -1;
for (auto &it : cur) if (it.size() == 1) {
++cnt1;
nxt = *it.begin();
}
if (cnt1 != 1) {
ok = false;
break;
}
for (auto &it : cur) if (it.count(nxt)) it.erase(nxt);
ans.push_back(nxt);
}
if (ok) {
set<set<int>> all(segs.begin(), segs.end());
for (int i = 1; i < n; ++i) {
set<int> seg;
seg.insert(ans[i]);
bool found = false;
for (int j = i - 1; j >= 0; --j) {
seg.insert(ans[j]);
if (all.count(seg)) {
found = true;
all.erase(seg);
break;
}
}
if (!found) ok = false;
}
}
if (ok) {
for (auto it : ans) cout << it << " ";
cout << endl;
break;
}
}
}
return 0;
}
|
1344
|
A
|
Hilbert's Hotel
|
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, \textbf{including zero and negative integers}. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).
For any integer $k$ and positive integer $n$, let $k\bmod n$ denote the remainder when $k$ is divided by $n$. More formally, $r=k\bmod n$ is the smallest non-negative integer such that $k-r$ is divisible by $n$. It always holds that $0\le k\bmod n\le n-1$. For example, $100\bmod 12=4$ and $(-1337)\bmod 3=1$.
Then the shuffling works as follows. There is an array of $n$ integers $a_0,a_1,\ldots,a_{n-1}$. Then for each integer $k$, the guest in room $k$ is moved to room number $k+a_{k\bmod n}$.
After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.
|
Suppose that $i+a_i\equiv j+a_j\pmod{n}$ for some $0\le i<j<n$. Then $i+a_i=j+a_j+kn$ for some integer $k$, so the guest in room $i$ is assigned the same room as guest $j+kn$. Similarly, suppose that two different guests $k$ and $m$ are assigned the same room. Then we have $i+a_i\equiv j+a_j\pmod{n}$ for $i=k\bmod n$ and $j=m\bmod n$. This proves there is a collision if and only if all $i+a_i$ are not distinct $\pmod n$. That is, $\{(0+a_0)\bmod n,(1+a_1)\bmod n,\ldots,(n-1+a_{n-1})\bmod n\}=\{0,1,\ldots,n-1\}$. This is simply checked with a boolean array to make sure each number from $0$ to $n-1$ is included. Note that there are also no vacancies if this condition holds: Let $k$ be some room. Then $k\bmod n$ must appear in the array, so there is some $i$ with $i+a_i\equiv k\pmod n$. Then there is an integer $m$ with $i+mn+a_i=k$, meaning guest $i+mn$ is moved to room $k$. Complexity is $O(n)$.
|
[
"math",
"number theory",
"sortings"
] | 1,600
| null |
1344
|
B
|
Monopole Magnets
|
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an $n\times m$ grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
- There is at least one south magnet in every row and every column.
- If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations \textbf{from the initial placement}.
- If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations \textbf{from the initial placement}.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
|
Suppose two cells $A$ and $B$ are colored black in the same row. Since there must be a south magnet in every row, there are segments of black cells from $A$ and $B$ to the cell with the south magnet. The same result holds for columns. Therefore, for a solution to exist, every row and every column has exactly one segment of black cells or is all-white. Suppose there is an all-white row, but not an all-white column. (Or similarly, an all-white column but not an all-white row.) Then wherever we place a south magnet in this row, its column will have a black cell. But then the south magnet would be reachable, contradicting the fact that the row is all-white. Therefore, there should be an all-white row if and only if there is an all-white column, or no solution exists. Now that we have excluded these cases where no solution exists, let's construct a solution. Place a south magnet in a cell if: The cell is colored black, or Its row and column are both all-white. Then place one north magnet in each connected component of black cells. A north magnet cannot travel between components, so this is optimal.
|
[
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs"
] | 2,000
| null |
1344
|
C
|
Quantifier Question
|
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. \textbf{The set of real numbers includes zero and negatives.} There are two kinds of quantifiers: universal ($\forall$) and existential ($\exists$). You can read more about them here.
The universal quantifier is used to make a claim that a statement holds for all real numbers. For example:
- $\forall x,x<100$ is read as: for all real numbers $x$, $x$ is less than $100$. This statement is false.
- $\forall x,x>x-1$ is read as: for all real numbers $x$, $x$ is greater than $x-1$. This statement is true.
The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example:
- $\exists x,x<100$ is read as: there exists a real number $x$ such that $x$ is less than $100$. This statement is true.
- $\exists x,x>x-1$ is read as: there exists a real number $x$ such that $x$ is greater than $x-1$. This statement is true.
Moreover, these quantifiers can be nested. For example:
- $\forall x,\exists y,x<y$ is read as: for all real numbers $x$, there exists a real number $y$ such that $x$ is less than $y$. This statement is true since for every $x$, there exists $y=x+1$.
- $\exists y,\forall x,x<y$ is read as: there exists a real number $y$ such that for all real numbers $x$, $x$ is less than $y$. This statement is false because it claims that there is a maximum real number: a number $y$ larger than every $x$.
\textbf{Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.}
There are $n$ variables $x_1,x_2,\ldots,x_n$, and you are given some formula of the form $$ f(x_1,\dots,x_n):=(x_{j_1}<x_{k_1})\land (x_{j_2}<x_{k_2})\land \cdots\land (x_{j_m}<x_{k_m}), $$
where $\land$ denotes logical AND. That is, $f(x_1,\ldots, x_n)$ is true if every inequality $x_{j_i}<x_{k_i}$ holds. Otherwise, if at least one inequality does not hold, then $f(x_1,\ldots,x_n)$ is false.
Your task is to assign quantifiers $Q_1,\ldots,Q_n$ to either universal ($\forall$) or existential ($\exists$) so that the statement $$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$
is true, and \textbf{the number of universal quantifiers is maximized}, or determine that the statement is false for every possible assignment of quantifiers.
\textbf{Note that the order the variables appear in the statement is fixed.} For example, if $f(x_1,x_2):=(x_1<x_2)$ then you are not allowed to make $x_2$ appear first and use the statement $\forall x_2,\exists x_1, x_1<x_2$. If you assign $Q_1=\exists$ and $Q_2=\forall$, it will \textbf{only} be interpreted as $\exists x_1,\forall x_2,x_1<x_2$.
|
Build a directed graph of variables, where an edge $x_i\to x_j$ corresponds to an inequality $x_i<x_j.$ Say that two variables are comparable if there is a directed path from one variable to the other. Suppose $x_i$ and $x_j$ are comparable with $i<j$. Then $x_j$ cannot be universal since $x_i$ is determined before $x_j$ in the order and their comparability restricts the value of $x_j$. So, a requirement for universality is that the variable is only comparable with larger-indexed variables. If there is a cycle of inequalities, then there is no solution since the formula is contradictory. Otherwise, the graph is acyclic, so we can find a topological order. For each variable, we can find the minimum index of a node comparable to it by doing DP in forward and reverse topological order. Then for every variable not comparable to a smaller indexed variable, let it be universal. All other variables must be existential. Our requirement of universality proves this is optimal. Let's prove this assignment gives a true statement (other than proof by AC). First, we can decrease the index of existential variables, which only strengthens the statement. So let's decrease the index of each existential variable to appear just after its largest-indexed comparable universal variable. An existential variable $x_i$ may be comparable to many universal variables, but $x_i$ must be either greater than them all or less than them all. (Otherwise, we would have two comparable universals.) Without loss of generality, say $x_i$ is greater than its comparable universals. And suppose $x_i$ is less than another existential variable $x_j$. Then $x_j$ is comparable to the same universals as $x_i$, so we can determine the value of $x_j$ later such that it depends on $x_i$. Therefore, each existential variable is only restricted by a lower bound or an upper bound of smaller-indexed variables. We can properly assign values to them, satisfying all inequalities.
|
[
"dfs and similar",
"dp",
"graphs",
"math"
] | 2,600
| null |
1344
|
D
|
Résumé Review
|
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)
You have completed many programming projects. In fact, there are exactly $n$ types of programming projects, and you have completed $a_i$ projects of type $i$. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.
You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:
$$ f(b_1,\ldots,b_n)=\sum\limits_{i=1}^n b_i(a_i-b_i^2). $$
Here, $b_i$ denotes the number of projects of type $i$ you include in your résumé. Of course, you cannot include more projects than you have completed, so you require $0\le b_i \le a_i$ for all $i$.
Your résumé only has enough room for $k$ projects, and you will absolutely not be hired if your résumé has empty space, so you require $\sum\limits_{i=1}^n b_i=k$.
Find values for $b_1,\ldots, b_n$ that maximize the value of $f(b_1,\ldots,b_n)$ while satisfying the above two constraints.
|
If we increment some $b_i$ to $x$, the value of $f$ changes by $\Delta_i (x):=\left[x(a_i-x^2)\right]-\left[(x-1)(a_i-(x-1)^2)\right]=a_i-3x^2+3x-1,$ which decreases for $x\ge 1.$ If we initially set all $b_i$ to $0$, then greedily incrementing the best index gives an optimal solution. Since $k$ is large, we cannot afford to do this one increment at a time. However, we can observe that this process increments the values as long as $\Delta_i (x)\ge A$ for some constant $A$. Simply binary search on the value of $A$ so that we increment exactly $k$ times. To compute the cutoffs for the $x$ values, we can either use the quadratic formula or do another binary search. There may be ties for the $\Delta_i(x)$ values, but this can be handled without too much trouble. Let $A=\max_{i=1,\ldots,n}\{a_i\}$. Complexity is $O(n\log(A))$ with the quadratic formula, or $O(n\log^2(A))$ with another binary search.
|
[
"binary search",
"greedy",
"math"
] | 2,700
| null |
1344
|
E
|
Train Tracks
|
That's right. I'm a Purdue student, and I shamelessly wrote a problem about trains.
There are $n$ stations and $m$ trains. The stations are connected by $n-1$ one-directional railroads that form a tree rooted at station $1$. All railroads are pointed in the direction from the root station $1$ to the leaves. A railroad connects a station $u$ to a station $v$, and has a distance $d$, meaning it takes $d$ time to travel from $u$ to $v$. Each station with at least one outgoing railroad has a switch that determines the child station an incoming train will be directed toward. For example, it might look like this:
\begin{center}
Here, stations $1$ and $3$ have switches directed toward stations $2$ and $4$, respectively.
\end{center}
Initially, no trains are at any station. Train $i$ will enter station $1$ at time $t_i$. Every unit of time, starting at time $1$, the following two steps happen:
- You can switch at most one station to point to a different child station. A switch change takes effect before step $2$.
- For every train that is on a station $u$, it is directed toward the station $v$ indicated by $u$'s switch. So, if the railroad from $u$ to $v$ has distance $d$, the train will enter station $v$ in $d$ units of time from now.
Every train has a destination station $s_i$. When it enters $s_i$, it will stop there permanently. If at some point the train is going in the wrong direction, so that it will never be able to reach $s_i$ no matter where the switches point, it will immediately explode.
Find the \textbf{latest possible time of the first explosion} if you change switches optimally, or determine that you can direct every train to its destination so that no explosion occurs. Also, find the \textbf{minimum number of times you need to change a switch} to achieve this.
|
First, observe that a train can never pass one that enters earlier. So let's consider the trains independently. For a train $i$, look at the path from $1$ to $s_i$. We may need to change the switches of several stations on this path. We must make each switch within a time interval $(L, R]$, where $L$ is the most recent time some other train was directed the other way, and $R$ is the time train $i$ will enter the station. Let's mark all of these switches as changed before processing the next train. Suppose the total number of switch changes is $k$, and for each station, we know its time intervals. We can manage all events in a priority queue of size $n$, always changing the switch with the earliest deadline that we can. Keep doing this until we are too late for a deadline, in which case an explosion happens, or until we have successfully made every switch change. This part will take $O(k\log n)$ time. Let's find a nice upper bound on $k$. Note that the switches decompose the tree into a set of disjoint paths. When we process a train $i$, we are changing the switches to make a path from the root to $s_i$. It turns out this is exactly the same as an access operation on a link/cut tree! Because link/cut trees have $O(\log n)$ amortized time per operation, we can guarantee that the total number of switch changes is $k=O(n+m\log n)$. Now let's consider the problem of finding all time intervals. We could use a link/cut tree, but everyone hates those, so let's discuss other methods. One strategy is to maintain a list of trains that go through a station, for every station. We start at the leaves and merge the lists going up. We can merge the lists efficiently by inserting elements from the smaller list to the larger list. Then a switch only needs to be changed when consecutive trains go to different children. Unlike some of the testers, I wasn't smart enough to come up with the elegant small-to-large merging idea. So let's discuss an alternate solution using segment trees. When processing a train $i$, we want to do the following: Find the top node $x$ of the path leading to $s_i$. If $x$ is not the root, make the parent of $x$ point to $x$, and record the time interval we must make this switch. Repeat from step $1$ until $x$ is the root. The queries we want to support are thus: Find the time the most recent train passed through a node $x$ (ignoring trains with $s_i=x,$ where it only stops at $x$). Find the top node of the path containing node $x$. Let's handle queries of type $1$ with a segment tree. After processing train $i$, update the value at index $s_i$ to $i$. To answer a query, find the maximum value in the range corresponding to the relevant subtree. Let's also handle queries of type $2$ with a segment tree. At a segment tree node, store the minimum value on its range. To answer a query, check the range $[x,x]$. Support lazy updates of the form "On a range $[l, r]$, replace all values $X$ with value $Y$, with the precondition that $X$ is currently the minimum value in $[l,r]$ and $Y$ will remain the minimum value after the update". To make a switch change, we only need to do two lazy updates. Therefore, finding all the time intervals will take $O((m+k)\log n)$ time. The overall complexity is $O(n\log n+m\log^2 n)$.
|
[
"data structures",
"trees"
] | 3,100
| null |
1344
|
F
|
Piet's Palette
|
Piet Mondrian is an artist most famous for his minimalist works, consisting only of the four colors red, yellow, blue, and white. Most people attribute this to his style, but the truth is that his paint behaves in a very strange way where mixing two primary colors only produces another primary color!
\begin{center}
A lesser known piece, entitled "Pretentious rectangles"
\end{center}
A sequence of primary colors (red, yellow, blue) is mixed as follows. While there are at least two colors, look at the first two. If they are distinct, replace them with the missing color. If they are the same, remove them from the sequence. In the end, if there is one color, that is the resulting color. Otherwise, if the sequence is empty, we say the resulting color is white. Here are two example mixings:
Piet has a color palette with cells numbered from $1$ to $n$. Each cell contains a primary color or is empty. Piet is very secretive, and will not share his palette with you, so you do not know what colors belong to each cell.
However, he did perform $k$ operations. There are four kinds of operations:
- In a \textbf{mix} operation, Piet chooses a subset of cells and mixes their colors together in some order. The order is not necessarily by increasing indexes. He records the resulting color. Empty cells are skipped over, having no effect on the mixing process. The mixing does not change the color values stored in the cells.
- In a \textbf{RY} operation, Piet chooses a subset of cells. Any red cells in this subset become yellow, and any yellow cells in this subset become red. Blue and empty cells remain unchanged.
- In a \textbf{RB} operation, Piet chooses a subset of cells. Any red cells in this subset become blue, and any blue cells in this subset become red. Yellow and empty cells remain unchanged.
- In a \textbf{YB} operation, Piet chooses a subset of cells. Any yellow cells in this subset become blue, and any blue cells in this subset become yellow. Red and empty cells remain unchanged.
Piet only tells you the list of operations he performs in chronological order, the indexes involved, and the resulting color of each mix operation. For each mix operation, you also know the order in which the cells are mixed. Given this information, determine the color of each cell in the initial palette. That is, you should find one possible state of the palette (before any operations were performed), or say that the described situation is impossible.
|
Equate an empty cell with the color white, and let's represent the colors as 0/1 vectors: $W=\begin{bmatrix}0\\0\end{bmatrix},\ R=\begin{bmatrix}1\\0\end{bmatrix},\ Y=\begin{bmatrix}0\\1\end{bmatrix},\ B=\begin{bmatrix}1\\1\end{bmatrix}.$ Under this representation, mixing becomes addition $\pmod{2}$. And the operations $\mathrm{RY}$, $\mathrm{RB}$, $\mathrm{YB}$ are linear transformations of the colors. That is, each of these operations is equivalent to multiplying the corresponding matrix by a cell's vector: $\mathrm{RY}=\begin{bmatrix}0&1\\1&0\end{bmatrix},\ \mathrm{RB}=\begin{bmatrix}1&0\\1&1\end{bmatrix},\ \mathrm{YB}=\begin{bmatrix}1&1\\0&1\end{bmatrix}.$ We simply have a system of $2k$ linear equations on $2n$ unknowns, which we can solve with Gaussian elimination using bitsets. Complexity is $O((2k)^2 (2n) / 64).$
|
[
"matrices"
] | 3,200
| null |
1345
|
A
|
Puzzle Pieces
|
You are given a special jigsaw puzzle consisting of $n\cdot m$ identical pieces. Every piece has three tabs and one blank, as pictured below.
The jigsaw puzzle is considered solved if the following conditions hold:
- The pieces are arranged into a grid with $n$ rows and $m$ columns.
- For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece.
Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.
|
If $n=1$ or $m=1$, then we can chain the pieces together to form a solution. If $n=m=2$, we can make the following solution: Any other potential solution would contain a $2\times 3$ or a $3\times 2$ solution, which we can show is impossible. A $2\times 3$ grid has $7$ shared edges between the pieces, and each shared edge must have a blank. But there are only $6$ blanks available as there are $6$ pieces.
|
[
"math"
] | 800
| null |
1345
|
B
|
Card Constructions
|
A card pyramid of height $1$ is constructed by resting two cards against each other. For $h>1$, a card pyramid of height $h$ is constructed by placing a card pyramid of height $h-1$ onto a base. A base consists of $h$ pyramids of height $1$, and $h-1$ cards on top. For example, card pyramids of heights $1$, $2$, and $3$ look as follows:
You start with $n$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?
|
Let's count the number of cards in a pyramid of height $h$. There are $2(1+2+3+\cdots+h)$ cards standing up, and there are $0+1+2+\cdots+(h-1)$ horizontal cards. So, there are $2\frac{h(h+1)}{2}+\frac{(h-1)h}{2}=\frac{3}{2}h^2+\frac12 h$ cards total. Using this formula, we can quickly find the largest height $h$ that uses at most $n$ cards. The quadratic formula or binary search can be used here, but are unnecessary. Simply iterating through all $h$ values works in $O(\sqrt n)$ time per test. It's enough to see that this takes $O(t\sqrt N)$ time overall, where $N$ is the sum of $n$ across all test cases. But interestingly, we can argue for a tighter bound of $O(\sqrt{tN})$ due to the Cauchy-Schwarz Inequality: $\sum_{i=1}^t \left(1\cdot \sqrt{n_i}\right)\le \sqrt{\left(\sum_{i=1}^t1^2\right)\left(\sum_{i=1}^t\left(\sqrt n_i\right)^2\right)}=\sqrt{tN}$
|
[
"binary search",
"brute force",
"dp",
"math"
] | 1,100
| null |
1348
|
A
|
Phoenix and Balance
|
Phoenix has $n$ coins with weights $2^1, 2^2, \dots, 2^n$. He knows that $n$ is even.
He wants to split the coins into two piles such that each pile has exactly $\frac{n}{2}$ coins and the difference of weights between the two piles is \textbf{minimized}. Formally, let $a$ denote the sum of weights in the first pile, and $b$ denote the sum of weights in the second pile. Help Phoenix minimize $|a-b|$, the absolute value of $a-b$.
|
We observe that the coin with the weight $2^n$ is greater than the sum of all the other weights combined. This is true because $\sum\limits_{i = 1}^{n-1}2^i=2^n-2$. Therefore, the pile that has the heaviest coin will always weigh more. To minimize the weight differences, we put the $n/2-1$ lightest coins into the pile with the heaviest coin. The answer will be $(2^n+\sum\limits_{i = 1}^{n/2-1}2^i)-\sum\limits_{i = n/2}^{n-1}2^i$. Time complexity for each test case: $O(n)$ You can also solve the problem in $O(1)$ by simplifying the mathematical expression.
|
[
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
int N;
cin>>N;
//note: 1<<X means 2^X
//we put largest coin in first pile
int sum1=(1<<N), sum2=0;
//we put n/2-1 smallest coins in first pile
for (int i=1;i<N/2;i++)
sum1+=(1<<i);
//we put remaining n/2 coins in second pile
for (int i=N/2;i<N;i++)
sum2+=(1<<i);
cout<<sum1-sum2<<endl;
}
int main(){
int t; cin>>t;
while (t--)
solve();
}
|
1348
|
B
|
Phoenix and Beauty
|
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $k$ have the same sum. A subarray of an array is any sequence of consecutive elements.
Phoenix currently has an array $a$ of length $n$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $1$ and $n$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is \textbf{not trying} to minimize the number of inserted integers.
|
For an array to be beautiful for some $k$, the array must be periodic with period $k$. If there exists more than $k$ distinct numbers in the array $a$, there is no answer and we print -1 (because the array cannot be periodic with period $k$). Otherwise, we propose the following construction. Consider a list of all the distinct numbers in array $a$. If there are less than $k$ of them, we will append some $1$s (or any other number) until the list has size $k$. We can just print this list $n$ times. The length of our array $b$ is $nk$, which never exceeds $10^4$. Array $b$ can always be constructed by inserting some numbers into array $a$ because every number in $a$ corresponds to one list. Time complexity for each test case: $O(n \log{n}+nk)$
|
[
"constructive algorithms",
"data structures",
"greedy",
"sortings"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
int N,K;
cin>>N>>K;
set<int>s;
for (int i=0;i<N;i++){
int a;
cin>>a;
s.insert(a);
}
//if more than K distinct numbers, print -1
if (s.size()>K){
cout<<-1<<endl;
return;
}
cout<<N*K<<endl;
for (int i=0;i<N;i++){
//print the distinct numbers
for (int b:s)
cout<<b<<' ';
//print the extra 1s
for (int j=0;j<K-(int)s.size();j++)
cout<<1<<' ';
}
cout<<endl;
}
int main(){
int t; cin>>t;
while (t--)
solve();
}
|
1348
|
C
|
Phoenix and Distribution
|
Phoenix has a string $s$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $k$ \textbf{non-empty} strings $a_1, a_2, \dots, a_k$ such that every letter of $s$ goes to exactly one of the strings $a_i$. The strings $a_i$ \textbf{do not} need to be substrings of $s$. Phoenix can distribute letters of $s$ and rearrange the letters within each string $a_i$ however he wants.
For example, if $s = $ baba and $k=2$, Phoenix may distribute the letters of his string in many ways, such as:
- ba and ba
- a and abb
- ab and ab
- aa and bb
But these ways are invalid:
- baa and ba
- b and ba
- baba and empty string ($a_i$ should be non-empty)
Phoenix wants to distribute the letters of his string $s$ into $k$ strings $a_1, a_2, \dots, a_k$ to \textbf{minimize} the lexicographically maximum string among them, i. e. minimize $max(a_1, a_2, \dots, a_k)$. Help him find the optimal distribution and print the minimal possible value of $max(a_1, a_2, \dots, a_k)$.
String $x$ is lexicographically less than string $y$ if either $x$ is a prefix of $y$ and $x \ne y$, or there exists an index $i$ ($1 \le i \le min(|x|, |y|))$ such that $x_i$ < $y_i$ and for every $j$ $(1 \le j < i)$ $x_j = y_j$. Here $|x|$ denotes the length of the string $x$.
|
We first try to assign one letter to each string $a_i$. Let's denote the smallest letter in $s$ as $c$. If there exists at least $k$ occurrences of $c$ in $s$, we will assign $c$ as the first letter of each string $a_i$. Otherwise, the minimal solution is the $k$th smallest letter in $s$. For example, if $s=$aabbb and $k=3$, the $3$rd smallest letter is $b$ and that will be the answer. Otherwise, we consider the letters that are left in $s$. If they are all the same letter (or there are no letters left because $n=k$), we split the remaining letters as evenly as possible among $a_i$. If not, we will show that it is optimal to sort the remaining letters in $s$ and append them to arbitrary $a_i$. For example, let's suppose after assigning a letter to each $a_i$ that the remaining letters in $s$ are aaabb. We want to assign the $b$s as late as possible, so any string $a_i$ that receives a $b$ should have some number of $a$s before. It makes sense in fact that the string that receives a $b$ should receive all the $a$s, because if not it will be lexicographically larger. It can then be shown that all remaining larger letters should be sorted and added to the same string $a_i$ to minimize the answer. Time complexity for each test case: $O(n \log{n})$ (for sorting $s$)
|
[
"constructive algorithms",
"greedy",
"sortings",
"strings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
int n,k;
cin>>n>>k;
string s;
cin>>s;
sort(s.begin(),s.end());
//if smallest k letters are not all the same, answer is kth smallest letter
if (s[0]!=s[k-1]){
cout<<s[k-1]<<endl;
return;
}
cout<<s[0];
//if remaining letters aren't the same, we append remaining letters to answer
if (s[k]!=s[n-1]){
for (int i=k;i<n;i++)
cout<<s[i];
}
else{
//remaining letters are the same, so we distribute evenly
for (int i=0;i<(n-k+k-1)/k;i++)
cout<<s[n-1];
}
cout<<endl;
}
int main(){
int t; cin>>t;
while (t--)
solve();
}
|
1348
|
D
|
Phoenix and Science
|
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.
Initially, on day $1$, there is one bacterium with mass $1$.
Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $m$ splits, it becomes two bacteria of mass $\frac{m}{2}$ each. For example, a bacterium of mass $3$ can split into two bacteria of mass $1.5$.
Also, every night, the mass of every bacteria will increase by one.
Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $n$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!
|
There exists many constructive solutions, here is one I think is very elegant. We will try to approach the problem by considering how much the total mass increases every night. If there are $x$ bacteria some day before the splitting, that night can have a mass increase between $x$ and $2x$ inclusive (depending on how many bacteria split that day). Therefore, we can reword the problem as follows: construct a sequence $a$ of minimal length $a_0=1, a_1, \dots, a_k$ such that $a_i \le a_{i+1} \le 2a_i$ and the sum of $a_i$ is $n$. To minimize the length of sequence $a$, we will start building our sequence with $1, 2, \dots, 2^x$ such that the total sum $s$ is less than or equal to $n$. If the total sum is $n$, we are done. Otherwise, we insert $n-s$ into our sequence and sort. This gives a valid sequence of minimal length. To transform our sequence $a$ into the answer, we can just print the differences $a_i-a_{i-1}$ because the number of bacteria that split during the day is equal to how much the mass increase changes. Time complexity for each test case: $O(\log{n})$, if you sort by insertion
|
[
"binary search",
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
void solve(){
vector<int>inc;
int N;
cin>>N;
//construct sequence 1, 2, 4, ... while sum <= N
for (int i=1;i<=N;i*=2){
inc.push_back(i);
N-=i;
}
//if sum is not N, we insert and sort
if (N>0){
inc.push_back(N);
sort(inc.begin(),inc.end());
}
cout<<inc.size()-1<<endl;
for (int i=1;i<(int)inc.size();i++)
cout<<inc[i]-inc[i-1]<<' ';
cout<<endl;
}
int main(){
int t; cin>>t;
while (t--)
solve();
}
|
1348
|
E
|
Phoenix and Berries
|
Phoenix is picking berries in his backyard. There are $n$ shrubs, and each shrub has $a_i$ red berries and $b_i$ blue berries.
Each basket can contain $k$ berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a basket must be from the same shrub or/and have the same color.
For example, if there are two shrubs with $5$ red and $2$ blue berries in the first shrub and $2$ red and $1$ blue berries in the second shrub then Phoenix can fill $2$ baskets of capacity $4$ completely:
- the first basket will contain $3$ red and $1$ blue berries from the first shrub;
- the second basket will contain the $2$ remaining red berries from the first shrub and $2$ red berries from the second shrub.
Help Phoenix determine the maximum number of baskets he can \textbf{fill completely}!
|
Solution 1: There is no obvious greedy solution, so we will try dynamic programming. Let $dp[i][j]$ be a boolean array that denotes whether we can have $j$ extra red berries after considering the first $i$ shrubs. A berry is extra if it is not placed into a full basket (of any kind). Note that if we know that there are $j$ extra red berries, we can also easily calculate how many extra blue berries there are. Note that we can choose to never have more than $k-1$ extra red berries, because otherwise we can fill some number of baskets with them. To transition from shrub $i-1$ to shrub $i$, we loop over all possible values $l$ from $0$ to $min(k-1, a_i)$ and check whether or not we can leave $l$ extra red berries from the current shrub $i$. For some $i$ and $j$, we can leave $l$ extra red berries and put the remaining red berries in baskets possibly with blue berries from the same shrub if $(a_i-l)$ $mod$ $k+b_i \ge k$. The reasoning for this is as follows: First of all, we are leaving $l$ red berries (or at least trying to). We show that from this shrub, there will be at most one basket containing both red and blue berries (all from this shrub). To place the remaining red berries into full baskets, the more blue berries we have the better. It is optimal to place the remaining $a_i-l$ red berries into their own separate baskets first before merging with the blue berries (this way requires fewest blue berries to satisfy the condition). Then, if $(a_i-l)$ $mod$ $k+b_i$ is at least $k$, we can fill some basket with the remaining red berries and possibly some blue berries. Remember that we do not care about how many extra blue berries we leave because that is uniquely determined by the number of extra red berries. Also note that we can always leave $a_i$ $mod$ $k$ extra red berries. Denote the total number of berries as $t$. The answer will be maximum over all $(t-j)/k$ such that $dp[n][j]$ is true, $0\le j\le k-1$. Time Complexity: $O(nk^2)$ Solution 2: We use dynamic programming. Let $dp[i][j]$ be true if after considering the first $i$ shrubs , $j$ is the number of red berries in heterogenous baskets modulo $k$. Heterogenous baskets contain berries from the same shrub, and homogenous baskets contain berries of the same type. Suppose we know the number of red berries in heterogeneous baskets modulo $k$. This determines the number of blue berries in heterogeneous baskets modulo $k$. Since the number of red berries in homogeneous baskets is a multiple of $k$, it also determines the number of red berries not in any baskets (we can safely assume this to be less than $k$ since otherwise we can form another basket). Similarly, we can determine the number of blue berries not in any basket, and thus deduce the number of baskets. To compute the possible numbers of red berries in heterogeneous baskets modulo $k$, it suffices to look at each shrub separately and determine the possible numbers of red berries modulo $k$ in heterogeneous baskets for that shrub. If there is more than one heterogeneous basket for one shrub, we can rearrange the berries to leave at most one heterogeneous. Now we have two cases. If there are no heterogeneous baskets, the number of red berries in those baskets is obviously zero. If there is one heterogeneous basket, let $x$ be the number of red berries in it and $k-x$ be the number of blue berries in it. Clearly, $0\le x \le a_i$ and $0 \le k-x \le b_i$. Rearranging, we get $max(0,k-b_i)\le x \le min(a_i,k)$. These correspond to the transitions for our DP. There exists faster solutions (like $O(nk)$), can you find it?
|
[
"brute force",
"dp",
"greedy",
"math"
] | 2,400
|
//Solution 1
#include <bits/stdc++.h>
using namespace std;
int N,K;
int a[505],b[505];
bool dp[505][505]; //number of shrubs considered, "extra" red berries
int main(){
cin>>N>>K;
long long totA=0,totB=0;
for (int i=1;i<=N;i++){
cin>>a[i]>>b[i];
totA+=a[i];
totB+=b[i];
}
dp[0][0]=true;
for (int i=1;i<=N;i++){
for (int j=0;j<K;j++){
//leave a[i]%K extra red berries
dp[i][j]=dp[i-1][(j-a[i]%K+K)%K];
for (int l=0;l<=min(K-1,a[i]);l++){
//check if we can leave l extra red berries
if ((a[i]-l)%K+b[i]>=K)
dp[i][j]|=dp[i-1][(j-l+K)%K];
}
}
}
long long ans=0;
for (int i=0;i<K;i++){
if (dp[N][i])
ans=max(ans,(totA+totB-i)/K);
}
cout<<ans<<endl;
}
|
1348
|
F
|
Phoenix and Memory
|
Phoenix is trying to take a photo of his $n$ friends with labels $1, 2, \dots, n$ who are lined up in a row in a special order. But before he can take the photo, his friends get distracted by a duck and mess up their order.
Now, Phoenix must restore the order but he doesn't remember completely! He only remembers that the $i$-th friend from the left had a label between $a_i$ and $b_i$ inclusive. Does there exist a unique way to order his friends based of his memory?
|
There are many many many solutions to this problem (which is cool!). I describe two of them below. Both solutions first find an arbitrary valid ordering. This can be done in $O(n\log{n})$ with a greedy algorithm. We can sort the intervals $(a_i,b_i)$ and sweep from left to right. To see which position that we can assign friend $j$ to, we process all intervals with $a_i \le j$ and insert $b_i$ into a multiset (or similar) structure. We match friend $j$ to the interval with minimal $b_i$. Solution $1$: We prove that if there exists more than one valid ordering, we can transform one into another by swapping two friends. Proof: In our valid ordering, each friend is assigned a position. We can think of this as a point being assigned to an interval (Friend - point, position - interval). We will prove there exists a cycle of length $2$ or there exists no cycle at all. Suppose we have a cycle: each point is on its interval and its predecessor's interval. Let's take the shortest cycle of length at least two. Let $q$ be the leftmost point, $p$ be $q$'s predecessor, and $r$ be $q$'s successor. Case $1$: $q$'s interval's right endpoint is to the right of $p$. $p$ and $q$ form a cycle of length $2$. Case $2$: $q$'s interval's right endpoint is to the left of $p$. $r$ must be between $q$ and $p$. So, we can remove $q$ and get a shorter cycle. This is a contradiction. $\square$ Denote $p_i$ as the position that friend $i$ is assigned to in our arbitrary ordering. Now, we are interested whether or not there exists a friend $i$ such that there also exists some friend $j$ with $p_j$ such that $p_i < p_j \le b_{p_i}$ and $a_{p_j} \le p_i$. If there does, we can swap friends $i$ and $j$ to make another valid ordering. This can be done with a segment tree (build it with values $a_i$). Time Complexity: $O(n \log n)$ Solution $2$: The problem is equivalent to checking if there is a unique perfect matching in the following bipartite graph: The vertices on the left correspond to position. The vertices on the right correspond to labels of the friends. A directed edge from a position node to a label node exists iff the friend with that label can be at that position. Find a perfect matching (corresponding to finding any valid assignment) as described above. The matching is unique iff contracting the edges (merging nodes connected by edges from our perfect matching into one node) in the perfect matching creates a DAG. The reasoning is as follows: Consider a simpler graph, with only nodes representing positions. We draw a directed edge from node $i$ to node $j$ if the friend currently assigned at position $i$ (from our greedy) can also be assigned to position $j$. So, if there exists any cycle, we can shift the friends around the cycle to create another valid ordering. In other words, if our graph is a DAG, the perfect matching is unique. Now, returning back to the bipartite graph, we see that it is essentially the same. By contracting edges, all position nodes are equivalent to the friend node that is assigned to them (from the greedy). So, following an edge from the left side (position) to the right side (friend) puts us back on the left side (position), and this graph corresponds to the simpler version I explained above. So, this can be done by DFS in $O(n^2)$, but this is too slow. We can speed it up by storing a set of unvisited vertices and only iterating across those (by binary search on set-like structure). Binary search works because every position corresponds to a range of friends. Time Complexity: $O(n \log{n})$
|
[
"data structures",
"dfs and similar",
"graphs",
"greedy"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
int N;
int a[200005],b[200005];
int label[200005]; //the label of the person at i-th position in our perfect matching
int label2[200005]; //which position the i-th person is at
void perfectMatch(){ //finds a perfect matching
deque<pair<pair<int,int>,int>>v;
for (int i=1;i<=N;i++)
v.push_back({{a[i],b[i]},i});
sort(v.begin(),v.end());
multiset<pair<int,int>>mst;
for (int i=1;i<=N;i++){
while ((int)v.size()>0 && v[0].first.first<=i){
mst.insert({v[0].first.second,v[0].second});
v.pop_front();
}
//match person with label to earliest ending interval
label2[i]=mst.begin()->second;
label[mst.begin()->second]=i;
mst.erase(mst.find(*mst.begin()));
}
}
set<int>active;
int vis[200005];
int from[200005];
int ans[200005];
void foundAnother(int node, int nextNode){
vector<int>v;
int cur=node;
//backtracks on cycle to find other ordering
while (cur!=label2[nextNode]){
v.push_back(cur);
cur=from[cur];
}
reverse(v.begin(),v.end());
v.push_back(label2[nextNode]);
reverse(v.begin(),v.end());
cout<<"NO"<<endl;
for (int i=1;i<=N;i++)
cout<<label[i]<<' ';
cout<<endl;
for (int i=1;i<=N;i++)
ans[i]=label[i];
int temp=ans[v.back()];
for (int i=0;i<(int)v.size();i++)
swap(temp,ans[v[i]]);
for (int i=1;i<=N;i++)
cout<<ans[i]<<' ';
cout<<endl;
exit(0);
}
void dfs(int node){
//activates node
vis[node]=1;
queue<int>toRemove;
for (;;){
//binary search for unvisisited neighbor
auto it=active.lower_bound(a[node]);
if (it!=active.end() && *it==label[node]){
toRemove.push(*it);
it++;
}
if (it==active.end() || *it>b[node])
break;
if (vis[label2[*it]]==1) //found cycle (another ordering)
foundAnother(node,*it);
toRemove.push(*it);
if (vis[label2[*it]]==2)
continue;
from[label2[*it]]=node;
dfs(label2[*it]);
}
//removes visited nodes from set
while (!toRemove.empty()){
if (active.count(toRemove.front()))
active.erase(toRemove.front());
toRemove.pop();
}
//deactivates and retire node
vis[node]=2;
}
int main(){
cin>>N;
for (int i=1;i<=N;i++)
cin>>a[i]>>b[i];
perfectMatch();
for (int i=1;i<=N;i++)
active.insert(i);
for (int i=1;i<=N;i++)
if (vis[i]==0)
dfs(i);
cout<<"YES"<<endl;
for (int i=1;i<=N;i++)
cout<<label[i]<<' ';
cout<<endl;
}
|
1349
|
A
|
Orac and LCM
|
For the multiset of positive integers $s=\{s_1,s_2,\dots,s_k\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow:
- $\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisible on $x$.
- $\textrm{lcm}(s)$ is the minimum positive integer $x$, that divisible on all integers from $s$.
For example, $\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$ and $\textrm{lcm}(\{4,6\})=12$. Note that for any positive integer $x$, $\gcd(\{x\})=\textrm{lcm}(\{x\})=x$.
Orac has a sequence $a$ with length $n$. He come up with the multiset $t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$, and asked you to find the value of $\gcd(t)$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.
|
In this tutorial $p$ stands for a prime, $v$ stands for the maximum of $a_i$ and $ans$ stands for the answer. Observation. $p^k\ \mid\ ans$ if and only if there are at least $n-1$ integers in $a$ that $\mathrm{s.t. }\ p^k\mid\ a_i$. Proof. if there are at most $n-2$ integers in $a$ that $\mathrm{s.t. }\ p^k\mid\ a_i$, there exists $x\neq y$ $\mathrm{s.t.}\ p^k\nmid a_x$ $\mathrm{and}$ $p^k\nmid a_y$, so $p^k \nmid \textrm{lcm}(\{a_x,a_y\})$ and $p^k\ \nmid\ ans$. On the contrary, if there are at least $n-1$ integers in $a$ $\mathrm{s.t. }\ p^k\mid\ a_i$, between every two different $a_i$ there will be at least one multiple of $p^k$. So for every $(x,y)$, $p^k \mid \textrm{lcm}(\{a_x,a_y\})$. Therefore $p^k\ \mid\ ans$. Solution 1. Define $d_i$ as a set that consists of all the numbers in $a$ except $a_i$. So $\gcd(d_i)$ is divisible by at least $n-1$ numbers in $a$. Also, if at least $n-1$ integers in $a$ $\mathrm{s.t. }\ p^k\ \mid\ a_i$, we can always find $i$ $\mathrm{s.t. }\ p^k \mid \gcd(d_i)$. According to the Observation, $ans=\textrm{lcm}(\{\gcd(d_1),\gcd(d_2),\gcd(d_3),...,\gcd(d_n)\})$. Now consider how to calculate $\gcd(d_i)$. For every $i$, calculate $pre_i=\gcd(\{a_1,a_2,...,a_i\})$ and $suf_i=\gcd(\{a_{i},a_{i+1},...,a_n\})$. Therefore $\gcd(d_i)=\gcd(\{pre_{i-1},suf_{i+1}\})$ and we can get $pre$ and $suf$ in $O(n\cdot \log(v))$ time. Time complexity: $O(n \log v)$ Solution 2. Enumerate every prime $\leq v$. For a prime $p$, enumerate every $a_i$ and calculate $k_i$ which stands for the maximum integer that $\mathrm{s.t. }\ p^{k_i} \mid a_i$. According to the Observation, the second smallest $k_i$ is the maximum integer $k$ that $\mathrm{s.t. }\ p^k \mid ans$. Now let's optimize this solution. If there has been at least two $a_i$ not divisible by $p$, then $p \nmid ans$, so just stop enumerate $a_i$. Time complexity of the optimized solution is $O(v+n \log v)$ because every integer can be divided for at most $\log v$ times.
|
[
"data structures",
"math",
"number theory"
] | 1,600
|
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const int maxn=100005;
int n;
ll a[maxn];
ll pre[maxn],suf[maxn];
ll gcd(ll x, ll y)
{
if(y==0) return x;
else return gcd(y,x%y);
}
ll ga,ans;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
pre[1]=a[1]; suf[n]=a[n];
for(int i=2;i<=n;i++)
pre[i]=gcd(pre[i-1],a[i]);
for(int i=n-1;i>=1;i--)
suf[i]=gcd(suf[i+1],a[i]);
for(int i=0;i<=n-1;i++)
{
if(i==0)
ans=suf[2];
else if(i==n-1)
ans=ans*pre[n-1]/gcd(pre[n-1],ans);
else
ans=ans*gcd(pre[i],suf[i+2])/gcd(gcd(pre[i],suf[i+2]),ans);
}
printf("%lld\n",ans);
return 0;
}
|
1349
|
B
|
Orac and Medians
|
Slime has a sequence of positive integers $a_1, a_2, \ldots, a_n$.
In one operation Orac can choose an arbitrary subsegment $[l \ldots r]$ of this sequence and replace all values $a_l, a_{l + 1}, \ldots, a_r$ to the value of median of $\{a_l, a_{l + 1}, \ldots, a_r\}$.
In this problem, for the integer multiset $s$, the median of $s$ is equal to the $\lfloor \frac{|s|+1}{2}\rfloor$-th smallest number in it. For example, the median of $\{1,4,4,6,5\}$ is $4$, and the median of $\{1,7,5,8\}$ is $5$.
Slime wants Orac to make $a_1 = a_2 = \ldots = a_n = k$ using these operations.
Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.
|
Let $B_i=\left\{\begin{aligned} 0,A_i<k\\1,A_i=k\\2,A_i>k\end{aligned} \right.$,then just consider whether it can be done to make all elements in $B$ become $1$ in a finite number of operations. It can be proved that a solution exists if and only if $\exists 1\le i\le n,\mathrm{s.t.}B_i=1$ and $\exists 1\le i<j\le n,\mathrm{s.t.}j-i\le2,B_i>0,B_j>0$ . The necessity is obvious: if $\forall 1\le i\le n, B_i\neq 1$ , no elements in $B$ can be transformed into $1$; If there are at least two zeros between any two positive numbers, then the median of each interval equals to $0$, no solution exists. Consider the sufficiency. If there are two adjacent elements in $B$ both equals to $1$ , just select an interval which contains at least three elements and exact one element unequal to $1$ , and operate once on this interval. After this operation, there are still two adjacent elements in $B$ both equals to $1$, so we keep doing this until all elements are transformed into $1$. Therefore, if there is a interval $[l,r]$ which satisfies $r-l+1\ge2$ and the median of $\{B_l,B_{l+1},\dots,B_r\}$ equals to $1$, just perform an operation on $[l,r]$ , then use the above strategy. It can be shown that such an interval can always be created in several operations with the condition. If an interval $[i,i+2]$ satisfies $\{B_i,B_{i+1},B_{i+2}\}=\{0,1,2\}$ or $\{1,1,2\}$ or $\{0,1,1\}$ or $\{1,1,1\}$,just perform an operation on $[i,i+2]$ . If $[i,i+2]$ satisfies $\{B_i,B_{i+1},B_{i+2}\}=\{1,2,2\}$ , then $\{B_i,B_{i+1}\}=\{1,2\}$ or $\{B_{i+1},B_{i+2}\}=\{1,2\}$ . Perform an operation on $[i,i+1]$ or $[i+1,i+2]$ . If any interval with three elements doesn't satisfy the above conditions, because $\exists 1\le i<j\le n,\mathrm{s.t.}j-i\le2,B_i>0,B_j>0$ ,there is an interval $[i,i+2]$ which satisfies $\{B_i,B_{i+1},B_{i+2}\}=\{0,2,2\}$ or $\{2,2,2\}$ . Take such an interval $[i,i+2]$ , perform an operation on $[i,i+2]$ first, then select an interval which contains at least three elements and exact one element unequal to $2$ until two adjacent numbers equals to $1$ and $2$ respectively. Perform one operation on these two adjacent elements. Therefore, the sufficiency is proved. So just check whether there is an element in $B$ equals to $1$, and whether there is a pair of two positive integers $(i,j)$ which satisfies $1\le j-i\le 2,B_i>0,B_j>0$ . The complexity is $O(n)$.
|
[
"constructive algorithms",
"greedy",
"math"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
#define x first
#define y second
#define mp make_pair
#define pb push_back
template <typename TYPE> inline void chkmax(TYPE &x,TYPE y){x<y?x=y:TYPE();}
template <typename TYPE> inline void chkmin(TYPE &x,TYPE y){y<x?x=y:TYPE();}
template <typename TYPE> void readint(TYPE &x)
{
x=0;int f=1;char c;
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())x=x*10+c-'0';
x*=f;
}
const int MAXN=500005;
int n,k,a[MAXN];
bool solve()
{
readint(n),readint(k);
bool flag=0;
for(int i=1;i<=n;++i)
{
readint(a[i]);
if(a[i]<k)a[i]=0;
else if(a[i]>k)a[i]=2;
else a[i]=1;
if(a[i]==1)flag=1;
}
if(!flag)return 0;
if(n==1)return 1;
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n && j-i<=2;++j)
if(a[i] && a[j])return 1;
return 0;
}
int main()
{
int T;
readint(T);
while(T--)printf(solve()?"yes\n":"no\n");
return 0;
}
|
1349
|
C
|
Orac and Game of Life
|
\textbf{Please notice the unusual memory limit of this problem.}
Orac likes games. Recently he came up with the new game, "Game of Life".
You should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white.
For each iteration of the game (the initial iteration is $0$), the color of each cell will change under the following rules:
- If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same.
- Otherwise, the color of the cell on the next iteration will be different.
Two cells are adjacent if they have a mutual edge.
Now Orac has set an initial situation, and he wants to know for the cell $(i,j)$ (in $i$-th row and $j$-th column), what will be its color at the iteration $p$. He may ask you these questions several times.
|
A cell $(i,j)$ is said to be good if and only if there is a cell $(i',j')$ adjacent to $(i,j)$ which has the same color to $(i,j)$ . If a cell $(i,j)$ is not good, it is said to be bad. Therefore, the color of a cell changes after a turn if and only if the cell is good. According to the definition, any cell never changes its color if every cell is bad. Also, a good cell $(i,j)$ would never turn into a bad cell . For a bad cell $(i,j)$, if there is a good cell $(i',j')$ adjacent to $(i,j)$, $(i,j)$ will turn into a good cell after a turn because $(i',j')$ currently has a different color from $(i,j)$ and the color of $(i',j')$ will change after a turn but the color of $(i,j)$ won't change; otherwise, after a turn, the color of $(i,j)$ and cells adjacent to $(i,j)$ stays the same, so $(i,j)$ is still bad. For a cell $(i,j)$, let $f_{i,j}$ be the number of turns needed for that $(i,j)$ becomes a good cell. According to the paragraph above, $f_{i,j}$ equals to the minimal Manhattan distance from $(i,j)$ to a good cell. Therefore, $f_{i,j}$ can be figured out by BFS. Notice that for $k \le f_{i,j}$ , the color of $(i,j)$ stays the same after the $k$-th turn; for $k>f_{i,j}$ , the color of $(i,j)$ changes after the $k$-th turn. Therefore, each query can be processed with $O(1)$ time complexity. The total time complexity is $O(nm+t)$ . P.S. R.I.P. John Horton Conway, you are a great mathematician that should be remembered forever.
|
[
"dfs and similar",
"graphs",
"implementation",
"shortest paths"
] | 2,000
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define pii pair<int,int>
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
const int MAXN = 1005;
inline ll readint()
{
ll res = 0, f = 1;
char c = 0;
while(!isdigit(c))
{
c = getchar();
if(c=='-')
f = -1;
}
while(isdigit(c))
res = res*10+c-'0', c = getchar();
return res*f;
}
int n,m,T,a[MAXN][MAXN];
char str[MAXN];
int f[MAXN][MAXN],pos[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
bool vis[MAXN][MAXN];
inline bool check(int x, int y)
{
for(int i = 0; i<4; i++)
{
int nx = x+pos[i][0], ny = y+pos[i][1];
if(a[nx][ny]==a[x][y])
return true;
}
return false;
}
pii q[MAXN*MAXN];
inline void bfs()
{
int front = 0, rear = 0;
for(int i = 1; i<=n; i++)
for(int j = 1; j<=m; j++)
if(check(i,j))
f[i][j] = 0, vis[i][j] = true, q[rear++] = mp(i,j);
while(front<rear)
{
pii now = q[front++];
for(int i = 0; i<4; i++)
{
int nx = now.fi+pos[i][0], ny = now.se+pos[i][1];
if(nx<1||nx>n||ny<1||ny>m||vis[nx][ny])
continue;
f[nx][ny] = f[now.fi][now.se]+1;
vis[nx][ny] = true;
q[rear++] = mp(nx,ny);
}
}
}
int main()
{
n = readint(), m = readint(), T = readint();
memset(a,-1,sizeof(a));
for(int i = 1; i<=n; i++)
{
scanf("%s",str+1);
for(int j = 1; j<=m; j++)
a[i][j] = str[j]-'0';
}
bfs();
int x,y;
ll t;
while(T--)
{
x = readint(), y = readint(), t = readint();
if(vis[x][y])
printf("%d\n",a[x][y]^(max(0ll,t-f[x][y])&1));
else
printf("%d\n",a[x][y]);
}
return 0;
}
|
1349
|
D
|
Slime and Biscuits
|
Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play.
At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits.
As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time.
For convenience, as the answer can be represented as a rational number $\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \cdot q^{-1})\mod 998\,244\,353$. You can prove that $q\mod 998\,244\,353 \neq 0$.
|
Let $E_x$ be the sum of probability times time when the game end up with all biscuits are owned by the x-th person (At here, the sum of probability is not 1, though the sum of probability in all $E_x$ is 1). So the answer is $\sum\limits_{i=1}^nE_i$ Let $E'_x$ be the expectation of time when the game only ends when the x-th person own all the biscuits. Let $P_x$ be the probability that the game end up with all biscuits are owned by the x-th person. It's easy to find that $\sum\limits_{i=1}^n P_i = 1$. And we let constant $C$ be the expect time from when all biscuits are owned by i-th person to when all biscuits are owned by j-th person (now the end condition is that all biscuits are owned by j-th person, is the same with $E'_x$ . And for all (i, j), the value of $C$ is the same). So we have a identity: $E_x = E'_x-\sum\limits_{i=1}^n[i\neq x]( P_i\cdot C+E_i)$ We can get this by consider which people own all the biscuits when the game ends in all possible situation of $E'_x$ . Then we can get: $\sum\limits_{i=1}^n E_i=E'_x-C\cdot \sum\limits_{i=1}^n[i\neq x]P_i$ Sum it up for $x=1,2,\cdots,n$ , and we get: $n\sum\limits_{i=1}^nE_i=\sum\limits_{i=1}^nE'_i-C(n-1)\sum\limits_{i=1}^nP_i$ Mention that $ans=\sum\limits_{i=1}^nE_i$ and $\sum\limits_{i=1}^nP_i=1$ , so we find that: $n\cdot ans=\sum\limits_{i=1}^nE'_i-C(n-1)$ When we find the value of $E'_x$ and $C$ , we only want to know whether the biscuit is owned by the person we want or not, so we can let $f_m$ represent the expect time the person will own $m+1$ biscuits when the person own $m$ biscuits now. We can easily get $f_0$ and equation between $f_i$ and $f_{i-1}$ . So we can get all $f_m$ and $C$ in $O(\sum\limits_{i=1}^na_i \cdot \log\ mod)$ time. And we can get the answer. The overall complexity is $O(\sum\limits_{i=1}^na_i \cdot \log\ mod)$ .
|
[
"math",
"probabilities"
] | 3,200
|
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}
template <typename T> bool chkmin(T &x,T y){return x>y?x=y,true:false;}
int readint(){
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int cys=998244353;
int n,m;
ll a[100005],ans[300005];
ll qpow(ll x,ll p){
ll ret=1;
for(;p;p>>=1,x=x*x%cys) if(p&1) ret=ret*x%cys;
return ret;
}
int main(){
n=readint();
for(int i=1;i<=n;i++) a[i]=readint(),m+=a[i];
ll invm=qpow(m,cys-2),invn1=qpow(n-1,cys-2);
for(int i=m;i>=1;i--){
ll k1=i*invm%cys*invn1%cys,k2=(m-i)*invm%cys;
ans[i]=(k2*ans[i+1]+1)%cys*qpow(k1,cys-2)%cys;
}
for(int i=1;i<=m;i++) ans[i]=(ans[i]+ans[i-1])%cys;
ll res=0;
for(int i=1;i<=n;i++) res=(res+ans[m-a[i]])%cys;
res=(res+cys-ans[m]*(n-1)%cys)%cys;
printf("%lld\n",res*qpow(n,cys-2)%cys);
return 0;
}
|
1349
|
E
|
Slime and Hats
|
Slime and Orac are holding a turn-based game. In a big room, there are $n$ players sitting on the chairs, looking forward to a column and each of them is given a number: player $1$ sits in the front of the column, player $2$ sits directly behind him; player $3$ sits directly behind player $2$, and so on; player $n$ sits directly behind player $n-1$. Each player wears a hat that is either black or white. As each player faces forward, player $i$ knows the color of player $j$'s hat if and only if $i$ is larger than $j$.
At the start of each turn, Orac will tell \textbf{whether there exists a player wearing a black hat in the room}.
After Orac speaks, if the player can uniquely identify the color of his hat, he will put his hat on the chair, stand up and leave the room. All players are smart, so if it is possible to understand the color of their hat using the obtained information during this and previous rounds, they will understand it.
In each turn, all players who know the color of their hats will leave at the same time in this turn, which means a player can only leave in the next turn if he gets to know the color of his hat only after someone left the room at this turn.
Note that when the player needs to leave, he will put the hat on the chair before leaving, so the players ahead of him still cannot see his hat.
The $i$-th player will know who exactly left the room among players $1,2,\ldots,i-1$, and how many players among $i+1,i+2,\ldots,n$ have left the room.
Slime stands outdoor. He watches the players walking out and records the numbers of the players and the time they get out. Unfortunately, Slime is so careless that he has only recorded some of the data, and this given data is in the format "player $x$ leaves in the $y$-th round".
Slime asked you to tell him the color of each player's hat. If there are multiple solutions, you can find any of them.
|
First, let's renumber the players for convenience. Number the player at the front as $n$ ,the player sitting behind him as $n-1$ , and so on. Let $c_i$ be the color of player $i$'s hat. Consider how to calculate ${t_i}$ if we have already known $c_1,c_2,\dots,c_n$. If $c_1=c_2=\dots=c_n=0$, then $t_1=t_2=\dots=t_n=1$. Otherwise, let $x$ be the maximal number of a player with a black hat. In the first turn, player $1$ knows that someone wears a black hat. If $x=1$, player $1$ finds out that everyone except him wears a white hat, so he wears a black hat and he leaves. In the second turn, other players can figure out that $c_2=c_3=\dots=c_n=0$. Therefore, $t_1=1,t_2=t_3=\dots=t_n=2$. If $x\ge 2$, there is a player with a black hat sitting in front of player $1$ , so he can't figure out the color of his own hat and doesn't leave. Other players know that $x\ge 2$ in the next turn, and the problem is transformed into a subproblem on player $2,3,\dots,n$. No one leaves until the $x$-th turn, player $x$ knows that there is at least one player with a black hat in $x,x+1,\dots,n$, but player $x,x+1,\dots,n$ all wear white hats, so he leaves. In the next turn, $x+1,x+2,\dots,n$ leaves. According to the above process, player $x$ leaves in the $x$-th turn, player $x+1,x+2,\dots,n$ leave in the $(x+1)$-th turn, and a new process begins. Therefore, we can figure out the value of $t_1,t_2,\dots,t_n$. - If $c_i=1$ , then $t_i=\sum\limits_{j\ge i,c_j=1}j$ . Let $b_i=i$ . - If $c_i=0$ , let $k$ be the maximal number which satisfies $c_k=1$ and $k<i$ , then $t_i=t_k+1$ . For convenience, let $c_0=1, t_0=\sum\limits_{c_j=1}j$ , so $k$ always exists. Let $b_i=k$. Therefore, we can calculate $t_1,t_2,\dots,t_n$ using $c_1,c_2,\dots c_n$, and $t_i=t_{b_i}+(1-c_i)$ is satisfied. Consider how to solve the original problem. Before using dynamic programming to solve the problem, we need to do some preparation for that. If $i\ge j$ and $c_i=c_j=1$ , it is obviously that $t_i\le t_j$. Also, if $t_i>t_j$, $b_i\ge b_j$. Therefore, $\forall i>j, t_i-t_j=t_{b_i}+(1-c_i)-t_{b_j}-(1-c_j)=t_{b_i}-t_{b_j}+(c_j-c_i)\le c_j-c_i\le 1$ $\left\{ \begin{array}{lcl} t_i-t_j=1,\space\mathrm{if}\space c_j=1\ \textrm{and}\ \forall i\ge k>j,c_k=0 \\ t_i-t_j=0,\space\mathrm{if}\space \exists i>k>j,c_k=1,c_1=c_2=\dots=c_{k-1}=c_{k+1}=\dots=c_n=0\ \textrm{or}\ \forall i\ge k\ge j,c_k=0 \\ t_i-t_j<0,\space\mathrm{otherwise} \end{array} \right.$ Define a set of intervals $A=\{[l_1,r_1],[l_2,r_2],\dots,[l_m,r_m]\}$ which satisfies these rules: $1\le l_1\le r_1<l_2\le r_2<\dots<l_m\le r_m\le n$ $\forall 1\le k\le m, \exists l_k\le i\le r_k$, $t_i$ is given. $\forall 1\le i\le n$, if $t_i$ is given, $\exists k, \mathrm{s.t.}\space l_k\le i\le r_k$ For all pairs $(i,j)$ where $i>j$ and $t_i,t_j$ are both given, $i$ and $j$ are in the same interval if and only if $t_i\ge t_j$. If $l_i\neq 1$, it can be known that $c_{l_i+1}=c_{l_i+2}=\dots=c_{r_i}=0$ and $b_{l_i}=b_{l_i+1}=\dots=b_{r_i}$. Let $B_i=b_{l_i}$. After the preparatory work, let's work on dp. Let $f_{i,j}$ be the maximal possible value of $B_i$ when $c_{l_i}=j$ . Consider how to calculate $f_{i,j'}$ if we know the value of $f_{i+1,0}$ and $f_{i+1,1}$ . For $f_{i+1,j}$, enumerate all possible $f_{i,j'}$ from large to small, $B_i=f_{i,j'}$ might be satisfied if $t_{f_{i,j'}}=\sum\limits_{k\ge f_{i,j'},c_k=1}k=\left(\sum\limits_{k\ge f_{i+1,j},c_k=1}k\right) + \left(\sum\limits_{f_{i+1,j}>k\ge f_{i,j'},c_k=1}k\right) =t_{f_{i+1,j}}+f_{i,j'}+\sum\limits_{r_i<k<f_{i+1,j},c_j=1}k$ Besides $f_{i,j}$, record whether $f_{i,j}$ is transformed from $f_{i+1,0}$ or $f_{i+1,1}$. Using these we can easily give a solution. Notice that when $l_1=1$, $[l_1,r_1]$ doesn't satisfy $c_{l_1+1}=c_{l_1+2}=\dots=c_{r_1}=0$ . However, there is at most one $i$ in $[l_1,r_1]$ where $c_i=1$. Just brute force which $c_i$ equals to $1$ is okay. The whole complexity is $O(n\log n)$.
|
[
"constructive algorithms",
"dp",
"greedy"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,ll> pii;
#define x first
#define y second
#define pb push_back
const int MAXN=200005;
int n,m,cnt;
pii a[MAXN];
bool avis[MAXN];
struct Range
{
int l,r,type;
ll val;
Range(){}
Range(int l,int r,int type,ll val):l(l),r(r),type(type),val(val){}
}b[MAXN];
int f[2][MAXN],wh[2][MAXN],res[MAXN];
vector<int> str[2][MAXN];
bool check(ll s,int l,int r)
{
if(s<=0)return !s && r-l+1>=0;
ll L=1,R=r-l+1,mid,ans=0;
while(L<=R)
{
mid=(L+R)>>1;
if((l+l+mid-1)*mid<=s*2)ans=mid,L=mid+1;
else R=mid-1;
}
return s*2<=(r+r-ans+1)*ans;
}
void modify(ll s,int l,int r,vector<int> &tar,int start)
{
ll L=1,R=r-l+1,mid,ans=0;
while(L<=R)
{
mid=(L+R)>>1;
if((l+l+mid-1)*mid<=s*2)ans=mid,L=mid+1;
else R=mid-1;
}
for(int i=l;i<=r;i++)
if(ans && (i+i+ans-2)*(ans-1)<=(s-i)*2 && (s-i)*2<=(r+r-ans+2)*(ans-1))
{--ans,s-=i;tar.pb(1);}
else tar.pb(0);
}
void update(int i,int ti,int ti_1,int pos,ll d)
{
if(pos<=f[ti][i])return;
str[ti][i].clear();
f[ti][i]=pos;wh[ti][i]=ti_1;
str[ti][i].pb(1);
for(int j=f[ti][i]+1;j<=b[i].r;j++)str[ti][i].pb(0);
modify(d-f[ti][i],b[i].r+1,f[ti_1][i-1]-1,str[ti][i],f[ti][i]);
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("code.in","r",stdin);
//freopen("code.out","w",stdout);
#endif
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
ll y;
scanf("%lld",&y);
if(!y)continue;
a[++m]=make_pair(n-i+1,y);
avis[n-i+1]=1;
}
if(!m)
{
for(int i=1;i<=n;i++)putchar('0');
return 0;
}
sort(a+1,a+m+1);
b[cnt=1]=Range(a[m].x,a[m].x,2,a[m].y);
for(int i=m-1;i;i--)
{
if(a[i].y==a[i+1].y)b[cnt].l=a[i].x,b[cnt].type=0;
else if(a[i].y==a[i+1].y-1)b[cnt].l=a[i].x,b[cnt].type=1,b[cnt].val--;
else b[++cnt]=Range(a[i].x,a[i].x,2,a[i].y);
}
b[cnt+1]=Range(-1,-1,0,0);
bool error=0;
f[0][0]=-1;f[1][0]=n+1;
for(int i=1;i<=cnt;i++)
{
f[0][i]=f[1][i]=-1;
for(int t=0;t<=1;t++)
if(f[t][i-1]>b[i].r)
{
if(b[i].type==0 || b[i].type==2)
{
ll d=(b[i].val-1)-(b[i-1].val-1+t);
int pos=-1;
for(int j=min(b[i].l-1ll,d);j>b[i+1].r;--j)
if(check(d-j,b[i].r+1,f[t][i-1]-1)){pos=j;break;}
update(i,0,t,pos,d);
}
if(b[i].type==1 || b[i].type==2)
{
ll d=b[i].val-(b[i-1].val-1+t);
if(check(d-b[i].l,b[i].r+1,f[t][i-1]-1))
update(i,1,t,b[i].l,d);
}
}
if(f[0][i]<0 && f[1][i]<0 && i==cnt && !b[i].type)error=1;
}
if(error)
{
for(int t=0;t<=1;t++)
if(f[t][cnt-1]>b[cnt].r)
{
ll d=(b[cnt].val-1)-(b[cnt-1].val-1+t);
int pos=-1;
for(int j=min((ll)b[cnt].r,d);j>=b[cnt].l;--j)
{
if(avis[j])continue;
if(check(d-j,b[cnt].r+1,f[t][cnt-1]-1)){pos=j;break;}
}
update(cnt,0,t,pos,d);
}
}
int cur=(f[1][cnt]>0);
for(int i=1;i<f[cur][cnt];i++)res[i]=0;
for(int i=cnt;i>0;i--)
{
for(int j=0;j<(int)str[cur][i].size();j++)res[j+f[cur][i]]=str[cur][i][j];
cur=wh[cur][i];
}
for(int i=n;i>0;i--)putchar(res[i]+'0');
return 0;
}
|
1349
|
F1
|
Slime and Sequences (Easy Version)
|
\textbf{Note that the only differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if all versions are solved.}
Slime is interested in sequences. He defined \textbf{good} positive integer sequences $p$ of length $n$ as follows:
- For each $k>1$ that presents in $p$, there should be at least one pair of indices $i,j$, such that $1 \leq i < j \leq n$, $p_i = k - 1$ and $p_j = k$.
For the given integer $n$, the set of all good sequences of length $n$ is $s_n$. For the fixed integer $k$ and the sequence $p$, let $f_p(k)$ be the number of times that $k$ appears in $p$. For each $k$ from $1$ to $n$, Slime wants to know the following value:
$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$
|
First we can make a bijection between all the good sequences and permutations. Let a permutation of length $n$ be $a_1,a_2,\cdots , a_n$ , and we fill '>' or '<' sign between each $a_i$ and $a_{i+1}$ , so the value of $p_{a_i}$ is the number of '<' sign between $a_1,a_2,\cdots, a_i$ plus one, it's easy to proof that this is a correct bijection. Let $d_{i,j}$ be the number of permutations of length $i+1$ that have at least $j$ '<' signs in it. Then for each '<' sign, we can combine the places next to it, so for some combined places, there are only one way to put the numbers in it for a fix set of numbers. And we know that $d_{i,j}$ have $i-j+1$ sets of combined places, so the value of $d_{i,j}$ is the number of ways to assign $i+1$ numbers into $i-j+1$ different sets. From the EGF of the second kind of Stirling numbers, we know that $d_{i,j}=(i+1)^{i-j+1}$ . We can also use DP that similar with the Stirling numbers to get all $d_{i,j}$ . When we find the answers, for each $1\leq i\leq n$ , we consider the contribution of each places, so for each $a_j$ , we need to find the number of permutations that have $i-1$ '<' signs before it. So we can get: $ans_{i+1}=\sum\limits_{x=0}^{n-1}\sum\limits_{y=i}^x (-1)^{y-i} {y\choose i}d_{x,y}\frac{n!}{(x+1)!}$ $=\frac {n!}{i!}\sum\limits_{x=0}^{n-1}\sum\limits_{y=i}^x (-1)^{y-i}\frac{y!d_{x,y}}{(y-i)!(x+1)!}$ $=\frac{n!}{i!} \sum\limits_{y=i}^{n-1}\frac{(-1)^{y-i}y!}{(y-i)!}\sum\limits_{x=y}^{n-1}\frac{d_{x,y}}{(x+1)!}$ $=\frac {n!}{i!}\sum\limits_{y=i}^{n-1} \frac{(-1)^{y-i}y!}{(y-i)!} \sum\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}$ If we can find $\sum\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}$ for each $y$ , then we can find the answer in one convolution. And because of the simple $O(n^2)$ DP algorithm to find all $d_{x,y}$ , so we can get a $O(n^2)$ complexity to solve the problem, and it can pass the easy version (other forms of DP can also get to this time complexity, but now we only introduce the form that leads to the solution of the hard version).
|
[
"dp",
"fft",
"math"
] | 3,100
|
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}
template <typename T> bool chkmin(T &x,T y){return x>y?x=y,true:false;}
int readint(){
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int cys=998244353;
int n;
ll fac[5005],inv[5005],d[5005][5005],ans[5005];
ll qpow(ll x,ll p){
ll ret=1;
for(;p;p>>=1,x=x*x%cys) if(p&1) ret=ret*x%cys;
return ret;
}
int main(){
n=readint();
d[0][0]=fac[0]=inv[0]=1;
for(int i=1;i<=n;i++) fac[i]=fac[i-1]*i%cys;
inv[n]=qpow(fac[n],cys-2);
for(int i=n-1;i>=1;i--) inv[i]=inv[i+1]*(i+1)%cys;
for(int i=1;i<=n;i++) for(int j=1;j<=i;j++) d[i][j]=(d[i-1][j-1]*(i-j+1)+d[i-1][j]*j)%cys;
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) ans[i]=(ans[i]+d[j][i]*inv[j])%cys;
for(int i=1;i<=n;i++) printf("%lld ",ans[i]*fac[n]%cys);
printf("\n");
return 0;
}
|
1349
|
F2
|
Slime and Sequences (Hard Version)
|
\textbf{Note that the only differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if all versions are solved.}
Slime is interested in sequences. He defined \textbf{good} positive integer sequences $p$ of length $n$ as follows:
- For each $k>1$ that presents in $p$, there should be at least one pair of indices $i,j$, such that $1 \leq i < j \leq n$, $p_i = k - 1$ and $p_j = k$.
For the given integer $n$, the set of all good sequences of length $n$ is $s_n$. For the fixed integer $k$ and the sequence $p$, let $f_p(k)$ be the number of times that $k$ appears in $p$. For each $k$ from $1$ to $n$, Slime wants to know the following value:
$$\left(\sum_{p\in s_n} f_p(k)\right)\ \textrm{mod}\ 998\,244\,353$$
|
Now we consider how to get these values in less than $O(n^2)$ time. $\sum\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}=\sum\limits_{x=y+1}^n[z^x](e^z-1)^{x-y}$ $=[z^y]\sum\limits_{x=y+1}^n(\frac{e^z-1}z)^{x-y}=[z^y]\sum\limits_{x=1}^{n-y}(\frac{e^z-1}z)^x$ Let $F=\frac{e^z-1}z$ , so now we just want to find $[z^i]\sum\limits_{k=1}^{n-i}F^k$ for each $0\leq i\leq n-1$ . $[z^i]\sum\limits_{k=1}^{n-i}F^k =[z^i]\frac 1{1-F}-[z^i]\frac{F^{n-i+1}}{1-F}$ We can get the value of $[z^i]\frac 1{1-F}$ in one polynomial inversion, now we only need to deal with the second one. $[z^i]\frac{F^{n-i+1}}{1-F}=[z^{n+1}]\frac{(zF)^{n-i+1}}{1-F}$ Let $w(z)=zF(z)$ , $\phi(z)$ satisfies $\frac{w(z)}{\phi (w(z))}=z$ , so $\frac{zF(z)}{\phi (w(z))}=z$ , $F=\phi (w)$ . $[z^{n+1}]\frac{(zF)^{n-i+1}}{1-F}=[z^{n+1}u^{n-i+1}]\sum\limits_{k=0}^\infty \frac{(uzF)^k}{1-F}$ $=[z^{n+1}u^{n-i+1}] \frac 1{1-\phi (w)}\frac 1{1-uw}$ And from the Lagrange Inversion $=[u^{n-i+1}]\frac 1{n+1} [z^n] ((\frac 1{1-\phi z}\frac 1{1-uz})'\cdot \phi (z)^{n+1})$ $=\frac 1{n+1} [z^nu^{n-i+1}] (\phi (z)^{n+1}\frac{u+\phi'(z)-u\phi(z)-uz\phi'(z)}{(1-\phi (z))^2(1-uz)^2})$ $=\frac 1{n+1} [z^nu^{n-i+1}] (\phi(z)^{n+1}(\frac {u}{(1-\phi (z))(1-uz)^2}+\frac {\phi'(z)}{(1-\phi (z))^2(1-uz)}))$ $=\frac 1{n+1}[z^nu^{n-i+1}](\phi (z)^{n+1}(\frac 1{1-\phi(z)}\sum\limits_{k=0}^\infty (k+1)z^ku^{k+1}+\frac{\phi'(z)}{(1-\phi (z))^2}\sum\limits_{k=0}^\infty z^ku^k))$ $=\frac 1{n+1}[z^n](\phi (z)^{n+1}(\frac{(n-i+1)z^{n-i}}{1-\phi (z)}+\frac{\phi'(z)z^{n-i+1}}{(1-\phi(z))^2}))$ $=\frac 1{n+1}([z^i](\phi(z)^{n+1}\frac{n-i+1}{1-\phi(z)})+[z^{i-1}](\phi(z)^{n+1}\frac{\phi'(z)}{(1-\phi(z))^2}))$ We can get $\phi(z)^{n+1}\frac{n-i+1}{1-\phi(z)}$ and $\phi(z)^{n+1}\frac{\phi'(z)}{(1-\phi(z))^2}$ in $O(n\log n)$ or $O(n\log ^2n)$ time, and then get the answer. The overall complexity is $O(n\log n)$ or $O(n\log ^2n)$ . You can also view
|
[
"dp",
"fft",
"math"
] | 3,500
|
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vi;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}
template <typename T> bool chkmin(T &x,T y){return x>y?x=y,true:false;}
int readint(){
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int cys=998244353,g=3,invg=(cys+1)/3;
int n;
ll ni[200015],fac[200015],inv[200015],tw[200005];
int mod(int x){return x>=cys?x-cys:x;}
ll qpow(ll x,ll p){
ll ret=1;
for(;p;p>>=1,x=x*x%cys) if(p&1) ret=ret*x%cys;
return ret;
}
vi operator+(vi a,vi b){
vi ret(max(a.size(),b.size()));
for(int i=0;i<ret.size();i++) ret[i]=mod((i<a.size()?a[i]:0)+(i<b.size()?b[i]:0));
return ret;
}
vi operator-(vi a,vi b){
vi ret(max(a.size(),b.size()));
for(int i=0;i<ret.size();i++) ret[i]=mod((i<a.size()?a[i]:0)+cys-(i<b.size()?b[i]:0));
return ret;
}
vi operator*(vi a,ll b){
for(int i=0;i<a.size();i++) a[i]=1ll*a[i]*b%cys;
return a;
}
vi operator>>(vi a,int b){
for(int i=0;i<a.size()-b;i++) a[i]=a[i+b];
a.resize(a.size()-b);
return a;
}
namespace poly{
int N,l;
int A[1100000],B[1100000],r[1100000],pre1[20][600000],pre2[20][600000];
void pre(){
for(int i=1,r=0;i<(1<<19);i<<=1,r++){
int w=1,wn=qpow(g,(cys-1)/(i<<1));
for(int j=0;j<i;j++,w=1ll*w*wn%cys) pre1[r][j]=w;
}
for(int i=1,r=0;i<(1<<19);i<<=1,r++){
int w=1,wn=qpow(invg,(cys-1)/(i<<1));
for(int j=0;j<i;j++,w=1ll*w*wn%cys) pre2[r][j]=w;
}
}
void ntt(int *A,int N,int f){
for(int i=0;i<N;i++) if(i<r[i]) swap(A[i],A[r[i]]);
for(int i=1,r=0;i<N;i<<=1,r++){
for(int j=0;j<N;j+=(i<<1)){
for(int k=j;k<j+i;k++){
int x=A[k],y=1ll*A[k+i]*(f>0?pre1[r][k-j]:pre2[r][k-j])%cys;
A[k]=mod(x+y); A[k+i]=mod(x+cys-y);
}
}
}
if(f<0){
int invn=qpow(N,cys-2);
for(int i=0;i<N;i++) A[i]=1ll*A[i]*invn%cys;
}
}
void init(int t){
N=1,l=0;
for(;N<t;N<<=1) l++;
for(int i=0;i<N;i++) r[i]=(r[i>>1]>>1)|((i&1)<<(l-1));
}
void getmul(){
ntt(A,N,1); ntt(B,N,1);
for(int i=0;i<N;i++) A[i]=1ll*A[i]*B[i]%cys;
ntt(A,N,-1);
}
vi mul(vi a,vi b){
init(a.size()+b.size());
for(int i=0;i<N;i++) A[i]=i<a.size()?a[i]:0;
for(int i=0;i<N;i++) B[i]=i<b.size()?b[i]:0;
getmul();
vi ret(a.size()+b.size()-1);
for(int i=0;i<ret.size();i++) ret[i]=A[i];
return ret;
}
vi polyinv(vi a,int l){
if(l==1) return vi(1,qpow(a[0],cys-2));
a.resize(l);
vi b=polyinv(a,(l+1)/2);
init(l<<1);
for(int i=0;i<N;i++) A[i]=i<l?a[i]:0;
for(int i=0;i<N;i++) B[i]=i<(l+1)/2?b[i]:0;
ntt(A,N,1); ntt(B,N,1);
for(int i=0;i<N;i++) A[i]=1ll*A[i]*B[i]%cys*B[i]%cys;
ntt(A,N,-1);
vi t=b*2;
t.resize(l);
for(int i=0;i<l;i++) t[i]=mod(t[i]+cys-A[i]);
return t;
}
vi polydiff(vi a){
for(int i=0;i<a.size()-1;i++) a[i]=1ll*(i+1)*a[i+1]%cys;
a.resize(a.size()-1);
return a;
}
vi polyint(vi a){
a.resize(a.size()+1);
for(int i=a.size()-1;i>=1;i--) a[i]=1ll*a[i-1]*ni[i]%cys;
a[0]=0;
return a;
}
vi polyln(vi a,int l){
return polyint(mul(polydiff(a),polyinv(a,l)));
}
vi polyexp(vi a,int l){
if(l==1) return vi(1,1);
a.resize(l);
vi b=polyexp(a,(l+1)/2);
init(l<<1);
vi t=mul(b,vi(1,1)-polyln(b,l)+a);
t.resize(l);
return t;
}
vi polypow(vi a,int l,int k){
return polyexp(polyln(a,l)*k,l);
}
}
vi getans(){
vi f(0);
for(int i=0;i<=n+1;i++) f.push_back(inv[i+1]);
vi tmp=poly::mul(f,poly::polyinv((vi(1,1)-f)>>1,n+1));
vi tw(0); tw.resize(n);
for(int i=0;i<n;i++) tw[i]=tmp[i+1];
vi h(0);
h.push_back(1),h.push_back(1);
h=poly::polyinv(poly::polyln(h,n+3)>>1,n+2);
vi g=poly::polyinv((vi(1,1)-h)>>1,n+1);
vi ph=poly::polypow(h,n+1,n+1);
vi t1=poly::mul(g,ph);
vi tmp1=poly::mul(poly::polydiff(h),ph);
tmp1.resize(n+1);
vi tmp2=poly::mul(g,g);
tmp2.resize(n+1);
vi t2=poly::mul(tmp1,tmp2);
for(int i=0;i<n;i++) tw[i]=mod(tw[i]+cys-ni[n+1]*mod(t1[i+1]*(n-i+1)%cys+t2[i+1])%cys);
for(int i=0;i<n;i++) tw[i]=tw[i]*fac[i]%cys;
reverse(tw.begin(),tw.end());
tmp.clear();
for(int i=0;i<n;i++) tmp.push_back(i&1?cys-inv[i]:inv[i]);
tw=poly::mul(tw,tmp);
tw.resize(n);
reverse(tw.begin(),tw.end());
return tw;
}
int main(){
poly::pre();
n=readint();
fac[0]=inv[0]=1;
for(int i=1;i<=n+5;i++) fac[i]=fac[i-1]*i%cys;
inv[n+5]=qpow(fac[n+5],cys-2);
for(int i=n+4;i>=1;i--) inv[i]=inv[i+1]*(i+1)%cys;
for(int i=1;i<=n+5;i++) ni[i]=inv[i]*fac[i-1]%cys;
vi res=getans();
for(int i=0;i<n;i++) printf("%lld ",res[i]*fac[n]%cys*inv[i]%cys);
printf("\n");
return 0;
}
|
1350
|
A
|
Orac and Factors
|
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers $a$ and $b$, $a$ is a divisor of $b$ if and only if there exists an integer $c$, such that $a\cdot c=b$.
For $n \ge 2$, we will denote as $f(n)$ the smallest positive divisor of $n$, except $1$.
For example, $f(7)=7,f(10)=2,f(35)=5$.
For the fixed integer $n$, Orac decided to add $f(n)$ to $n$.
For example, if he had an integer $n=5$, the new value of $n$ will be equal to $10$. And if he had an integer $n=6$, $n$ will be changed to $8$.
Orac loved it so much, so he decided to repeat this operation several times.
Now, for two positive integers $n$ and $k$, Orac asked you to add $f(n)$ to $n$ exactly $k$ times (note that $n$ will change after each operation, so $f(n)$ may change too) and tell him the final value of $n$.
For example, if Orac gives you $n=5$ and $k=2$, at first you should add $f(5)=5$ to $n=5$, so your new value of $n$ will be equal to $n=10$, after that, you should add $f(10)=2$ to $10$, so your new (and the final!) value of $n$ will be equal to $12$.
Orac may ask you these queries many times.
|
If we simulate the whole process we will get TLE because $k$ is too large. So we need some trivial observations: If $n$ is even, then for each operation $n$ will be added by $2$ and keep being even. If $n$ is odd, then for the first time $n$ will be added by an odd number and then become even. So it's easy to see that the answer is $\left\{ \begin{array}{lcl} n+2k & n\textrm{ is even}\\ n+2(k-1)+d(n) & n\textrm{ is odd}\\ \end{array} \right.$ The overall complexity is $O(n)$ .
|
[
"math"
] | 900
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
int T;
cin >> T;
while(T--)
{
int n,k;
cin >> n >> k;
if(n%2==0)
{
cout << n+2*k << endl;
continue;
}
int p = 0;
for(int i = n; i>=2; i--)
if(n%i==0)
p = i;
cout << n+p+2*(k-1) << endl;
}
return 0;
}
|
1350
|
B
|
Orac and Models
|
There are $n$ models in the shop numbered from $1$ to $n$, with sizes $s_1, s_2, \ldots, s_n$.
Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).
Orac thinks that the obtained arrangement is \textbf{beatiful}, if for any two adjacent models with indices $i_j$ and $i_{j+1}$ (note that $i_j < i_{j+1}$, because Orac arranged them properly), $i_{j+1}$ is divisible by $i_j$ and $s_{i_j} < s_{i_{j+1}}$.
For example, for $6$ models with sizes $\{3, 6, 7, 7, 7, 7\}$, he can buy models with indices $1$, $2$, and $6$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.
Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.
|
Considering DP, we can design DP statuses as follow: $f_i$ stands for the length of the longest beautiful sequence end up with index $i$. We can find the transformation easily: $f_i = \max\limits_{j\mid i, s_j<s_i} \{f_j + 1\}$ Then, the length of answer sequence is the maximum value among $f_1,f_2,\cdots,f_n$. About the complexity of DP: If you transform by iterating multiples, it will be $O(n\log n)$ (According to properties of Harmonic Series); if you iterate divisors, then it will be $O(n\sqrt n)$. Fortunately, both of them are acceptable in this problem.
|
[
"dp",
"math",
"number theory"
] | 1,400
|
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 500005;
inline int readint()
{
int res = 0;
char c = 0;
while(!isdigit(c))
c = getchar();
while(isdigit(c))
res = res*10+c-'0', c = getchar();
return res;
}
int n,a[MAXN],f[MAXN];
int main()
{
int T = readint();
while(T--)
{
n = readint();
for(int i = 1; i<=n; i++)
a[i] = readint();
for(int i = 1; i<=n; i++)
f[i] = 1;
for(int i = 1; i<=n; i++)
for(int j = i*2; j<=n; j += i)
if(a[i]<a[j])
f[j] = max(f[j],f[i]+1);
int ans = 0;
for(int i = 1; i<=n; i++)
ans = max(ans,f[i]);
cout << ans << endl;
}
return 0;
}
|
1352
|
A
|
Sum of Round Numbers
|
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $1$ to $9$ (inclusive) are round.
For example, the following numbers are round: $4000$, $1$, $9$, $800$, $90$. The following numbers are \textbf{not} round: $110$, $707$, $222$, $1001$.
You are given a positive integer $n$ ($1 \le n \le 10^4$). Represent the number $n$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $n$ as a sum of the least number of terms, each of which is a round number.
|
Firstly, we need to understand the minimum amount of round numbers we need to represent $n$. It equals the number of non-zero digits in $n$. Why? Because we can "remove" exactly one non-zero digit in $n$ using exactly one round number (so we need at most this amount of round numbers) and, on the other hand, the sum of two round numbers has at most two non-zero digits (the sum of three round numbers has at most three non-zero digits and so on) so this is useless to try to remove more than one digit using the sum of several round numbers. So we need to find all digits of $n$ and print the required number for each of these digits. For example, if $n=103$ then $n=1 \cdot 10^2 + 0 \cdot 10^1 + 3 \cdot 10^0$, so we need two round numbers: $1 \cdot 10^2$ and $3 \cdot 10^0$. Because the last digit of $n$ is $n \% 10$ (the remainder of $n$ modulo $10$) and we can remove the last digit of the number by integer division on $10$, we can use the following code to solve the problem:
|
[
"implementation",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> ans;
int power = 1;
while (n > 0) {
if (n % 10 > 0) {
ans.push_back((n % 10) * power);
}
n /= 10;
power *= 10;
}
cout << ans.size() << endl;
for (auto number : ans) cout << number << " ";
cout << endl;
}
}
|
1352
|
B
|
Same Parity Summands
|
You are given two positive integers $n$ ($1 \le n \le 10^9$) and $k$ ($1 \le k \le 100$). Represent the number $n$ as the sum of $k$ positive integers of the same parity (have the same remainder when divided by $2$).
In other words, find $a_1, a_2, \ldots, a_k$ such that all $a_i>0$, $n = a_1 + a_2 + \ldots + a_k$ and either all $a_i$ are even or all $a_i$ are odd at the same time.
If such a representation does not exist, then report it.
|
Consider two cases: when we choose all odd numbers and all even numbers. In both cases let's try to maximize the maximum. So, if we choose odd numbers, let's try to take $k-1$ ones and the remainder $n-(k-1)$. But we need to sure that $n-k+1$ is greater than zero and odd. And in case of even numbers, let's try to take $k-1$ twos and the remainder $n-2(k-1)$. We also need to check that the remainder is greater than zero and even. If none of these cases is true, print "NO".
|
[
"constructive algorithms",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
int n1 = n - (k - 1);
if (n1 > 0 && n1 % 2 == 1) {
cout << "YES" << endl;
for (int i = 0; i < k - 1; ++i) cout << "1 ";
cout << n1 << endl;
continue;
}
int n2 = n - 2 * (k - 1);
if (n2 > 0 && n2 % 2 == 0) {
cout << "YES" << endl;
for (int i = 0; i < k - 1; ++i) cout << "2 ";
cout << n2 << endl;
continue;
}
cout << "NO" << endl;
}
}
|
1352
|
C
|
K-th Not Divisible by n
|
You are given two positive integers $n$ and $k$. Print the $k$-th positive integer that is not divisible by $n$.
For example, if $n=3$, and $k=7$, then all numbers that are not divisible by $3$ are: $1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$. The $7$-th number among them is $10$.
|
Suppose the answer is just $k$-th positive integer which we should "shift right" by some number. Each multiplier of $n$ shifts our answer by $1$. The number of such multipliers is $need = \lfloor\frac{k-1}{n-1}\rfloor$, where $\lfloor \frac{x}{y} \rfloor$ is $x$ divided by $y$ rounded down. So the final answer is $k + need$ ($k$-th positive integer with the required number of skipped integers multipliers of $n$). You can also use a binary search to solve this problem :)
|
[
"binary search",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
int need = (k - 1) / (n - 1);
cout << k + need << endl;
}
}
|
1352
|
D
|
Alice, Bob and Candies
|
There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy \textbf{from left to right}, and Bob — \textbf{from right to left}. The game ends if all the candies are eaten.
The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).
Alice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.
On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is \textbf{strictly greater} than the sum of the sizes of candies that the other player ate on the \textbf{previous} move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.
For example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then:
- move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$.
- move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$.
- move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$.
- move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$.
- move 5: Bob ate $8$ on the previous move, which means Alice must eat $9$ or more. Alice eats two candies with the total size of $5+9=14$ and the sequence of candies becomes $[2,6]$.
- move 6 (the last): Alice ate $14$ on the previous move, which means Bob must eat $15$ or more. It is impossible, so Bob eats the two remaining candies and the game ends.
Print the number of moves in the game and two numbers:
- $a$ — the total size of all sweets eaten by Alice during the game;
- $b$ — the total size of all sweets eaten by Bob during the game.
|
This is just an implementation problem and it can be solved in $O(n)$ time but we didn't ask for such solutions so you could solve it in $O(n^2)$ or maybe even in $O(n^2 log n)$. I'll describe $O(n)$ solution anyway. Firstly, we need to maintain several variables: $cnt$ (initially $0$, the number of moves passed), $l$ (the position of the leftmost remaining candy, initially $0$), $r$ (the position of the rightmost remaining candy, initially $n-1$), $ansl$ (the sum of candies eaten by Alice, initially $0$), $ansr$ (the sum of candied eaten by Bob, initially $0$), $suml$ (the sum of candies eaten by Alice during her last move, initially $0$) and $sumr$ (the sum of candies eaten by Bob during his last move, initially $0$). So, let's just simulate the following process while $l \le r$: if the number of moves $cnt$ is even then now is Alice's move and we need to maintain one more variable $nsuml = 0$ - the sum of candies Alice eats during this move. How to calculate it? While $l \le r$ and $nsuml \le sumr$, let's eat the leftmost candy, so variables will change like this: $nsuml := nsuml + a_l, l := l + 1$. After all, let's add $nsuml$ to $ansl$, replace $suml$ with $nsuml$ (assign $suml := nsuml$) and increase $cnt$ by $1$. If the number of moves $cnt$ is odd then the process is the same but from the Bob's side. I'll also add a simply implemented $O(n^2)$ solution written by Gassa below :)
|
[
"implementation"
] | 1,300
|
// Author: Ivan Kazmenko (gassa@mail.ru)
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
void main ()
{
auto tests = readln.strip.to !(int);
foreach (test; 0..tests)
{
auto n = readln.strip.to !(int);
auto a = readln.splitter.map !(to !(int)).array;
int [2] total;
int prev = 0;
int moves = 0;
while (!a.empty)
{
moves += 1;
int cur = 0;
while (!a.empty && cur <= prev)
{
cur += a[0];
a = a[1..$];
}
total[moves % 2] += cur;
prev = cur;
reverse (a);
}
writeln (moves, " ", total[1], " ", total[0]);
}
}
|
1352
|
E
|
Special Elements
|
Pay attention to the non-standard memory limit in this problem.
In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.
The array $a=[a_1, a_2, \ldots, a_n]$ ($1 \le a_i \le n$) is given. Its element $a_i$ is called special if there exists a pair of indices $l$ and $r$ ($1 \le l < r \le n$) such that $a_i = a_l + a_{l+1} + \ldots + a_r$. In other words, an element is called special if it can be represented as the sum of \textbf{two or more consecutive elements} of an array (no matter if they are special or not).
Print the number of special elements of the given array $a$.
For example, if $n=9$ and $a=[3,1,4,1,5,9,2,6,5]$, then the answer is $5$:
- $a_3=4$ is a special element, since $a_3=4=a_1+a_2=3+1$;
- $a_5=5$ is a special element, since $a_5=5=a_2+a_3=1+4$;
- $a_6=9$ is a special element, since $a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$;
- $a_8=6$ is a special element, since $a_8=6=a_2+a_3+a_4=1+4+1$;
- $a_9=5$ is a special element, since $a_9=5=a_2+a_3=1+4$.
Please note that some of the elements of the array $a$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.
|
The intended solution for this problem uses $O(n^2)$ time and $O(n)$ memory. Firstly, let's calculate $cnt_i$ for each $i$ from $1$ to $n$, where $cnt_i$ is the number of occurrences of $i$ in $a$. This part can be done in $O(n)$. Then let's iterate over all segments of $a$ of length at least $2$ maintaining the sum of the current segment $sum$. We can notice that we don't need sums greater than $n$ because all elements do not exceed $n$. So if the current sum does not exceed $n$ then add $cnt_{sum}$ to the answer and set $cnt_{sum} := 0$ to prevent counting the same elements several times. This part can be done in $O(n^2)$.
|
[
"brute force",
"implementation",
"two pointers"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
vector<int> cnt(n + 1);
int ans = 0;
for (auto &it : a) {
cin >> it;
++cnt[it];
}
for (int l = 0; l < n; ++l) {
int sum = 0;
for (int r = l; r < n; ++r) {
sum += a[r];
if (l == r) continue;
if (sum <= n) {
ans += cnt[sum];
cnt[sum] = 0;
}
}
}
cout << ans << endl;
}
}
|
1352
|
F
|
Binary String Reconstruction
|
For some binary string $s$ (i.e. each character $s_i$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $2$ were written. For each pair (substring of length $2$), the number of '1' (ones) in it was calculated.
You are given three numbers:
- $n_0$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $0$;
- $n_1$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $1$;
- $n_2$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $2$.
For example, for the string $s=$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $n_0=1$, $n_1=3$, $n_2=5$.
Your task is to restore \textbf{any} suitable binary string $s$ from the given values $n_0, n_1, n_2$. It is guaranteed that at least one of the numbers $n_0, n_1, n_2$ is greater than $0$. Also, it is guaranteed that a solution exists.
|
Consider case $n_1 = 0$ separately and print the sting of $n_0 + 1$ zeros or $n_2 + 1$ ones correspondingly. Now our string has at least one pair "10" or "01". Let's form the pattern "101010 ... 10" of length $n_1 + 1$. So, all substrings with the sum $1$ are satisfied. Now let's insert $n_0$ zeros before the first zero, in this way we satisfy the substrings with the sum $0$. And then just insert $n_2$ ones before the first one, in this way we satisfy the substrings with the sum $2$.
|
[
"constructive algorithms",
"dfs and similar",
"math"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n0, n1, n2;
cin >> n0 >> n1 >> n2;
if (n1 == 0) {
if (n0 != 0) {
cout << string(n0 + 1, '0') << endl;
} else {
cout << string(n2 + 1, '1') << endl;
}
continue;
}
string ans;
for (int i = 0; i < n1 + 1; ++i) {
if (i & 1) ans += "0";
else ans += "1";
}
ans.insert(1, string(n0, '0'));
ans.insert(0, string(n2, '1'));
cout << ans << endl;
}
}
|
1352
|
G
|
Special Permutation
|
A permutation of length $n$ is an array $p=[p_1,p_2,\dots,p_n]$, which contains every integer from $1$ to $n$ (inclusive) and, moreover, each number appears exactly once. For example, $p=[3,1,4,2,5]$ is a permutation of length $5$.
For a given number $n$ ($n \ge 2$), find a permutation $p$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $2$ and $4$, inclusive. Formally, find such permutation $p$ that $2 \le |p_i - p_{i+1}| \le 4$ for each $i$ ($1 \le i < n$).
Print any such permutation for the given integer $n$ or determine that it does not exist.
|
If $n < 4$ then there is no answer. You can do some handwork to be sure. Otherwise, the answer exists and there is one simple way to construct it: firstly, let's put all odd integers into the answer in decreasing order, then put $4$, $2$, and all other even numbers in increasing order. To test that it always works, you can run some kind of checker locally (you can check all $1000$ tests very fast, in less than one second, this may be very helpful sometimes).
|
[
"constructive algorithms"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
if (n < 4) {
cout << -1 << endl;
continue;
}
for (int i = n; i >= 1; --i) {
if (i & 1) cout << i << " ";
}
cout << 4 << " " << 2 << " ";
for (int i = 6; i <= n; i += 2) {
cout << i << " ";
}
cout << endl;
}
}
|
1353
|
A
|
Most Unstable Array
|
You are given two integers $n$ and $m$. You have to construct the array $a$ of length $n$ consisting of \textbf{non-negative integers} (i.e. integers greater than or equal to zero) such that the sum of elements of this array is \textbf{exactly} $m$ and the value $\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$ is the maximum possible. Recall that $|x|$ is the absolute value of $x$.
In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $a=[1, 3, 2, 5, 5, 0]$ then the value above for this array is $|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$. Note that this example \textbf{doesn't show the optimal answer} but it shows how the required value for some array is calculated.
You have to answer $t$ independent test cases.
|
If $n=1$ then the answer is $0$. Otherwise, the best way is to construct the array $[0, m, 0, \dots, 0]$. For $n=2$ we can't reach answer more than $m$ and for $n > 2$ we can't reach the answer more than $2m$ because each unit can't be used more than twice. So the answer can be represented as $min(2, n - 1) \cdot m$.
|
[
"constructive algorithms",
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
cout << min(2, n - 1) * m << endl;
}
return 0;
}
|
1353
|
B
|
Two Arrays And Swaps
|
You are given two arrays $a$ and $b$ both consisting of $n$ positive (greater than zero) integers. You are also given an integer $k$.
In one move, you can choose two indices $i$ and $j$ ($1 \le i, j \le n$) and swap $a_i$ and $b_j$ (i.e. $a_i$ becomes $b_j$ and vice versa). Note that $i$ and $j$ can be equal or different (in particular, swap $a_2$ with $b_2$ or swap $a_3$ and $b_9$ both are acceptable moves).
Your task is to find the \textbf{maximum} possible sum you can obtain in the array $a$ if you can do no more than (i.e. at most) $k$ such moves (swaps).
You have to answer $t$ independent test cases.
|
Each move we can choose the minimum element in $a$, the maximum element in $b$ and swap them (if the minimum in $a$ is less than maximum in $b$). If we repeat this operation $k$ times, we get the answer. This can be done in $O(n^3)$, $O(n^2)$ but authors solution is $O(n \log n)$.
|
[
"greedy",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto &it : a) cin >> it;
vector<int> b(n);
for (auto &it : b) cin >> it;
sort(a.begin(), a.end());
sort(b.rbegin(), b.rend());
int ans = 0;
for (int i = 0; i < n; ++i) {
if (i < k) ans += max(a[i], b[i]);
else ans += a[i];
}
cout << ans << endl;
}
return 0;
}
|
1353
|
C
|
Board Moves
|
You are given a board of size $n \times n$, where $n$ is \textbf{odd} (not divisible by $2$). Initially, each cell of the board contains one figure.
In one move, you can select \textbf{exactly one figure} presented in some cell and move it to one of the cells \textbf{sharing a side or a corner with the current cell}, i.e. from the cell $(i, j)$ you can move the figure to cells:
- $(i - 1, j - 1)$;
- $(i - 1, j)$;
- $(i - 1, j + 1)$;
- $(i, j - 1)$;
- $(i, j + 1)$;
- $(i + 1, j - 1)$;
- $(i + 1, j)$;
- $(i + 1, j + 1)$;
Of course, you \textbf{can not} move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.
Your task is to find the minimum number of moves needed to get \textbf{all the figures} into \textbf{one} cell (i.e. $n^2-1$ cells should contain $0$ figures and one cell should contain $n^2$ figures).
You have to answer $t$ independent test cases.
|
It is intuitive (and provable) that the best strategy is to move each figure to the center cell $(\frac{n+1}{2}, \frac{n+1}{2})$. Now, with some paperwork or easy observations, we can notice that we have exactly $8$ cells with the shortest distance $1$, $16$ cells with the shortest distance $2$, $24$ cells with the shortest distance $3$ and so on. So we have $8i$ cells with the shortest distance $i$. So the answer is $1 \cdot 8 + 2 \cdot 16 + 3 \cdot 24 + \dots + (\frac{n-1}{2})^2 \cdot 8$. It can be rewritten as $8 (1 + 4 + 9 + \dots + (\frac{n-1}{2})^2)$ so we can just calculate the sum of squares of all integers from $1$ to $\frac{n-1}{2}$ using loop (or formula $\frac{n(n+1)(2n+1)}{6}$) and multiply the answer by $8$. Time complexity: $O(n)$ or $O(1)$.
|
[
"math"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
long long ans = 0;
for (int i = 1; i <= n / 2; ++i) {
ans += i * 1ll * i;
}
cout << ans * 8 << endl;
}
return 0;
}
|
1353
|
D
|
Constructing the Array
|
You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears:
- Choose the maximum by length subarray (\textbf{continuous subsegment}) consisting \textbf{only} of zeros, among all such segments choose the \textbf{leftmost} one;
- Let this segment be $[l; r]$. If $r-l+1$ is odd (not divisible by $2$) then assign (set) $a[\frac{l+r}{2}] := i$ (where $i$ is the number of the current action), otherwise (if $r-l+1$ is even) assign (set) $a[\frac{l+r-1}{2}] := i$.
Consider the array $a$ of length $5$ (initially $a=[0, 0, 0, 0, 0]$). Then it changes as follows:
- Firstly, we choose the segment $[1; 5]$ and assign $a[3] := 1$, so $a$ becomes $[0, 0, 1, 0, 0]$;
- then we choose the segment $[1; 2]$ and assign $a[1] := 2$, so $a$ becomes $[2, 0, 1, 0, 0]$;
- then we choose the segment $[4; 5]$ and assign $a[4] := 3$, so $a$ becomes $[2, 0, 1, 3, 0]$;
- then we choose the segment $[2; 2]$ and assign $a[2] := 4$, so $a$ becomes $[2, 4, 1, 3, 0]$;
- and at last we choose the segment $[5; 5]$ and assign $a[5] := 5$, so $a$ becomes $[2, 4, 1, 3, 5]$.
Your task is to find the array $a$ of length $n$ after performing all $n$ actions. \textbf{Note that the answer exists and unique}.
You have to answer $t$ independent test cases.
|
This is just an implementation problem. We can use some kind of heap or ordered set to store all segments we need in order we need. To solve this problem on C++ with std::set, we can just rewrite the comparator for std::set like this: And then just write the std::set like this: Now the minimum element of the set will be the segment that we need to choose. Initially, the set will contain only one segment $[0;n-1]$. Suppose we choose the segment $[l; r]$ during the $i$-th action. Let $id = \lfloor\frac{l+r}{2}\rfloor$, where $\lfloor\frac{x}{y}\rfloor$ is $x$ divided by $y$ rounded down. Assign (set) $a[id] := i$, then if the segment $[l; id-1]$ has positive (greater than zero) length, push this segment to the set and the same with the segment $[id+1;r]$. After $n$ such actions we get the answer. Time complexity: $O(n \log n)$.
|
[
"constructive algorithms",
"data structures",
"sortings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
struct cmp {
bool operator() (const pair<int, int> &a, const pair<int, int> &b) const {
int lena = a.second - a.first + 1;
int lenb = b.second - b.first + 1;
if (lena == lenb) return a.first < b.first;
return lena > lenb;
}
};
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
set<pair<int, int>, cmp> segs;
segs.insert({0, n - 1});
vector<int> a(n);
for (int i = 1; i <= n; ++i) {
pair<int, int> cur = *segs.begin();
segs.erase(segs.begin());
int id = (cur.first + cur.second) / 2;
a[id] = i;
if (cur.first < id) segs.insert({cur.first, id - 1});
if (id < cur.second) segs.insert({id + 1, cur.second});
}
for (auto it : a) cout << it << " ";
cout << endl;
}
return 0;
}
|
1353
|
E
|
K-periodic Garland
|
You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$.
In one move, you can choose \textbf{one lamp} and change its state (i.e. turn it on if it is turned off and vice versa).
The garland is called $k$-periodic if the distance between \textbf{each pair of adjacent turned on lamps} is \textbf{exactly} $k$. Consider the case $k=3$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that \textbf{the garland is not cyclic}, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.
Your task is to find the \textbf{minimum} number of moves you need to make to obtain $k$-periodic garland from the given one.
You have to answer $t$ independent test cases.
|
Let $t_i$ be the string containing all characters of $s$ that have indices $i, i + k, i + 2k$ and so on (i.e. all such positions that have the remainder $i$ modulo $k$). Suppose we choose that all turned on lamps will have remainder $i$ modulo $k$. Then we need to remove all ones at the positions that do not belong to this remainder. Also considering the string $t_i$, we need to spend the minimum number of moves to make this string of kind "contiguous block of zeros, contiguous block of ones and again contiguous block of zeros", because considering the characters modulo $k$ will lead us to exactly this pattern (notice that some blocks can be empty). How to calculate the answer for the string $t_i$ in linear time? Let $dp_i[p]$ be the number of moves we need to fix the prefix of $t_i$ till the $p$-th character in a way that the $p$-th character of $t_i$ is '1'. Let $cnt(S, l, r)$ be the number of ones in $S$ on the segment $[l; r]$. Notice that we can calculate all required values $cnt$ in linear time using prefix sums. Then we can calculate $dp_i[p]$ as $min(cnt(t_i, 0, p - 1) + [t_i[p] \ne~ '1'], dp_i[p-1] + [t_i[p] \ne~ '1'])$, where $[x]$ is the boolean value of the expression $x$ ($1$ if $x$ is true and $0$ otherwise). Let $len(S)$ be the length of $S$. Then the actual answer for the string $t_i$ can be calculated as $ans_i = \min(cnt(t_i, 0, len(t_i) - 1), \min\limits_{p=0}^{len(t_i) - 1} (dp_i[p] + cnt(t_i, p + 1, len(t_i) - 1)))$ (thus we consider the case when the obtained string doesn't contan ones at all and consider each position as the last position of some one). So the actual answer can be calculated as $\min\limits_{i=0}^{k-1} (ans_i + cnt(s, 0, len(s) - 1) - cnt(t_i, 0, len(t_i) - 1))$. Time complexity: $O(n)$.
|
[
"brute force",
"dp",
"greedy"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
auto solve = [](const string &s) {
int n = s.size();
int all = count(s.begin(), s.end(), '1');
int ans = all;
vector<int> res(n);
int pref = 0;
for (int i = 0; i < n; ++i) {
int cur = (s[i] == '1');
pref += cur;
res[i] = 1 - cur;
if (i > 0) res[i] += min(res[i - 1], pref - cur);
ans = min(ans, res[i] + all - pref);
}
return ans;
};
int t;
cin >> t;
while (t--) {
int n, k;
string s;
cin >> n >> k >> s;
vector<string> val(k);
int cnt = count(s.begin(), s.end(), '1');
for (int i = 0; i < n; ++i) {
val[i % k] += s[i];
}
int ans = 1e9;
for (auto &it : val) ans = min(ans, solve(it) + (cnt - count(it.begin(), it.end(), '1')));
cout << ans << endl;
}
return 0;
}
|
1353
|
F
|
Decreasing Heights
|
You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size $n \times m$, where the height of the cell $(i, j)$ is $a_{i, j}$.
You are in the cell $(1, 1)$ right now and want to get in the cell $(n, m)$. You can move only down (from the cell $(i, j)$ to the cell $(i + 1, j)$) or right (from the cell $(i, j)$ to the cell $(i, j + 1)$). There is an additional \textbf{restriction}: if the height of the current cell is $x$ then you can move only to the cell with height $x+1$.
\textbf{Before the first move} you can perform several operations. During one operation, you can decrease the height of \textbf{any} cell by one. I.e. you choose some cell $(i, j)$ and assign (set) $a_{i, j} := a_{i, j} - 1$. Note that you \textbf{can} make heights \textbf{less than or equal to zero}. Also note that you \textbf{can} decrease the height of the cell $(1, 1)$.
Your task is to find the \textbf{minimum} number of operations you have to perform to obtain at least one suitable path from the cell $(1, 1)$ to the cell $(n, m)$. It is guaranteed that the answer exists.
You have to answer $t$ independent test cases.
|
Firstly, consider the field in $0$-indexation. Suppose that the cell $(0, 0)$ has some fixed height. Let it be $b_{0, 0}$. Then we can determine what should be the height of the cell $(i, j)$ as $b_{i, j} = b_{0, 0} + i + j$. In fact, it does not matter which way we choose, we actually need only the number of moves to reach the cell and the height of the cell $(0, 0)$. Then (when the height of the cell $(0, 0)$ is fixed) we can solve the problem with the following dynamic programming: $dp_{i, j}$ is the minimum number of operations we need to reach the cell $(i, j)$ from the cell $(0, 0)$. Initially, all values $dp_{i, j} = +\infty$ except $dp_{0, 0} = 0$. Then $dp_{i, j}$ can be calculated as $min(dp_{i - 1, j}, dp_{i, j - 1}) + (a_{i, j} - b_{i, j})$. But one more thing: if $a_{i, j} < b_{i, j}$ then this value of $dp$ is incorrect and we cannot use it. We also can't update $dp$ from the incorrect values. The answer for the problem with the fixed height of the cell $(0, 0)$ is $dp_{n - 1, m - 1} + a_{0, 0} - b_{0, 0}$ (only when $dp_{n-1,m-1}$ is correct and $a_{i, j} \ge b_{i, j}$). This part can be calculated in $O(n^2)$. But if we iterate over all possible heights, our solution obvious will get time limit exceeded verdict. Now we can notice one important fact: in the optimal answer, the height of some cell remains unchanged. Let this cell be $(i, j)$. Then we can restore the height of the cell $(0, 0)$ as $a_{i, j} - i - j$ and run our quadratic dynamic programming to find the answer for this height. Time complexity: $O(n^4)$.
|
[
"brute force",
"dp"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
const long long INF64 = 1e18;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<vector<long long>> a(n, vector<long long>(m));
forn(i, n) forn(j, m) {
cin >> a[i][j];
}
long long a00 = a[0][0];
long long ans = INF64;
forn(x, n) forn(y, m) {
long long need = a[x][y] - x - y;
if (need > a00) continue;
a[0][0] = need;
vector<vector<long long>> dp(n, vector<long long>(m, INF64));
dp[0][0] = a00 - need;
forn(i, n) forn(j, m) {
long long need = a[0][0] + i + j;
if (need > a[i][j]) continue;
if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + a[i][j] - need);
if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + a[i][j] - need);
}
ans = min(ans, dp[n - 1][m - 1]);
}
cout << ans << endl;
}
return 0;
}
|
1354
|
A
|
Alarm Clock
|
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $a$ minutes to feel refreshed.
\textbf{Polycarp can only wake up by hearing the sound of his alarm.} So he has just fallen asleep and his first alarm goes off in $b$ minutes.
Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $a$ minutes in total, then he sets his alarm to go off in $c$ minutes after it is reset and spends $d$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.
If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $c$ minutes and tries to fall asleep for $d$ minutes again.
You just want to find out when will Polycarp get out of his bed or report that it will never happen.
\textbf{Please check out the notes for some explanations of the example.}
|
Let's handle some cases. Firstly, if $b \ge a$ then Polycarp wakes up rested enough immediately, so $b$ is the answer. Otherwise, what does Polycarp do? He sets alarm to go off in $c$ minutes and falls asleep in $d$ minutes. Thus, he spends $c-d$ minutes sleeping. Notice that if $c-d$ is non-positive, then Polycarp always resets his alarm without sleeping. So for that case the answer is -1. Finally, if Polycarp resets his alarm $x$ times then he ends up with $b + x \cdot (c - d)$ minutes of sleep in total and ends up spending $b + x \cdot c$ minutes of time. We know that $b + x \cdot (c - d)$ should be greater or equal to $a$ and $x$ should be the smallest possible. $b + x \cdot (c - d) \ge a \leftrightarrow x \cdot (c - d) \ge a - b \leftrightarrow x \ge \frac{a - b}{c - d}$ Thus, the smallest possible integer $x$ is equal to $\lceil \frac{a - b}{c - d} \rceil$. And the answer is $b + x \cdot c$. Overall complexity: $O(1)$ per testcase.
|
[
"math"
] | 900
|
t = int(input())
for _ in range(t):
a, b, c, d = map(int, input().split())
if b >= a:
print(b)
continue
if c <= d:
print(-1)
continue
a -= b
dif = c - d
print(b + (a + dif - 1) // dif * c)
|
1354
|
B
|
Ternary String
|
You are given a string $s$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $s$ such that it contains each of these three characters at least once.
A contiguous substring of string $s$ is a string that can be obtained from $s$ by removing some (possibly zero) characters from the beginning of $s$ and some (possibly zero) characters from the end of $s$.
|
There are multiple solutions involving advanced methods such as binary search or two pointers, but I'll try to describe a simpler one. The main idea of my solution is that the answer should look like abb...bbbbbc: one character of type $a$, a block of characters of type $b$, and one character of type $c$. If we find all blocks of consecutive equal characters in our string, each candidate for the answer can be obtained by expanding a block to the left and to the right by exactly one character. So the total length of all candidates is $O(n)$, and we can check them all. Why does the answer look like abb...bbbbbc? If the first character of the substring appears somewhere else in it, it can be deleted. The same applies for the last character. So, the first and the last characters should be different, and should not appear anywhere else within the string. Since there are only three types of characters, the answer always looks like abb...bbbbbc.
|
[
"binary search",
"dp",
"implementation",
"two pointers"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
char buf[200043];
int main()
{
int t;
scanf("%d", &t);
for(int i = 0; i < t; i++)
{
scanf("%s", buf);
string s = buf;
int ans = int(1e9);
int n = s.size();
vector<pair<char, int> > c;
for(auto x : s)
{
if(c.empty() || c.back().first != x)
c.push_back(make_pair(x, 1));
else
c.back().second++;
}
int m = c.size();
for(int i = 1; i < m - 1; i++)
if(c[i - 1].first != c[i + 1].first)
ans = min(ans, c[i].second + 2);
if(ans > n)
ans = 0;
printf("%d\n", ans);
}
}
|
1354
|
C1
|
Simple Polygon Embedding
|
\textbf{The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.}
You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon.
Your task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square.
You can rotate $2n$-gon and/or the square.
|
It's not hard to come up with a solution if you just imagine how $2n$-gon looks when $n$ is even. The solution is to rotate $2n$-gon in such way that several its sides are parallel to sides of the square. And the answer is equal to the distance from center to any side multiplied by two, or: $ans = \frac{1}{\tan{\frac{\pi}{2 \cdot n}}}$
|
[
"binary search",
"geometry",
"math",
"ternary search"
] | 1,400
| null |
1354
|
C2
|
Not So Simple Polygon Embedding
|
\textbf{The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.}
You are given a regular polygon with $2 \cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon.
Your task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square.
You can rotate $2n$-gon and/or the square.
|
At first, lets place $2n$-gon in such way that the lowest side of $2n$-gon is horizontal. Now we can, without loss of generality, think that the square has horizontal and vertical sides and we just rotate $2n$-gon around its center. If we rotate the $2n$-gon at angle $\frac{\pi}{n}$ then it will move on itself. Moreover, after rotating at angle $\frac{\pi}{2n}$ we'll get left and right sides vertical and the following rotation is meaningless since it's the same as if we just swap $x$ and $y$ coordinates. So we don't we to rotate more than $\frac{\pi}{2n}$. Also, we can see that while rotating the difference between max $x$ and min $x$ decreasing while the distance between max $y$ and min $y$ increasing. The answer is, obviously, the maximum among these differences. So, for example, we can just ternary search the optimal answer. Or we can note that the behavior of differences is symmetrical (just swap $x$ and $y$ coordinates) so the answer is in the middle angle, i.e. we just need to rotate $2n$-gon at angle $\frac{\pi}{4n}$. Finally, observing several right triangles we can come up with quite an easy answer: $ans = \frac{\cos(\frac{\pi}{4n})}{\sin(\frac{\pi}{2n})}$
|
[
"binary search",
"brute force",
"geometry",
"math"
] | 2,000
|
import kotlin.math.*
fun main() {
val PI = acos(-1.0)
val T = readLine()!!.toInt()
for (tc in 1..T) {
val n = readLine()!!.toInt()
var ans : Double
if (n % 2 == 0) {
ans = 1.0 / tan(PI / (2 * n))
} else {
ans = cos(PI / (4 * n)) / sin(PI / (2 * n))
}
println("%.9f".format(ans))
}
}
|
1354
|
D
|
Multiset
|
\textbf{Note that the memory limit is unusual.}
You are given a multiset consisting of $n$ integers. You have to process queries of two types:
- add integer $k$ into the multiset;
- find the $k$-th order statistics in the multiset and remove it.
$k$-th order statistics in the multiset is the $k$-th element in the sorted list of all elements of the multiset. For example, if the multiset contains elements $1$, $4$, $2$, $1$, $4$, $5$, $7$, and $k = 3$, then you have to find the $3$-rd element in $[1, 1, 2, 4, 4, 5, 7]$, which is $2$. If you try to delete an element which occurs multiple times in the multiset, only one occurence is removed.
After processing all queries, print \textbf{any} number belonging to the multiset, or say that it is empty.
|
First solution: write some data structure that would simulate the operations as they are given, for example, a segment tree or a Fenwick tree. Probably will require optimization since the limits are strict. Second solution: notice that we have to find only one number belonging to the multiset. For example, let's find the minimum element. We can do it with binary search as follows: let's write a function that, for a given element $x$, tells the number of elements not greater than $x$ in the resulting multiset. To implement it, use the fact that all elements $\le x$ are indistinguishable, and all elements $> x$ are indistinguishable too, so the multiset can be maintained with just two counters. Okay, how does this function help? The minimum in the resulting multiset is the minimum $x$ such that this function returns non-zero for it, and since the function is monotonous, we can find the answer with binary search.
|
[
"binary search",
"data structures"
] | 1,900
|
#include<bits/stdc++.h>
using namespace std;
int n, q;
vector<int> a, k;
int count_le(int x)
{
int cnt = 0;
for(auto y : a)
if(y <= x)
cnt++;
for(auto y : k)
{
if(y > 0 && y <= x)
cnt++;
if(y < 0 && abs(y) <= cnt)
cnt--;
}
return cnt;
}
int main()
{
scanf("%d %d", &n, &q);
a.resize(n);
k.resize(q);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
for(int i = 0; i < q; i++)
scanf("%d", &k[i]);
if(count_le(int(1e9)) == 0)
{
puts("0");
return 0;
}
int lf = 0;
int rg = int(1e6) + 1;
while(rg - lf > 1)
{
int mid = (lf + rg) / 2;
if(count_le(mid) > 0)
rg = mid;
else
lf = mid;
}
printf("%d\n", rg);
return 0;
}
|
1354
|
E
|
Graph Coloring
|
You are given an undirected graph without self-loops or multiple edges which consists of $n$ vertices and $m$ edges. Also you are given three integers $n_1$, $n_2$ and $n_3$.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
- Each vertex should be labeled by exactly one number 1, 2 or 3;
- The total number of vertices with label 1 should be equal to $n_1$;
- The total number of vertices with label 2 should be equal to $n_2$;
- The total number of vertices with label 3 should be equal to $n_3$;
- $|col_u - col_v| = 1$ for each edge $(u, v)$, where $col_x$ is the label of vertex $x$.
If there are multiple valid labelings, print any of them.
|
Let's rephrase the fifth condition. Each edge should connect two vertices with the numbers of different parity (either $1$ to $2$ or $3$ to $2$). So the graph should actually be bipartite and the first partition should have only the odd numbers ($1$ or $3$) and the second partition should have only the even numbers (only $2$). Notice how $1$ and $3$ are completely interchangeable in the sense that if you have exactly $n_1 + n_3$ vertices which should be assigned odd numbers then you can assign whichever $n_1$ of them to $1$ and the rest to $3$ you want. So you can guess that the first step is to check if the given graph is bipartite. If it isn't then the answer doesn't exist. It can be done with a single dfs. Actually the algorithm for that extracts the exact partitions, which comes pretty handy. If the graph was a single connected component then the problem would be easy. Just check if either the first partition or the second one has size $n_2$ and assigned its vertices color $2$. If neither of them are of size $n_2$ then the answer obviously doesn't exist. However, the issue is that there might be multiple connected components and for each of them you can choose the partition to assign $2$ to independently. Still, each of the connected components should be bipartite for the answer to exist. This can be done with a knapsack-like dp. Let the $i$-th connected component have partitions of sizes $(l_i, r_i)$. Then the state can be $dp[i][j]$ is true if $i$ connected components are processed and it's possible to assign $2$ to exactly $j$ vertices of these components. As for transitions, for the $i$-th component you can either take the partition with $l_i$ vertices or with $r_i$ vertices. Thus, if $dp[i][j]$ is true then both of $dp[i + 1][j + l_i]$ and $dp[i + 1][j + r_i]$ are also true. If $dp[number\_of\_connected\_components][n_2]$ is false then there is no answer. Otherwise, you can always restore the answer through the dp. The easiest way is probably to store not true/false in $dp[i][j]$ but three values: $-1$ for false, $0$ for the case the state is reached by taking the first partition of the $(i-1)$-th component and $1$ for the second partition. Also, you should store not only the sizes of the partitions but the vertices in each of them as well. This way you can recover the answer by backtracking from the final state. Overall complexity: $O(n^2)$.
|
[
"dfs and similar",
"dp",
"graphs"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define sqr(a) ((a) * (a))
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
template <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {
return out << "(" << a.x << ", " << a.y << ")";
}
template <class A> ostream& operator << (ostream& out, const vector<A> &v) {
out << "[";
forn(i, sz(v)) {
if(i) out << ", ";
out << v[i];
}
return out << "]";
}
mt19937 rnd(time(NULL));
const int INF = int(1e9);
const li INF64 = li(1e18);
const int MOD = int(1e9) + 7;
const ld EPS = 1e-9;
const ld PI = acos(-1.0);
const int N = 5000 + 7;
int n, m;
int a[3];
vector<int> g[N];
bool read () {
if (scanf("%d%d", &n, &m) != 2)
return false;
forn(i, 3) scanf("%d", &a[i]);
forn(i, n)
g[i].clear();
forn(i, m){
int v, u;
scanf("%d%d", &v, &u);
--v, --u;
g[v].pb(u);
g[u].pb(v);
}
return true;
}
int tot0, tot1;
int clr[N];
vector<vector<int>> vts[2];
bool ok;
void dfs(int v){
tot0 += clr[v] == 0;
tot1 += clr[v] == 1;
vts[clr[v]].back().pb(v);
for (auto u : g[v]){
if (clr[u] == -1){
clr[u] = clr[v] ^ 1;
dfs(u);
}
else if (clr[u] == clr[v]){
ok = false;
}
}
}
int dp[N][N];
int res[N];
void solve() {
vector<pt> siz;
memset(clr, -1, sizeof(clr));
vts[0].clear();
vts[1].clear();
forn(i, n) if (clr[i] == -1){
tot0 = tot1 = 0;
clr[i] = 0;
ok = true;
vts[0].pb(vector<int>());
vts[1].pb(vector<int>());
dfs(i);
if (!ok){
puts("NO");
return;
}
siz.pb(mp(tot0, tot1));
}
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
forn(i, sz(siz)) forn(j, N) if (dp[i][j] != -1){
dp[i + 1][j + siz[i].x] = 0;
dp[i + 1][j + siz[i].y] = 1;
}
if (dp[sz(siz)][a[1]] == -1){
puts("NO");
return;
}
puts("YES");
memset(res, -1, sizeof(res));
int cur = a[1];
for (int i = sz(siz); i > 0; --i){
for (auto it : vts[dp[i][cur]][i - 1])
res[it] = 2;
cur -= sz(vts[dp[i][cur]][i - 1]);
}
forn(i, n) if (res[i] == -1){
if (a[0] > 0){
res[i] = 1;
--a[0];
}
else{
res[i] = 3;
--a[2];
}
}
forn(i, n) printf("%d", res[i]);
puts("");
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int tt = clock();
#endif
cerr.precision(15);
cout.precision(15);
cerr << fixed;
cout << fixed;
while(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
}
|
1354
|
F
|
Summoning Minions
|
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.
Polycarp can summon $n$ different minions. The initial power level of the $i$-th minion is $a_i$, and when it is summoned, all previously summoned minions' power levels are increased by $b_i$. The minions can be summoned in any order.
Unfortunately, Polycarp cannot have more than $k$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.
Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).
Help Polycarp to make up a plan of actions to summon the strongest possible army!
|
First of all, let's try to find the best strategy to play minions. All minions should be summoned (if someone is not summoned, summoning and deleting it won't make the answer worse), the resulting number of minions should be exactly $k$ (if it is less, then we didn't need to delete the last deleted minion). Furthermore, if some minion should be deleted, we can delete it just after it is summoned. All these greedy ideas lead to the following structure of the answer: we choose $k - 1$ minions and summon them in some order; we choose $n - k$ minions which will be summoned and instantly deleted; we summon the remaining minion. Let's analyze how these minions affect the answer. The first minion has power $a_i$ and does not give bonus to anyone, the second one has power $a_i$ and gives bonus to one minion, and so on - the $j$-th minion from the first group adds $a_i + (j - 1)b_i$ to the answer. Minions from the second group buff $k - 1$ minions each, so they add $b_i(k - 1)$ to the answer; and the last minion adds $a_i + b_i(k - 1)$. Let's unite the first group and the last minion; then we will have two groups of minions - those which are destroyed (the second group) and those which are not destroyed (the first group). From there, we will have two possible ways to finish the solution: there are $n$ minions and $n$ positions for them, and for each pair (minion, position) we may calculate the value this pair adds to the answer. After that, we should assign each monster a position in such a way that each position is chosen exactly once, and the sum of values is maximized. It can be done with mincost flows or Hungarian algorithm; the minions from the first group should be played in non-descending order of their $b_i$. Let's sort all minions by $b_i$ and write the following dynamic programming: $dp_{x, y}$ is the maximum answer if we considered $x$ first minions, and $y$ of them were assigned to the first group. Since the minions are sorted by $b_i$, whenever we add a minion to the first group, it should add exactly $a_i + yb_i$ to the answer (and increase $y$ by $1$); and if a minion is added to the second group, the answer is increased by $(k - 1)b_i$.
|
[
"constructive algorithms",
"dp",
"flows",
"graph matchings",
"greedy",
"sortings"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define sqr(a) ((a) * (a))
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
template <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {
return out << "(" << a.x << ", " << a.y << ")";
}
template <class A> ostream& operator << (ostream& out, const vector<A> &v) {
out << "[";
forn(i, sz(v)) {
if(i) out << ", ";
out << v[i];
}
return out << "]";
}
mt19937 rnd(time(NULL));
const int INF = int(1e9);
const li INF64 = li(1e18);
const int MOD = int(1e9) + 7;
const ld EPS = 1e-9;
const ld PI = acos(-1.0);
const int N = 100;
int n, k;
pair<pt, int> a[N];
bool read () {
if (scanf("%d%d", &n, &k) != 2)
return false;
forn(i, n){
scanf("%d%d", &a[i].x.x, &a[i].x.y);
a[i].y = i;
}
return true;
}
int dp[N][N];
int p[N][N];
void solve() {
sort(a, a + n, [](const pair<pt, int> &a, const pair<pt, int> &b){
if (a.x.y != b.x.y)
return a.x.y < b.x.y;
return a.x.x < b.x.x;
});
forn(i, N) forn(j, N)
dp[i][j] = -INF;
dp[0][0] = 0;
forn(i, n) forn(j, N) if (dp[i][j] >= 0){
if (dp[i + 1][j] < dp[i][j] + a[i].x.y * (k - 1)){
dp[i + 1][j] = dp[i][j] + a[i].x.y * (k - 1);
p[i + 1][j] = j;
}
if (dp[i + 1][j + 1] < dp[i][j] + a[i].x.y * j + a[i].x.x){
dp[i + 1][j + 1] = dp[i][j] + a[i].x.y * j + a[i].x.x;
p[i + 1][j + 1] = j;
}
}
vector<int> ans1, ans2;
int cur = k;
for (int i = n; i > 0; --i){
if (p[i][cur] == cur)
ans2.pb(a[i - 1].y + 1);
else
ans1.pb(a[i - 1].y + 1);
cur = p[i][cur];
}
reverse(all(ans1));
reverse(all(ans2));
printf("%d\n", sz(ans1) + sz(ans2) * 2);
forn(i, sz(ans1) - 1)
printf("%d ", ans1[i]);
for (auto it : ans2)
printf("%d %d ", it, -it);
printf("%d\n", ans1.back());
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int tt = clock();
#endif
cerr.precision(15);
cout.precision(15);
cerr << fixed;
cout << fixed;
int tc;
scanf("%d", &tc);
while(tc--) {
read();
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
}
|
1354
|
G
|
Find a Gift
|
This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.
There are $n$ gift boxes in a row, numbered from $1$ to $n$ from left to right. It's known that exactly $k$ of them contain valuable gifts — other boxes contain just lucky stones. All boxes look the same and differ only in weight. All boxes with stones have the same weight and are strictly heavier than boxes with valuable items. But valuable gifts may be different, so the boxes with valuable items may have different weights.
You can ask no more than $50$ queries (printing an answer doesn't count). By each query you can compare total weights of two non-intersecting subsets of boxes $a_1, a_2, \dots, a_{k_a}$ and $b_1, b_2, \dots, b_{k_b}$. In return you'll get one of four results:
- FIRST, if subset $a_1, a_2, \dots, a_{k_a}$ is strictly \textbf{heavier};
- SECOND, if subset $b_1, b_2, \dots, b_{k_b}$ is strictly \textbf{heavier};
- EQUAL, if subsets have equal total weights;
- WASTED, if the query is incorrect or the limit of queries is exceeded.
Using such queries (or, maybe, intuition) find the box with a valuable gift with \textbf{the minimum index}.
|
The solution consists of several steps. The first step. Let's find out "does the first box contain stone or valuable gift" using random. Let's make $30$ queries to compare the weight of the first box with the weight of another random box. If the first box is lighter than we found an answer, otherwise the probability of the first box having stones is at least $1 - 2^{-30}$. The second step. Let's compare the weights of the first box and the second one. If they are equal then let's compare the weights of boxes $[1, 2]$ and $[3,4]$. If they are equal then let's compare the boxes $[1 \dots 4]$ and $[5 \dots 8]$ and so on. In other words, let's find the minimum $k \ge 0$ such that $[1, 2^k]$ contains only boxes with stones but $[2^k + 1, 2^{k + 1}]$ contain at least one box with a valuable gift. It's easy to see that we'd spend no more than $10$ queries. The third step. We have segment $[1, 2^k]$ with only stones and $[2^k + 1, 2^{k + 1}]$ with at least one gift. Let's just binary search the leftmost gift in the segment $[2^k + 1, 2^{k + 1}]$ using boxes from $[1, 2^k]$ as reference: if we need to know "does segment of boxes $[l, mid)$ have at least one gift", let's just compare it with segment $[0, mid - l)$ which have only stones. if $[l, mid)$ is lighter then it has, otherwise doesn't have. This part also requires no more than $10$ queries.
|
[
"binary search",
"interactive",
"probabilities"
] | 2,600
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int MAG = 30;
int lst;
int n, k;
inline bool read() {
if(!(cin >> n >> k))
return false;
return true;
}
int ask(int l1, int r1, int l2, int r2) {
assert(l1 < r1 && l2 < r2);
assert(r1 <= l2 || r2 <= l1);
cout << "? " << r1 - l1 << " " << r2 - l2 << endl;
fore(i, l1, r1) {
if (i > l1) cout << " ";
cout << i + 1;
}
cout << endl;
fore(i, l2, r2) {
if (i > l2) cout << " ";
cout << i + 1;
}
cout << endl;
cout.flush();
string resp;
cin >> resp;
if (resp == "FIRST")
return -1;
if (resp == "SECOND")
return 1;
if (resp == "EQUAL")
return 0;
exit(0);
}
inline void solve() {
//check first position
mt19937 rnd(lst ^ (n * 1024 + k));
for(int q = 0; q < MAG; q++) {
int cur = 1 + rnd() % (n - 1);
int resp = ask(0, 1, cur, cur + 1);
if (resp == 1) {
cout << "! 1" << endl;
cout.flush();
return;
}
}
int len = 1;
while(true) {
int cnt = min(len, n - len);
int resp = ask(0, cnt, len, len + cnt);
if (resp != 0) {
assert(resp == -1);
break;
}
len <<= 1;
}
int lf = len, rg = min(2 * len, n);
while(rg - lf > 1) {
int mid = (lf + rg) >> 1;
int resp = ask(0, mid - lf, lf, mid);
assert(resp != 1);
if (resp == 0)
lf = mid;
else
rg = mid;
}
cout << "! " << lf + 1 << endl;
cout.flush();
lst = lf + 1;
}
int main() {
int tc;
cin >> tc;
lst = tc;
while(tc--) {
assert(read());
solve();
}
return 0;
}
|
1355
|
A
|
Sequence with Digits
|
Let's define the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$
Here $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes.
Your task is calculate $a_{K}$ for given $a_{1}$ and $K$.
|
Let's calculate the sequence for fixed $a_{1} = 1$: $1, 2, 6, 42, 50, 50, 50, \ldots$ We got lucky and the minimal digit has become 0, after that the element has stopped changing because we always add 0. Actually it is not luck and that will always happen. Note that we add no more than $9 \cdot 9 = 81$ every time, so the difference between two consecutive elements of the sequence is bounded by 81. Assume that we will never have minimal digit equal to 0. Then the sequence will go to infinity. Let's take $X = 1000(\lfloor \frac{a_{1}}{1000} \rfloor + 1)$. All the numbers on segment $[X;X+99]$ have 0 in hundreds digit, so none of them can be element of our sequence. But our sequence should have numbers greater than $X$. Let's take the smallest of them, it should be at least $X + 100$. But then the previous number in the sequence is at least $(X + 100) - 81 = X + 19$. It is greater than $X$ but smaller than the minimal of such numbers. Contradiction. In the previous paragraph we have actually shown that we have no numbers greater than $X + 100$ in our sequence and we will see the number with 0 among first 1001 elements. That means that we can build the sequence till we find the first number with 0 and then it will repeat forever. In reality the maximal index of the first elements with 0 is 54 and minimal $a_{1}$ for that to happen is 28217.
|
[
"brute force",
"implementation",
"math"
] | 1,200
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
double startTime;
double getCurrentTime() {
return ((double)clock() - startTime) / CLOCKS_PER_SEC;
}
ll getAdd(ll x) {
ll m1 = 10, m2 = 0;
while(x > 0) {
ll y = x % 10;
x /= 10;
m1 = min(m1, y);
m2 = max(m2, y);
}
return m1 * m2;
}
int main()
{
startTime = (double)clock();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int t;
scanf("%d", &t);
while(t--) {
ll x, k;
scanf("%lld%lld", &x, &k);
k--;
while(k--) {
ll y = getAdd(x);
if (y == 0) break;
x += y;
}
printf("%lld\n", x);
}
return 0;
}
|
1355
|
B
|
Young Explorers
|
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $e_i$ — his inexperience. Russell decided that an explorer with inexperience $e$ can only join the group of $e$ or more people.
Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.
|
Let's sort all the explorers by non-decreasing inexperience. Suppose we have formed some group, how can we check is this group is valid? Inexperience of all the explorers in the group should be not greater than the group size. But we have sorted all the explorers, so the last explorer from the group has the largest inexperience. Therefore, to check the group for validity it is necessary and sufficient to check that inexperience of the last explorer is not greater than the group size. We can notice that we don't even look at all the explorers except the last one, the only important thing is their number. In fact, we can organize the creation of groups in this way: first choose the explorers that will be the last in their groups, then assign sufficient number of other explorers to corresponding groups. It is not profitable to assign more explorers than needed for this particular last explorer, because we can always leave them at the camp. So how should we choose the last explorers? We want to make more groups, so the groups themselves should me smaller... It is tempting to use the following greedy algorithm: let's greedily pick the leftmost (which means with the smallest necessary group size) explorer such that they have enough explorers to the left of them to create a valid group. The idea is that we spend the smallest number of explorers and leave the most potential last explorers in the future. Let's strictly prove this greedy: The solution is defined by positions of the last explorers in their corresponding groups $1 \le p_{1} < p_{2} < \ldots < p_{k} \le n$. Notice that the solution is valid if and only if $e_{p_{1}} + e_{p_{2}} + \ldots + e_{p_{i}} \le p_{i}$ for all $1 \le i \le k$ (we always have enough explorers to form first $i$ groups). Let $1 \le p_{1} < p_{2} < \ldots < p_{k} \le n$ be the greedy solution and $1 \le q_{1} < q_{2} < \ldots < q_{m} \le n$ be the optimal solution such that it has the largest common prefix with greedy one among all optimal solutions. Let $t$ be the position of first difference in these solutions. $t \le k$ since otherwise the greedy algorithm couldn't add one more group but it was possible. $p_{t} < q_{t}$ since otherwise the greedy algorithm would take $q_{t}$ instead of $p_{t}$. Since the explorers are sorted we have $e_{p_{t}} \le e_{q_{t}}$. But then $1 \le q_{1} < q_{2} < \ldots < q_{t - 1} < p_{t} < q_{t + 1} < \ldots < q_{m} \le n$ is a valid optimal solution and it has strictly larger common prefix with the greedy one which contradicts the choosing of our optimal solution. To implement this solution it is enough to sort the explorers by the non-decreasing inexperience, then go from left to right and maintain the number of unused explorers. As soon as we encounter the possibility to create a new group, we do it.
|
[
"dp",
"greedy",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector <int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
int ans = 0, cur = 0;
for (int i = 0; i < n; i++) {
if (++cur == a[i]) {
ans++;
cur = 0;
}
}
cout << ans << '\n';
}
return 0;
}
|
1355
|
C
|
Count Triangles
|
Like any unknown mathematician, Yuri has favourite numbers: $A$, $B$, $C$, and $D$, where $A \leq B \leq C \leq D$. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides $x$, $y$, and $z$ exist, such that $A \leq x \leq B \leq y \leq C \leq z \leq D$ holds?
Yuri is preparing problems for a new contest now, so he is very busy. That's why he asked you to calculate the number of triangles with described property.
The triangle is called non-degenerate if and only if its vertices are not collinear.
|
Since $x \le y \le z$ to be a non-degenerate triangle for given triple it is necessary and sufficient to satisfy $z < x + y$. Let's calculate for all $s = x + y$ how many ways there are to choose $(x, y)$. To do that we will try all $x$ and add 1 on segment $[x + B; x + C]$ offline using prefix sums. Let's calculate prefix sums once more, now we can find in $O(1)$ how many ways there are to choose $(x, y)$ such that their sum if greater than $z$. Try all $z$, calculate the answer. Total complexity - $O(C)$.
|
[
"binary search",
"implementation",
"math",
"two pointers"
] | 1,800
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
double startTime;
double getCurrentTime() {
return ((double)clock() - startTime) / CLOCKS_PER_SEC;
}
const int N = (int)1e6 + 77;
int A, B, C, D;
ll a[N];
int main()
{
startTime = (double)clock();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
scanf("%d%d%d%d", &A, &B, &C, &D);
for (int i = A; i <= B; i++) {
a[i + B]++;
a[i + C + 1]--;
}
for (int i = 1; i < N; i++)
a[i] += a[i - 1];
for (int i = 1; i < N; i++)
a[i] += a[i - 1];
ll ans = 0;
for (int i = C; i <= D; i++)
ans += a[N - 1] - a[i];
printf("%lld\n", ans);
return 0;
}
|
1355
|
D
|
Game With Array
|
Petya and Vasya are competing with each other in a new interesting game as they always do.
At the beginning of the game Petya has to come up with an array of $N$ positive integers. Sum of all elements in his array should be equal to $S$. Then Petya has to select an integer $K$ such that $0 \leq K \leq S$.
In order to win, Vasya has to find a non-empty subarray in Petya's array such that the sum of all selected elements equals to either $K$ or $S - K$. Otherwise Vasya loses.
You are given integers $N$ and $S$. You should determine if Petya can win, considering Vasya plays optimally. If Petya can win, help him to do that.
|
For $S \ge 2N$ Petya wins: let's take array $[2, 2, \ldots, 2, S - 2(N - 1)]$ and $K = 1$. All the elements are strictly greater than 1, so there are no segment with sum 1 or $S - 1$. Let's prove that for $S < 2N$ Petya will lose. Suppose it is not true and there exist an array and $K > 0$ (it is obvious that $K = 0$ is bad). Note that the condition that there is a segment with sum $K$ or $S - K$ is equivalent to the condition that there is a segment with sum $K$ in cyclic array. Let's calculate prefix sums for our array, and for prefix sum $M$ let's mark all the numbers of the form $M + TS$ for integer $T \ge 0$. It is easy to see that numbers $X$ and $X + K$ cannot be marked simultaneously: otherwise there is a segment with sum $K$ in a cyclic array. Let's consider half-interval $[0; 2KS)$. It is clear that exactly $2KN$ numbers are marked on this half-interval. On the other hand, we can split all the numbers from this half-interval into $KS$ pairs with difference $K$: $(0, K), (1, K + 1), \ldots, (K - 1, 2K - 1), (2K, 3K), (2K + 1, 3K + 1), \ldots (2KS - K - 1, 2KS - 1)$. In every such pair no more than one number is marked, so the total number of marked numbers is bounded by $KS$. Therefore $2KN \le KS$ which means $2N \le S$. Contradiction.
|
[
"constructive algorithms",
"math"
] | 1,400
|
#include <iostream>
using namespace std;
int main() {
int n, s;
cin >> n >> s;
if (2 * n <= s) {
cout << "YES\n";
for (int i = 0; i < n - 1; i++) {
cout << 2 << ' ';
s -= 2;
}
cout << s << '\n' << 1;
} else {
cout << "NO";
}
return 0;
}
|
1355
|
E
|
Restorer Distance
|
You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights.
You are allowed the following operations:
- put a brick on top of one pillar, the cost of this operation is $A$;
- remove a brick from the top of one non-empty pillar, the cost of this operation is $R$;
- move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $M$.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $0$.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
|
First of all let's do $M = \min(M, A + R)$ - this is true since we can emulate moving by adding+removing. After that it is never profitable to add and remove in one solution, since we can always move instead. Suppose we have fixed $H$ - the resulting height for all pillars. How can we calculate the minimal cost for given $H$? Some pillars have no more than $H$ bricks, let the total number of missing bricks in these pillars be $P$. Other pillars have no less than $H$ bricks, let the total number of extra bricks in these pillars be $Q$. If $P \ge Q$ then we are missing $(P - Q)$ bricks in total, so we have to make $(P - Q)$ additions. There won't be any more additions or removals, and we have to do at least $Q$ moves since we have to somehow get rid of extra bricks from those pillars which have more than $H$ bricks initially. It is clear that $Q$ moves is enough. Therefore the total cost will be $C = A(P - Q) + MQ$. Similarly, if $Q \ge P$ then the total cost will be $C = R(Q - P) + MP$. Let's now assume that $P \ge Q$, we have exactly $X$ pillars with no more than $H$ bricks and exactly $N - X$ pillars with strictly more than $H$ bricks. Let's try to increase $H$ by 1 and see how the total cost will change. $P' = P + X$, $Q' = Q - (N - X) = Q - N + X$. $C' = A(P' - Q') + MQ' = A(P + X - Q + N - X) + M(Q - N + X) = A(P - Q) + MQ + AN - M(N - X)$. We can see that the total cost has changed by $AN - M(N - X)$. While $X$ is constant the cost change will be constant. What are the moments when $X$ changes? When $H$ is equal to the initial height of some pillar. Therefore the cost as a function of $H$ is piecewise linear with breakpoints in points corresponding to initial heights. There is a nuance - we have assumed $P \ge Q$. The same thing will be true for $P \le Q$ but there can be additional breakpoints when we change between these two states. This change will happen only once for $H \approx \frac{\sum h_{i}}{N}$ (approximate equality here means that this point can be non-integral so we should add both $\lfloor \frac{\sum h_{i}}{N} \rfloor$ and $\lceil \frac{\sum h_{i}}{N} \rceil$ as breakpoints). The minima of piecewise linear function are in breakpoints so it is enough to calculate the cost for breakpoints (initial heights and $H \approx \frac{\sum h_{i}}{N}$) and choose minimal of them. To calculate the cost for given $H$ fast we can sort the initial heights and calculate prefix sums of heights. Then using binary search we can determine which pillars have height less than $H$ and greater than $H$ and then calculate $P$ and $Q$ using prefix sums. We can use two pointers instead of binary searches but it will not improve the total complexity which is $O(N \log N)$ due to sorting (and binary searches if we are using them).
|
[
"binary search",
"greedy",
"math",
"sortings",
"ternary search"
] | 2,100
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
double startTime;
double getCurrentTime() {
return ((double)clock() - startTime) / CLOCKS_PER_SEC;
}
const ll INF = (ll)2e18 + 77;
const int N = 100100;
int n;
ll h[N];
ll pref[N];
ll A, R, M;
ll ans = INF;
ll solve(ll H) {
int pos = lower_bound(h, h + n, H) - h;
ll res = 0;
ll k1 = H * pos - pref[pos];
ll k2 = pref[n] - pref[pos] - H * (n - pos);
res = min(k1, k2);
k1 -= res;
k2 -= res;
res *= M;
res += k1 * A;
res += k2 * R;
return res;
}
int main()
{
startTime = (double)clock();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
scanf("%d%lld%lld%lld", &n, &A, &R, &M);
M = min(M, A + R);
for (int i = 0; i < n; i++)
scanf("%lld", &h[i]);
sort(h, h + n);
for (int i = 0; i < n; i++)
pref[i + 1] = pref[i] + h[i];
ll L = h[0], R = h[n - 1];
while(R - L > (ll)1e6) {
ll M1 = L + (R - L) / 3, M2 = R - (R - L) / 3;
if (solve(M1) > solve(M2)) {
L = M1;
} else {
R = M2;
}
}
for (ll x = L; x <= R; x++)
ans = min(ans, solve(x));
printf("%lld\n", ans);
return 0;
}
|
1355
|
F
|
Guess Divisors Count
|
This is an interactive problem.
We have hidden an integer $1 \le X \le 10^{9}$. You \textbf{don't have to} guess this number. You have to \textbf{find the number of divisors} of this number, and you \textbf{don't even have to find the exact number}: your answer will be considered correct if its absolute error is not greater than 7 \textbf{or} its relative error is not greater than $0.5$. More formally, let your answer be $ans$ and the number of divisors of $X$ be $d$, then your answer will be considered correct if \textbf{at least one} of the two following conditions is true:
- $| ans - d | \le 7$;
- $\frac{1}{2} \le \frac{ans}{d} \le 2$.
You can make at most $22$ queries. One query consists of one integer $1 \le Q \le 10^{18}$. In response, you will get $gcd(X, Q)$ — the greatest common divisor of $X$ and $Q$.
The number $X$ is fixed before all queries. In other words, \textbf{interactor is not adaptive}.
Let's call the process of guessing the number of divisors of number $X$ a game. In one test you will have to play $T$ independent games, that is, guess the number of divisors $T$ times for $T$ independent values of $X$.
|
If $X = p_{1}^{\alpha_{1}} \cdot p_{2}^{\alpha_{2}} \cdot \ldots \cdot p_{k}^{\alpha_{k}}$ then $d(X) = (\alpha_{1} + 1) \cdot (\alpha_{2} + 1) \cdot \ldots \cdot (\alpha_{k} + 1)$. If $X$ has prime $p$ in power $\alpha$ and $Q$ has $p$ in power $\beta$ then $gcd(X, Q)$ will have $p$ in power $\gamma = \min (\alpha, \beta)$. If $\gamma < \beta$ then $\alpha = \gamma$, otherwise $\gamma = \beta$ and $\alpha \ge \gamma$. We don't know $X$, but we can choose $Q$. If we'll choose $Q$ with known prime factorization then we'll be able to extract all the information from query fast (in $O(\log Q)$). After all the queries for each prime $p$ we'll know either the exact power in which $X$ has it, or lower bound for it. We can get upper bound from the fact that $X \le 10^{9}$. It is clear that we cannot get information about all primes - there are too many of them and too few queries. We want to somehow use the fact that we don't have to find the exact answer... Suppose we have figured out that $X = X_{1} \cdot X_{2}$ where we know $X_{1}$ exactly and we also know that $X_{2}$ has no more than $t$ prime factors (including multiplicity). Then $d(X_{1}) \le d(X) \le d(X_{1}) \cdot d(X_{2}) \le d(X_{1}) \cdot 2^{t}$. If $t \le 1$ then our answer will have relative error no more than $0.5$... One of the ways to guarantee that $X_{2}$ has few prime factors is to show that it cannot have small prime factors. That means that we have to calculate the exact power for all small primes. This gives an overall idea for the solution: let's make a query $Q=p^{\beta}$ for all primes $p \le B$ (for some bound $B$) where $\beta$ is chosen in such a way that $p^{\beta} > 10^{9}$. This allows us to know the exact power in which $X$ has $p$. This basic idea can be improved in several ways: $X$ has no more than 9 different prime factors, so for most primes its power is 0. If we could exclude these redundant primes fast it could speed up the solution significantly. And there is a way: we could make a query $Q = p_{1} p_{2} \ldots p_{s}$ for $s$ different primes, after that we will know which of them are factors of $X$; $\beta$ can be chosen such that $p^{\beta + 1} > 10^{9}$, because even if $\gamma = \beta$ and $\alpha \ge \gamma = \beta$ we will know that $\alpha \le \beta$ since otherwise $X > 10^{9}$; From the previous point follows that we can find the exact power for two primes simultaneously, just make a query with a product of two respective numbers. How to choose $B$? Apparently we want $B^{2} > 10^{9}$. But actually $t \le 2$ is ok for us: if we know that $L \le d(X) \le 4L$ then we can answer $2L$ and the relative error will be no more than $0.5$. That means we want $B^{3} > 10^{9}$ or $B = 1001$. We are close: there are 168 primes less than 1001, we can check 6 primes (for being a factor of $X$) in one query since $1000^{6} \le 10^{18}$, so we need 28 queries. Let's note that if we have found some prime factors of $X$ (let's say their product is $X_{1}$) then $X_{2} \le \frac{10^{9}}{X_{1}}$. Suppose we have checked all the primes not greater than $p$ and $X_{1} \cdot p^{3} > 10^{9}$. That means that $X_{2}$ has no more than 2 prime divisors and we are good. What is left is to use our right to have absolute error: if $X_{1} \le 3$ we can just print 8! Either $X_{1} \le 3$ and we are fine with $X_{2}$ having 3 prime factors, or $X_{1} \ge 4$ and we have to check all primes up to $\sqrt[3]{10^{9} / 4} < 630$. There are 114 such primes, so we need only 19 queries. We will also need some queries to find out the exact power for those small prime factors of $X$ we have found. If we have found no more than 2 prime factors, we'll need 1 query, otherwise we'll have to check primes only up to $\sqrt[3]{10^{9} / (2 \cdot 3 \cdot 5)} < 330$, of which there are only 66 so the first part of the solution spends no more than 11 queries. So we have shown that the solution spends no more than 20 queries. We did some rough estimations, the actual bound for this solution is 17 queries.
|
[
"constructive algorithms",
"interactive",
"number theory"
] | 2,600
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
double startTime;
double getCurrentTime() {
return ((double)clock() - startTime) / CLOCKS_PER_SEC;
}
const int N = 2020;
const ll INF = (ll)1e18;
bool p[N];
ll query(ll x) {
printf("? %lld\n", x);
cerr << "? " << x << endl;
fflush(stdout);
scanf("%lld", &x);
cerr << "gcd " << x << endl;
return x;
}
void solve() {
ll C = (ll)1e9 / 2 / 2;
vector<ll> hv;
vector<ll> cur;
ll curProd = 1;
for (int i = 2; i < N; i++) {
if (!p[i]) continue;
ll cc = C;
for (int j = 0; j < 3; j++)
cc /= i;
if (cc == 0) break;
if (INF / i < curProd) {
ll g = query(curProd);
while(!cur.empty()) {
if (g % cur.back() == 0) {
hv.push_back(cur.back());
if ((int)hv.size() <= 2) C *= 2;
C /= hv.back();
}
cur.pop_back();
}
curProd = 1;
}
cur.push_back((ll)i);
curProd *= i;
}
if (!cur.empty()) {
ll g = query(curProd);
while(!cur.empty()) {
if (g % cur.back() == 0) hv.push_back(cur.back());
cur.pop_back();
}
}
if ((int)hv.size() & 1) {
for (int i = 2; i < N; i++) {
if (!p[i]) continue;
bool fnd = false;
for (ll x : hv)
fnd |= i == x;
if (!fnd) {
hv.push_back(i);
break;
}
}
}
ll ans = 2;
for (int i = 0; i < (int)hv.size(); i += 2) {
ll p1 = hv[i], p2 = hv[i + 1];
ll x1 = 1, x2 = 1;
while(x1 * p1 <= (ll)1e9) x1 *= p1;
while(x2 * p2 <= (ll)1e9) x2 *= p2;
ll g = query(x1 * x2);
int t1 = 1, t2 = 1;
while(g % p1 == 0) {
g /= p1;
t1++;
}
while(g % p2 == 0) {
g /= p2;
t2++;
}
ans *= t1 * t2;
}
printf("! %lld\n", max(8LL, ans));
cerr << "ans " << ans << endl;
fflush(stdout);
}
int main()
{
startTime = (double)clock();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
for (int i = 2; i < N; i++)
p[i] = 1;
for (int i = 2; i < N; i++) {
if (!p[i]) continue;
for (int j = 2 * i; j < N; j += i)
p[j] = 0;
}
int t;
scanf("%d", &t);
cerr << "tests = " << t << endl;
while(t--) solve();
return 0;
}
|
1358
|
A
|
Park Lighting
|
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $1$. For example, park with $n=m=2$ has $12$ streets.
You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).
\begin{center}
{\small The park sizes are: $n=4$, $m=5$. The lighted squares are marked yellow. Please note that all streets have length $1$. Lanterns are placed in the middle of the streets. In the picture \textbf{not all} the squares are lit.}
\end{center}
Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.
|
Note that if at least one of the sides is even, the square can be divided into pairs of neighbors and the answer is $\frac{nm}{2}$. If both sides are odd, we can first light up a $(n - 1) \times m$ part of the park. Then we'll still have the part $m \times 1$. We can light it up with $\frac{m + 1}{2}$ lanterns. Then the total number of the lanterns is $\frac{(n-1) \cdot m}{2} + \frac{m + 1}{2} = \frac{nm - m + m + 1}{2} = \frac{nm + 1}{2}$. Note that both cases can be combined into one formula: $\lfloor \frac{nm + 1}{2} \rfloor$. The overall compexity is $\mathcal{O}(1)$ per test.
|
[
"greedy",
"math"
] | 800
|
#include <iostream>
using namespace std;
int main() {
int t, n, m;
cin >> t;
while (t--) {
cin >> n >> m;
cout << (n * m + 1) / 2 << '\n';
}
}
|
1358
|
B
|
Maria Breaks the Self-isolation
|
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has $n$ friends who are also grannies (Maria is not included in this number). The $i$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $a_i$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $i$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $a_i$.
Grannies gather in the courtyard like that.
- Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $1$). All the remaining $n$ grannies are still sitting at home.
- On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $a_i$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard \textbf{at the same moment of time}.
- She cannot deceive grannies, that is, the situation when the $i$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $a_i$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance.
Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!
Consider an example: if $n=6$ and $a=[1,5,4,5,1,9]$, then:
- at the first step Maria can call grannies with numbers $1$ and $5$, each of them will see two grannies at the moment of going out into the yard (note that $a_1=1 \le 2$ and $a_5=1 \le 2$);
- at the second step, Maria can call grannies with numbers $2$, $3$ and $4$, each of them will see five grannies at the moment of going out into the yard (note that $a_2=5 \le 5$, $a_3=4 \le 5$ and $a_4=5 \le 5$);
- the $6$-th granny cannot be called into the yard — therefore, the answer is $6$ (Maria herself and another $5$ grannies).
|
Let $x$ be the maximum number of grannies that can go out to the yard. Then if Maria Ivanovna calls them all at the same time, then everyone will see $x$ grannies. Since $x$ is the maximum answer, then each granny of them satisfy $a_i \le x$ (otherwise there's no way for these grannies to gather in the yard), that is, such call is correct. So it is always enough to call once. Note that if you order grannies by $a_i$, Maria Ivanovna will have to call $x$ first grannies from this list. She can take $x$ grannies if $a_x \le x$ (otherwise, after all $x$ grannies arrived, the last one will leave). To find $x$ we can do a linear search. The overall compexity is $\mathcal{O}(n\log{n})$ per test.
|
[
"greedy",
"sortings"
] | 1,000
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> arr(n);
for (int &el : arr)
cin >> el;
sort(arr.begin(), arr.end());
for (int i = n - 1; i >= 0; i--) {
if (arr[i] <= i + 1) {
cout << i + 2 << '\n';
return;
}
}
cout << 1 << '\n';
}
int main() {
int t;
cin >> t;
while (t--)
solve();
}
|
1358
|
C
|
Celex Update
|
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:
The cell with coordinates $(x, y)$ is at the intersection of $x$-th row and $y$-th column. Upper left cell $(1,1)$ contains an integer $1$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $(x,y)$ in one step you can move to the cell $(x+1, y)$ or $(x, y+1)$.
After another Dinwows update, Levian started to study "Celex-2021" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $(x_1, y_1)$ to another given cell $(x_2, y_2$), if you can only move one cell down or right.
Formally, consider all the paths from the cell $(x_1, y_1)$ to cell $(x_2, y_2)$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.
|
Let's look at the way with the minimum sum (first we go $y_2-y_1$ steps right, and then $x_2-x_1$ steps down). Let's look at such a change in the "bends" of the way: After each step, the sum on the way will increase by $1$. We're going to bend like this until we get to the maximum sum. We're not going to miss any possible sum, because we're incrementing the sum by 1. We started with the minimum sum and finished with the maximum sum, so we can use these changes to get all possible sums. In order for us to come from the minimum to the maximum way, we must bend the way exactly 1 time per each cell of table (except for the cells of the minimum way). That is, the number of changes equals the number of cells not belonging to the minimum way - $(x_2-x_1)\cdot(y_2-y_1)$. Then the number of different sums will be $(x_2-x_1)\cdot(y_2-y_1) + 1$. The overall compexity is $\mathcal{O}(1)$ per test.
|
[
"math"
] | 1,600
|
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long a, b, c, d;
cin >> a >> b >> c >> d;
cout << (c - a) * (d - b) + 1 << '\n';
}
}
|
1358
|
D
|
The Best Vacation
|
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of days you will spend visiting your friend. You will spend exactly $x$ consecutive (successive) days visiting Coronavirus-chan.
They use a very unusual calendar in Naha: there are $n$ months in a year, $i$-th month lasts exactly $d_i$ days. Days in the $i$-th month are numbered from $1$ to $d_i$. There are no leap years in Naha.
The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get $j$ hugs if you visit Coronavirus-chan on the $j$-th day of the month.
You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan).
Please note that your trip should \textbf{not necessarily} begin and end in the same year.
|
We will double the array of days and solve the problem when the day vacation starts and the day it ends is always in the same year. Then $a$ is an array of number of days in each of the months. Consider array $B = [1, 2, ..., a_1] + [1, 2, ..., a_2] + ... [1, 2, ..., a_n] + [1, 2, ..., a_n]$. Our task is to find a subsection of length $k$ with the maximum sum in it. Further we will call this segment optimal. Statement: We will find such an optimal segment that its end coincides with the end of some month. Proof by contradiction: Pretend that's not the case. Consider the rightmost optimal segment. Let its last element be $x$, then the next one is $x+1$, otherwise $x$ coincides with $a_i$. Note that if we move this segment to the right, the sum must be reduced, which means that the first element of the segment $>x+1$. Then its left neighbor $>x$. It means that you can move the segment by $1$ to the left so that the sum increases. So, the chosen segment is not optimal. Contradiction. (see picture) Solution: now we just need to go through all the possible ends of the segment, which are only $\mathcal{O}(n)$. Let's build two arrays of prefix sums: $c_i = a_1 + a_2 + ... + a_i\\$ $d_i = \frac{a_1 (a_1 + z)}{2} + ... + \frac{a_i (a_i + 1)}{2}$ $c_i$ is responsible for the number of days before the $i$-th month, and $d_i$ is responsible for the sum of numbers of all days before the $i$-th month. For each of the n ends, let's make a binsearch to find which month contains its left border ($k$ days less than the right one). You can use array $c_i$ to check whether the left border lies to the left/in the block/to the right, and use array $d_i$ to restore the answer. The overall compexity is $\mathcal{O}(n\log{n})$.
|
[
"binary search",
"brute force",
"greedy",
"implementation",
"two pointers"
] | 1,900
|
#include <iostream>
#include <algorithm>
#include <vector>
#define int long long
using namespace std;
signed main() {
int n, len;
cin >> n >> len;
vector<int> A(2 * n);
for (int i = 0; i < n; i++) {
cin >> A[i];
A[n + i] = A[i];
}
n *= 2;
vector<int> B = {0}, C = {0};
for (int i = 0; i < n; i++)
B.push_back(B.back() + A[i]);
for (int i = 0; i < n; i++)
C.push_back(C.back() + (A[i] * (A[i] + 1)) / 2);
int ans = 0;
for (int i = 0; i < n; i++) {
if (B[i + 1] >= len) {
int z = upper_bound(B.begin(), B.end(), B[i + 1] - len) - B.begin();
int cnt = C[i + 1] - C[z];
int days = B[i + 1] - B[z];
int too = len - days;
cnt += ((A[z - 1] * (A[z - 1] + 1)) / 2);
cnt -= (((A[z - 1] - too) * (A[z - 1] - too + 1)) / 2);
ans = max(ans, cnt);
}
}
cout << ans;
}
|
1358
|
E
|
Are You Fired?
|
Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the $n$ consecutive months — in the $i$-th month the company had income equal to $a_i$ (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the first $\lceil \tfrac{n}{2} \rceil$ months income might have been completely unstable, but then everything stabilized and for the last $\lfloor \tfrac{n}{2} \rfloor$ months \textbf{the income was the same}.
Levian decided to tell the directors $n-k+1$ numbers — the total income of the company for each $k$ consecutive months. In other words, for each $i$ between $1$ and $n-k+1$ he will say the value $a_i + a_{i+1} + \ldots + a_{i + k - 1}$. For example, if $a=[-1, 0, 1, 2, 2]$ and $k=3$ he will say the numbers $0, 3, 5$.
Unfortunately, if at least one total income reported by Levian is not a profit (income $\le 0$), the directors will get angry and fire the failed accountant.
Save Levian's career: find any such $k$, that for each $k$ months in a row the company had made a profit, or report that it is impossible.
|
Let's call the value of all elements in the second half of the array $x$. Let $s_i = a_i + a_{i+1} + \ldots + a_{i+k-1}$ - the reported incomes. Pretend there exists such a $k$ that $k\le\tfrac{n}{2}$. Consider the following reported incomes: $s_i$ and $s_{i+k}$. Notice that if we double $k$, the $i$-th reported income will be equal to $s_i+s_{i+k}$. $s_i>0$ and $s_{i+k}>0$ imply $s_i+s_{i+k}>0$. It means that after doubling $k$, the new value will still be correct $\ \implies\$ if some $k$ exists, there's also $k>\tfrac{n}{2}$. Now, let's notice that $s_{i+1} = s_i + (a_{i + k} - a_i)$. It means we can think of $s_i$ as prefix sums of the following array: $\\p = [s_1,\ a_{k+1}-a_1,\ a_{k+2}-a_2,\ \ldots,\ a_n - a_{n-k}]$. $\\$ As $k>\tfrac{n}{2}$, $a_{k+j} = x$ holds for $j \ge 0$, so, actually $\\p = [s_1,\ x-a_1,\ x-a_2,\ \ldots,\ x-a_{n-k}]$. How is this array changed when we increment $k$ by 1? $\\p_{new} = [s_1+a_{k+1},\ a_{k+2}-a_1,\ a_{k+3}-a_2,\ \ldots,\ a_n-a_{n-k-1}]$, which equals $[s_1+x,\ x-a_1,\ x-a_2,\ \ldots,\ x-a_{n-k-1}]$. $\\$ So, when you increase $k$ by 1, the first element is changed, and the last element is removed - and that's it. Recall that $s_i = p_1 + p_2 + \ldots + p_i$. Notice that the minimum reported income (some number from $s$) doesn't depend on the first element of $p$ because it's a term of all sums ($s_1, s_2, \ldots$). For example, if $p_1$ is increased by $1$, all $s_i$ are increased by $1$ too. So, let's calculate the following array $m$: $\\$ $m_i = min(s_1-p_1, s_2-p_1, \ldots, s_i-p_1) = min(0, p_2,\ p_2+p_3,\ \ldots,\ p_2+\ldots+p_i)$. $\\$ This can be done in $\mathcal{O}(n)$. Notice that this array is the same for all $k$, except its size. So, it's obvious that the minimum reported income for a particular $k$ is $p_1+m_{n-k+1}=a_1+\ldots+a_k+m_{n-k+1}$. So, we can just check if this number is greater than $0$ for some $k$. We can calculate prefix sums and $m$ in $\mathcal{O}(n)$, so the overall complexity is $\mathcal{O}(n)$.
|
[
"constructive algorithms",
"data structures",
"greedy",
"implementation"
] | 2,400
|
#include <iostream>
#include <vector>
using namespace std;
#define int long long
signed main() {
int n;
cin >> n;
int N = (n + 1) / 2;
vector<int> a(N);
for (int &el : a)
cin >> el;
int Ax;
cin >> Ax;
vector<int> m(N + 1, 0);
int Pprefsm = 0;
for (int i = 1; i < N + 1; ++i) {
Pprefsm += Ax - a[i - 1];
m[i] = min(m[i - 1], Pprefsm);
}
int Aprefsm = 0;
for (int k = 1; k <= N; ++k)
Aprefsm += a[k - 1];
for (int k = N; k <= n; ++k) {
if (Aprefsm + m[n - k] > 0)
return cout << k, 0;
Aprefsm += Ax;
}
cout << -1;
}
|
1358
|
F
|
Tasty Cookie
|
Oh, no!
The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem.
You are given two arrays $A$ and $B$ of size $n$. You can do operations of two types with array $A$:
- Reverse array $A$. That is the array $[A_1,\ A_2,\ \ldots,\ A_n]$ transformes into $[A_n,\ A_{n-1},\ \ldots,\ A_1]$.
- Replace $A$ with an array of its prefix sums. That is, the array $[A_1,\ A_2,\ \ldots,\ A_n]$ goes to $[A_1,\ (A_1+A_2),\ \ldots,\ (A_1+A_2+\ldots+A_n)]$.
You need to understand if you can get an array $B$ from the array $A$. If it is possible, you will have to restore the order of these operations by minimizing the number of operations of the second type. Fortunately, the coronavirus is good today, so he has allowed you not to restore actions if the minimum number of second type operations is more than $2\cdot 10^5$. But coronavirus resents you, so if you restore the answer, the total number of operations should not exceed $5\cdot 10^5$.
Solve this problem and get the cookie, or the coronavirus will extend the quarantine for five years and make the whole economy collapse!
|
Let's define a few operations and constants: $pref$ - replace an array with its prefix sums array $reverse$ - reverse an array $rollback$ - restore the original array from a prefix sums array $C$ - the array values upper bound - $10^{12}$ First, we can prove that $rollback$ is unambiguosly defined for strictly increasing arrays. Consider an array $X$. Let $Y$ be the prefix sums array of $X$. Notice that $X_0 = Y_0$, $X_i = Y_i - Y_{i - 1}$ (for $i>1$). Thus we can restore $X$ from $Y$. Note that if we apply $rollback$ to an array for which $Y_i > Y_{i - 1}$ doesn't hold, the resulting array will have a non-positive element which is forbidden by the statements. Now let's analyze how many $pref$ operations can theoretically be applied for arrays of different lengths (let's call their count $t$) (We can do that by applying $pref$ to array $[1, 1, ..., 1]$ while all numbers are below $C$): It's obvious that we'll need no more than $t$ $rollback$s for an array of length $n$. It can also be proved that $t = \mathcal{O}(\sqrt[n-1]{C\cdot(n-1)!})$. Let's restore the array $B$ in steps. One each step we have several cases: If $B$ equals $A$ or $reverse(A)$, we know how to get $A$ from $B$. If $B$ is strictly increasing, apply $rollback$. If $B$ is strictly decreasing, apply $reverse$. Otherwise, the answer is "$impossible$". This solution will run infinitely when $n=1$ and $A \ne B$, so the case when $n=1$ has to be handled separately. The asymptotic of this solution is $\mathcal{O}(n\cdot ans)$. Notice that $ans \le 2t+1$ because we can't have two $reverse$ operations in a row. It means this solution will fit into TL for $n \ge 3$, but we need a separate solution for $n=2$. Consider an array $[x, y]$. If we $rollback$ it while $x<y$, the array will be transformed into $[x, y \mod x]$. It means we can $rollback$ several iterations at once. So, the solution for $n=2$ is: First sort $A$ and $B$ so that they both increase (and take this into account when printing answer) Now start the $rollback$ loop: If $B_1=A_1$, we can break the loop if $(B_2 - A_2) \mod B_1=0$, otherwise the answer is "$impossible$". If $B_1 \ne A_1$, we can calculate how many $rollback$ operations we should apply to transform $B=[x, y]$ into $[x, y \mod x]$, modify the answer accordingly and jump to the next iteration for $B=[y \mod x, x]$ (after applying one $reverse$ operation). If $B_1=A_1$, we can break the loop if $(B_2 - A_2) \mod B_1=0$, otherwise the answer is "$impossible$". If $B_1 \ne A_1$, we can calculate how many $rollback$ operations we should apply to transform $B=[x, y]$ into $[x, y \mod x]$, modify the answer accordingly and jump to the next iteration for $B=[y \mod x, x]$ (after applying one $reverse$ operation). This algorithm is very similar to the Euclidian's algorithm, and that's how we can prove there will be $\mathcal{O}(\log C)$ $rollback$s. The overall complexity is $\mathcal{O}(n\cdot ans)$ for $n>2$; $\mathcal{O}(\log C)$ for $n=2$. Thank you, everyone, for participating in the round! We hope you've raised your rating! And if you haven't, don't be sad, you'll do it!
|
[
"binary search",
"constructive algorithms",
"greedy",
"implementation"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
signed main() {
int n;
cin >> n;
vector<int> a(n), b(n);
for (int i = 0; i < n; ++i) cin >> a[i];
for (int i = 0; i < n; ++i) cin >> b[i];
if (n == 1) {
if (a[0] == b[0]) cout << "SMALL\n" << 0;
else cout << "IMPOSSIBLE";
return 0;
}
if (n == 2) {
vector<pair<int, bool>> res;
int kol = 0;
while (true) {
if (b[0] == 0 || b[1] == 0) {
cout << "IMPOSSIBLE";
return 0;
}
if (a == b) break;
if (a[0] == b[1] && a[1] == b[0]) {
res.emplace_back(1, false);
break;
}
if (b[0] == b[1]) {
cout << "IMPOSSIBLE";
return 0;
}
if (b[0] > b[1]) {
res.emplace_back(1, false);
swap(b[0], b[1]);
}
if (a[0] == b[0] && a[1] < b[1] && a[1] % b[0] == b[1] % b[0]) {
res.emplace_back((b[1] - a[1]) / b[0], true);
kol += res.back().first;
break;
}
if (a[1] == b[0] && a[0] < b[1] && a[0] % b[0] == b[1] % b[0]) {
res.emplace_back((b[1] - a[0]) / b[0], true);
kol += res.back().first;
res.emplace_back(1, false);
break;
}
kol += b[1] / b[0];
res.emplace_back(b[1] / b[0], true);
b[1] %= b[0];
}
if (kol > 2e5) {
cout << "BIG\n";
cout << kol;
} else {
cout << "SMALL\n";
int flex = 0;
for (auto i : res) flex += i.first;
cout << flex << "\n";
for (int i = res.size() - 1; i >= 0; --i) {
for (int j = 0; j < res[i].first; ++j) {
if (res[i].second) cout << "P";
else cout << "R";
}
}
}
return 0;
}
vector<bool> ans;
int kol = 0;
while (true) {
if (a == b) break;
reverse(b.begin(), b.end());
if (a == b) {
ans.push_back(false);
break;
}
reverse(b.begin(), b.end());
bool vozr = false, ub = false, r = false;
for (int i = 1; i < n; ++i) {
if (b[i] > b[i - 1]) vozr = true;
else if (b[i] < b[i - 1]) ub = true;
else r = true;
}
if (r || (vozr && ub)) {
cout << "IMPOSSIBLE";
return 0;
}
vector<int> c(n);
if (ub) {
ans.push_back(false);
reverse(b.begin(), b.end());
}
c[0] = b[0];
for (int i = 1; i < n; ++i) {
c[i] = b[i] - b[i - 1];
}
ans.push_back(true);
b = c;
++kol;
}
if (kol > 2e5) {
cout << "BIG\n" << kol;
} else {
cout << "SMALL\n" << ans.size() << "\n";
for (int i = ans.size() - 1; i >= 0; --i) {
if (ans[i]) cout << "P";
else cout << "R";
}
}
}
|
1359
|
A
|
Berland Poker
|
The game of Berland poker is played with a deck of $n$ cards, $m$ of which are jokers. $k$ players play this game ($n$ is divisible by $k$).
At the beginning of the game, each player takes $\frac{n}{k}$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $x - y$, where $x$ is the number of jokers in the winner's hand, and $y$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $0$ points.
Here are some examples:
- $n = 8$, $m = 3$, $k = 2$. If one player gets $3$ jokers and $1$ plain card, and another player gets $0$ jokers and $4$ plain cards, then the first player is the winner and gets $3 - 0 = 3$ points;
- $n = 4$, $m = 2$, $k = 4$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $0$ points;
- $n = 9$, $m = 6$, $k = 3$. If the first player gets $3$ jokers, the second player gets $1$ joker and $2$ plain cards, and the third player gets $2$ jokers and $1$ plain card, then the first player is the winner, and he gets $3 - 2 = 1$ point;
- $n = 42$, $m = 0$, $k = 7$. Since there are no jokers, everyone gets $0$ jokers, everyone is a winner, and everyone gets $0$ points.
Given $n$, $m$ and $k$, calculate the maximum number of points a player can get for winning the game.
|
There are many different ways to solve this problem. The easiest one, in my opinion, is to iterate on the number of jokers the winner has (let it be $a_1$) and the number of jokers the runner-up has (let it be $a_2$). Then the following conditions should be met: $a_1 \ge a_2$ (the winner doesn't have less jokers than the runner-up); $a_1 \le \frac{n}{k}$ (the number of jokers in the winner's hand does not exceed the number of cards in his hand); $a_1 + a_2 \le m$ (the number of jokers for these two players does not exceed the total number of jokers); $a_1 + (k - 1)a_2 \ge m$ (it is possible to redistribute remaining jokers among other players so that they have at most $a_2$ jokers). Iterating on $a_1$ and $a_2$, then checking these constraints gives us a $O(n^2)$ solution. It is possible to get a constant-time solution using some greedy assumptions and math (the first player should get as many jokers as possible, while the remaining jokers should be evenly distributed among other players).
|
[
"brute force",
"greedy",
"math"
] | 1,000
|
t = int(input())
for i in range(t):
n, m, k = map(int, input().split())
ans = 0
d = n // k
for a1 in range(m + 1):
for a2 in range(a1 + 1):
if(a1 > d):
continue
if(a1 + a2 > m):
continue
if(a1 + (k - 1) * a2 < m):
continue
ans = max(ans, a1 - a2)
print(ans)
|
1359
|
B
|
New Theatre Square
|
You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.
The square still has a rectangular shape of $n \times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement.
You are given the picture of the squares:
- if $a_{i,j} = $ "*", then the $j$-th square in the $i$-th row should be \textbf{black};
- if $a_{i,j} = $ ".", then the $j$-th square in the $i$-th row should be \textbf{white}.
The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles:
- $1 \times 1$ tiles — each tile costs $x$ burles and covers exactly $1$ square;
- $1 \times 2$ tiles — each tile costs $y$ burles and covers exactly $2$ adjacent squares of the \textbf{same row}. \textbf{Note that you are not allowed to rotate these tiles or cut them into $1 \times 1$ tiles.}
\textbf{You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.}
What is the smallest total price of the tiles needed to cover all the white squares?
|
Notice that rows can be solved completely separately of each other. Each tile takes either one or two squares but it's always in the same row. So let's take a look at a single row. There are sequences of dot characters separated by some asterisks. Once again each of these sequences can be solved independently of the others. Thus, we have these empty strips of empty squares $1 \times k$ which, when solved, can be summed up into the whole answer. There are two cases, depending on if a $1 \times 2$ is cheaper than two $1 \times 1$ tiles. If it is then we want to use of many $1 \times 2$ tiles as possible. So given $k$, we can place $\lfloor \frac k 2 \rfloor$ $1 \times 2$ tiles and cover the rest $k - 2 \cdot \lfloor \frac k 2 \rfloor = k~mod~2$ squares with $1 \times 1$ tiles. If it isn't cheaper then we want to cover everything with $1 \times 1$ tiles and never use $1 \times 2$ ones. So all $k$ should be $1 \times 1$. The easier way to implement this might be the following. Let's update the price of the $1 \times 2$ tile with the minimum of $y$ and $2 \cdot x$. This way the first algorithm will produce exactly the same result of the second one in the case when a $1 \times 2$ tile isn't cheaper than two $1 \times 1$ ones. Overall complexity: $O(nm)$ per testcase.
|
[
"brute force",
"dp",
"greedy",
"implementation",
"two pointers"
] | 1,000
|
t = int(input())
for _ in range(t):
n, m, x, y = map(int, input().split())
ans = 0
y = min(y, 2 * x)
for __ in range(n):
s = input()
i = 0
while i < m:
if s[i] == '*':
i += 1
continue
j = i
while j + 1 < m and s[j + 1] == '.':
j += 1
l = j - i + 1
ans += l % 2 * x + l // 2 * y
i = j + 1
print(ans)
|
1359
|
C
|
Mixing Water
|
There are two infinite sources of water:
- hot water of temperature $h$;
- cold water of temperature $c$ ($c < h$).
You perform the following procedure of alternating moves:
- take \textbf{one} cup of the \textbf{hot} water and pour it into an infinitely deep barrel;
- take \textbf{one} cup of the \textbf{cold} water and pour it into an infinitely deep barrel;
- take \textbf{one} cup of the \textbf{hot} water $\dots$
- and so on $\dots$
\textbf{Note that you always start with the cup of hot water}.
The barrel is initially empty. You have to pour \textbf{at least one cup} into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.
You want to achieve a temperature as close as possible to $t$. So if the temperature in the barrel is $t_b$, then the \textbf{absolute difference} of $t_b$ and $t$ ($|t_b - t|$) should be as small as possible.
How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $t$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
|
Idea: adedalic So there are two kinds of stops to consider: $k$ hot and $k$ cold cup and $(k + 1)$ hot and $k$ cold cups. The first case is trivial: the temperature is always $\frac{h + c}{2}$. In the second case the temperature is always strictly greater than $\frac{h + c}{2}$. Thus, if $t \le \frac{h + c}{2}$, then the answer is $2$. Let's show that otherwise the answer is always achieved through the second case. The temperature after $(k + 1)$ hot cups and $k$ cold cups is $t_k = \frac{(k + 1) \cdot h + k \cdot c}{2k + 1}$. The claim is that $t_0 > t_1 > \dots$. Let's prove that by induction. $t_0 = h, t_1 = \frac{2 \cdot h + c}{3}$. $c < h$, thus $t_0 > t_1$. Now compare $t_k$ and $t_{k+1}$. $t_k > t_{k+1}$ $\frac{(k + 1) \cdot h + k \cdot c}{2k + 1} > \frac{(k + 2) \cdot h + (k + 1) \cdot c}{2k + 3}$ $\frac{k \cdot (h + c) + h}{2k + 1} > \frac{(k + 1) \cdot (h + c) + h}{2k + 3}$ $2k \cdot (k \cdot (h + c) + h) + 3k \cdot (h + c) + 3h > 2k \cdot ((k + 1) \cdot (h + c) + h) + (k + 1) \cdot (h + c) + h$ $2k \cdot (k \cdot (h + c) + h - (k + 1) \cdot (h + c) - h) > (k + 1) \cdot (h + c) + h - 3k \cdot (h + c) - 3h$ $2k \cdot (-(h + c)) > (-2k + 1) \cdot (h + c) - 2h$ $2h > (h + c)$ $h > c$ We can also show that this series converges to $\frac{h + c}{2}$: I'm sorry that I'm not proficient with any calculus but my intuition says that it's enough to show that $\forall k~t_k > \frac{h + c}{2}$ and $\forall \varepsilon \exists k~t_k < \frac{h + c}{2}$ with $k \ge 0$. So the first part is: $\frac{(k + 1) \cdot h + k \cdot c}{2k + 1} > \frac{h + c}{2}$ $\frac{k \cdot (h + c) + h}{2k + 1} > \frac{h + c}{2}$ $2k \cdot (h + c) + 2h > (2k + 1) \cdot (h + c)$ $2h > h + c$ $h > c$ And the second part is: $\frac{(k + 1) \cdot h + k \cdot c}{2k + 1} < \frac{h + c}{2} + \varepsilon$ $\frac{k \cdot (h + c) + h}{2k + 1} < \frac{h + c}{2} + \varepsilon$ $2k \cdot (h + c) + 2h < (2k + 1) \cdot (h + c) + (2k + 1) \cdot \varepsilon$ $2h < (h + c) + (2k + 1) \cdot \varepsilon$ $h < c + (2k + 1) \cdot \varepsilon$ $\frac{h - c}{\varepsilon} < 2k + 1$ So that claim makes us see that for any $t$ greater than $\frac{h + c}{2}$ the answer is always achieved from the second case. That allows us to find such $k$, that the value of $t_k$ is exactly $t$. However, such $k$ might not be integer. $\frac{(k + 1) \cdot h + k \cdot c}{2k + 1} = t \leftrightarrow$ $\frac{k \cdot (h + c) + h}{2k + 1} = t \leftrightarrow$ $k \cdot (h + c) + h = 2kt + t \leftrightarrow$ $k \cdot (h + c - 2t) = t - h \leftrightarrow$ $k = \frac{t - h}{h + c - 2t}$. The only thing left is to compare which side is better to round $k$ to. It seems some implementations with float numbers might fail due to precision errors. However, it's possible to do these calculations completely in integers. Let's actually rewrite that so that the denominator is always positive $k = \frac{h - t}{2t - h - c}$. Now we can round this value down and compare $k$ and $k + 1$. So the optimal value is $k$ if $|\frac{k \cdot (h + c) + h}{2k + 1} - t| \le |\frac{(k + 1) \cdot (h + c) + h}{2k + 3} - t|$. So $|(k \cdot (h + c) + h) - t \cdot (2k + 1)| \cdot (2k + 3) \le |((k + 1) \cdot (h + c) + h) - t \cdot (2k + 3)| \cdot (2k + 1)$. Otherwise, the answer is $k + 1$. You can also find the optimal $k$ with binary search but the formulas are exactly the same and you have to rely on monotonosity as well. Also, these formulas can get you the better understanding for the upper bound of the answer. Overall complexity: $O(1)$ or $O(\log h)$ per testcase.
|
[
"binary search",
"math"
] | 1,700
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int tc;
scanf("%d", &tc);
forn(_, tc){
int h, c, t;
scanf("%d%d%d", &h, &c, &t);
if (h + c - 2 * t >= 0)
puts("2");
else{
int a = h - t;
int b = 2 * t - c - h;
int k = 2 * (a / b) + 1;
long long val1 = abs(k / 2 * 1ll * c + (k + 1) / 2 * 1ll * h - t * 1ll * k);
long long val2 = abs((k + 2) / 2 * 1ll * c + (k + 3) / 2 * 1ll * h - t * 1ll * (k + 2));
printf("%d\n", val1 * (k + 2) <= val2 * k ? k : k + 2);
}
}
return 0;
}
|
1359
|
D
|
Yet Another Yet Another Task
|
Alice and Bob are playing yet another card game. This time the rules are the following. There are $n$ cards lying in a row in front of them. The $i$-th card has value $a_i$.
First, Alice chooses a non-empty consecutive segment of cards $[l; r]$ ($l \le r$). After that Bob removes a single card $j$ from that segment $(l \le j \le r)$. The score of the game is the total value of the remaining cards on the segment $(a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)$. In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is $0$.
Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.
What segment should Alice choose so that the score is maximum possible? Output the maximum score.
|
Alice wants to choose such a segment $[l; r]$ that $\sum \limits_{l \le i \le r} a_i - \max \limits_{l \le i \le r} a_i$ is maximum possible. There is a well-known problem where you have to find a segment with maximum $\sum \limits_{l \le i \le r} a_i$. That problem is solved with Kadane algorithm. Let's learn how to reduce our problem to that one. Notice that the values in the array are unusually small. Let's iterate over the maximum value on segment. Let $mx$ be the current value. If we make all $a_i$ such that $a_i > mx$ equal to $-\infty$, then it will never be optimal to take them in a segment. Find the maximum sum subarray in that modified array and update the answer with its $sum - mx$. Notice that you can ignore the fact if there is a value exactly equal to $mx$ on the maximum sum segment. If there isn't then you'll update the answer with a smaller value than the actual one. Let the actual maximum on the maximum sum segment be some $y$. You can see that for any value between $y$ and $mx$ the maximum sum segment will always be that chosen one. Thus, when you reach $y$, you'll update the answer with the correct value. Overall complexity: $O(\max a_i \cdot n)$.
|
[
"data structures",
"dp",
"implementation",
"two pointers"
] | 2,000
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int INF = 1e9;
int main() {
int n;
scanf("%d", &n);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
long long ans = 0;
forn(mx, 31){
long long cur = 0;
long long best = 0;
forn(i, n){
int val = (a[i] > mx ? -INF : a[i]);
cur += val;
best = min(best, cur);
ans = max(ans, (cur - best) - mx);
}
}
printf("%lld\n", ans);
return 0;
}
|
1359
|
E
|
Modular Stability
|
We define $x \bmod y$ as the remainder of division of $x$ by $y$ ($\%$ operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers $[a_1, a_2, \dots, a_k]$ stable if for every permutation $p$ of integers from $1$ to $k$, and for every non-negative integer $x$, the following condition is met:
\begin{center}
$ (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} $
\end{center}
That is, for each non-negative integer $x$, the value of $(((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k$ does not change if we reorder the elements of the array $a$.
For two given integers $n$ and $k$, calculate the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$.
|
We claim that the array is stable if and only if all elements are divisible by its minimum. The proof of this fact will be at the end of the editorial. To calculate the number of stable arrays now, we need to iterate on the minimum in the array and choose the remaining elements so that they are multiples of it. If the minimum is $i$, then the resulting elements should be divisible by $i$. There are $d = \lfloor\frac{n}{i}\rfloor$ such numbers between $1$ and $n$, and we have to choose $k - 1$ elements out of $d - 1$ (since $i$ is already chosen). The number of ways to do it can be calculated by precomputing factorials modulo $998244353$, since it is a binomial coefficient. Proof of the claim at the beginning of the editorial: On the one hand, since $(x \bmod a) \bmod (ba) = (x \bmod (ba)) \bmod a = x \bmod a$, if all elements in the array are divisible by some element, nothing depends on the order of these elements. On the other hand, suppose there exists an element $a_i$ such that it is not divisible by $a_1$. Let's take $x = a_i$ and two following reorders of the array $a$: $[a_1, a_2, \dots, a_k]$ and $[a_i, a_1, a_2, \dots, a_{i - 1}, a_{i + 1}, \dots, a_k]$. For the first array, we get $x \bmod a_1 = a_i \bmod a_1$, which is non-zero; and for the second array, $a_i \bmod a_i = 0$, so the result is zero.
|
[
"combinatorics",
"math",
"number theory"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
const int N = 500043;
const int MOD = 998244353;
int fact[N];
int add(int x, int y)
{
x += y;
while(x >= MOD) x -= MOD;
while(x < 0) x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int binpow(int x, int y)
{
int z = 1;
while(y > 0)
{
if(y % 2 == 1)
z = mul(z, x);
x = mul(x, x);
y /= 2;
}
return z;
}
int inv(int x)
{
return binpow(x, MOD - 2);
}
int divide(int x, int y)
{
return mul(x, inv(y));
}
void precalc()
{
fact[0] = 1;
for(int i = 1; i < N; i++)
fact[i] = mul(i, fact[i - 1]);
}
int C(int n, int k)
{
if(k > n) return 0;
return divide(fact[n], mul(fact[n - k], fact[k]));
}
int main()
{
int n, k;
cin >> n >> k;
int ans = 0;
precalc();
for(int i = 1; i <= n; i++)
{
int d = n / i;
ans = add(ans, C(d - 1, k - 1));
}
cout << ans << endl;
}
|
1359
|
F
|
RC Kaboom Show
|
You know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event "Remote Control Kaboom Show" and stream everything online.
For the preparation you arranged an arena — an infinite 2D-field. You also bought $n$ remote controlled cars and set them up on the arena. Unfortunately, the cars you bought can only go forward without turning left, right or around. So you additionally put the cars in the direction you want them to go.
To be formal, for each car $i$ ($1 \le i \le n$) you chose its initial position ($x_i, y_i$) and a direction vector ($dx_i, dy_i$). Moreover, each car has a constant speed $s_i$ units per second. So after car $i$ is launched, it stars moving from ($x_i, y_i$) in the direction ($dx_i, dy_i$) with constant speed $s_i$.
The goal of the show is to create a car collision as fast as possible! You noted that launching every car at the beginning of the show often fails to produce any collisions at all. Thus, you plan to launch the $i$-th car at some moment $t_i$. \textbf{You haven't chosen $t_i$, that's yet to be decided.} Note that it's not necessary for $t_i$ to be integer and $t_i$ is allowed to be equal to $t_j$ for any $i, j$.
The show starts at time $0$. The show ends when two cars $i$ and $j$ ($i \ne j$) collide (i. e. come to the same coordinate at the same time). The duration of the show is the time between the start and the end.
What's the fastest crash you can arrange by choosing all $t_i$? If it's possible to arrange a crash then print the shortest possible duration of the show. Otherwise, report that it's impossible.
|
Let $f(t)$ be true if it's possible to have a collision before time $t$. That function is monotonous, thus let's binary search for $t$. For some fixed $t$ car $i$ can end up in any point from $(x_i, y_i)$ to $s_i \cdot t$ units along the ray $((x_i, y_i), (x_i + dx_i, y_i + dy_i))$. That makes it a segment. So the collision can happen if some pair of segments intersects. Let's learn how to find that out. The general idea is to use sweep line. So let's add the events that the $i$-th segment $(x1_i, y1_i, x2_i, y2_i)$ such that $x1_i < x2_i$ opens at $x1_i$ and closes at $x2_i$. There were no vertical segments, so $x1_i$ and $x2_i$ are always different. At every moment of time $T$ we want to maintain the segments ordered by their intersection with the line $x = T$. Note that if two segments change their order moving along the sweep line, then they intersect. So we can maintain a set with a custom comparator that returns if one segment intersects the current line lower than the other one. When adding a segment to set, you want to check it's intersections with the next segment in the order and the previous one. When removing a segment, you want to check the intersection between the next and the previous segment in the order. If any check triggers, then return true immediately. It's easy to show that if the intersection happens between some pair of segments, then the intersection between only these pairs of segment also happens. Now for the implementation details. Precision errors play a huge role here since we use binary search and also store some stuff dependant on floats in the set. The solution I want to tell requires no epsilon comparisons, thus it calculates the answer only with the precision of binary search. So the first issue rises when we have to erase elements from the set. Notice that we can make a mistake when we are adding the segment and there is a segment with almost the same intersection point. That will not make the answer incorrect (that's not trivial to show but it's possible if you consider some cases). If you can find it later to remove, then it's not an issue at all. However, that will probably mess up the lower_bound in the set. Thus, let's save the pointer to each element in the set and remove it later by that pointer. The second issue comes when you have to check the intersection of two segments. The error might appear when one segment $((x_i, y_i), (nx_i, ny_i))$ (let the first point be the original $(x_i, y_i)$ and the second point be calculated depending on $t$) has it's intersection point with segment $((x_j, y_j), (nx_j, ny_j))$ at exactly $(x_i, y_i)$. So the slightest miscalculations could matter a lot. Let's learn to intersect in such a way that no epsilon comparisons are required. Firstly, we can store lines in the set instead of segments. Second, we can check the intersection of rays first and only then proceed to check the intersection of segments. So two rays intersect if: their lines intersect - easy to check in integers; the intersection point lies in the correct direction of both rays - the intersection point is always a pair of fractions $(\frac{Dx}{D}, \frac{Dy}{D})$ and you want to compare the signs of $dx_i$ and $\frac{Dx}{D} - x_i$. Finally, if all the checks hold, then you can compare maximum of distances from $(x_i, y_i)$ and $(x_j, y_j)$ to the intersection point and $t$. If $t$ is greater or equal then they intersect in time. There is no way to make that comparison in integers. However, it's precision only depends on the precision of $t$ as in the error here can't affect the answer greatly. Overall complexity: $O(n \log n \log maxt)$.
|
[
"binary search",
"brute force",
"data structures",
"geometry",
"math"
] | 2,900
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define x first
#define y second
using namespace std;
const double INF = 1e13;
struct line{
int A, B, C;
line(){}
line(int x1, int y1, int x2, int y2){
A = y1 - y2;
B = x2 - x1;
C = -A * x1 - B * y1;
// A is guaranteed to be non-zero
if (A < 0) A = -A, B = -B, C = -C;
int g = __gcd(A, __gcd(abs(B), abs(C)));
A /= g, B /= g, C /= g;
}
};
bool operator ==(const line &a, const line &b){
return a.A == b.A && a.B == b.B && a.C == b.C;
}
double x;
bool operator <(const line &a, const line &b){
double val1 = (-a.A * x - a.C) / a.B;
double val2 = (-b.A * x - b.C) / b.B;
return val1 < val2;
}
struct car{
int x, y, dx, dy, s;
line l;
double vx, vy;
};
int n;
vector<car> a(n);
long long det(int a, int b, int c, int d){
return a * 1ll * d - b * 1ll * c;
}
bool inter(const line &a, const line &b, long long &D, long long &Dx, long long &Dy){
D = det(a.A, a.B, b.A, b.B);
if (D == 0) return false;
Dx = -det(a.C, a.B, b.C, b.B);
Dy = -det(a.A, a.C, b.A, b.C);
return true;
}
int sg(int x){
return x < 0 ? -1 : 1;
}
int sg(long long a, long long b, int c){
// sign of a/b-c
if (b < 0) a = -a, b = -b;
return a - c * b < 0 ? -1 : (a - c * b > 0);
}
bool inter(int i, int j, double &len){
if (i == -1 || j == -1)
return false;
long long D, Dx, Dy;
if (!inter(a[i].l, a[j].l, D, Dx, Dy))
return false;
if (sg(Dx, D, a[i].x) != 0 && sg(a[i].dx) != sg(Dx, D, a[i].x))
return false;
if (sg(Dx, D, a[j].x) != 0 && sg(a[j].dx) != sg(Dx, D, a[j].x))
return false;
double x = Dx / double(D);
double y = Dy / double(D);
double di = (a[i].x - x) * (a[i].x - x) + (a[i].y - y) * (a[i].y - y);
double dj = (a[j].x - x) * (a[j].x - x) + (a[j].y - y) * (a[j].y - y);
return len * len >= di / a[i].s && len * len >= dj / a[j].s;
}
vector<set<pair<line, int>>::iterator> del;
set<pair<line, int>> q;
void get_neighbours(int i, int &l, int &r){
l = r = -1;
auto it = q.lower_bound({a[i].l, -1});
if (it != q.end())
r = it->y;
if (!q.empty() && it != q.begin()){
--it;
l = it->y;
}
}
bool check(double t){
vector<pair<double, pair<int, int>>> cur;
del.resize(n);
forn(i, n){
double x1 = a[i].x;
double x2 = a[i].x + a[i].vx * t;
if (x1 > x2) swap(x1, x2);
cur.push_back({x1, {i, 0}});
cur.push_back({x2, {i, 1}});
}
q.clear();
sort(cur.begin(), cur.end());
for (auto &qr : cur){
x = qr.x;
int i = qr.y.x;
int l, r;
if (qr.y.y == 0){
get_neighbours(i, l, r);
if (r != -1 && a[i].l == a[r].l)
return true;
if (inter(i, l, t))
return true;
if (inter(i, r, t))
return true;
del[i] = q.insert({a[i].l, i}).x;
}
else{
q.erase(del[i]);
get_neighbours(i, l, r);
if (inter(l, r, t))
return true;
}
}
return false;
}
int main() {
scanf("%d", &n);
a.resize(n);
forn(i, n){
scanf("%d%d%d%d%d", &a[i].x, &a[i].y, &a[i].dx, &a[i].dy, &a[i].s);
a[i].l = line(a[i].x, a[i].y, a[i].x + a[i].dx, a[i].y + a[i].dy);
double d = sqrt(a[i].dx * a[i].dx + a[i].dy * a[i].dy);
a[i].vx = a[i].dx / d * a[i].s;
a[i].vy = a[i].dy / d * a[i].s;
a[i].s *= a[i].s;
}
double l = 0, r = INF;
bool ok = false;
forn(_, 100){
double m = (l + r) / 2;
if (check(m)){
ok = true;
r = m;
}
else{
l = m;
}
}
if (!ok)
puts("No show :(");
else
printf("%.15lf\n", l);
return 0;
}
|
1360
|
A
|
Minimal Square
|
Find the minimum area of a \textbf{square} land on which you can place two identical rectangular $a \times b$ houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
- You are given two identical rectangles with side lengths $a$ and $b$ ($1 \le a, b \le 100$) — positive integers (you are given just the sizes, but \textbf{not} their positions).
- Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square.
Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.
\begin{center}
{\small The picture shows a square that contains red and green rectangles.}
\end{center}
|
Obviously that both rectangles should completely touch by one of the sides. Otherwise, you can move them closer to each other so that the total height or total width decreases, and the other dimension does not change. Thus, there are only two options: The rectangles touch by width, we get the side of the square equal to $\max(2b, a)$, The rectangles touch by height, we get the side of the square equal to $\max(2a, b)$.
|
[
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
int solve(int a, int b) {
int side = min(max(a * 2, b), max(a, b * 2));
return side * side;
}
int main(int argc, char* argv[]) {
int t;
cin >> t;
forn(tt, t) {
int a, b;
cin >> a >> b;
cout << solve(a, b) << endl;
}
}
|
1360
|
B
|
Honest Coach
|
There are $n$ athletes in front of you. Athletes are numbered from $1$ to $n$ from left to right. You know the strength of each athlete — the athlete number $i$ has the strength $s_i$.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $A$ and $B$ so that the value $|\max(A) - \min(B)|$ is as small as possible, where $\max(A)$ is the maximum strength of an athlete from team $A$, and $\min(B)$ is the minimum strength of an athlete from team $B$.
For example, if $n=5$ and the strength of the athletes is $s=[3, 1, 2, 6, 4]$, then one of the possible split into teams is:
- first team: $A = [1, 2, 4]$,
- second team: $B = [3, 6]$.
In this case, the value $|\max(A) - \min(B)|$ will be equal to $|4-3|=1$. This example illustrates one of the ways of optimal split into two teams.
Print the minimum value $|\max(A) - \min(B)|$.
|
Let's found two athletes with numbers $a$ and $b$ (the strength of $a$ is not greater than the strength of $b$), which have the minimal modulus of the difference of their strength. Obviously, we cannot get an answer less than this. Let's show how to get the partition with exactly this answer. Sort all athletes by strength. Our two athletes will stand in neighboring positions (otherwise, we can decrease the answer). Let the first team contains all athletes who stand on positions not further than $a$, and the second team contains other athletes. We got a partition, in which the athlete with number $a$ has the maximal strength in the first team, and the athlete with number $b$ has the minimal strength in the second team.
|
[
"greedy",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int test;
cin >> test;
for (int tt = 0; tt < test; tt++) {
int n;
cin >> n;
vector<int> a(n);
for (int &x : a) {
cin >> x;
}
sort(a.begin(), a.end());
int result = a[n - 1] - a[0];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
result = min(result, a[j] - a[i]);
}
}
cout << result << endl;
}
return 0;
}
|
1360
|
C
|
Similar Pairs
|
We call two numbers $x$ and $y$ similar if they have the same parity (the same remainder when divided by $2$), or if $|x-y|=1$. For example, in each of the pairs $(2, 6)$, $(4, 3)$, $(11, 7)$, the numbers are similar to each other, and in the pairs $(1, 4)$, $(3, 12)$, they are not.
You are given an array $a$ of $n$ ($n$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.
For example, for the array $a = [11, 14, 16, 12]$, there is a partition into pairs $(11, 12)$ and $(14, 16)$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.
|
Let $e$ - be the number of even numbers in the array, and $o$ - be the number of odd numbers in the array. Note that if the parities of $e$ and of $o$ do not equal, then the answer does not exist. Otherwise, we consider two cases: $e$ and $o$ - are even numbers. Then all numbers can be combined into pairs of equal parity. $e$ and $o$ - are odd numbers. Then you need to check whether there are two numbers in the array such that the modulus of their difference is $1$. If there are two such numbers, then combine them into one pair. $e$ and $o$ will decrease by $1$ and become even, then the solution exists as shown in the previous case.
|
[
"constructive algorithms",
"graph matchings",
"greedy",
"sortings"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
using ld = long double;
using ll = long long;
void solve() {
int n;
cin >> n;
vector<int> v(n);
int a = 0, b = 0;
for (int &e : v) {
cin >> e;
if (e % 2 == 0) {
a++;
} else {
b++;
}
}
if (a % 2 != b % 2) {
cout << "NO\n";
} else {
if (a % 2 == 0) {
cout << "YES\n";
} else {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (v[i] % 2 != v[j] % 2 && abs(v[i] - v[j]) == 1) {
cout << "YES\n";
return;
}
}
}
cout << "NO\n";
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1360
|
D
|
Buying Shovels
|
Polycarp wants to buy \textbf{exactly} $n$ shovels. The shop sells packages with shovels. The store has $k$ types of packages: the package of the $i$-th type consists of exactly $i$ shovels ($1 \le i \le k$). The store has an infinite number of packages of each type.
Polycarp wants to choose \textbf{one} type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $n$ shovels?
For example, if $n=8$ and $k=7$, then Polycarp will buy $2$ packages of $4$ shovels.
Help Polycarp find the minimum number of packages that he needs to buy, given that he:
- will buy exactly $n$ shovels in total;
- the sizes of \textbf{all} packages he will buy are all the same and the number of shovels in each package is an integer from $1$ to $k$, inclusive.
|
If Polycarp buys $a$ packages of $b$ shovels and gets exactly $n$ shovels in total, then $a \cdot b = n$, that is, $a$ and $b$ are divisors of $n$. Then the problem reduces to the following, you need to find the maximum divisor of the number $n$ not greater than $k$. To do this, iterate over all the numbers $x$ from $1$ to $\sqrt n$ inclusive and check whether $n$ is divisible by $x$. If so, then $x$ and $\frac{n}{x}$ - are both divisors of $n$ and you can use them to try to improve the answer.
|
[
"math",
"number theory"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int test;
cin >> test;
for (int tt = 0; tt < test; tt++) {
int n, k;
cin >> n >> k;
int ans = n;
for (int j = 1; j * j <= n; j++) {
if (n % j == 0) {
if (j <= k) {
ans = min(ans, n / j);
}
if (n / j <= k) {
ans = min(ans, j);
}
}
}
cout << ans << endl;
}
return 0;
}
|
1360
|
E
|
Polygon
|
Polygon is not only the best platform for developing problems but also a square matrix with side $n$, initially filled with the character 0.
On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $2n$ cannons were placed.
\begin{center}
{\small Initial polygon for $n=4$.}
\end{center}
Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.
More formally:
- if a cannon stands in the row $i$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($i, 1$) and ends in some cell ($i, j$);
- if a cannon stands in the column $j$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($1, j$) and ends in some cell ($i, j$).
For example, consider the following sequence of shots:
\begin{center}
{\small 1. Shoot the cannon in the row $2$. 2. Shoot the cannon in the row $2$. 3. Shoot the cannon in column $3$.}
\end{center}
You have a report from the military training on your desk. This report is a square matrix with side length $n$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?
Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.
|
Let's see how the matrix looks like after some sequence of shoots: The matrix consists of 0, or There is at least one 1 at position ($n, i$) or ($i, n$), and any 1 not at position ($n, j$) or ($j, n$) must have 1 below or right. If the second condition is violated, then the 1 in the corresponding cell would continue its flight. Thus, it is necessary and sufficient to verify that the matrix satisfies the condition above.
|
[
"dp",
"graphs",
"implementation",
"shortest paths"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
bool a[50][50];
int main() {
int tests;
cin >> tests;
while (tests--) {
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
char c;
cin >> c;
a[i][j] = c - '0';
}
}
bool ans = true;
for (int i = n - 2; i >= 0; --i) {
for (int j = n - 2; j >= 0; --j) {
if (a[i][j] && !a[i + 1][j] && !a[i][j + 1]) {
ans = false;
}
}
}
cout << (ans ? "YES" : "NO") << endl;
}
}
|
1360
|
F
|
Spy-string
|
You are given $n$ strings $a_1, a_2, \ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters.
Find any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one position $j$ such that $a_i[j] \ne s[j]$.
Note that the desired string $s$ may be equal to one of the given strings $a_i$, or it may differ from all the given strings.
For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.
|
Consider all strings that differ from the first one in no more than one position (this is either the first string or the first string with one character changed). We will go through all such strings and see if they can be the answer. To do this, go through all the strings and calculate the number of positions where they differ.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"hashing",
"strings"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
using ld = long double;
using ll = long long;
void solve() {
int n, m;
cin >> n >> m;
vector<string> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
string ans = v[0];
for (int j = 0; j < m; j++) {
char save = ans[j];
for (char d = 'a'; d <= 'z'; d++) {
ans[j] = d;
bool flag = true;
for (int z = 0; z < n; z++) {
int cntErrors = 0;
for (int c = 0; c < m; c++) {
if (v[z][c] != ans[c]) {
cntErrors++;
}
}
if (cntErrors > 1) {
flag = false;
break;
}
}
if (flag) {
cout << ans << endl;
return;
}
}
ans[j] = save;
}
cout << "-1" << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1360
|
G
|
A/B Matrix
|
You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions:
- each row of the matrix contains exactly $a$ ones;
- each column of the matrix contains exactly $b$ ones;
- all other elements are zeros.
If the desired matrix does not exist, indicate this.
For example, for $n=3$, $m=6$, $a=2$, $b=1$, there exists a matrix satisfying the conditions above:
$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$
|
Let's see how the desired matrix looks like. Since each row should have exactly $a$ ones, and each column should have exactly $b$ ones, the number of ones in all rows $a \cdot n$ should be equal to the number of ones in all columns $b \cdot m$. Thus, the desired matrix exists iff $a \cdot n = b \cdot m$ or $\frac{n}{m} = \frac{b}{a}$. Let's show how to construct the desired matrix if it exists. Let's find any number $0<d<m$ such that $(d \cdot n) \% m = 0$, where $a \% b$ - is the remainder of dividing $a$ by $b$. In the first row of the desired matrix, we put the ones at the positions $[1, a]$, and in the $i$-th row we put the ones, as in the $i-1$ row, but cyclically shifted by $d$ to the right.
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int test;
cin >> test;
for (int tt = 0; tt < test; tt++) {
int h, w, a, b;
cin >> h >> w >> a >> b;
if (h * a != w * b) {
cout << "NO" << endl;
continue;
}
vector<vector<int>> result(h, vector<int>(w, 0));
int shift = 0;
for (shift = 1; shift < w; shift++) {
if (shift * h % w == 0) {
break;
}
}
for (int i = 0, dx = 0; i < h; i++, dx += shift) {
for (int j = 0; j < a; j++) {
result[i][(j + dx) % w] = 1;
}
}
cout << "YES" << endl;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cout << result[i][j];
}
cout << endl;
}
}
return 0;
}
|
1360
|
H
|
Binary Median
|
Consider all binary strings of length $m$ ($1 \le m \le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in total.
The string $s$ is lexicographically smaller than the string $t$ (both have the same length $m$) if in the first position $i$ from the left in which they differ, we have $s[i] < t[i]$. This is exactly the way strings are compared in dictionaries and in most modern programming languages when comparing them in a standard way. For example, the string 01011 is lexicographically smaller than the string 01100, because the first two characters are the same, and the third character in the first string is less than that in the second.
We remove from this set $n$ ($1 \le n \le \min(2^m-1, 100)$) \textbf{distinct} binary strings $a_1, a_2, \ldots, a_n$, each of length $m$. Thus, the set will have $k=2^m-n$ strings. Sort all strings of the resulting set in lexicographical ascending order (as in the dictionary).
We number all the strings after sorting from $0$ to $k-1$. Print the string whose index is $\lfloor \frac{k-1}{2} \rfloor$ (such an element is called median), where $\lfloor x \rfloor$ is the rounding of the number down to the nearest integer.
For example, if $n=3$, $m=3$ and $a=[$010, 111, 001$]$, then after removing the strings $a_i$ and sorting, the result will take the form: $[$000, 011, 100, 101, 110$]$. Thus, the desired median is 100.
|
If we did not delete the strings, then the median would be equal to the binary notation of $2^{(m-1)}$. After deleting $n$ strings, the median cannot change (numerically) by more than $2 \cdot n$. Let's start with the median $2^{(m-1)}$ and each time decrease it by one if there are fewer not deleted smaller numbers than not deleted large numbers. Similarly, you need to increase the median by one, otherwise. The algorithm stops when the result is the median of the current set. All these steps will run at most $200$ times.
|
[
"binary search",
"bitmasks",
"brute force",
"constructive algorithms"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
using ld = long double;
using ll = long long;
void solve() {
ll m, n;
cin >> n >> m;
vector<ll> v(n);
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (char c : s) {
v[i] *= 2;
v[i] += c - '0';
}
}
ll need = ((1ll << m) - n - 1) / 2 + 1;
ll cur = (1ll << (m - 1)) - 1;
while (true) {
ll left = cur + 1;
bool flag = false;
for (int i = 0; i < n; i++) {
flag |= v[i] == cur;
if (v[i] <= cur) {
left--;
}
}
if (left == need && !flag) {
string s;
for (int i = 0; i < m; i++) {
s += (char)(cur % 2 + '0');
cur /= 2;
}
reverse(s.begin(), s.end());
cout << s << endl;
return;
} else if (left < need) {
cur++;
} else {
cur--;
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
|
1361
|
A
|
Johnny and Contribution
|
Today Johnny wants to increase his contribution. His plan assumes writing $n$ blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are $n$ different topics, numbered from $1$ to $n$ sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most $n - 1$ neighbors.
For example, if already written neighbors of the current blog have topics number $1$, $3$, $1$, $5$, and $2$, Johnny will choose the topic number $4$ for the current blog, because topics number $1$, $2$ and $3$ are already covered by neighbors and topic number $4$ isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
|
We can view blogs as a graph, references as edges, and topics as colors. Now we can reformulate our problem as finding a permutation of vertices such that given in the statement greedy coloring algorithm returns coloring as described in the input. Let us start with two observations: Observation 1: If there is an edge between vertices with the same color, then the answer is $-1$. Observation 2: If for a vertex $u$ with color $c$ there exist a color $c' < c$ such that $u$ has no edge to any vertex with color $c'$ then the answer is $-1$. Both observations are rather straightforward to prove, so we skip it. Let us create permutation where vertices are sorted firstly by desired color and secondly by indices. We claim that if there exists any ordering fulfilling given regulations, then this permutation fulfills these too. Let us prove it: Let us analyze vertex $u$ with color $c$. From observation $2$ we know that for each color $c' < c$ there exist $v$ with color $c'$ such that $u$ and $v$ are connected by an edge. Because vertices are sorted by colors in our permutation, $v$ is before $u$ in ordering. So the greedy algorithm will assign that vertex color $k \geq c$. From observation $1$, we now that $u$ does not have an edge to vertex with color $c$, so the greedy algorithm has to assign to $u$ color $k \leq c$. Combining both inequalities, we reach that greedy must assign color $k = c$, which completes our proof. So now the algorithm is rather straightforward - sort vertices by colors, check if that ordering fulfills given regulations, if so, then write it down, otherwise print $-1$. This can be implemented in $\mathcal{O}(n \log n)$ or $\mathcal{O}(n)$.
|
[
"constructive algorithms",
"graphs",
"greedy",
"sortings"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int n, m;
int ans[N];
int last[N];
vector <int> G[N];
vector <int> in[N];
int main(){
scanf("%d %d", &n, &m);
for(int i = 1; i <= m; ++i){
int u, v;
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i = 1; i <= n; ++i){
int color;
scanf("%d", &color);
in[color].push_back(i);
if(color > n){
puts("-1");
exit(0);
}
}
vector <int> result;
for(int i = 1; i <= n; ++i){
for(auto u: in[i]){
for(auto v: G[u])
last[ans[v]] = u;
ans[u] = 1;
while(last[ans[u]] == u)
++ans[u];
if(ans[u] != i){
puts("-1");
exit(0);
}
result.push_back(u);
}
}
for(int i = 0; i < n; ++i)
printf("%d%c", result[i], i == n - 1 ? '\n' : ' ');
return 0;
}
|
1361
|
B
|
Johnny and Grandmaster
|
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$.
|
The solution for the case $p = 1$ is trivial, the answer is $1$ for odd $n$ and $0$ for even $n$. From now on, I will assume that $p > 1$. Instead of partitioning the elements into two sets, I will think of placing plus and minus signs before them to minimize the absolute value of the resulting expression. We will process the exponents in non-increasing order and maintain the invariant that the current sum is nonnegative. Say we are processing $k_i.$ In such cases, we will know the current sum modulo $10^{9}+7$ and its exact value divided by $p^{k_i}$ (denoted as $v$) or information that it's too big. Initially, the sum (I will denote it $s$) equals $0$. While processing elements: If $s > 0$, subtract the current element from the sum (it easy to show that it won't be negative after this operation). If $s = 0$, add the current element to the sum. If at any point of the algorithm, $v = \frac{s}{p^{k_i}} > n$, there is no need to store the exact value of $v$ anymore, because it is so big that all the elements from this moment on will be subtracted. Thus, it is enough to store this information and the current sum modulo $10^{9}+7$. When we move to the next element, the exponent may change, and $v$ needs to be multiplied by a power of $p$. Since the exponents can be large, we use fast multiplication. The time complexity of this solution is $\mathcal{O}(n \log n + n \log \max k_i)$.
|
[
"greedy",
"implementation",
"math",
"sortings"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e6+100;
const ll mod = ll(1e9)+7;
ll fexp (ll a, int e)
{
ll ret = 1LL;
while (e>0)
{
if (e%2==1) ret = ret * a % mod;
a = a*a % mod;
e/=2;
}
return ret;
}
int main ()
{
int t;
scanf ("%d", &t);
for (int test = 0; test < t; test++)
{
int n;
ll p;
scanf ("%d %lld", &n, &p);
vector <int> K(n);
for (int &x: K) scanf ("%d", &x);
sort(K.begin(), K.end());
vector <int> Exp = K;
ll currSum = 0;
ll result = 0;
bool infty = false;
int prevExp = 1e6+10;
while (!Exp.empty())
{
/* Update the currSum and result (multiply by a power of k) */
int k = Exp.back();
Exp.pop_back();
int delta = prevExp - k;
prevExp = k;
result = result * fexp(p, delta) % mod;
/* Multiplying by p 20 times will either
not change the currSum at all or make it bigger than n */
for (int i=0; i<min(delta, 20); i++)
{
currSum *= p;
if (currSum > INF) infty = true;
}
/* Process all the elements equal p^k */
while (!K.empty() && K.back()==k)
{
K.pop_back();
if (infty || currSum > 0)
{
currSum--;
result+=mod - 1;
}
else
{
currSum++;
result++;
}
result%=mod;
}
}
result = result * fexp(p, prevExp) % mod;
printf ("%lld\n", result % mod);
}
}
|
1361
|
C
|
Johnny and Megan's Necklace
|
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace — do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors $u$ and $v$ is defined as follows: let $2^k$ be the greatest power of two dividing $u \oplus v$ — exclusive or of $u$ and $v$. Then the beauty equals $k$. If $u = v$, you may assume that beauty is equal to $20$.
Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build \textbf{exactly one} necklace consisting of \textbf{all of them} with the largest possible beauty. Help her!
|
Say that we want to check if it is possible to construct a necklace with beauty at least $b$. To this end, we will construct a graph of $2^{b}$ vertices. For a necklace part with pearls in colors $u$ and $v$ there will be an edge in this graph between vertices with zero-based indices $v\text{ & }(2^b-1)$ and $u\text{ & }(2^b-1)$. In a necklace with beauty (at least) $b$, only pearl with colors having last $b$ bits the same can be glued together. Note that this is the exact condition that the edge endpoints have to satisfy to be in the same vertex. Since all the necklace parts have to be used, a necklace of beauty at least $b$ is an Euler cycle of this graph. The solution will construct the graph mentioned above for all possible values of $b$ (we can iterate over all of them since there are only $21$ of them). If the constructed graph is Eulerian, it is possible to achieve the current value of $b$. In order to find a sample necklace with the optimal beauty, one has to find the Euler cycle in the graph corresponding to the optimal value. Challenge: In another version of this task you are not allowed to glue pearls of the same color together. There is also a guarantee that there are no three pearls of the same color. Time complexity of the solution is the same.
|
[
"binary search",
"bitmasks",
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
#define st first
#define nd second
#define PII pair <int, int>
const int N = 1 << 20;
int n;
int part[N][2];
bool vis[N];
vector <int> ans;
vector <PII> G[N];
//mark whole component as visited
void dfs(int u){
vis[u] = true;
for(auto v: G[u])
if(!vis[v.st])
dfs(v.st);
}
//check if the graph for a given Mask is correct
bool check(int Mask){
for(int i = 0; i <= Mask; ++i)
G[i].clear(), vis[i] = false;
for(int i = 1; i <= n; ++i){
int u = part[i][0] & Mask;
int v = part[i][1] & Mask;
G[u].push_back({v, 2 * i - 1});
G[v].push_back({u, 2 * i - 2});
}
//calculate number of components and check if all degrees are even
int comps = 0;
for(int i = 0; i <= Mask; ++i){
if(G[i].size() & 1)
return false;
if(!vis[i] && G[i].size() > 0){
++comps;
dfs(i);
}
}
return comps == 1;
}
//find euler cycle
void go(int u, int prv = -1){
while(G[u].size()){
auto e = G[u].back();
G[u].pop_back();
if(vis[e.nd / 2])
continue;
vis[e.nd / 2] = true;
go(e.st, e.nd);
}
if(prv != -1){
ans.push_back(prv);
ans.push_back(prv ^ 1);
}
}
//restore the sequence corresponding to the result for given mask
//the result is already checked so the graph is built
void restore(int Mask){
for(int i = 0; i <= n; ++i)
vis[i] = false;
for(int i = 0; i <= Mask; ++i)
if(G[i].size()){
go(i);
break;
}
//cycle is reversed but thats fine
for(int i = 0; i < n + n; ++i)
printf("%d%c", ans[i] + 1, " \n"[i + 1 == n + n]);
}
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
scanf("%d %d", &part[i][0], &part[i][1]);
for(int i = 20; i >= 0; --i)
if(check((1 << i) - 1)){
printf("%d\n", i);
restore((1 << i) - 1);
exit(0);
}
assert(false);
return 0;
}
|
1361
|
D
|
Johnny and James
|
James Bond, Johnny's favorite secret agent, has a new mission. There are $n$ enemy bases, each of them is described by its coordinates so that we can think about them as points in the Cartesian plane.
The bases can communicate with each other, sending a signal, which is the ray directed from the chosen point to the origin or in the opposite direction. The exception is the central base, which lies at the origin and can send a signal in any direction.
When some two bases want to communicate, there are two possible scenarios. If they lie on the same line with the origin, one of them can send a signal directly to the other one. Otherwise, the signal is sent from the first base to the central, and then the central sends it to the second base. We denote the distance between two bases as the total Euclidean distance that a signal sent between them has to travel.
Bond can damage all but some $k$ bases, which he can choose arbitrarily. A damaged base can't send or receive the direct signal but still can pass it between two working bases. In particular, James can damage the central base, and the signal \textbf{can still be sent} between any two undamaged bases as before, so the distance between them remains the same. What is the maximal sum of the distances between all pairs of remaining bases that 007 can achieve by damaging exactly $n - k$ of them?
|
We can easily model the way of calculating distances from the problem statement as a tree with $n$ vertices, each corresponding to a base. This tree has the following structure: there is only one vertex which can have degree bigger than $2$ (the one corresponding to the central base), I will call it the center of the tree. There are also some paths consisting of vertices corresponding to bases lying on the same half-line starting at point $(0, 0)$. We will call those arms of the tree. Assume that the center does not belong to any arm. The task is to choose $k$ vertices in a way that maximizes the sum of distances between them. Let us start with a lemma: If $x$ vertices are chosen from an arm, at least $min(x, \lfloor \frac{k}{2} \rfloor)$ of them are the ones furthest from the center. Say that less than $min(x, \lfloor \frac{k}{2} \rfloor)$ is chosen from the end of the arm (counting from the center). Then there exists such chosen vertex $v$ on the arm, that the next (counting from the center) vertex $u$ is not chosen. Let the length of the edge between them be $l$ and let there be $t$ vertices further from the center than $v$. If we had chosen $u$ instead of $v$, the sum of distances would change by $l \cdot (k - t - 1) - l \cdot t = l \cdot (k - 2t - 1)$ (the chosen vertex would move closer by $l$ to $t$ vertices, but also it's distance to $k-t-1$ vertices would increase by $l$). But since $t < \frac{k}{2}$, this value is non-negative (the sum of distances would not decrease). There are two cases which will be solved independently: First case: there is no arm containing more than $\frac{k}{2}$ vertices chosen. By the lemma, in every arm, only vertices furthest from the center will be selected in an optimal solution. If a vertex is chosen, all the ones in the same arm further from the center are chosen as well. Using this knowledge, we can assign weights to vertices in such a way that the result for a set will be the sum of weights. Weight for vertex $v$ equals: $w_v = dist(center, v) * (k - 1 - t - t)$ where $t$ is the number of vertices further from center in the same arm as $v$. The weight of the center equals $0$. Note that (with exception to the center) $w_v \leq 0$ iff taking $v$ would violate the condition that at most $\frac{k}{2}$ are chosen from every arm. The algorithm for this case is to add the vertices greedily to the set until $k$ vertices have been chosen. The complexity of the above algorithm is $\mathcal{O}(n \log n)$. Second case: there is an arm, in which more than $\frac{k}{2}$ vertices are chosen in the optimal solution. From the lemma, we know that $\lfloor \frac{k}{2} \rfloor$ vertices lying furthest from the center will be chosen. It can be proved (in a similar manner as the lemma) that in an optimal solution, all other selected vertices from this arm will be as close to the center as possible. Furthermore, the center and all the vertices in the other arms will be selected. Intuitively, when there are $\lfloor \frac{k}{2} \rfloor$ chosen vertices on a single-arm, we will not decrease the sum of distances by moving another selected vertex further from them along an edge. There is at most one set of $k$ vertices satisfying those conditions so that this part can be implemented in $\mathcal{O}(n)$. The time complexity of this solution is $\mathcal{O}(n \log n)$.
|
[
"greedy",
"implementation",
"math",
"trees"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
typedef long double T;
#define st first
#define nd second
#define PII pair <int, int>
const int N = 1e6 + 7;
int n, m, k;
vector <T> arms[N];
void read(){
map <PII, int> M;
scanf("%d %d", &n, &k);
for(int i = 1; i <= n; ++i){
int x, y;
scanf("%d %d", &x, &y);
if(x == 0 && y == 0)
continue;
int d = __gcd(abs(x), abs(y));
PII my_id = {x / d, y / d};
if(!M.count(my_id))
M[my_id] = ++m;
auto id = M[my_id];
arms[id].push_back(sqrtl((T)x * x + (T)y * y));
}
for(int i = 1; i <= m; ++i){
sort(arms[i].begin(), arms[i].end());
reverse(arms[i].begin(), arms[i].end());
}
}
T solve_center(){
T ans = 0;
vector <T> vals = {0};
for(int i = 1; i <= m; ++i){
int it = 0;
for(auto v: arms[i]){
++it;
vals.push_back(v * (k - it - it + 1));
}
}
sort(vals.begin(), vals.end());
reverse(vals.begin(), vals.end());
for(int i = 0; i < k; ++i)
ans += vals[i];
return ans;
}
T solve_arm(int id){
T ans = 0;
for(int i = 1; i <= m; ++i){
if(i == id)
continue;
int it = 0;
for(auto v: arms[i]){
++it;
ans += v * (k - it - it + 1);
}
}
int half = k / 2;
int first_half = k - half - (n - arms[id].size());
for(int i = 0; i < half; ++i)
ans += arms[id][i] * (k - i - i - 1);
for(int i = 0; i < first_half; ++i){
T val = arms[id][arms[id].size() - i - 1];
ans += val * (k - half - half - 2 * first_half + 2 * i + 1);
}
return ans;
}
int main(){
read();
T ans = solve_center();
if(k < n){
for(int i = 1; i <= m; ++i)
if(2 * (n - (int)arms[i].size()) <= k)
ans = max(ans, solve_arm(i));
}
printf("%.10Lf\n", ans);
return 0;
}
|
1361
|
E
|
James and the Chase
|
James Bond has a new plan for catching his enemy. There are some cities and \textbf{directed} roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there.
The city $a$ is called interesting, if for each city $b$, there is exactly one simple path from $a$ to $b$. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city.
Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.
You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than $20\%$ of all cities.
|
First, let us describe an algorithm for checking if a vertex is interesting. Let $v$ be the vertex we want to check. Find any DFS tree rooted in that vertex. We can see that $v$ is interesting if and only if that tree is unique. The tree is unique iff every non-tree edge leads from some vertex $u$ to $u$'s ancestor. That condition can be easily checked in $\mathcal{O}(n)$. Using the fact that we are interested only in cases when at least $20\%$ of vertices are interesting, we can find any interesting vertex by choosing a random vertex, checking if it is interesting and repeating that algorithm $T$ times or until we find an interesting vertex. For $T = 100$ the probability of failure is around $2 \cdot 10^{-10}$. Denote that vertex as $r$. Find the DFS tree rooted in that vertex. We can notice that vertex is interesting if and only if it has a unique path to all of its ancestors in this tree. We will say that edge is passing vertex $v$ if it starts in its subtree (including $v$) and ends in one of the proper ancestors of $v$. It is evident that if two edges pass through $v$, then $v$ cannot be interesting. Let us pick vertex $v$ such that there is at most one edge passing through it. It is evident that if $v \neq r$, then there is at least one such edge (because our graph is strongly connected). Let $u$ be the endpoint of this edge being a proper ancestor of $v$. We prove that $v$ is interesting if and only if $u$ is interesting. Pick arbitrary ancestor of $v$ which is not an ancestor of $u$, let us denote it by $t$. There is precisely one simple path from $v$ to $t$ - descending in the subtree of $v$, using the non-tree edge to $u$ and then tree edges to reach $t$. Now pick arbitrary common ancestor of $v$ and $u$, let it be $k$. If there is more than one simple path from $u$ to $k$, then obviously there is more than one simple path from $v$ to $k$. Otherwise, there is precisely one simple path from $v$ to $k$ - descend in the subtree, use edge to $u$ and from $u$ there is one simple path to $k$. The above observations allow computing interesting vertices using simple DFSs. The final complexity is $\mathcal{O}(Tn)$.
|
[
"dfs and similar",
"graphs",
"probabilities",
"trees"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
int n, m;
bool bad[N];
vector <int> G[N];
int vis[N];
bool interesting;
int lvl[N];
int best[N];
int balance[N];
void clear(){
for(int i = 1; i <= n; ++i){
lvl[i] = 0;
best[i] = 0;
balance[i] = 0;
G[i].clear();
bad[i] = false;
}
}
void no_answer(){
puts("-1");
clear();
}
int getInt(int a = INT_MIN, int b = INT_MAX){
static mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
return uniform_int_distribution <int> (a, b)(rng);
}
void dfs(int u){
vis[u] = 1;
for(auto v: G[u])
if(vis[v] == 0)
dfs(v);
else if(vis[v] == 2)
interesting = false;
vis[u] = 2;
}
bool check(int r){
for(int i = 1; i <= n; ++i)
vis[i] = 0;
interesting = true;
dfs(r);
return interesting;
}
int find_any(){
int tests = 100;
while(tests--){
int r = getInt(1, n);
if(check(r))
return r;
}
return -1;
}
int find_bad(int u){
vis[u] = 1;
best[u] = u;
for(auto v: G[u])
if(vis[v] == 0){
lvl[v] = lvl[u] + 1;
balance[u] += find_bad(v);
if(lvl[best[v]] < lvl[best[u]])
best[u] = best[v];
}
else{
balance[u]++;
balance[v]--;
if(lvl[v] < lvl[best[u]])
best[u] = v;
}
if(balance[u] > 1)
bad[u] = true;
return balance[u];
}
void propagate_bad(int u){
vis[u] = 1;
if(!bad[u] && bad[best[u]])
bad[u] = true;
for(auto v: G[u])
if(vis[v] == 0)
propagate_bad(v);
}
vector <int> find_all(int r){
for(int i = 1; i <= n; ++i)
vis[i] = 0;
vector <int> ans;
find_bad(r);
for(int i = 1; i <= n; ++i)
vis[i] = 0;
propagate_bad(r);
for(int i = 1; i <= n; ++i)
if(!bad[i])
ans.push_back(i);
return ans;
}
void solve(){
scanf("%d %d", &n, &m);
for(int i = 1; i <= m; ++i){
int u, v;
scanf("%d %d", &u, &v);
G[u].push_back(v);
}
int id = find_any();
if(id == -1){
no_answer();
return;
}
auto ans = find_all(id);
if(5 * ans.size() >= n){
for(auto v: ans)
printf("%d ", v);
puts("");
clear();
}
else
no_answer();
}
int main(){
int cases;
scanf("%d", &cases);
while(cases--)
solve();
return 0;
}
|
1361
|
F
|
Johnny and New Toy
|
Johnny has a new toy. As you may guess, it is a little bit extraordinary. The toy is a permutation $P$ of numbers from $1$ to $n$, written in one row next to each other.
For each $i$ from $1$ to $n - 1$ between $P_i$ and $P_{i + 1}$ there is a weight $W_i$ written, and those weights form a permutation of numbers from $1$ to $n - 1$. There are also extra weights $W_0 = W_n = 0$.
The instruction defines subsegment $[L, R]$ as good if $W_{L - 1} < W_i$ and $W_R < W_i$ for any $i$ in $\{L, L + 1, \ldots, R - 1\}$. For such subsegment it also defines $W_M$ as minimum of set $\{W_L, W_{L + 1}, \ldots, W_{R - 1}\}$.
Now the fun begins. In one move, the player can choose one of the good subsegments, cut it into $[L, M]$ and $[M + 1, R]$ and swap the two parts. More precisely, before one move the chosen subsegment of our toy looks like: $$W_{L - 1}, P_L, W_L, \ldots, W_{M - 1}, P_M, W_M, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_R$$ and afterwards it looks like this: $$W_{L - 1}, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_M, P_L, W_L, \ldots, W_{M - 1}, P_M, W_R$$ Such a move can be performed multiple times (possibly zero), and the goal is to achieve the minimum number of inversions in $P$.
Johnny's younger sister Megan thinks that the rules are too complicated, so she wants to test her brother by choosing some pair of indices $X$ and $Y$, and swapping $P_X$ and $P_Y$ ($X$ might be equal $Y$). After each sister's swap, Johnny wonders, what is the minimal number of inversions that he can achieve, starting with current $P$ and making legal moves?
You can assume that the input is generated \textbf{randomly}. $P$ and $W$ were chosen independently and equiprobably over all permutations; also, Megan's requests were chosen independently and equiprobably over all pairs of indices.
|
Let us start with an analysis of good subsegments for the fixed permutation. The whole permutation is a good subsegment itself, as $W_0 = W_n = 0 < W_k$ for any $k \in [1, 2, \ldots, n - 1]$. If we denote the minimal weight in $W_1, \ldots, W_{n - 1}$ as $W_m$, then we can notice that subsegments $[1, m]$ and $[m + 1, n]$ contain all good subsegments except the whole permutation. As a result, we can recursively find all good subsegments by recursive calls in $[1, m]$ and $[m + 1, n]$. We can view the structure of good subsegments as a binary tree. Example structure of tree for $P = [3, 4, 6, 2, 1, 5]$ and $W = [5, 2, 3, 1, 4]$: Now we want to analyze the possible moves for players. It turns out that the player's move is equivalent to choosing a vertex of a tree and swapping its left and right subtree. Notice that moves made in different vertices influence disjoint pairs of elements, so in some sense these moves are independent if we are interested only in the number of inversions. This observation allows us to find a simple method for calculating the result. For each vertex, calculate the number of inversions between the left and right subtree. Using these numbers for each vertex, we can find out whether we want to swap its subtrees or not, so the result can be calculated by a simple loop over all vertices. From randomness of the input, we can deduce that the tree we built has height $\mathcal{O}(\log n)$. We can calculate the number of inversions easily if in each vertex we keep a structure with elements from permutation contained in that vertex. Such structure must support querying the number of elements smaller than some $x$. The shortest implementation uses the ordered set, but any BST can do it (segment tree needs some squeezing to fit into ML). The above solution works fast if there are no queries. We can view each request as two removals and additions of elements. If so, we can notice that each query modifies the number of inversions in at most $\mathcal{O}(\log n)$ vertices. So all we need to do is update the number of inversions in these vertices and recalculate the global result. Building a tree and calculating initial number of inversions takes $\mathcal{O}(n \log n)$ or $\mathcal{O}(n \log^2n)$, answering each query cost $\mathcal{O}(\log^2 n)$, so the final complexity is $\mathcal{O}(n \log n + q \log^2 n)$.
|
[
"data structures",
"implementation",
"math"
] | 3,300
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef tree < int, null_type, less <int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set;
const int N = 2e5 + 7;
//cartesian tree node
//while creating we calculate set of elements and number of inversions
struct node{
int splitter = -1;
long long invs = 0;
ordered_set S;
node *left = nullptr, *right = nullptr;
node(){}
};
int n;
int in[N];
int weight[N];
long long ans = 0;
node *root = nullptr;
void read(){
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
scanf("%d", &in[i]);
for(int i = 1; i < n; ++i)
scanf("%d", &weight[i]);
}
//add/delete contribution from fiven node to result
void add_result(node *cur, int mt = 1){
if(cur -> splitter == 0)
return;
ans += mt * min(cur -> invs, (ll)cur -> left -> S.size() * (ll)cur -> right -> S.size() - cur -> invs);
}
//Create cartesian tree
//Because expected depth is O(logn) we can use bruteforce to find the smallest weight
node* get_cartesian(int from, int to){
node *ret = new node();
if(from == to){
ret -> S.insert(in[from]);
return ret;
}
int id = from;
for(int i = from + 1; i < to; ++i)
if(weight[i] < weight[id])
id = i;
ret -> splitter = id;
ret -> left = get_cartesian(from, id);
ret -> right = get_cartesian(id + 1, to);
//get elements from ordered set
for(auto v: ret -> right -> S)
ret -> S.insert(v);
//calculate number of inversions
for(auto v: ret -> left -> S){
ret -> S.insert(v);
ret -> invs += ret -> right -> S.order_of_key(v);
}
//add contribution to the result
add_result(ret);
return ret;
}
//depending on mt, removes/add element val on position p
void update_cart(int p, int val, int mt){
node *cur = root;
while(cur -> splitter != -1){
add_result(cur, -1);
if(mt == -1)
cur -> S.erase(val);
else
cur -> S.insert(val);
if(p <= cur -> splitter){
cur -> invs += mt * (int)(cur -> right -> S.order_of_key(val));
cur = cur -> left;
}
else{
cur -> invs += mt * (int)(cur -> left -> S.size() - cur -> left -> S.order_of_key(val));
cur = cur -> right;
}
}
if(mt == -1)
cur -> S.erase(val);
else
cur -> S.insert(val);
cur = root;
while(cur -> splitter != -1){
add_result(cur, 1);
if(p <= cur -> splitter)
cur = cur -> left;
else
cur = cur -> right;
}
}
int main(){
read();
root = get_cartesian(1, n);
int q;
scanf("%d", &q);
while(q--){
int x, y;
scanf("%d %d", &x, &y);
if(x == y){
printf("%lld\n", ans);
continue;
}
//remove both numbers
update_cart(x, in[x], -1);
update_cart(y, in[y], -1);
swap(in[x], in[y]);
//add both numbers
update_cart(x, in[x], 1);
update_cart(y, in[y], 1);
printf("%lld\n", ans);
}
return 0;
}
|
1362
|
A
|
Johnny and Ancient Computer
|
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it \textbf{cuts off some ones}. So, in fact, in one operation, you can multiply or divide your number by $2$, $4$ or $8$, and division is only allowed if the number is divisible by the chosen divisor.
Formally, if the register contains a positive integer $x$, in one operation it can be replaced by one of the following:
- $x \cdot 2$
- $x \cdot 4$
- $x \cdot 8$
- $x / 2$, if $x$ is divisible by $2$
- $x / 4$, if $x$ is divisible by $4$
- $x / 8$, if $x$ is divisible by $8$
For example, if $x = 6$, in one operation it can be replaced by $12$, $24$, $48$ or $3$. Value $6$ isn't divisible by $4$ or $8$, so there're only four variants of replacement.
Now Johnny wonders how many operations he needs to perform if he puts $a$ in the register and wants to get $b$ at the end.
|
Let us write $a$ as $r_a \cdot 2^x$ and $b$ as $r_b \cdot 2^y$, where $r_a$ and $r_b$ are odd. The only operation we have changes $x$ by $\{-3, -2, -1, 1, 2, 3\}$ so $r_a$ must be equal to $r_b$, otherwise the answer is $-1$. It is easy to notice that we can greedily move $x$ toward $y$ so the answer is equal to $\lceil \frac{|x - y|}{3} \rceil$.
|
[
"implementation"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL getR(LL a){
while(a % 2 == 0)
a /= 2;
return a;
}
void solve(){
LL a, b;
scanf("%lld %lld", &a, &b);
if(a > b) swap(a, b);
LL r = getR(a);
if(getR(b) != r){
puts("-1");
return;
}
int ans = 0;
b /= a;
while(b >= 8)
b /= 8, ++ans;
if(b > 1) ++ans;
printf("%d\n", ans);
}
int main(){
int quest;
scanf("%d", &quest);
while(quest--)
solve();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.