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
⌀ |
|---|---|---|---|---|---|---|---|
1006
|
B
|
Polycarp's Practice
|
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.
Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.
The profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\max\limits_{l \le i \le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.
You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.
For example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$.
|
The maximum possible total profit you can obtain is the sum of the $k$ largest values of the given array. This is obvious because we can always separate these $k$ maximums and then extend the segments corresponding to them to the left or to the right and cover the entire array. I suggest the following: extract $k$ largest values of the given array and place a separator right after each of them (except the rightmost one). Overall complexity is $O(n \log n)$.
|
[
"greedy",
"implementation",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
vector<pair<int, int>> res(n);
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> res[i].first;
a[i] = res[i].first;
res[i].second = i + 1;
}
sort(res.begin(), res.end());
reverse(res.begin(), res.end());
sort(res.begin(), res.begin() + k, [&](pair<int, int> a, pair<int, int> b) { return a.second < b.second; });
int lst = 0, sum = 0;
for (int i = 0; i < k - 1; ++i) {
sum += *max_element(a.begin() + lst, a.begin() + res[i].second);
lst = res[i].second;
}
sum += *max_element(a.begin() + lst, a.end());
cout << sum << endl;
lst = 0;
for (int i = 0; i < k - 1; ++i) {
cout << res[i].second - lst << " ";
lst = res[i].second;
}
cout << n - lst << endl;
return 0;
}
|
1006
|
C
|
Three Parts of the Array
|
You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers.
Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array.
Let the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible.
More formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then:
$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$ $$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$ $$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$
The sum of an empty array is $0$.
Your task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible.
|
Since the given array consists of positive integers, for each value of $a$, there can be at most one value of $c$ such that $sum_1 = sum_3$. We can use binary search on the array of prefix sums of $d$ to find the correct value of $c$, given that it exists. If it does exist and $a+c \le n$, this is a candidate solution so we store it. Alternatively, we can use the two pointers trick - when $a$ increases, $c$ cannot decrease. Be careful to use 64 bit integers to store sums. Overall complexity is $O(n \log n)$ or $O(n)$.
|
[
"binary search",
"data structures",
"two pointers"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
int n;
int a[200005];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cerr.tie(nullptr);
cin >> n;
for (int i=1; i<=n; i++)
cin >> a[i];
int i = 0, j = n+1;
ll zi = 0, zj = 0, solidx = 0;
while (i < j) {
if (zi < zj)
zi += a[++i];
else if (zi > zj)
zj += a[--j];
else {
solidx = i;
zi += a[++i];
zj += a[--j];
}
}
cout << accumulate(a+1, a+solidx+1, 0ll); // here
}
|
1006
|
D
|
Two Strings Swaps
|
You are given two strings $a$ and $b$ consisting of lowercase English letters, both of length $n$. The characters of both strings have indices from $1$ to $n$, inclusive.
You are allowed to do the following changes:
- Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $b_i$;
- Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $a_{n - i + 1}$;
- Choose any index $i$ ($1 \le i \le n$) and swap characters $b_i$ and $b_{n - i + 1}$.
Note that if $n$ is odd, you are formally allowed to swap $a_{\lceil\frac{n}{2}\rceil}$ with $a_{\lceil\frac{n}{2}\rceil}$ (and the same with the string $b$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.
You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.
In one preprocess move you can replace a character in $a$ with another character. In other words, in a single preprocess move you can choose any index $i$ ($1 \le i \le n$), any character $c$ and set $a_i := c$.
Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $a$ and $b$ equal by applying some number of changes described in the list above.
Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $b$ or make any preprocess moves after the first change is made.
|
Let's divide all characters of both strings into groups in such a way that characters in each group can be swapped with each other with changes. So, there will be following groups: $\{a_1, a_n, b_1, b_n\}$, $\{a_2, a_{n - 1}, b_2, b_{n - 1}\}$ and so on. Since these groups don't affect each other, we can calculate the number of preprocess moves in each group and then sum it up. How to determine if a group does not need any preprocess moves? For a group consisting of $2$ characters (there will be one such group if $n$ is odd, it will contain $a_{\lceil\frac{n}{2}\rceil}$ and $b_{\lceil\frac{n}{2}\rceil}$), that's easy - if the characters in this group are equal, the answer is $0$, otherwise it's $1$. To determine the required number of preprocess moves for a group consising of four characters, we may use the following fact: this group doesn't require preprocess moves iff the characters in this group can be divided into pairs. So if the group contains four equal characters, or two pairs of equal characters, then the answer for this group is $0$. Otherwise we may check that replacing only one character of $a_i$ and $a_{n - i + 1}$ will be enough; if so, then the answer is $1$, otherwise it's $2$. Overall complexity is $O(n)$.
|
[
"implementation"
] | 1,700
|
#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 = INF + 7;
const ld EPS = 1e-9;
const ld PI = acos(-1.0);
int n;
string s, t;
bool read() {
if (!(cin >> n >> s >> t))
return false;
return true;
}
void solve() {
int ans = 0;
forn(i, n / 2) {
map<char, int> a;
a[s[i]]++; a[s[n - i - 1]]++;
a[t[i]]++; a[t[n - i - 1]]++;
if (sz(a) == 4)
ans += 2;
else if (sz(a) == 3)
ans += 1 + (s[i] == s[n - i - 1]);
else if (sz(a) == 2)
ans += a[s[i]] != 2;
}
if (n % 2 == 1 && s[n / 2] != t[n / 2])
ans++;
cout << ans << endl;
}
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;
#ifdef _DEBUG
while (read()) {
#else
if (read()) {
#endif
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
}
|
1006
|
E
|
Military Problem
|
In this problem you will have to help Berland army with organizing their command delivery system.
There are $n$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $a$ is the direct superior of officer $b$, then we also can say that officer $b$ is a direct subordinate of officer $a$.
Officer $x$ is considered to be a subordinate (direct or indirect) of officer $y$ if one of the following conditions holds:
- officer $y$ is the direct superior of officer $x$;
- the direct superior of officer $x$ is a subordinate of officer $y$.
For example, on the picture below the subordinates of the officer $3$ are: $5, 6, 7, 8, 9$.
The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.
Formally, let's represent Berland army as a tree consisting of $n$ vertices, in which vertex $u$ corresponds to officer $u$. The parent of vertex $u$ corresponds to the direct superior of officer $u$. The root (which has index $1$) corresponds to the commander of the army.
Berland War Ministry has ordered you to give answers on $q$ queries, the $i$-th query is given as $(u_i, k_i)$, where $u_i$ is some officer, and $k_i$ is a positive integer.
To process the $i$-th query imagine how a command from $u_i$ spreads to the subordinates of $u_i$. Typical DFS (depth first search) algorithm is used here.
Suppose the current officer is $a$ and he spreads a command. Officer $a$ chooses $b$ — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $a$ chooses the one having minimal index. Officer $a$ gives a command to officer $b$. Afterwards, $b$ uses exactly the same algorithm to spread the command to its subtree. After $b$ finishes spreading the command, officer $a$ chooses the next direct subordinate again (using the same strategy). When officer $a$ cannot choose any direct subordinate who still hasn't received this command, officer $a$ finishes spreading the command.
Let's look at the following example:
If officer $1$ spreads a command, officers receive it in the following order: $[1, 2, 3, 5 ,6, 8, 7, 9, 4]$.
If officer $3$ spreads a command, officers receive it in the following order: $[3, 5, 6, 8, 7, 9]$.
If officer $7$ spreads a command, officers receive it in the following order: $[7, 9]$.
If officer $9$ spreads a command, officers receive it in the following order: $[9]$.
To answer the $i$-th query $(u_i, k_i)$, construct a sequence which describes the order in which officers will receive the command if the $u_i$-th officer spreads it. Return the $k_i$-th element of the constructed list or -1 if there are fewer than $k_i$ elements in it.
You should process queries independently. A query doesn't affect the following queries.
|
Let's form the following vector $p$: we run DFS from the first vertex and push the vertex $v$ to the vector when entering this vertex. Let $tin_v$ be the position of the vertex $v$ in the vector $p$ (the size of the vector $p$ in moment we call DFS from the vertex $v$) and $tout_v$ be the position of the first vertex pushed to the vector after leaving the vertex $v$ (the size of the vector $p$ in moment when we return from DFS from the vertex $v$). Then it is obvious that the subtree of the vertex $v$ lies in half-interval $[tin_v; tout_v)$. After running such DFS we can answer the queries. Let $pos_i = v_i + k_i - 1$ (answering the $i$-th query). If $pos_i$ is greater than or equal to $n$ then answer to the $i$-th query is "-1". We need to check if the vertex $p_{pos_i}$ lies in the subtree of the vertex $v_i$. The vertex $a$ is in the subtree of the vertex $b$ if and only if $[tin_a; tout_a) \subseteq [tin_b; tout_b)$. If the vertex $p_{pos_i}$ is not in the subtree of the vertex $v_i$ then answer is "-1". Otherwise the answer is $p_{pos_i}$. Overall complexity is $O(n + q)$.
|
[
"dfs and similar",
"graphs",
"trees"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
int n, q;
vector<vector<int>> tree;
int current_preorder;
vector<int> preorder, max_preorder;
vector<int> sorted_by_preorder;
void Dfs(int w) {
sorted_by_preorder[current_preorder] = w;
preorder[w] = current_preorder++;
for (int c : tree[w]) {
Dfs(c);
}
max_preorder[w] = current_preorder - 1;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> q;
assert(2 <= n);
assert(1 <= q);
tree.resize(n);
for (int i = 1; i < n; i++) {
int p;
cin >> p;
p--;
assert(0 <= p and p < n);
tree[p].push_back(i);
}
preorder.resize(n);
max_preorder.resize(n);
sorted_by_preorder.resize(n);
current_preorder = 0;
Dfs(0);
for (int i = 0; i < q; i++) {
int u, k;
cin >> u >> k;
u--; k--;
assert(0 <= u and u < n);
assert(0 <= k and k < n);
k += preorder[u];
int answer = -1;
if (k <= max_preorder[u]) {
answer = sorted_by_preorder[k] + 1;
assert(1 <= answer and answer <= n);
}
cout << answer << '\n';
}
return 0;
}
|
1006
|
F
|
Xor-Paths
|
There is a rectangular grid of size $n \times m$. Each cell has a number written on it; the number on the cell ($i, j$) is $a_{i, j}$. Your task is to calculate the number of paths from the upper-left cell ($1, 1$) to the bottom-right cell ($n, m$) meeting the following constraints:
- You can move to the right or to the bottom only. Formally, from the cell ($i, j$) you may move to the cell ($i, j + 1$) or to the cell ($i + 1, j$). The target cell can't be outside of the grid.
- The xor of all the numbers on the path from the cell ($1, 1$) to the cell ($n, m$) must be equal to $k$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal).
Find the number of such paths in the given grid.
|
This is a typical problem on the meet-in-the-middle technique. The number of moves we will made equals $n + m - 2$. So if $n + m$ would be small enough (25 is the upper bound, I think), then we can just run recursive backtracking in $O(2^{n + m - 2})$ or in $O($${n + m - 2}\choose{m - 1}$$\cdot (n + m - 2))$ to iterate over all binary masks of lengths $n + m - 2$ containing exactly $m - 1$ ones and check each path described by such mask ($0$ in this mask is the move to the bottom and $1$ is the move to the right) if its xor is $k$. But it is too slow. So let's split this mask of $n + m - 2$ bits into two parts - the left part will consist of $mid = \lfloor\frac{n + m - 2}{2}\rfloor$ bits and the right part will consist of $n + m - 2 - mid$ bits. Note that each left mask (and each right mask too) uniquely describes the endpoint of the path and the path itself. Let's carry $n \times m$ associative arrays $cnt$ where $cnt_{x, y, c}$ for the endpoint $(x, y)$ and xor $c$ will denote the number of paths which end in the cell $(x, y)$ having xor $c$. Let's run recursive backtracking which will iterate over paths starting from the cell $(1, 1)$ and move to the right or to the bottom and maintain xor of the path. If we made $mid$ moves and we are currently in the cell $(x, y)$ with xor $c$ right now, set $cnt_{x, y, c} := cnt_{x, y, c} + 1$ and return from the function. Otherwise try to move to the bottom or to the right changing xor as needed. Let's run another recursive backtracking which will iterate over paths starting from the cell $(n, m)$ and move to the left or to the top and maintain xor of the path except the last cell. The same, if we made $n + m - 2 - mid$ moves and we are currently in the cell $(x, y)$ with xor $c$ right now, let's add $cnt_{x, y, k ^ c}$ to the answer (obvious, that way we "complement" our xor from the right part of the path with the suitable xor from the left part of the path). Otherwise try to move to the left or to the top changing xor as needed. So, this is the meet-in-the-middle technique (at least the way I code it). Overall complexity is $O(2^{\frac{n + m - 2}{2}} \cdot \frac{n + m - 2}{2})$.
|
[
"bitmasks",
"brute force",
"dp",
"meet-in-the-middle"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int N = 20;
map<long long, int> v[N][N];
int n, m;
int half;
long long k;
long long a[N][N];
long long ans;
void calclf(int x, int y, long long val, int cnt) {
val ^= a[x][y];
if (cnt == half) {
++v[x][y][val];
return;
}
if (x + 1 < n)
calclf(x + 1, y, val, cnt + 1);
if (y + 1 < m)
calclf(x, y + 1, val, cnt + 1);
}
void calcrg(int x, int y, long long val, int cnt) {
if (cnt == n + m - 2 - half) {
if (v[x][y].count(k ^ val))
ans += v[x][y][k ^ val];
return;
}
if (x > 0)
calcrg(x - 1, y, val ^ a[x][y], cnt + 1);
if (y > 0)
calcrg(x, y - 1, val ^ a[x][y], cnt + 1);
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> m >> k;
half = (n + m - 2) / 2;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> a[i][j];
}
}
calclf(0, 0, 0, 0);
calcrg(n - 1, m - 1, 0, 0);
cout << ans << endl;
return 0;
}
|
1007
|
A
|
Reorder the Array
|
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
|
The answer is $n$ minus maximal number of equal elements. Let the maximal number of equals be $x$. Let's proove that $n-x$ is reachable. It's clear that for every permutation of the array the answer will be the same, so let's sort the array in non-decreasing order. Now we should just make a left shift on $x$. After it the $n-x$ right elements will move to a position of a smaller element. Now let's proove that the answer is no more than $n-x$. Let's consider some permutation. It's known that every permutation breaks into cycles. Let's look at two occurences of the same number in the same cycle. Then there is at least one number between them which will move on a postion of a non-smaller element. Even if it the same occurence and even if the length of the cycle is $1$, we can say that for every occurence of this number there is at least one number which moves on a postion of a non-smaller one. So if some number occurs $x$ times, there are at least $x$ bad positions and therefore no more than $n-x$ good positions. To count the number of equals you can, for instance, use std::map.
|
[
"combinatorics",
"data structures",
"math",
"sortings",
"two pointers"
] | 1,300
| null |
1007
|
B
|
Pave the Parallelepiped
|
You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$.
Find the number of different groups of three integers ($a$, $b$, $c$) such that $1\leq a\leq b\leq c$ and parallelepiped $A\times B\times C$ can be paved with parallelepipeds $a\times b\times c$. Note, that all small parallelepipeds \textbf{have to be rotated in the same direction}.
For example, parallelepiped $1\times 5\times 6$ can be divided into parallelepipeds $1\times 3\times 5$, but can not be divided into parallelepipeds $1\times 2\times 3$.
|
First solution. First, for every natural number up to $10^5$ we count its number of divisors in $O(\sqrt{n})$. Also for every unordered set of $3$ masks $(m_1, m_2, m_3)$ of length $3$ we check if there is a way to enumerate them in such a way that $1 \in m_1$, $2 \in m_2$ and $3 \in m_3$. We will call such sets acceptable. Now let's consider two parallelepipeds. For each dimension of the second parallelepiped let's construct a mask of length $3$ which contains the numbers of the dimensions of the first parallelepiped for which the length of the first parallelepiped along this dimension is divisible by the length of the second parallelepiped along the chosen dimension. Now these three masks form an acceptable set iff we can pave the first parallelepiped with the second one. Now for a given parallelepiped let's calculate for every mask of length $3$ the number of possible lengths of the second parallelepiped which would produce this mask. We can do this by taking the GCD of the lengths of the first parallelepiped along the dimensions whose numbers are in the mask, and subtracting from it the calculated numbers for every submask. Now let's iterate over acceptable sets of masks. For each different mask from the set which is included into the set $k$ times we need to calculate the number of ways to take $k$ unordered lengths which produce this mask, and multiply these numbers. The sum of these numbers is the answers to the query. So for every query we need $O \left( 2^{m^2} \right)$ operations, where $m = 3$ is the number of dimensions of the parallelepiped. Second solution. First, for every natural number up to $10^5$ we count its number of divisors in $O(\sqrt{n})$. Then for every query for every subset of numbers in it we keep their GCD and the number of its divisors. So for every subset of this three numbers we know the number of their common divisors. Let's look at the parallelepiped $(a, b, c)$. The way we orient it with respect to the large parallelepiped is determined by a permutation of size $3$ - that is, which dimension would correspond to every dimension in the large one. Using the inclusion-exclusion principle on this permutations we can count how many there are such parallelepipeds (considering the orientation) that we can orient some way to then pave the large parallelepiped with it. Namely, we fix the set of permutations for which our parallelepiped shall satisfy. Then for every side of the small parallelepiped we know which sides of the large one it shall divide. To find the number of such sides of the small one we shall take the number of common divisors of the corresponding sides of the large one. Now to find the number of such small parallelepipeds we must multiply the three resultant numbers. In such way every satisfying this criteria parallelepiped (not considering the orientation) with three different side lengths was counted $6$ times, with two different lengths was counted $3$ times, with one different length was counted $1$ time. But it won't be difficult for us to use the same approach in counting such parallelepipeds, but with no less than two same side lengths: let's say the first and the second. To do this when we fix which permutations this parallelepiped shall satisfy we should just add the condition that its first and second side lengths must be equal, this means they both must divide both of the sets corresponding to them, so instead of this two sets we must take their union. Let's add the resultant number multiplied by three to the answer. Now every parallelepiped with three different side length is still counted $6$ times, with two different is now counted also $6$ times, and with one different is counted $4$ times. The number of satisfying parallelepipeds with equal sides is just the number of common divisors of all the sides of the large parallelepiped. Let's add it multiplied by two, and now every needed parallelepiped is counted $6$ times. We divide this number by $6$ and get the answer. So for every query we need $O \left( p(m) \cdot 2^{m!} \cdot m \right)$ operations, where $p(m)$ is the number of partitions of $m$, and $m = 3$ is the number of dimensions of the parallelepiped.
|
[
"bitmasks",
"brute force",
"combinatorics",
"math",
"number theory"
] | 2,400
| null |
1007
|
C
|
Guess two numbers
|
\textbf{This is an interactive problem.}
Vasya and Vitya play a game. Vasya thought of two integers $a$ and $b$ from $1$ to $n$ and Vitya tries to guess them. Each round he tells Vasya two numbers $x$ and $y$ from $1$ to $n$. If both $x=a$ and $y=b$ then Vitya wins. Else Vasya must say one of the three phrases:
- $x$ is less than $a$;
- $y$ is less than $b$;
- $x$ is greater than $a$ or $y$ is greater than $b$.
Vasya can't lie, but if multiple phrases are true, he may choose any of them. For example, if Vasya thought of numbers $2$ and $4$, then he answers with the phrase $3$ to a query $(3, 4)$, and he can answer with the phrase $1$ or phrase $3$ to a query $(1, 5)$.
Help Vitya win in no more than $600$ rounds.
|
First solution: Let's keep the set of possible answers as a union of three rectangles forming an angle: $A = \left[ x_l, x_m \right) \times \left[ y_l, y_m \right)$, $B = \left[ x_l, x_m \right) \times \left[ y_m, y_r \right)$ and $C = \left[ x_m, x_r \right) \times \left[ y_l, y_m \right)$, where $x_l < x_m \leq x_r$ and $y_l < y_m \leq y_r$. Let $S_A$, $S_B$ and $S_C$ be their areas. We will denote such state as $(x_l, x_m, x_r, y_l, y_m, y_r)$. The initial state is $(0, n + 1, n + 1, 0, n + 1, n + 1)$. Now there are three cases. $S_B \leq S_A + S_C$ and $S_B \leq S_A + S_B$, then we will make a query $\left( \left\lfloor \frac{x_l + x_m}{2} \right\rfloor, \left\lfloor \frac{y_l + y_m}{2} \right\rfloor \right)$. If $S_B > S_A + S_C$, we will make a query $\left( \left\lfloor \frac{x_l + x_m}{2} \right\rfloor, y_m \right)$. Finally, if $S_C > S_A + S_B$, we will make a query $\left( x_m, \left\lfloor \frac{y_l + y_m}{2} \right\rfloor \right)$. In case of every response to every query, the new set of possible answers will also form an angle. Now we want to prove that the area of the angle decreases at least by a quarter every two requests. In case (1) if the answer is $1$, then we move to a state $\left( \left\lfloor \frac{x_l + x_m}{2} \right\rfloor + 1, x_m, x_r, y_l, y_m, y_r \right)$. We cut off at least half of $A$ and at least half of $B$. But $\frac{S_A}{2} + \frac{S_B}{2} = \frac{S_A + S_B}{4} + \frac{S_A + S_B}{4} \geq \frac{S_A + S_B}{4} + \frac{S_C}{4} = \frac{S_A + S_B + S_C}{4}$. I.e. We have cut off at least a quarter already within just one request. If the answer is $2$, the situation is similar. Finally, if the answer is $3$, then we move to a state $\left( x_l, \left\lfloor \frac{x_l + x_m}{2} \right\rfloor, x_r, y_l, \left\lfloor \frac{y_l + y_m}{2} \right\rfloor, y_r \right)$. We cut off at least quarter of $A$, at least half of $B$ and at least half of $C$. But $\frac{S_A}{4} + \frac{S_B}{2} + \frac{S_C}{2} \geq \frac{S_A}{4} + \frac{S_B}{4} + \frac{S_C}{4} = \frac{S_A + S_B + S_C}{4}$. We also have cut off at least a quarter within just one request. Thus in case (1) we cut off at least a quarter within one request. In case (2) if the answer is $1$, then we move to a state $\left( \left\lfloor \frac{x_l + x_m}{2} \right\rfloor + 1, x_m, x_r, y_l, y_m, y_r \right)$. We cut off at least half of $A$ and at least half of $B$. But $\frac{S_A}{2} + \frac{S_B}{2} \geq \frac{S_B}{2} \geq \frac{S_B}{4} + \frac{S_B}{4} \geq \frac{S_B}{4} + \frac{S_A + S_C}{4} = \frac{S_A + S_B + S_C}{4}$. We have cut off at least a quarter within just one request. If the answer is $2$, then we move to a state $(x_l, x_r, x_r, y_m + 1, y_r, y_r)$. But then if will be case (1), thus we will cut off at least a quarter with the next request. Finally, if the answer is $3$, then we move to a state $\left( x_l, \left\lfloor \frac{x_l + x_m}{2} \right\rfloor, x_r, y_l, y_m, y_r \right)$. We cut off at at least half of $B$. But $\frac{S_B}{2} \geq \frac{S_B}{4} + \frac{S_B}{4} \geq \frac{S_B}{4} + \frac{S_A + S_C}{4} = \frac{S_A + S_B + S_C}{4}$. We also have cut off at least a quarter within just one request. Case (3) is similar to case (2). Thus the maximal number of requests will be no more than $1 + 2 * \log_{4/3} \left( \left( 10^{18} \right)^2 \right) \approx 577$. Second solution: Let's keep the set of possible answers in form of a ladder $A$. Then lets find minimal $X$ such that $S \left( A \cap \{x \leq X\} \right) \geq \frac{S(A)}{3}$. And lets find minimal $Y$ such that $S \left( A \cap \{y \leq Y\} \right) \geq \frac{S(A)}{3}$. Then Thus the maximal number of requests will be no more than $1 + \log_{3/2} \left( \left( 10^{18} \right)^2 \right) \approx 205$.
|
[
"binary search",
"interactive"
] | 3,000
| null |
1007
|
D
|
Ants
|
There is a tree with $n$ vertices. There are also $m$ ants living on it. Each ant has its own color. The $i$-th ant has two favorite pairs of vertices: ($a_i, b_i$) and ($c_i, d_i$). You need to tell if it is possible to paint the edges of the tree in $m$ colors so that every ant will be able to walk between vertices from one of its favorite pairs using only edges of his color; if it is possible, you need to print which pair every ant should use.
|
Slow solution. We need to choose one of two paths for each ant so that they will not contain a common edge. Let's make a 2-SAT, and for each ant, we will create two contrary vertices: one will denote that we take the first path, and another will denote that we take the second path. Then for every two paths which share an edge, we add a condition that they can't be taken together. Now we just need to check that the 2-SAT has a solution. The complexity is $O(n m^2)$. First solution. Let's build a binary tree with $m$ leaves for each edge. Each vertex of the tree will be associated with some vertex of the 2-SAT. The vertex of the tree which covers leaves from $l$ to $r$ will be associated with a vertex of the 2-SAT which says if the edge should be painted with a color from $l$ to $r$. To build a vertex which is associated with a leaf we just need to add for every path of the ant which covers the current edge a condition which tells that if we take this path, then this vertex is true. And for every non-leaf vertex of the tree we need to add three conditions. First and second: if any of the vertices associated with the two sons is true, then the vertex associated with the current vertex is also true ($l\rightarrow v$, $r\rightarrow v$). And third: both vertices associated with the two sons can't be true ($l\rightarrow !r$). The trees will be persistent, which means that if the vertex we want already exists, we will reuse it. Now we will build such trees recursively. First for the children, and then for the current edge. To build a tree for a new edge we first take an empty tree, then for each child, we recursively merge its tree with the current. If during the merge one of the vertices is empty, we return the second vertex. Then we add the paths which end in the current vertex. You have to be careful not to add the edges which will not be present in the final tree. For example, you can first build a tree, and then go through the new vertices one more time and add the edges. Then as in the previous solution, we check if there is a solution of this 2-SAT. It can be shown that for a vertex of the binary tree which covers $k$ leaves there will be created no more than $8k$ instances of this vertex, because there are at most $4k$ ends of the paths connected with these leaves and at most $8k - 1$ vertices which are the LCA of some set of these vertices. Now if we summarize it over all the vertices of the binary tree, we get approximately $8 m \log(m)$. So the total complexity is $O(m \log(m))$ Second solution. Let $L = 64$ be the number of bits in a machine word. Let's calculate a matrix $2m \times 2m$ of ones and zeros, where cell $(i, j)$ is filled with $1$ iff the paths $i$ and $j$ have a common edge. We will store this matrix as an array of bitsets. Let's run a DFS which for every edge will return a set of paths that cover it. We will store such sets in a map from number of block to a bitmask of length $L$. We recursively calculate the sets for the children. Also for every path which starts in the vertex, we make a set containing only this path. Then if some sets share the same path, we remove it from both. Then we merge them by always adding the smaller map to the larger. While doing so we iterate over the elements of the smaller map and over the blocks of the larger map and add a block of edges to the matrix. For now, it is enough to add each edge to the matrix only in one direction. It can be shown that it works in $O \left( m \log^2(m) + m^2 \cdot \frac{\log(L)}{L} \right)$. Now we want to transpose the matrix and add it to itself to make it complete. To do it we divide it into blocks $L \times L$, and transpose them one by one, then swap the blocks. Here is how we transpose a block. Assume $L = 2^K$. We will make $K$ iterations. On the $i-th$ iteration we will divide the block into subblocks $2^i \times 2^i$ and in each block, we will swap the top right quarter and the bottom left quarter. Each iteration can be performed in $O(L)$. We can prove by induction that after $i$ iterations each subblock $2^i \times 2^i$ will be transposed. This step works in $O \left( m^2 \cdot \frac{\log(L)}{L} \right)$. It is easy to get a bitset of straight edges and a bitset of reversed edges of the 2-SAT for every vertex using this matrix. Now if we store the visited vertices in a bitset, we can implement the 2-SAT algorithm in $O \left( \frac{m^2}{L} \right)$. The total complexity is $O \left( m \log^2(m) + m^2 \cdot \frac{\log(L)}{L} \right)$.
|
[
"2-sat",
"data structures",
"trees"
] | 3,200
| null |
1007
|
E
|
Mini Metro
|
In a simplified version of a "Mini Metro" game, there is only one subway line, and all the trains go in the same direction. There are $n$ stations on the line, $a_i$ people are waiting for the train at the $i$-th station at the beginning of the game. The game starts at the beginning of the $0$-th hour. At the end of each hour (couple minutes before the end of the hour), $b_i$ people instantly arrive to the $i$-th station. If at some moment, the number of people at the $i$-th station is larger than $c_i$, you lose.
A player has several trains which he can appoint to some hours. The capacity of each train is $k$ passengers. In the middle of the appointed hour, the train goes from the $1$-st to the $n$-th station, taking as many people at each station as it can accommodate. A train can not take people from the $i$-th station if there are people at the $i-1$-th station.
If multiple trains are appointed to the same hour, their capacities are being added up and they are moving together.
The player wants to stay in the game for $t$ hours. Determine the minimum number of trains he will need for it.
|
Let's enumerate the hours and the stations starting from zero. Let's add a station to the end with an infinite number of people and infinite capacity. It is obvious that it will not affect the answer. Also, every train now will be filled completely. Let's calculate $sa[p]$, $sb[p]$ and $sc[p]$: the sum of $a[i]$, $b[i]$ and $c[i]$ over the first $p$ stations respectively. Let $d[p][s][z]$ ($0 \leq p \leq n + 1$, $0 \leq s \leq t$, $0 \leq z \leq 1$) be the minimal number of trains (or $\infty$, if impossible) needed to hold on for $s$ hours, if there were only the first $p$ stations, so that every train we used would be filled completely. Herewith the initial number of people on the $i$-th station equals $z \cdot a[i]$. Let $g[p][s][z]$ ($0 \leq p \leq n + 1$, $0 \leq s \leq t$, $0 \leq z \leq 1$)be the minimal number of trains (or $\infty$, if impossible) needed to hold on for $s$ with a half hours (so that we can send some trains at the end), if there were only the first $p$ stations, so that every train we used would be filled completely and every station except for the last would contain in the end $0$ people. Herewith the initial number of people on the $i$-th station equals $z \cdot a[i]$. Then the answer for the problem is $d[n + 1][t][1]$. Lets calculate $d$ and $g$ using dynamic programming. In order to calculate $d[p][s][z]$ and $g[p][s][z]$ lets consider the last hour from $0$ to $s - 1$ in which some train will take a person from the last station. Notice that in case of $g[p][s][z]$ we do not consider the $s$-th hour though there could be such trains during this hour. First case: There were no such trains. In this case we just need to check that the last station won't overflow and that $d[p - 1][s][z] \neq \infty$. Then we can make transitions: (*) In case of $g[p][s][z]$ it is obvious that such number will be needed in order to set to zero all the stations except for the last one, and this number can be achieved since we can hold on for $s$ hours without taking a person from the last station. Second case: denote the number of this hour by $r$. Then the plan is as follows: First, we need to hold on for $r$ with a half hours and do so that on every station except for the last there will be $0$ people. Then we possibly send some more trains during the $r$-th hour. Then we need to hold on for $s - r$ without the first half hours without sending a train which will take a person from the last station. Then in case of $g[p][s][z]$ we send some more trains during the $s$-th hour. On the phase (2) we cat calculate the initial number of people on the last station: $m = z \cdot sa[p] + r \cdot sb[p] - k \cdot g[p][r][z]$, and then calculate the minimal number of trains we need to send so that the last station doesn't overflow by the end of the$(s-1)$-th hour: $x = \left\lceil \frac{\max(m + (s - r) \cdot b[p - 1] - c[p - 1], 0)}{k} \right\rceil$. If $x \cdot k > m$, then the transition is impossible, else it is benificial to send $x$ trains. During the phase (3) it is beneficial to send as few trains as possible, be'cause in case of $d[p][s][z]$ it is the last phase, and in case of $g[p][s][z]$ we can always send additional trains during the phase (4) and nothing will change. Notice in the beginning of phase (3) the first $p - 1$ are empty and also we can assume we are starting from the beginning of an hour and we need to hold on for $s - r$ hours. Thus we need to send $d[p - 1][s - r][0]$ trains. If $d[p - 1][s - r][0] = \infty$, then the transition is impossible. Finally, on the phase (4) we need to send as few trains as possible so that all the stations except for the last one would contain $0$ people. As in (*) we can see that on phases (3) and (4) we need to send in total at least val = $\left\lceil \frac{(s - r) \cdot sb[p - 1]}{k} \right\rceil$ trains, and we can achieve this number. We can make transitions: Solution time is $O(n t^2)$.
|
[
"dp"
] | 3,400
| null |
1008
|
A
|
Romaji
|
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
|
You need to check if after every letter except one of for these "aouien", there goes one of these "aouie". Do not forget to check the last letter.
|
[
"implementation",
"strings"
] | 900
| null |
1008
|
B
|
Turn the Rectangles
|
There are $n$ rectangles in a row. You can either turn each rectangle by $90$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. \textbf{You can not change the order of the rectangles.}
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
|
You need to iterate over the rectangles from left to right and turn each rectangle in such a way that its height is as big as possible but not greater than the height of the previous rectangle (if it's not the first one). If on some iteration there is no such way to place the rectangle, the answer is "NO".
|
[
"greedy",
"sortings"
] | 1,000
| null |
1009
|
A
|
Game Shopping
|
Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.
Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.
Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.
When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.
Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet \textbf{(this bill still remains the first one)} and proceeds to the next game.
For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.
Your task is to get the number of games Maxim will buy.
|
Let's keep the variable $pos$ which will represent the number of games Maxim buy. Initially $pos = 0$. Assume that arrays $a$ and $c$ are 0-indexed. Then let's iterate over all $i = 0 \dots n - 1$ and if $pos < m$ and $a[pos] \ge c[i]$ make $pos := pos + 1$. So $pos$ will be the answer after this cycle.
|
[
"implementation"
] | 800
|
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
pos = 0
for i in a:
pos += (pos < len(b) and b[pos] >= i)
print(pos)
|
1009
|
B
|
Minimum Ternary String
|
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "{\underline{01}0210}" $\rightarrow$ "{\underline{10}0210}";
- "{0\underline{10}210}" $\rightarrow$ "{0\underline{01}210}";
- "{010\underline{21}0}" $\rightarrow$ "{010\underline{12}0}";
- "{0102\underline{10}}" $\rightarrow$ "{0102\underline{01}}".
Note than you cannot swap "{\underline{02}}" $\rightarrow$ "{\underline{20}}" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
|
Let's notice that described swaps allows us to place any '1' character to any position of the string $s$ (relative order of '0' and '2' obviously cannot be changed). Let's remove all '1' characters from the string $s$ (and keep their count in some variable). Now more profitable move is to place all the '{1}' characters right before the first '2' character of $s$ (and if there is no '2' character in $s$, then place they after the end of the string).
|
[
"greedy",
"implementation"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
string s;
cin >> s;
string ans;
int cnt = 0;
for (auto c : s) {
if (c == '1') ++cnt;
else ans += c;
}
int n = ans.size();
int pos = -1;
while (pos + 1 < n && ans[pos + 1] == '0') ++pos;
ans.insert(pos + 1, string(cnt, '1'));
cout << ans << endl;
return 0;
}
|
1009
|
C
|
Annoying Present
|
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row!
And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.
Bob has chosen $m$ changes of the following form. For some integer numbers $x$ and $d$, he chooses an arbitrary position $i$ ($1 \le i \le n$) and for every $j \in [1, n]$ adds $x + d \cdot dist(i, j)$ to the value of the $j$-th cell. $dist(i, j)$ is the distance between positions $i$ and $j$ (i.e. $dist(i, j) = |i - j|$, where $|x|$ is an absolute value of $x$).
For example, if Alice currently has an array $[2, 1, 2, 2]$ and Bob chooses position $3$ for $x = -1$ and $d = 2$ then the array will become $[2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1]$ = $[5, 2, 1, 3]$. Note that Bob can't choose position $i$ outside of the array (that is, smaller than $1$ or greater than $n$).
Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.
What is the maximum arithmetic mean value Bob can achieve?
|
Judging by constraints, you can guess that the greedy approach is the right one. Firstly, let's transition from maximizing the arithmetic mean to the sum, it's the same thing generally. Secondly, notice that each $x$ is being added to each element regardless of the chosen position. Finally, take a look at a function $f(d, i)$ - total sum obtained by applying change with $d$ to position $i$ and notice that it is non-strictly convex. Its maximum or minimum values can always be found in one of these positions: $\frac{n}{2}$ (method of rounding doesn't matter), $1$ and $n$. Thus, the solution will look like this: for positive $d$ you apply the change to position $1$ and for non-positive $d$ - to position $\lfloor \frac{n}{2} \rfloor$. The impact of the change can be calculated with the formula of the sum of arithmetic progression. Also, you should either do all of your calculations in long double (10-byte type) or maintain sum in long long (you can estimate it with $m \cdot n^2 \cdot MAXN \le 10^{18}$, so it fits) and divide it by $n$ in the end (then double will work). Overall complexity: $O(m)$.
|
[
"greedy",
"math"
] | 1,700
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
typedef long long li;
int main() {
int n, m;
scanf("%d%d", &n, &m);
li neg = ((n - 1) / 2) * li((n - 1) / 2 + 1);
if (n % 2 == 0) neg += n / 2;
li pos = n * li(n - 1) / 2;
li ans = 0;
forn(i, m){
int x, d;
scanf("%d%d", &x, &d);
ans += x * li(n);
if (d < 0)
ans += neg * d;
else
ans += pos * d;
}
printf("%.15f\n", double(ans) / n);
return 0;
}
|
1009
|
D
|
Relatively Prime Graph
|
Let's call an undirected graph $G = (V, E)$ relatively prime if and only if for each edge $(v, u) \in E$ $GCD(v, u) = 1$ (the greatest common divisor of $v$ and $u$ is $1$). If there is no edge between some pair of vertices $v$ and $u$ then the value of $GCD(v, u)$ doesn't matter. The vertices are numbered from $1$ to $|V|$.
Construct a relatively prime graph with $n$ vertices and $m$ edges such that it is connected and it contains neither self-loops nor multiple edges.
If there exists no valid graph with the given number of vertices and edges then output "Impossible".
If there are multiple answers then print any of them.
|
Even though $n$ is up to $10^5$, straightforward $O(n^2 \log n)$ solution will work. You iterate for $i$ from $1$ to $n$ in the outer loop, from $i + 1$ to $n$ in the inner loop and check $GCD$ each time. When $m$ edges are found, you break from both loops. Here is why this work fast enough. The total number of pairs $(x, y)$ with $1 \le x, y \le n, gcd(x, y) = 1$ is $\varphi(1) + \varphi(2) + \dots + \varphi(n)$, where $\varphi$ is Euler's totient function. We also want to substract a single pair $(1, 1)$. And this sum grows so fast that after about $600$ iteratons $\varphi(1) + \varphi(2) + \dots + \varphi(600)$ will be greater than $100000$ for any $n$. The only thing left is to check that $m$ is big enough to build a connected graph ($m \ge n - 1$) and small enough to fit all possible edges for given $n$ (the formula above). Overall complexity: $O(n^2 \log n)$.
|
[
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"math"
] | 1,700
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 100000;
pair<int, int> ans[N];
int main() {
int n, m;
scanf("%d%d", &n, &m);
if (m < n - 1) {
puts("Impossible");
return 0;
}
int cur = 0;
forn(i, n) for (int j = i + 1; j < n; ++j){
if (cur == m)
break;
if (__gcd(i + 1, j + 1) == 1)
ans[cur++] = make_pair(j, i);
}
if (cur != m){
puts("Impossible");
return 0;
}
puts("Possible");
forn(i, m)
printf("%d %d\n", ans[i].first + 1, ans[i].second + 1);
return 0;
}
|
1009
|
E
|
Intercity Travelling
|
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.
The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is $n$ km. Let's say that Moscow is situated at the point with coordinate $0$ km, and Saratov — at coordinate $n$ km.
Driving for a long time may be really difficult. Formally, if Leha has already covered $i$ kilometers since he stopped to have a rest, he considers the difficulty of covering $(i + 1)$-th kilometer as $a_{i + 1}$. It is guaranteed that for every $i \in [1, n - 1]$ $a_i \le a_{i + 1}$. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.
Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from $1$ to $n - 1$ may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty $a_1$, the kilometer after it — difficulty $a_2$, and so on.
For example, if $n = 5$ and there is a rest site in coordinate $2$, the difficulty of journey will be $2a_1 + 2a_2 + a_3$: the first kilometer will have difficulty $a_1$, the second one — $a_2$, then Leha will have a rest, and the third kilometer will have difficulty $a_1$, the fourth — $a_2$, and the last one — $a_3$. Another example: if $n = 7$ and there are rest sites in coordinates $1$ and $5$, the difficulty of Leha's journey is $3a_1 + 2a_2 + a_3 + a_4$.
Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are $2^{n - 1}$ different distributions of rest sites (two distributions are different if there exists some point $x$ such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate $p$ — the expected value of difficulty of his journey.
Obviously, $p \cdot 2^{n - 1}$ is an integer number. You have to calculate it modulo $998244353$.
|
Let's consider each kilometer of the journey separatedly and calculate the expected value of its difficulty (and then use linearity of expectation to obtain the answer). The difficulty of each kilometer depends on the rest site right before it (or, if there were no rest sites, on the distance from Moscow to this kilometer). So when considering the difficulty of $i$-th kilometer (one-indexed), we may obtain a formula: $diff_i = \frac{a_1}{2} + \frac{a_2}{2^2} + \dots + \frac{a_{i - 1}}{2^{i - 1}} + \frac{a_i}{2^{i - 1}}$. The denominator of the last summand is $2^{i - 1}$ because it represents the situation where the last rest was in Moscow, and its probability is exactly $\frac{1}{2^{i - 1}}$. We can actually rewrite this as follows: $diff_1 = a_1$, $diff_{i + 1} = diff_i - \frac{a_i}{2^i} + \frac{a_{i + 1}}{2^i}$, thus calculating all that we need in linear time.
|
[
"combinatorics",
"math",
"probabilities"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int add(int x, int y)
{
x += y;
while(x >= MOD)
x -= MOD;
while(x < 0)
x += MOD;
return x;
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int main()
{
int n;
scanf("%d", &n);
vector<int> a(n);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
int ans = 0;
vector<int> pw2(1, 1);
while(pw2.size() < n)
pw2.push_back(mul(pw2.back(), 2));
int cur = mul(pw2[n - 1], a[0]);
for(int i = 0; i < n; i++)
{
ans = add(ans, cur);
if(i < n - 1)
{
cur = add(cur, -mul(pw2[n - 2 - i], a[i]));
cur = add(cur, mul(pw2[n - 2 - i], a[i + 1]));
}
}
printf("%d\n", ans);
}
|
1009
|
F
|
Dominant Indices
|
You are given a rooted undirected tree consisting of $n$ vertices. Vertex $1$ is the root.
Let's denote a depth array of vertex $x$ as an infinite sequence $[d_{x, 0}, d_{x, 1}, d_{x, 2}, \dots]$, where $d_{x, i}$ is the number of vertices $y$ such that both conditions hold:
- $x$ is an ancestor of $y$;
- the simple path from $x$ to $y$ traverses exactly $i$ edges.
The dominant index of a depth array of vertex $x$ (or, shortly, the dominant index of vertex $x$) is an index $j$ such that:
- for every $k < j$, $d_{x, k} < d_{x, j}$;
- for every $k > j$, $d_{x, k} \le d_{x, j}$.
For every vertex in the tree calculate its dominant index.
|
In this problem we can use small-to-large merging trick (also known as DSU on tree): when building a depth array for a vertex, we firstly build depth arrays recursively for its children, then pull them upwards and merge them with small-to-large technique. In different blogs on this technique it was mentioned that this will require $O(n \log n)$ operations with structures we use to maintain depth arrays overall. However, in this problem we may prove a better estimate: it will require $O(n)$ operations. That's because the size of depth array (if considering only non-zero elements) for a vertex is equal to the height of its subtree, not to the number of vertices in it. To prove that the number of operations is $O(n)$, one can use the intuitive fact that when we merge two depth arrays, all elements of the smaller array are "destroyed" in the process, so if the size of smaller array is $k$, then we require $O(k)$ operations to "destroy" $k$ elements. The main problem is that we sometimes need to "pull" our depth arrays upwards, thus inserting a $1$ to the beginning of the array. Standard arrays don't support this operation, so we need to either use something like std::map (and the complexity will be $O(n \log n)$), or keep the depth arrays in reversed order and handle them using std::vector (and then complexity will be $O(n)$).
|
[
"data structures",
"dsu",
"trees"
] | 2,300
|
#define _CRT_SECURE_NO_WARNINGS
#include <vector>
#include <cstdio>
#include <iostream>
#include <algorithm>
// RJ? No, thanks
using namespace std;
const int N = 1000043;
struct state
{
vector<int>* a;
int cur_max;
int sz()
{
return a->size();
}
void add(int i, int val)
{
(*a)[i] += val;
if(make_pair((*a)[i], i) > make_pair((*a)[cur_max], cur_max))
cur_max = i;
}
};
state pull(state z)
{
if(z.sz() == 0)
{
state c;
c.a = new vector<int>(1, 1);
c.cur_max = 0;
return c;
}
else
{
state c;
c.a = z.a;
c.cur_max = z.cur_max;
c.a->push_back(0);
c.add(c.sz() - 1, 1);
return c;
}
}
state merge(state a, state b)
{
if(a.sz() < b.sz())
swap(a, b);
state c;
c.a = a.a;
c.cur_max = a.cur_max;
int as = c.sz();
int bs = b.sz();
for(int i = 0; i < bs; i++)
a.add(as - i - 1, (*(b.a))[bs - i - 1]);
return a;
}
state s[N];
int ans[N];
vector<int> g[N];
void dfs(int x, int p = -1)
{
s[x].a = new vector<int>(0);
s[x].cur_max = 0;
for(auto y : g[x])
if(y != p)
{
dfs(y, x);
s[x] = merge(s[x], s[y]);
}
s[x] = pull(s[x]);
ans[x] = s[x].sz() - s[x].cur_max - 1;
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n - 1; i++)
{
int x, y;
scanf("%d %d", &x, &y);
--x;
--y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(0);
for(int i = 0; i < n; i++)
printf("%d\n", ans[i]);
return 0;
}
|
1009
|
G
|
Allowed Letters
|
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup!
Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent.
In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there.
Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?)
More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible).
What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters?
If Polycarp can't produce any valid name then print "Impossible".
|
The idea of solution is the following: we build the answer letter-by-letter; when choosing a character for some position, we try all possible characters and check that we can build the suffix after placing this character. But we need to somehow do this checking fast. As in many previous Educational Rounds, in this round some participants' solutions were much easier to write and understand than our own model solution. Authors' solution (uses network flows): Let's build a flow network, where we have $6$ vertices representing the characters of the string and $2^6$ vertices representing the masks of characters. Add directed edges from the source to every node representing some character with capacity equal to the number of such characters in the original string; also add directed edges from every node representing some character to all vertices representing masks where this character is contained (with infinite capacity); and finally, add a directed edge from every "mask"-node to the sink with capacity equal to the number of positions where this mask of characters is allowed. If we find maximum flow in this network, we can check that the answer exists, and if it exists, build some answer. Now let's try to build optimal answer by somehow rebuilding the flow in the network. Suppose we are trying to place a character $x$ to position containing mask $m$. To check whether we can do it, we have to try rebuilding the flow in such a way that the edge from vertex corresponding to $x$ to vertex corresponding to $m$ has non-zero flow. If it is already non-zero, then we are done; otherwise we may cancel a unit of flow going through an edge from source to $x$-vertex, then cancel a unit of flow going through an edge from $m$-vertex to sink, decrease the capacity of these two edges by $1$ and check that there exists an augmenting path. If it exists, then returning the capacities back and adding one unit of flow through the path $source \rightarrow x \rightarrow m \rightarrow sink$ actually builds some answer where some character $x$ is placed on some position with mask $m$, so we may place it there; otherwise it's impossible. When we finally decided to place $x$ on position $m$, we have to decrease the flow through $source \rightarrow x \rightarrow m \rightarrow sink$ and the capacities of edges $source \rightarrow x$ and $m \rightarrow sink$. All this algorithm runs in $O(n \cdot 2^A \cdot A^2)$, where $A$ is the size of the alphabet. Participants' solution (uses Hall's theorem): Hall's theorem allows us to check that we may build the suffix of the answer much easier. Each time we try to place some character, we need to iterate on all possible subsets of characters we still need to place and check that the number of positions that are suitable for at least one character in a subset is not less than the size of subset (just like in regular Hall's theorem). The key fact here is that if we have, for example, $3$ characters a yet to place, then we don't need to check any subset containing exactly $1$ or $2$ characters a, since the number of "suitable" positions for this subset won't become larger if we add all remaining characters a to a subset. So the subsets we have to consider are limited by the masks of possible characters, and there will be only $64$ of them.
|
[
"bitmasks",
"flows",
"graph matchings",
"graphs",
"greedy"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
#define sz(a) ((int)(a).size())
struct edge
{
int y;
int c;
int f;
edge() {};
edge(int y, int c, int f) : y(y), c(c), f(f) {};
};
const int N = 100;
vector<edge> e;
vector<int> g[N];
int edge_num[N][N];
int char_vertex[6];
int mask_vertex[N];
int used[N];
int cc = 0;
int s, t;
void add_edge(int x, int y, int c)
{
edge_num[x][y] = sz(e);
g[x].push_back(sz(e));
e.push_back(edge(y, c, 0));
edge_num[y][x] = sz(e);
g[y].push_back(sz(e));
e.push_back(edge(x, 0, 0));
}
int rem(int num)
{
return e[num].c - e[num].f;
}
int dfs(int x, int mx)
{
if(x == t) return mx;
if(used[x] == cc) return 0;
used[x] = cc;
for(auto num : g[x])
{
if(rem(num))
{
int pushed = dfs(e[num].y, min(mx, rem(num)));
if(pushed)
{
e[num].f += pushed;
e[num ^ 1].f -= pushed;
return pushed;
}
}
}
return 0;
}
bool check(int ch, int mask)
{
if((mask & (1 << ch)) == 0)
return false;
int cv = char_vertex[ch];
int mv = mask_vertex[mask];
int e1 = edge_num[s][cv];
int e2 = edge_num[mv][t];
if(e[e1].f == 0 || e[e2].f == 0)
return false;
e[e1].f--;
e[e1 ^ 1].f++;
vector<int> affected_edges;
affected_edges.push_back(e1);
for(auto x : g[cv])
{
if((x & 1) == 0 && e[x].f > 0)
{
affected_edges.push_back(x);
e[x].f--;
e[x ^ 1].f++;
int y = e[x].y;
for(auto x2 : g[y])
{
if((x2 & 1) == 0)
{
affected_edges.push_back(x2);
e[x2].f--;
e[x2 ^ 1].f++;
break;
}
}
break;
}
}
if(e[e2].f < e[e2].c)
{
e[e1].c--;
e[e2].c--;
return true;
}
affected_edges.push_back(e2);
e[e2].f--;
e[e2 ^ 1].f++;
for(auto x : g[mv])
{
if((x & 1) == 1 && e[x].f < 0)
{
affected_edges.push_back(x ^ 1);
e[x].f++;
e[x ^ 1].f--;
int y = e[x].y;
for(auto x2 : g[y])
{
if((x2 & 1) == 1)
{
affected_edges.push_back(x2 ^ 1);
e[x2].f++;
e[x2 ^ 1].f--;
break;
}
}
break;
}
}
cc++;
e[e1].c--;
e[e2].c--;
if(dfs(s, 1))
return true;
else
{
e[e1].c++;
e[e2].c++;
for(auto x : affected_edges)
{
e[x].f++;
e[x ^ 1].f--;
}
return false;
}
}
char buf[100043];
string allowed[100043];
int allowed_mask[100043];
int main()
{
s = 70;
t = 71;
scanf("%s", buf);
string z = buf;
int n = sz(z);
int m;
scanf("%d", &m);
for(int i = 0; i < n; i++)
{
allowed[i] = "abcdef";
allowed_mask[i] = 63;
}
for(int i = 0; i < m; i++)
{
int idx;
scanf("%d", &idx);
--idx;
scanf("%s", buf);
allowed[idx] = buf;
allowed_mask[idx] = 0;
for(auto x : allowed[idx])
{
allowed_mask[idx] |= (1 << (x - 'a'));
}
}
for(int i = 0; i < 6; i++)
char_vertex[i] = i;
for(int i = 0; i < (1 << 6); i++)
mask_vertex[i] = i + 6;
for(int i = 0; i < (1 << 6); i++)
for(int j = 0; j < 6; j++)
if(i & (1 << j))
add_edge(char_vertex[j], mask_vertex[i], 100000);
for(int i = 0; i < 6; i++)
{
int cnt = 0;
for(int j = 0; j < n; j++)
if(z[j] == 'a' + i)
cnt++;
add_edge(s, char_vertex[i], cnt);
}
for(int i = 0; i < (1 << 6); i++)
{
int cnt = 0;
for(int j = 0; j < n; j++)
if(allowed_mask[j] == i)
cnt++;
add_edge(mask_vertex[i], t, cnt);
}
int flow = 0;
while(true)
{
cc++;
int p = dfs(s, 100000);
if(p)
flow += p;
else
break;
}
if(flow != n)
{
puts("Impossible");
return 0;
}
for(int i = 0; i < n; i++)
for(int j = 0; j < 6; j++)
{
if(check(j, allowed_mask[i]))
{
printf("%c", j + 'a');
break;
}
}
puts("");
}
|
1010
|
A
|
Fly
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \to 2 \to \ldots n \to 1$.
Flight from $x$ to $y$ consists of two phases: take-off from planet $x$ and landing to planet $y$. This way, the overall itinerary of the trip will be: the $1$-st planet $\to$ take-off from the $1$-st planet $\to$ landing to the $2$-nd planet $\to$ $2$-nd planet $\to$ take-off from the $2$-nd planet $\to$ $\ldots$ $\to$ landing to the $n$-th planet $\to$ the $n$-th planet $\to$ take-off from the $n$-th planet $\to$ landing to the $1$-st planet $\to$ the $1$-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is $m$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $1$ ton of fuel can lift off $a_i$ tons of rocket from the $i$-th planet or to land $b_i$ tons of rocket onto the $i$-th planet.
For example, if the weight of rocket is $9$ tons, weight of fuel is $3$ tons and take-off coefficient is $8$ ($a_i = 8$), then $1.5$ tons of fuel will be burnt (since $1.5 \cdot 8 = 9 + 3$). The new weight of fuel after take-off will be $1.5$ tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
First, we learn how to determine if a rocket can fly the entire route. Consider an element from an array $a[]$ or $b[]$. We denote it by $t$. If $t=1$ (that is, one ton of fuel can carry only one ton (cargo + fuel)), then fuel can only take it to ourselves, and we need to take a rocket and a useful cargo (the mass of which is positive). That is, if $t=1$ at least for one $t$, it is necessary to deduce $-1$, otherwise, do the following calculations. It is clear that arrays $a[]$ and $b[]$ will be processed by the computer of the rocket in that order: $a_1,b_2,a_2,b_3,a_3,b_4,a_4,\ldots,b_{n-1},a_{n-1},b_n,a_n,b_1$. We will process this sequence from the end. Let at the current iteration the mass of the payload (including fuel that will not be used at this iteration) is $s$ tons, the current element from the array $a[]$ or $b[]$ is $t$, the mass of fuel that will be used at this iteration (it must be found), is $x$. We assign before the iterations $s=m$. We form the equation: total mass = mass that all fuel can transport $s+x=tx$ $x=\dfrac s{t-1}$ By this formula, you can find fuel in this iteration. For the next iteration to the payload weight, you need to add mass of fuel (since this fuel needs to be brought to this iteration), that is, perform the assignment $s=s+x$. In the end, it is necessary to deduce $s-m$. Complexity: $O(n)$. Bonus. In fact, it does not matter in which order to process arrays $a[]$ and $b[]$ (from the beginning, from the end or in general mixed): the answer from this will not change. Try to prove it by yourself.
|
[
"binary search",
"math"
] | 1,500
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
if(a[i]<=1)
{
printf("-1\n");
exit(0);
}
}
int b[n];
for(int i=0;i<n;i++)
{
cin>>b[i];
if(b[i]<=1)
{
printf("-1\n");
exit(0);
}
}
double s=m;
s+=s/(a[0]-1);
for(int i=n-1;i>=1;i--)
{
s+=s/(b[i]-1);
s+=s/(a[i]-1);
}
s+=s/(b[0]-1);
printf("%.10lf\n",s-m);
}
|
1010
|
B
|
Rocket
|
\textbf{This is an interactive problem.}
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define $x$ as the distance to Mars. Unfortunately, Natasha does not know $x$. But it is known that $1 \le x \le m$, where Natasha knows the number $m$. Besides, $x$ and $m$ are positive integers.
Natasha can ask the rocket questions. Every question is an integer $y$ ($1 \le y \le m$). The correct answer to the question is $-1$, if $x<y$, $0$, if $x=y$, and $1$, if $x>y$. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $t$, then, if the rocket answers this question correctly, then it will answer $t$, otherwise it will answer $-t$.
In addition, the rocket has a sequence $p$ of length $n$. Each element of the sequence is either $0$ or $1$. The rocket processes this sequence in the cyclic order, that is $1$-st element, $2$-nd, $3$-rd, $\ldots$, $(n-1)$-th, $n$-th, $1$-st, $2$-nd, $3$-rd, $\ldots$, $(n-1)$-th, $n$-th, $\ldots$. If the current element is $1$, the rocket answers correctly, if $0$ — lies. Natasha doesn't know the sequence $p$, but she knows its length — $n$.
You can ask the rocket no more than $60$ questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer $0$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
|
First we learn the sequence $p[]$. For this print the query "1" $n$ times. If the answer is "0" (that is, the distance to Mars is equal to one), then immediately terminate the program. Otherwise, it is clear that the correct answer is "1" (that is, the distance to Mars is greater than one). If $i$-th answer of rocket is "1", then $p[i]=1$ (that is, the rocket answered the truth), otherwise $p[i]=0$ (untruth). On this, we will spend no more than $n$ queries, within the given constraints it is $30$. Now you can find the number $x$ using binary search. For each answer, you need to check: if the corresponding element of the sequence $p$ equals to $0$, then the answer sign must be changed. On this, we will spend no more than $\lceil\log_2 m\rceil$ queries, within the given constraints it is $30$. The total number of queries does not exceed $n+\lceil\log_2 m\rceil\le 30+30=60$. Complexity: $O(n+\log m)$ Bonus. Try to solve a similar problem but with a constraint $1 \le m \le 1073741853$.
|
[
"binary search",
"interactive"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int query(int y)
{
cout<<y<<"\n";
fflush(stdout);
int t;
cin>>t;
if(t==0||t==-2)
exit(0);
return t;
}
int main()
{
int m,n;
cin>>m>>n;
int p[n];
for(int i=0;i<n;i++)
{
int t=query(1);
p[i]=t==1;
}
int l=2,r=m;
for(int q=0;;q++)
{
int y=(l+r)/2;
int t=query(y);
if(!p[q%n])
t*=-1;
if(t==1)
l=y+1;
else
r=y-1;
}
}
|
1010
|
C
|
Border
|
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.
There are $n$ banknote denominations on Mars: the value of $i$-th banknote is $a_i$. Natasha has an infinite number of banknotes of each denomination.
Martians have $k$ fingers on their hands, so they use a number system with base $k$. In addition, the Martians consider the digit $d$ (in the number system with base $k$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $k$ is $d$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.
Determine for which values $d$ Natasha can make the Martians happy.
Natasha can use only her banknotes. Martians don't give her change.
|
Note that the condition "the last digit in the record of Natasha's tax amount in the number system with the base $k$ will be $d$" is equivalent to the condition "the remainder of dividing the tax on $k$ will be $d$". Let $g=GCD(a_1,a_2,\ldots,a_n)$. It is stated that the original problem is equivalent to the problem where $n=1$ and the only banknote is $g$. Evidence. We prove this with the help of the Bézout's identity. It follows that an equation of the form $a_1$$x_1+a_2$$x_2+\dots+a_n$$x_n=c$, where at least one of the parameters $a_1,a_2,\dots,a_n$ is not zero, has a solution in integers if and only if $c \hspace{2pt} \vdots \hspace{2pt} GCD(a_1,a_2, \dots ,a_n)$. Then in this task Natasha can pay $x_i$ banknotes of the $i$-th nominal value for each $i$, where $1\le i\le n$, and the amount of tax ($a_1$$x_1+a_2$$x_2+\dots+a_n$$x_n$) can be any number $c$, multiple $g$. (Here some $x_i<0$, But Natasha can add for each par a sufficiently large number, multiple $k$, that $x_i$ became greater than zero, the balance from dividing the amount of tax on $k$ from this will not change.) Therefore, you can replace all pars with one par $g$ and the answer from this will not change. Now we can sort out all the numbers of the form $gx\bmod k$, where $0\le x<k$ (further the remainder of the sum, divided by $k$ will cycle repeatedly) and output them in ascending order. Complexity: $O(n+\log m+k\log k)$, where $m$ is the greatest $a_i$. Bonus. Try to improve the complexity to $O(n+k)$.
|
[
"number theory"
] | 1,800
|
#include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b)
{
if(a<b)
swap(a,b);
return (b==0)?a:gcd(b,a%b);
}
int main()
{
int n,k;
scanf("%d%d",&n,&k);
int g=0;
for(int i=0;i<n;i++)
{
int t;
scanf("%d",&t);
g=gcd(g,t);
}
set<int> ans;
for(long long i=0,s=0;i<k;i++,s+=g)
ans.insert(s%k);
printf("%d\n",ans.size());
for(set<int>::iterator i=ans.begin();i!=ans.end();i++)
printf("%d ",*i);
}
|
1010
|
D
|
Mars rover
|
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $1$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.
There are four types of logical elements: AND ($2$ inputs), OR ($2$ inputs), XOR ($2$ inputs), NOT ($1$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.
For each input, determine what the output will be if Natasha changes this input.
|
Let's count the bit at each vertex. This can be done using depth-first search on this tree. Now for each vertex, let's check: whether the bit on the output of the scheme will change if the bit in the current vertex is changed. If all the vertices on the path from this vertex to the output of the scheme. If at least one of them does not change, then the output of the scheme does not change, and vice versa: if the output of the scheme is changed, then each vertex on the path under consideration will change. Now the solution can be implemented as follows. For each vertex, let's make a note: whether the bit on the output of the scheme will be changed if the bit on the current vertex is changed. For output of the scheme, this note is $true$. Now let's do the depth-first search on this tree. If note at the current vertex is equal to $false$, then at the inputs to it we make the note equal $false$, otherwise, for each input to this vertex, we do the following. Let's see if the current vertex is changed if the current input is changed. If it is changed, then at this input we will make the note equal $true$, otherwise $false$. Complexity: $O(n)$.
|
[
"dfs and similar",
"graphs",
"implementation",
"trees"
] | 2,000
|
#pragma GCC optimize("O3")
#include<bits/stdc++.h>
using namespace std;
struct vertex
{
char type;
vector<int>in;
bool val;
bool change;
};
int n;
vector<vertex> g;
int dfs1(int v)
{
switch(g[v].type)
{
case 'A':
g[v].val = dfs1(g[v].in[0]) & dfs1(g[v].in[1]);
break;
case 'O':
g[v].val = dfs1(g[v].in[0]) | dfs1(g[v].in[1]);
break;
case 'X':
g[v].val = dfs1(g[v].in[0]) ^ dfs1(g[v].in[1]);
break;
case 'N':
g[v].val = ! dfs1(g[v].in[0]);
break;
}
return g[v].val;
}
void dfs2(int v)
{
if(g[v].change==false)
for(int i=0;i<g[v].in.size();i++)
g[g[v].in[i]].change=false;
else
switch(g[v].type)
{
case 'A':
if(g[v].val==(!g[g[v].in[0]].val&g[g[v].in[1]].val)) /// equal to if(g[g[v].in[1]].val==false)
g[g[v].in[0]].change=false;
else
g[g[v].in[0]].change=true;
if(g[v].val==(g[g[v].in[0]].val&!g[g[v].in[1]].val)) /// equal to if(g[g[v].in[0]].val==false)
g[g[v].in[1]].change=false;
else
g[g[v].in[1]].change=true;
break;
case 'O':
if(g[v].val==(!g[g[v].in[0]].val|g[g[v].in[1]].val)) /// equal to if(g[g[v].in[1]].val==true)
g[g[v].in[0]].change=false;
else
g[g[v].in[0]].change=true;
if(g[v].val==(g[g[v].in[0]].val|!g[g[v].in[1]].val)) /// equal to if(g[g[v].in[0]].val==true)
g[g[v].in[1]].change=false;
else
g[g[v].in[1]].change=true;
break;
case 'X':
if(g[v].val==(!g[g[v].in[0]].val^g[g[v].in[1]].val)) /// equal to if(false)
g[g[v].in[0]].change=false;
else
g[g[v].in[0]].change=true;
if(g[v].val==(g[g[v].in[0]].val^!g[g[v].in[1]].val)) /// equal to if(false)
g[g[v].in[1]].change=false;
else
g[g[v].in[1]].change=true;
break;
case 'N':
if(g[v].val==(!!g[g[v].in[0]].val)) /// equal to if(false)
g[g[v].in[0]].change=false;
else
g[g[v].in[0]].change=true;
break;
}
for(int i=0;i<g[v].in.size();i++)
dfs2(g[v].in[i]);
}
int main()
{
scanf("%d",&n);
g.resize(n);
for(int i=0;i<n;i++)
{
char c[4];
scanf("%s",c);
g[i].type=c[0];
int x;
switch(g[i].type)
{
case 'I':
scanf("%d",&x);
g[i].val=x;
break;
case 'N':
scanf("%d",&x);
g[i].in.push_back(x-1);
break;
default:
scanf("%d",&x);
g[i].in.push_back(x-1);
scanf("%d",&x);
g[i].in.push_back(x-1);
break;
}
}
dfs1(0);
g[0].change=true;
dfs2(0);
for(int i=0;i<n;i++)
if(g[i].type=='I')
printf("%d",g[0].val^g[i].change);
}
|
1010
|
E
|
Store
|
Natasha was already going to fly back to Earth when she remembered that she needs to go to the Martian store to buy Martian souvenirs for her friends.
It is known, that the Martian year lasts $x_{max}$ months, month lasts $y_{max}$ days, day lasts $z_{max}$ seconds. Natasha also knows that this store works according to the following schedule: 2 months in a year were selected: $x_l$ and $x_r$ ($1\le x_l\le x_r\le x_{max}$), 2 days in a month: $y_l$ and $y_r$ ($1\le y_l\le y_r\le y_{max}$) and 2 seconds in a day: $z_l$ and $z_r$ ($1\le z_l\le z_r\le z_{max}$). The store works at all such moments (month $x$, day $y$, second $z$), when simultaneously $x_l\le x\le x_r$, $y_l\le y\le y_r$ and $z_l\le z\le z_r$.
Unfortunately, Natasha does not know the numbers $x_l,x_r,y_l,y_r,z_l,z_r$.
One Martian told Natasha: "I went to this store $(n+m)$ times. $n$ times of them it was opened, and $m$ times — closed." He also described his every trip to the store: the month, day, second of the trip and whether the store was open or closed at that moment.
Natasha can go to the store $k$ times. For each of them, determine whether the store at the time of the trip is open, closed, or this information is unknown.
|
Consider $2$ options: $m=0$. This means that Natasha does not know about any moment when the store was closed. Let's find the numbers $x_l=min(x_i)$, $x_r=max(x_i)$, $y_l=min(y_i)$, $y_r=max(y_i)$, $z_l=min(z_i)$, $z_r=max(z_i)$, where $(x_i,y_i,z_i)$ are moments when store is open. For each query $(x_t,y_t,z_t)$ answer "OPEN", if $x_l\le x_t\le x_r$, $y_l\le y_t\le y_r$, and $z_l\le z_t\le z_r$. Answer "UNKNOWN" otherwise. $m\ne0$. Let's find the numbers $x_l=min(x_i)$, $x_r=max(x_i)$, $y_l=min(y_i)$, $y_r=max(y_i)$, $z_l=min(z_i)$, $z_r=max(z_i)$, where $(x_i,y_i,z_i)$ are moments when store is open. If there is at least one moment $(x_j,y_j,z_j)$, when the store is closed, and $x_l\le x_j\le x_r$, $y_l\le y_j\le y_r$ and $z_l\le z_j\le z_r$, then the answer is "INCORRECT". Otherwise, let's create a compressed two-dimensional segment tree. The first coordinate is number of the month in the year, the second coordinate is number of the day in a month. At each vertex of the tree of segments we store a pair of numbers - the greatest such number of a second $z$, when the store was closed, in this day of this month, that $z\le z_r$, and the smallest such number of a second $z$, when the store was closed, in this day of this month, that $z\ge z_l$. Now every query $(x_t,y_t,z_t)$ we will handle like this. If $x_l\le x_t\le x_r$, $y_l\le y_t\le y_r$ and $z_l\le z_t\le z_r$, answer "OPEN". Otherwise, consider the parallelepiped given by the coordinates of opposite vertices $(x_l,y_l,z_l)$ and $(x_r,y_r,z_r)$ and consider each vertex in turn $(x_p,y_p,z_p)$ the parallelepiped under consideration. Let's make the query in the segment tree $(x_p,x_t)$, $(y_p,y_t)$. Let the received answer is $(z_{first},z_{second})$. If the number $z_{first}$ or number $z_{second}$ is between numbers $z_p$ and $z_t$, this means that there is such a time point $(x_j,y_j,z_j)$, when the store is closed, that $x_j$ is between $x_p$ and $x_t$ (the month of the year when the store is closed, is between the month in the year when the store is open, and the month in the year in the query), $y_j$ is between $y_p$ and $y_t$ (the day in the month when the store is closed is between the day in the month when the store is open and the day in the month in the query), $z_j$ is between $z_p$ and $z_t$ (second in a day, when the store is closed, is between a second in a day, when the store is open and a second in a day in the query), hence the answer to the query is "CLOSED". If the condition is not satisfied for any vertex of the parallelepiped, the answer is "UNKNOWN". Complexity: $O(n+m\log m+k\log^2m)$.
|
[
"data structures"
] | 2,700
|
#include<bits/stdc++.h>
using namespace std;
int xmax,ymax,zmax,n,m,k;
map< int , map< int , pair< int ,int > > > pmap;
vector< pair< int , map< int , pair< int ,int > > > > pvector;
vector< pair< vector< pair< int , pair< int , int > > > , vector< pair< int , int > > > > tree;
int oxl,oxr,oyl,oyr,ozl,ozr;
pair<int,int> comb(pair<int,int> p1,pair<int,int> p2)
{
return make_pair(max(p1.first,p2.first),
min(p1.second,p2.second));
}
void build_y(int vx,int lxt, int rxt,int vy,int lyt, int ryt)
{
if(lyt==ryt)
{
if(lxt==rxt)
tree[vx].second[vy]=tree[vx].first[lyt].second;
else
{
int sl,sr;
sl=0,sr=tree[vx*2+1].first.size()-1;
while(sr>sl)
{
int sm=(sl+sr)/2;
if(tree[vx*2+1].first[sm].first>=tree[vx].first[lyt].first)
sr=sm;
else
sl=sm+1;
}
pair<int,int> res1=(tree[vx*2+1].first[sl].first==tree[vx].first[lyt].first)?
(tree[vx*2+1].first[sl].second):
make_pair(0,(int)zmax+1);
sl=0,sr=tree[vx*2+2].first.size()-1;
while(sr>sl)
{
int sm=(sl+sr)/2;
if(tree[vx*2+2].first[sm].first>=tree[vx].first[lyt].first)
sr=sm;
else
sl=sm+1;
}
pair<int,int> res2=(tree[vx*2+2].first[sl].first==tree[vx].first[lyt].first)?
(tree[vx*2+2].first[sl].second):
make_pair(0,(int)zmax+1);
tree[vx].second[vy]=comb(res1,res2);
}
}
else
{
int myt=(lyt+ryt)/2;
build_y(vx,lxt,rxt,vy*2+1,lyt,myt);
build_y(vx,lxt,rxt,vy*2+2,myt+1,ryt);
tree[vx].second[vy]=comb(tree[vx].second[vy*2+1],tree[vx].second[vy*2+2]);
}
}
void build_x(int vx,int lxt, int rxt)
{
if(lxt==rxt)
tree[vx].first=vector< pair< int , pair< int , int > > >(pvector[lxt].second.begin(),pvector[lxt].second.end());
else
{
int mxt=(lxt+rxt)/2;
build_x(2*vx+1,lxt,mxt);
build_x(2*vx+2,mxt+1,rxt);
for(vector< pair< int , pair< int , int > > >::iterator i=tree[2*vx+1].first.begin(),j=tree[2*vx+2].first.begin();;)
{
if(i==tree[2*vx+1].first.end())
{
for(;j!=tree[2*vx+2].first.end();j++)
tree[vx].first.push_back(*j);
break;
}
if(j==tree[2*vx+2].first.end())
{
for(;i!=tree[2*vx+1].first.end();i++)
tree[vx].first.push_back(*i);
break;
}
if(i->first<j->first)
{
tree[vx].first.push_back(*i);
i++;
}
else if(j->first<i->first)
{
tree[vx].first.push_back(*j);
j++;
}
else
{
tree[vx].first.push_back(make_pair(i->first,comb(i->second,j->second)));
i++;
j++;
}
}
}
tree[vx].second.resize(tree[vx].first.size()*4);
build_y(vx,lxt,rxt,0,0,tree[vx].first.size()-1);
}
pair<int,int> get_y(int vx, int vy, int lyt, int ryt, int lyc, int ryc)
{
if(lyc>ryc)
return make_pair(0,zmax+1);
if(lyc==lyt&&ryt==ryc)
return tree[vx].second[vy];
int myt=(lyt+ryt)/2;
return comb(get_y(vx,vy*2+1,lyt,myt,lyc,min(ryc,myt)),
get_y(vx,vy*2+2,myt+1,ryt,max(lyc,myt+1),ryc));
}
pair<int,int> get_x(int vx, int lxt, int rxt, int lxc, int rxc, int ly, int ry)
{
if(lxc>rxc)
return make_pair(0,zmax+1);
if(lxc==lxt&&rxt==rxc)
{
int sl,sr;
sl=0,sr=tree[vx].first.size()-1;
while(sr>sl)
{
int sm=(sl+sr)/2;
if(tree[vx].first[sm].first>=ly)
sr=sm;
else
sl=sm+1;
}
int lyc=sl;
sl=0,sr=tree[vx].first.size()-1;
while(sr>sl)
{
int sm=(sl+sr+1)/2;
if(tree[vx].first[sm].first<=ry)
sl=sm;
else
sr=sm-1;
}
int ryc=sr;
return (tree[vx].first[lyc].first>=ly&&tree[vx].first[ryc].first<=ry)?
get_y(vx,0,0,tree[vx].first.size()-1,lyc,ryc):
make_pair(0,(int)zmax+1);
}
int mxt=(lxt+rxt)/2;
return comb(get_x(vx*2+1,lxt,mxt,lxc,min(rxc,mxt),ly,ry),
get_x(vx*2+2,mxt+1,rxt,max(lxc,mxt+1),rxc,ly,ry));
}
int main()
{
scanf("%d%d%d%d%d%d",&xmax,&ymax,&zmax,&n,&m,&k);
oxl=xmax;
oxr=1;
oyl=ymax;
oyr=1;
ozl=zmax;
ozr=1;
for(int i=0;i<n;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
oxl=min(oxl,x);
oxr=max(oxr,x);
oyl=min(oyl,y);
oyr=max(oyr,y);
ozl=min(ozl,z);
ozr=max(ozr,z);
}
for(int i=0;i<m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
if(oxl<=x&&x<=oxr&&oyl<=y&&y<=oyr&&ozl<=z&&z<=ozr)
{
printf("INCORRECT\n");
exit(0);
}
map< int , pair< int ,int > >::iterator it=pmap[x].insert(make_pair(y,make_pair(0,zmax+1))).first;
if(z<=ozr)
it->second.first=max(it->second.first,z);
if(z>=ozl)
it->second.second=min(it->second.second,z);
}
printf("CORRECT\n");
if(m>0)
{
pvector=vector< pair< int , map< int , pair< int ,int > > > >(pmap.begin(),pmap.end());
tree.resize(pvector.size()*4);
build_x(0,0,pvector.size()-1);
}
for(int i=0;i<k;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
if(oxl<=x&&x<=oxr&&oyl<=y&&y<=oyr&&ozl<=z&&z<=ozr)
{
printf("OPEN\n");
continue;
}
if(m==0)
{
printf("UNKNOWN\n");
continue;
}
bool closed=false;
for(int ii=0;ii<=1;ii++)
for(int jj=0;jj<=1;jj++)
{
if(closed)
break;
int i=oxl+ii*(oxr-oxl);
int j=oyl+jj*(oyr-oyl);
int lx=min(x,i),rx=max(x,i);
int sl,sr;
sl=0,sr=pvector.size()-1;
while(sr>sl)
{
int sm=(sl+sr)/2;
if(pvector[sm].first>=lx)
sr=sm;
else
sl=sm+1;
}
int lxc=sl;
sl=0,sr=pvector.size()-1;
while(sr>sl)
{
int sm=(sl+sr+1)/2;
if(pvector[sm].first<=rx)
sl=sm;
else
sr=sm-1;
}
int rxc=sr;
if(pvector[lxc].first>=lx&&pvector[rxc].first<=rx)
{
pair<int,int> p=get_x(0,0,pvector.size()-1,lxc,rxc,min(y,j),max(y,j));
if(min({z,ozl,ozr})<=p.first||max({z,ozl,ozr})>=p.second)
closed=true;
}
}
if(closed)
printf("CLOSED\n");
else
printf("UNKNOWN\n");
}
}
|
1010
|
F
|
Tree
|
The Main Martian Tree grows on Mars. It is a binary tree (a rooted tree, with no more than two sons at each vertex) with $n$ vertices, where the root vertex has the number $1$. Its fruits are the Main Martian Fruits. It's summer now, so this tree does not have any fruit yet.
Autumn is coming soon, and leaves and branches will begin to fall off the tree. It is clear, that if a vertex falls off the tree, then its entire subtree will fall off too. In addition, the root will remain on the tree. Formally: the tree will have some connected subset of vertices containing the root.
After that, the fruits will grow on the tree (only at those vertices which remain). Exactly $x$ fruits will grow in the root. The number of fruits in each remaining vertex will be not less than the sum of the numbers of fruits in the remaining sons of this vertex. It is allowed, that some vertices will not have any fruits.
Natasha wondered how many tree configurations can be after the described changes. Since this number can be very large, output it modulo $998244353$.
Two configurations of the resulting tree are considered different if one of these two conditions is true:
- they have different subsets of remaining vertices;
- they have the same subset of remaining vertices, but there is a vertex in this subset where they have a different amount of fruits.
|
Let $b_v = a_v - \sum{a_{to}}$, (for each $(v, to)$, such that $to$ - is a son of $v$ and tree have both vertices $v$ and $to$), then all that we need is $b_v \geq 0$ and $\sum{b_v} = x$, so for fixed subset of vertices number of ways to arrange weights is just number of ways to partite $x$ into such number of parts. So let $f_i$ be number of ways to choose connected subtree of $i$ vertices, that contains vertex $1$, then answer is $\sum{f_i C_{x+i-1}^{i-1}}$. Then we need to calculate $f_i$ for each $1 \leq i \leq n$, and calculate $C_{x+i-1}^{i-1}$ for each $1 \leq i \leq n$. Let's use generating functions to calc $f_i$. Let $dp_v$ be generating function of $\sum{f_i \cdot x^i}$, (if we will assume that $v$ - root and we will look only at vertices inside subtree of $v$). Then if vertex $v$ - leaf, then $dp_v = x + 1$, if this vertex have one son, $dp_v = dp_{to} x + 1$, and if two, then $dp_v = dp_l dp_r x + 1$. Then let maintain $dp_v$ as a sequence of polynomials $a_1, a_2, \ldots, a_k$, such that $dp_v = (((a_1 + 1) a_2 + 1) \ldots) a_k + 1$). Then if we have the representation of $dp_v$ in such format, we can find the exact value of polynomial in the sum of sizes of polynomials $\cdot \log^2{n}$. For it you can note, that $dp_v$ is just $a_1 a_2 a_3 \ldots a_k + a_2 a_3 \ldots a_k + \ldots + a_k + 1$. And then with FFT you can calculate value and multiplication for left half ($P_l(x)$ and $Q_l(x)$), and for right half ($P_r(x)$ and $Q_r(x)$). Then $P(x) = (P_l(x) - 1) Q_r(x) + P_r(x)$, a $Q(x) = Q_l(x) Q_r(x)$. So, you can calculate exact value of $dp_v$ in $T(n) = 2T(n/2) + O(n \log {n}) = O(n \log^2 {n})$ (Where $n$ is sum of sizes of polynomials). Then if $v$ - leaf just add $x$ into the sequence of polynomials. If $v$ have one son, then add $x$ into the sequence of polynomials of a son, and take his sequence as a sequence for vertex $v$. And if $v$ have two sons, Let's take a son with the smaller size of a subtree, find its exact value as written, and add it into the sequence of another son. Sum of sizes of smaller subtrees is $O(n \log {n})$, so we can find $f$ in $O(n \log^3{n})$. Note, that you can find similar value when the tree is not binary too, for it you can find the exact value of all children without largest, and multiply it in $O(n \log^2 (n))$ with D&C. To calculate $C_{x+i-1}^{i-1}$ for each $1 \leq i \leq n$ you can note, that when $i=1$ it is just $1$, and to get a value for $i+1$ you need multiply current value on $x+i-1$ and divide on $i$. Then you can find scalar multiplication of these two vectors, and solve the task in $O(n \log^3{n}$).
|
[
"fft",
"graphs",
"trees"
] | 3,400
|
#include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#include <list>
#include <time.h>
#include <math.h>
#include <random>
#include <deque>
#include <queue>
#include <cassert>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <bitset>
#include <sstream>
using namespace std;
typedef long long ll;
mt19937 rnd(228);
const int md = 998244353;
inline void add(int &a, int b) {
a += b;
if (a >= md) a -= md;
}
inline void sub(int &a, int b) {
a -= b;
if (a < 0) a += md;
}
inline int mul(int a, int b) {
#if !defined(_WIN32) || defined(_WIN64)
return (int) ((long long) a * b % md);
#endif
unsigned long long x = (long long) a * b;
unsigned xh = (unsigned) (x >> 32), xl = (unsigned) x, d, m;
asm(
"divl %4; \n\t"
: "=a" (d), "=d" (m)
: "d" (xh), "a" (xl), "r" (md)
);
return m;
}
inline int power(int a, long long b) {
int res = 1;
while (b > 0) {
if (b & 1) {
res = mul(res, a);
}
a = mul(a, a);
b >>= 1;
}
return res;
}
inline int inv(int a) {
a %= md;
if (a < 0) a += md;
int b = md, u = 0, v = 1;
while (a) {
int t = b / a;
b -= t * a; swap(a, b);
u -= t * v; swap(u, v);
}
assert(b == 1);
if (u < 0) u += md;
return u;
}
namespace ntt {
int base = 1;
vector<int> roots = {0, 1};
vector<int> rev = {0, 1};
int max_base = -1;
int root = -1;
void init() {
int tmp = md - 1;
max_base = 0;
while (tmp % 2 == 0) {
tmp /= 2;
max_base++;
}
root = 2;
while (true) {
if (power(root, 1 << max_base) == 1) {
if (power(root, 1 << (max_base - 1)) != 1) {
break;
}
}
root++;
}
}
void ensure_base(int nbase) {
if (max_base == -1) {
init();
}
if (nbase <= base) {
return;
}
assert(nbase <= max_base);
rev.resize(1 << nbase);
for (int i = 0; i < (1 << nbase); i++) {
rev[i] = (rev[i >> 1] >> 1) + ((i & 1) << (nbase - 1));
}
roots.resize(1 << nbase);
while (base < nbase) {
int z = power(root, 1 << (max_base - 1 - base));
for (int i = 1 << (base - 1); i < (1 << base); i++) {
roots[i << 1] = roots[i];
roots[(i << 1) + 1] = mul(roots[i], z);
}
base++;
}
}
void fft(vector<int> &a) {
int n = (int) a.size();
assert((n & (n - 1)) == 0);
int zeros = __builtin_ctz(n);
ensure_base(zeros);
int shift = base - zeros;
for (int i = 0; i < n; i++) {
if (i < (rev[i] >> shift)) {
swap(a[i], a[rev[i] >> shift]);
}
}
for (int k = 1; k < n; k <<= 1) {
for (int i = 0; i < n; i += 2 * k) {
for (int j = 0; j < k; j++) {
int x = a[i + j];
int y = mul(a[i + j + k], roots[j + k]);
a[i + j] = x + y - md;
if (a[i + j] < 0) a[i + j] += md;
a[i + j + k] = x - y + md;
if (a[i + j + k] >= md) a[i + j + k] -= md;
}
}
}
}
vector<int> multiply(vector<int> a, vector<int> b, int eq = 0) {
int need = (int) (a.size() + b.size() - 1);
int nbase = 0;
while ((1 << nbase) < need) nbase++;
ensure_base(nbase);
int sz = 1 << nbase;
a.resize(sz);
b.resize(sz);
fft(a);
if (eq) b = a; else fft(b);
int inv_sz = inv(sz);
for (int i = 0; i < sz; i++) {
a[i] = mul(mul(a[i], b[i]), inv_sz);
}
reverse(a.begin() + 1, a.end());
fft(a);
a.resize(need);
while (!a.empty() && a.back() == 0) {
a.pop_back();
}
return a;
}
vector<int> square(vector<int> a) {
return multiply(a, a, 1);
}
};
const int N = 1e5 + 1;
vector <vector <int> > polys[N];
int l[N], r[N];
int who[N];
int sz[N];
vector <int> slozh(const vector <int> &a, const vector <int> &b)
{
int n = (int) a.size(), m = (int) b.size();
vector <int> c(max(n, m));
for (int i = 0; i < n; i++) add(c[i], a[i]);
for (int i = 0; i < m; i++) add(c[i], b[i]);
return c;
}
pair <vector <int>, vector <int> > eval(const vector <vector <int> > &a)
{
if (a.size() == 1)
{
auto ret = a[0];
ret[0]++;
return {ret, a[0]};
}
else
{
int m = (int) a.size() / 2;
vector <vector <int> > l, r;
for (int i = 0; i < m; i++)
{
l.push_back(a[i]);
}
for (int i = m; i < (int) a.size(); i++)
{
r.push_back(a[i]);
}
auto lf = eval(l), rf = eval(r);
add(lf.first[0], -1);
auto P = slozh(ntt::multiply(lf.first, rf.second), rf.first);
auto Q = ntt::multiply(lf.second, rf.second);
return {P, Q};
}
}
vector <int> g[N];
void dfs(int v, int pr)
{
vector <int> go;
int deg = 0;
for (int to : g[v])
{
if (to != pr)
{
go.push_back(to);
deg++;
}
}
if (deg == 0)
{
polys[v].push_back({0, 1});
sz[v] = 1;
who[v] = v;
}
else
{
if (deg == 2)
{
l[v] = go[0];
r[v] = go[1];
dfs(l[v], v);
dfs(r[v], v);
sz[v] = sz[l[v]] + sz[r[v]] + 1;
if (sz[l[v]] < sz[r[v]])
{
swap(l[v], r[v]);
}
auto go = eval(polys[who[r[v]]]).first;
go.insert(go.begin(), 0);
polys[who[l[v]]].push_back(go);
who[v] = who[l[v]];
}
else
{
int son = go[0];
dfs(son, v);
sz[v] = sz[son] + 1;
who[v] = who[son];
polys[who[v]].push_back({0, 1});
}
}
}
vector <int> binom(ll n, int k)
{
if (n == 0)
{
vector <int> ret(k + 1);
ret[0] = 1;
return ret;
}
else if (n % 2 == 0)
{
auto a = binom(n / 2, k);
a = ntt::square(a);
a.resize(k + 1);
return a;
}
else
{
auto a = binom(n - 1, k);
for (int i = k; i >= 0; i--)
{
if (i != 0)
{
add(a[i], a[i - 1]);
}
}
return a;
}
}
int main()
{
#ifdef ONPC
freopen("a.in", "r", stdin);
#endif
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
ll x;
cin >> x;
vector <int> fact(n + 1), rev_fact(n + 1);
fact[0] = 1;
for (int i = 1; i <= n; i++)
{
fact[i] = mul(fact[i - 1], i);
}
for (int i = 0; i <= n; i++)
{
rev_fact[i] = inv(fact[i]);
}
for (int i = 1; i < n; i++)
{
int a, b;
cin >> a >> b;
a--, b--;
g[a].push_back(b);
g[b].push_back(a);
}
dfs(0, -1);
auto solve = eval(polys[who[0]]).first;
auto big_binoms = binom(x, n);
for (int i = 0; i <= n; i++)
{
big_binoms[i] = mul(big_binoms[i], rev_fact[i]);
}
rev_fact.insert(rev_fact.begin(), 0);
big_binoms = ntt::multiply(big_binoms, rev_fact);
int ans = 0;
for (int i = 1; i <= n; i++)
{
add(ans, mul(mul(solve[i], big_binoms[i]), fact[i - 1]));
}
cout << ans << '\n';
}
|
1011
|
A
|
Stages
|
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
|
The problem can be solved by the following greedy algorithm. Sort letters in increasing order. Let's try to add letters in this order. If the current letter is the first in the string, then add it to the answer. Otherwise, check: if the current letter is at least two positions later in the alphabet than the previous letter of the answer, add it to the response, otherwise go over to the next letter. As soon as there are $k$ letters in the answer, print it. If after this algorithm the answer has less than $k$ letters, print -1. Complexity: $O(n\log n)$.
|
[
"greedy",
"implementation",
"sortings"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
cin>>n>>k;
string s;
cin>>s;
sort(s.begin(),s.end());
char last='a'-2;
int ans=0;
int len=0;
for(int i=0;i<n;i++)
if(s[i]>=last+2)
{
last=s[i];
ans+=s[i]-'a'+1;
len++;
if(len>=k)
cout<<ans,exit(0);
}
cout<<-1;
}
|
1011
|
B
|
Planning The Expedition
|
Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.
The warehouse has $m$ daily food packages. Each package has some food type $a_i$.
Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.
Formally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different.
What is the maximum possible number of days the expedition can last, following the requirements above?
|
Let $c_i$ be the number of food packages that equal to $i$. Calculate the array $c$. For any $d$ we can calculate the maximum number of people $k$, who can participate in the expedition for $d$ days. To do this, we'll go over all the elements of the array $c$. Let now be considered $c_i$. If $c_i \ge d$, we can decrease $c_i$ by $d$ and increase $k$ by $1$, that is, take $d$ daily food packages for one person. If still $c_i \ge d$, repeat the algorithm, and so on. That is for $i$-th iteration number $k$ increases by $\left\lfloor \dfrac{c_i}d \right\rfloor$. After all the iterations the number $k$ will be the required number of people. It is clear that the answer does not exceed $m$ (every day at least one food package is used). Let's iterate $d$ from $m$ to $1$, each time checking whether the answer can be equal $d$. To do this, we calculate the maximum number of people $k$, who can participate in the expedition for $d$ days. If $k \ge n$, then the answer is $d$. If no answer was received on any iteration, then the answer is $0$. Complexity: $O(m^2)$. Bonus. Try to improve the complexity to $O(m \log m)$.
|
[
"binary search",
"brute force",
"implementation"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
const int N = 100;
int main() {
int n, m;
cin >> n >> m;
vector<int> c(N + 1);
for (int i = 0; i < m; i++) {
int a;
cin >> a;
c[a]++;
}
for (int d = N; d >= 1; d--) {
vector<int> cc(c);
int k = 0;
for (int i = 1; i <= N; i++)
while (cc[i] >= d) {
k++;
cc[i] -= d;
}
if (k >= n) {
cout << d << endl;
return 0;
}
}
cout << 0 << endl;
}
|
1012
|
A
|
Photo of The Sky
|
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates $(x, y)$, such that $x_1 \leq x \leq x_2$ and $y_1 \leq y \leq y_2$, where $(x_1, y_1)$ and $(x_2, y_2)$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.
After taking the photo, Pavel wrote down coordinates of $n$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.
Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.
Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
|
At first let's sort array $a$, so we can assume that $a_1 \leq a_2 \leq \dots \leq a_{2 \cdot n}$. Note that area of rectangle with bottom-left corner in $(x_1, y_1)$, and up-right corner in $(x_2, y_2)$ is $(x_2 - x_1) \cdot (y_2 - y_1)$. So the task is to partite array $a$ into $2$ multisets (sets with equal elements) $X$ and $Y$ of size $n$, such that $(max(X) - min(X)) \cdot (max(Y) - min(Y))$ is minimal among all such partitions ($min(X)$ - minimum in multiset $X$, $max(X)$ - maximum in multiset $X$). Let's look at such partition There are $2$ cases: Minimum and maximum are in one multiset. Let's assume that they are both in $X$. Then $max(X) - min(X) = a_{2 \cdot n} - a_1$. We need to minimize $max(Y) - min(Y)$. If index of $min(Y)$ in $a$ is $i$, and $max(Y)$ is $j$, htne $j - i \geq n - 1$, because there are $n$ elements in $Y$. So we can use $Y = \{a_i, a_{i+1}, \dots, a_{i+n-1}\}$ and desired difference will not increase. So as $Y$ it is optimial to use some segment of length $n$. Minimum and maximum are not in one multiset. Let's assume that minimum in $X$, and maximum in $Y$. Then note, that maximum in $X$ always $\geq a_n$, because size of $X$ is $n$. And minimum in $Y$ will be $\leq a_{n+1}$, because size of $Y$ is $n$. So $(max(X) - min(X)) \cdot (max(Y) - min(Y)) \geq (a_n - a_1) \cdot (a_{2 \cdot n} - a_{n+1})$, so you can use prefix of length $n$ as $X$ and suffix of length $n$ as $Y$. So answer is minimum of $(a_{2 \cdot n} - a_1) \cdot (a_{i+n-1} - a_i)$ for each $2 \leq i \leq n$ and $(a_n - a_1) \cdot (a_{2 \cdot n} - a_{n+1})$. That is, you can simply check all contigious subsets as first set and all the remaints as the second one. Complexity is $O(n \cdot log(n))$.
|
[
"brute force",
"implementation",
"math",
"sortings"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M = 2e5 + 239;
const int BIG = 1e9 + 239;
int n, a[M];
int main()
{
cin.sync_with_stdio(0);
cin >> n;
for (int i = 0; i < (2 * n); i++)
cin >> a[i];
sort(a, a + (2 * n));
if (n == 1)
{
cout << "0";
return 0;
}
int now = BIG;
for (int i = 1; i < n; i++) now = min(now, a[i + n - 1] - a[i]);
cout << min((ll)(a[2 * n - 1] - a[0]) * (ll)now, (ll)(a[n - 1] - a[0]) * (ll)(a[2 * n - 1] - a[n]));
return 0;
}
|
1012
|
B
|
Chemical table
|
Innopolis University scientists continue to investigate the periodic table. There are $n·m$ known elements and they form a periodic table: a rectangle with $n$ rows and $m$ columns. Each element can be described by its coordinates $(r, c)$ ($1 ≤ r ≤ n$, $1 ≤ c ≤ m$) in the table.
Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions $(r_{1}, c_{1})$, $(r_{1}, c_{2})$, $(r_{2}, c_{1})$, where $r_{1} ≠ r_{2}$ and $c_{1} ≠ c_{2}$, then we can produce element $(r_{2}, c_{2})$.
Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.
Innopolis University scientists already have samples of $q$ elements. They want to obtain samples of all $n·m$ elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.
|
One of the way to solve this problem is to interprete the cells in 2d matrix as an edge in the bipartite graph, that is a cell $(i, j)$ is an edge between $i$ of the left part and $j$ of the right part. Note, that each fusion operation (we have edges $(r_{1}, c_{1})$, $(r_{1}, c_{2})$, $(r_{2}, c_{1})$ and get edge $(r_{2}, c_{2})$) doesn't change the connected components of the graph. Moreover, we can prove, that we can obtain each edge in the connected component by fusion. Let's examine example edge $(x, y)$, and some path between $x$ and $y$ (since they lay in one connected component). Since the graph is bipartite, the length of this path must be odd, and it is $ \ge 3$, otherwise the edge already exists. So we have this path. Take first three edges and make the corresponding fusion, replace this three edges with the brand new fused edge. The length of the path decreased by $2$. Repeat until the path is a mere edge. This way, the number of edges to add (cells to buy) is just number of connected components minus one.
|
[
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs",
"matrices"
] | 1,900
| null |
1012
|
C
|
Hills
|
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction.
From the window in your room, you see the sequence of $n$ hills, where $i$-th of them has height $a_{i}$. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is $5, 4, 6, 2$, then houses could be built on hills with heights $5$ and $6$ only.
The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build $k$ houses, so there must be at least $k$ hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?
However, the exact value of $k$ is not yet determined, so could you please calculate answers for all $k$ in range $1\leq k\leq\,\lceil\frac{n}{2}\rceil$? Here $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$ denotes $n$ divided by two, rounded up.
|
The problem's short statement is: "we allowed to decrease any element and should create at least $k$ local maximums, count the minimum number of operations for all $k$". Notice, that any set of positions, where no positions are adjacent could be made to be local maximums - we just need to decrease the neighbouring hills to some value. Let's introduce the following dynamic programming: dp[prefix][local_maxs] - the minimum cost if we analyze only given prefix, have the specified number of local maximums ("good hills to build on") and we make a local maximum in the last hill of this prefix. Th dumb implementation of this leads to $O(n^{2})$ states and $O(n^{4})$ time - in each state we can brute force the previous position of local maximum ($n$) and then calculate the cost of patching the segment from previous local maximum to current one. A more attentive look says that it is, in fact $O(n^{3})$ solution - on the segment only first and last elements need to be decreased (possibly first and last elements are same). To get the full solution full solution in $O(n^{2})$ we need to optimize dp a little bit. As we noticed in the previous paragraph, there is one extreme situation, when the first and elements are same, let's handle this transition by hand in $O(1)$ for each state. Otherwise, funny fact, the cost of the segment strictly between local maximums is the cost of it's left part plus it'cost of it's right part. Seems like something we can decompose, right? Since our goal is to update state $(prefix, local)$ now the right part is fixed constant for all such transitions. And we need to select minimum value of $dp[i][local - 1] + cost(i, i + 1)$ where $i < = prefix - 3$. This can be done by calculating a supplementary dp during the primarily dp calculation - for example we can calculate f[pref][j] = min dp[i][j] + cost(i, i + 1) for $i \le pref$.
|
[
"dp"
] | 1,900
| null |
1012
|
D
|
AB-Strings
|
There are two strings $s$ and $t$, consisting only of letters a and b. You can make the following operation several times: choose a prefix of $s$, a prefix of $t$ and swap them. Prefixes \underline{can be empty}, also a prefix can coincide with a whole string.
Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be \underline{minimized}.
|
The solution is basically like following: Note that we can compress equal adjacent letters. Now we can do a dynamic programming with params (first letter of $s$, length of $s$, first letter of $t$, length of $t$). However, the amount of transactions and even states is too large. But we can write a slow, but surely correct solution, and examine the transactions, which are made in dp. Basically, the most typical transaction is to just make a swap of first group in $s$ with first group in $t$. However there special cases, like when the first letters are the same or when the lengths are very small. Running a slow dynamic programming helps to get all the cases for the solution. Formally, the correctness of this algorithm can be proven by induction and the large cases analyses, which we skip for clarity. Another approach is to consider different first operations, and then go a greedy after it algorithm. See the second solution for the details. We don't prove it.
|
[
"constructive algorithms",
"strings"
] | 2,800
|
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class swap_prefixes_av_n {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
SwapPrefixesDp solver = new SwapPrefixesDp();
solver.solve(1, in, out);
out.close();
}
static class SwapPrefixesDp {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
String s = in.next(), t = in.next();
List<Integer> ans1 = solve("a" + s, "b" + t);
List<Integer> ans2 = solve("b" + s, "a" + t);
if (ans1.size() > ans2.size()) {
ans1 = ans2;
}
out.println(ans1.size() / 2);
for (int i = 0; i < ans1.size(); i += 2) {
out.println(ans1.get(i) + " " + ans1.get(i + 1));
}
}
private void makeSwap(List<Integer> realAns, List<Pair> compressedS, List<Pair> compressedT, int lenS, int lenT) {
List<Pair> newS = new ArrayList<>();
List<Pair> newT = new ArrayList<>();
int realLenS = 0, realLenT = 0;
for (int i = 0; i < lenS; i++) {
realLenS += compressedS.get(i).count;
}
for (int i = 0; i < lenT; i++) {
realLenT += compressedT.get(i).count;
}
realAns.add(realLenS - 1);
realAns.add(realLenT - 1);
concatLists(compressedS, compressedT, lenS, lenT, newS);
concatLists(compressedT, compressedS, lenT, lenS, newT);
compressedS.clear();
compressedS.addAll(newS);
compressedT.clear();
compressedT.addAll(newT);
}
private void concatLists(List<Pair> compressedS, List<Pair> compressedT, int lenS, int lenT, List<Pair> newS) {
newS.addAll(compressedT.subList(0, lenT));
newS.addAll(compressedS.subList(lenS, compressedS.size()));
if (lenT < newS.size() && newS.get(lenT - 1).ch == newS.get(lenT).ch) {
newS.get(lenT - 1).count += newS.get(lenT).count;
newS.remove(lenT);
}
}
private List<Integer> solve(String s, String t) {
List<Pair> compressedS = compress(s);
List<Pair> compressedT = compress(t);
if (compressedS.size() == 1 && compressedT.size() == 1) {
return new ArrayList<>();
}
int curI = compressedS.size(), curJ = compressedT.size();
int bestI = -1, bestJ = -1;
int bestCost = Integer.MAX_VALUE;
for (int lenI = 1; lenI <= compressedS.size(); lenI++) {
for (int lenJ = 1; lenJ <= compressedT.size(); lenJ++) {
if (lenI % 2 != lenJ % 2) {
continue;
}
if (lenI > 3 && lenJ > 3) {
break;
}
int nextI = lenJ + (curI - lenI) - ((curI != lenI && lenJ % 2 == lenI % 2) ? 1 : 0);
int nextJ = lenI + (curJ - lenJ) - ((curJ != lenJ && lenJ % 2 == lenI % 2) ? 1 : 0);
int cost = 1 + Math.max(nextI, nextJ);
if (cost < bestCost) {
bestCost = cost;
bestI = lenI;
bestJ = lenJ;
}
}
}
List<Integer> ans = new ArrayList<>();
makeSwap(ans, compressedS, compressedT, bestI, bestJ);
int nextI = compressedS.size(), nextJ = compressedT.size();
int prefixA = 0, prefixB = 0;
for (int i = 0; i < Math.max(nextI, nextJ) - 1; i++) {
if (i % 2 == 0) {
prefixA += i >= compressedS.size() ? 0 : compressedS.get(i).count;
prefixB += i >= compressedT.size() ? 0 : compressedT.get(i).count;
ans.add(prefixA - 1);
ans.add(prefixB - 1);
} else {
prefixA += i >= compressedT.size() ? 0 : compressedT.get(i).count;
prefixB += i >= compressedS.size() ? 0 : compressedS.get(i).count;
ans.add(prefixB - 1);
ans.add(prefixA - 1);
}
}
return ans;
}
private List<Pair> compress(String s) {
List<Pair> result = new ArrayList<>();
for (int i = 0; i < s.length(); ) {
int j = i;
while (j < s.length() && s.charAt(i) == s.charAt(j)) {
j++;
}
result.add(new Pair(s.charAt(i), j - i));
i = j;
// System.err.println(result);
}
return result;
}
class Pair {
char ch;
int count;
public Pair(char ch, int count) {
this.ch = ch;
this.count = count;
}
@Override
public String toString() {
return "Pair{" +
"ch=" + ch +
", count=" + count +
'}';
}
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}
}
|
1012
|
E
|
Cycle sort
|
You are given an array of $n$ positive integers $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: select several distinct indices $i_1, i_2, \dots, i_k$ ($1 \le i_j \le n$) and move the number standing at the position $i_1$ to the position $i_2$, the number at the position $i_2$ to the position $i_3$, ..., the number at the position $i_k$ to the position $i_1$. In other words, the operation cyclically shifts elements: $i_1 \to i_2 \to \ldots i_k \to i_1$.
For example, if you have $n=4$, an array $a_1=10, a_2=20, a_3=30, a_4=40$, and you choose three indices $i_1=2$, $i_2=1$, $i_3=4$, then the resulting array would become $a_1=20, a_2=40, a_3=30, a_4=10$.
Your goal is to make the array sorted in non-decreasing order with the minimum number of operations. The additional constraint is that the sum of cycle lengths over all operations should be less than or equal to a number $s$. If it's impossible to sort the array while satisfying that constraint, your solution should report that as well.
|
Let's solve an array if $a$ is permutation and the sum of cycle sizes is unlimited. It's known that each permutation is composition of some non-intersecting cycles. If permutation is sorted answer is $0$. If permutation is $1$ cycle and some fixed indexes answer is $1$, you should take this cycle to get this answer. If permutation is composition of $\geq 2$ cycles answer should be $\geq 2$, because it's impossible to use $1$ cycle. In this case it's possible to make the answer with $2$ cycles. Let's define inversed permutation for our permutation as composition of this cycles $(p_{{1}{1}} \to p_{{1}{2}} \to \dots \to p_{{1}{k_1}} \to p_{{1}{1}}), \dots, (p_{{m}{1}} \to p_{{m}{2}} \to \dots \to p_{{m}{k_m}} \to p_{{m}{1}})$ (all cycles, except cycles with length $1$). We can sort permutations using this $2$ cycles: $(p_{{1}{1}} \to p_{{1}{2}} \to \dots \to p_{{1}{k_1}} \to p_{{2}{1}} \to \dots \to p_{{m}{1}} \to p_{{m}{2}} \to \dots \to p_{{m}{k_m}} \to p_{{1}{1}})$ (all cycles, written in a row) and $(p_{{m}{1}} \to p_{{m-1}{1}} \to \dots p_{{1}{1}} \to p_{{m}{1}})$ (first elements of cycles in inversed order). This solution used sum of cycle sizes $t+m$, there $t$ - number of non-fixed elements and $m$ - number of cycles with size $1$. Now let's solve problem for permutation, if we can use sum of cycle sizes $\leq s$. Each solution should use sum of cycle sizes $\geq t$, because we should shift each non-fixed element. So if $s < t$ answer is $-1$. Let's call each cycle from $m$ cycles bad, if each of it's element shifted exactly $1$ time in the answer. It can be proved, that each bad cycle should be used in the answer. Let's define $x$ as number of bad cycles and $y$ number of other cycles. So $x+y=m$. Sum of cycles in the answer $\geq t+y$. So, $t+y \leq s$ ==> $y \leq s-t$ ==> $x=m-y \geq m+t-s$. Number of cycles in the answer $\geq x + min(y, 2)$. It's true, because each of $x$ bad cycles are in answer and other $y$ cycles can be sorted using $\geq min(y, 2)$ cycles. We should take $x$ as maximal as possible, because if we increase $x$ by $1$ sum $min(y, 2) + x$ won't increase. Minimal $x$, that we can use is $max(0, m+t-s)$. So we get $y=m-max(0,m+t-s)=m+min(s-t-m, 0)=min(s-t, 0)=s-t$ (because $s \geq t$). So answer in this case if $max(0, m+t-s)+min(s-t, 2)$. We can build it, if we use $x=max(0, m+t-s)$ any of $m$ cycles, and for other $y=s-t$ cycles do same construction as in previous case. Let's solve problem for array. Let's define $b$ as sorted array $a$ and $t$ as count of $1 \leq i \leq n$, such that $a_i \neq b_i$. Our solution will sort some permutation $p$, such that $a_{p_i} = b_i$, for all $i$. Answer for permutation is $max(0, m+t-s)+min(s-t, 2)$. In this formula $s$ and $t$ fixed. So to minimize the answer we should minimize $m$. So we should sort array using array with as minumal as possible number of cycles. To do it let's build directed graph: vertexes is number in array, let's add edge from $a_i$ to $b_i$ for all $i$, such that $a_i \neq b_i$. It's easy to see, that we should take euler cycle in each component of this graph and build permutation with this cycles to make number of cycles in permutation as minimal as possible. To code this solution without building graph let's take first any sorting permutation. After that, we can merge cycles. If $a_i = a_j$ and $i$ and $j$ in different cycles of permutation, we can merge this cycles using $swap(p_i, p_j)$. So let's merge all possible cycles using DSU for components. Time complexity: $O(n * log(n))$.
|
[
"dsu",
"math"
] | 3,100
|
#include <bits/stdc++.h>
using namespace std;
const int M = 2e5 + 239;
int n, s, a[M], p[M];
pair<int, int> b[M];
int parent[M], r[M];
inline void init()
{
for (int i = 0; i < n; i++)
{
parent[i] = i;
r[i] = 0;
}
}
inline int find_set(int p)
{
if (parent[p] == p) return p;
return (parent[p] = find_set(parent[p]));
}
inline void merge_set(int i, int j)
{
i = find_set(i);
j = find_set(j);
if (i == j) return;
if (r[i] > r[j]) swap(i, j);
if (r[i] == r[j]) r[j]++;
parent[i] = j;
}
inline bool is_connect(int i, int j)
{
return (find_set(i) == find_set(j));
}
int t;
bool used[M];
vector<int> c[M];
void dfs(int x)
{
used[x] = true;
c[t].push_back(x);
if (!used[p[x]]) dfs(p[x]);
}
int main()
{
ios::sync_with_stdio(0);
cin >> n >> s;
for (int i = 0; i < n; i++)
{
cin >> a[i];
b[i] = make_pair(a[i], i);
}
sort(b, b + n);
for (int i = 0; i < n; i++) p[b[i].second] = i;
for (int i = 0; i < n; i++)
if (a[i] == b[i].first && p[i] != i)
{
p[b[i].second] = p[i];
b[p[i]].second = b[i].second;
p[i] = i;
b[i].second = i;
}
init();
for (int i = 0; i < n; i++) merge_set(p[i], i);
int ls = -1;
for (int i = 0; i < n; i++)
{
if (p[b[i].second] == b[i].second) continue;
if (ls >= 0 && a[ls] == a[b[i].second])
{
int x = ls;
int y = b[i].second;
if (is_connect(x, y)) continue;
merge_set(x, y);
swap(p[x], p[y]);
}
ls = b[i].second;
}
t = 0;
for (int i = 0; i < n; i++)
if (!used[i] && p[i] != i)
{
dfs(i);
t++;
}
int kol = 0;
for (int i = 0; i < t; i++)
kol += (int)c[i].size();
if (kol > s)
{
cout << "-1";
return 0;
}
s -= kol;
s = min(s, t);
if (s <= 1)
{
cout << t << "\n";
for (int i = 0; i < t; i++)
{
cout << c[i].size() << "\n";
for (int x : c[i])
cout << (x + 1) << " ";
cout << "\n";
}
return 0;
}
cout << (t - s + 2) << "\n";
for (int i = 0; i < t - s; i++)
{
cout << c[i + s].size() << "\n";
for (int x : c[i + s])
cout << (x + 1) << " ";
cout << "\n";
kol -= (int)c[i + s].size();
}
cout << kol << "\n";
for (int i = 0; i < s; i++)
for (int x : c[i])
cout << (x + 1) << " ";
cout << "\n";
cout << s << "\n";
for (int i = s - 1; i >= 0; i--)
cout << (c[i][0] + 1) << " ";
cout << "\n";
return 0;
}
|
1012
|
F
|
Passports
|
Gleb is a famous competitive programming teacher from Innopolis. He is planning a trip to $N$ programming camps in the nearest future. Each camp will be held in a different country. For each of them, Gleb needs to apply for a visa.
For each of these trips Gleb knows three integers: the number of the first day of the trip $s_{i}$, the length of the trip in days $len_{i}$, and the number of days $t_{i}$ this country's consulate will take to process a visa application and stick a visa in a passport. Gleb has $P$ ($1 ≤ P ≤ 2$) valid passports and is able to decide which visa he wants to put in which passport.
For each trip, Gleb will have a flight to that country early in the morning of the day $s_{i}$ and will return back late in the evening of the day $s_{i} + len_{i} - 1$.
To apply for a visa on the day $d$, Gleb needs to be in Innopolis in the middle of this day. So he can't apply for a visa while he is on a trip, including the first and the last days. If a trip starts the next day after the end of the other one, Gleb can't apply for a visa between them as well. The earliest Gleb can apply for a visa is day 1.
After applying for a visa of country $i$ on day $d$, Gleb will get his passport back in the middle of the day $d + t_{i}$. Consulates use delivery services, so Gleb can get his passport back even if he is not in Innopolis on this day. Gleb can apply for another visa on the same day he received his passport back, if he is in Innopolis this day.
Gleb will not be able to start his trip on day $s_{i}$ if he doesn't has a passport with a visa for the corresponding country in the morning of day $s_{i}$. In particular, the passport should not be in another country's consulate for visa processing.
Help Gleb to decide which visas he needs to receive in which passport, and when he should apply for each visa.
|
Let's solve the $P = 1$ case first. We'll use dynamic programming on subsets. Let's try to add visas to subset in order of application. Notice that if we only have one passport, every visa processing segment should lie between some two consecutive trips. For convenience, let's find all these segments beforehand. Define $dp[A]$ as the minimum day, before which all visas from set $A$ can be acquired. Try all possible $i$ as a visa which Gleb will apply for next. Now we have to find minimum possible day of application $d$, such that $d \ge dp[A]$, segment $[d, d + t_{i}]$ does not intersect with any trip, and $d + t_{i} < s_{i}$. Such $d$ can be found in $O(n)$ by a linear search over precalculated free segment. Relax the value of $d p[A\cup\{i\}]$ with $d + t_{i}$. If $dp[{1..n}] < + \infty $ then there is a solution that can be restored using standard techniques. Total time complexity is $O(2^{n} n^{2})$, that can be too slow for $n = 22$. Let's generalize this solution for $P = 2$. Still, Gleb can apply for a visa only when he is in Innopolis. However, the last day of visa processing can be during some trip, but only if all trips between the day of visa application and the day of visa acquisition use another passport. We will slightly change the definition of $dp[A]$: now this value is equal to the minimum possible day, by which it's possible to finish processing all visas from set $A$ with one passport, assuming all trips not from $A$ use another passport. By this definition, calculation of DP transition is a little bit different: when trying to add visa $i$ we have to find minimum $d$, such that $d \ge dp[A]$, during day $d$ Gleb is in Innopolis, and segment $[d, d + t_{i}]$ does not intersect with half-closed intervals $[s_{j}, s_{j} + len_{j})$ for all $j\in A$. This can be implemented similarly to the first part in $O(n)$. Total running time is $O(2^{n} n^{2})$, that can pass system tests with some optimizations. We'll optimize the solution down to $O(2^{n} n)$. To do that, we process all transition from set $A$ in $O(n)$ total time. Sort all visas in order of increasing $t_{i}$. Then the optimal visa application day $d$ will be increasing if visa processing time $t_{i}$ increases. Now we can apply two pointers technique to get $O(n)$ total processing time for one set and $O(2^{n} n)$ for all sets. After calculating $dp[A]$ for all subsets, we have to try all partitions of ${1..n}$ into two sets $A$ and $B$ and check if both $A$ and $B$ can be done with one passport each. This is equivalent to $dp[A] < + \infty $. If there are two such sets that $dp[A] < + \infty $ and $dp[B] < + \infty $, then we have found the answer, otherwise there is no answer.
|
[
"dp",
"implementation"
] | 3,400
| null |
1013
|
A
|
Piles With Stones
|
There is a beautiful garden of stones in Innopolis.
Its most beautiful place is the $n$ piles with stones numbered from $1$ to $n$.
EJOI participants have visited this place twice.
When they first visited it, the number of stones in piles was $x_1, x_2, \ldots, x_n$, correspondingly. One of the participants wrote down this sequence in a notebook.
They visited it again the following day, and the number of stones in piles was equal to $y_1, y_2, \ldots, y_n$. One of the participants also wrote it down in a notebook.
It is well known that every member of the EJOI jury during the night either sits in the room $108$ or comes to the place with stones. Each jury member who comes there either takes one stone for himself or moves one stone from one pile to another. We can assume that there is an unlimited number of jury members. No one except the jury goes to the place with stones at night.
Participants want to know whether their notes can be correct or they are sure to have made a mistake.
|
It can be simply showed that the answer is <<Yes>> if and only if the sum in the first visit is not less than the sum in the second visit.
|
[
"math"
] | 800
| null |
1013
|
B
|
And
|
There is an array with $n$ elements $a_{1}, a_{2}, ..., a_{n}$ and the number $x$.
In one operation you can select some $i$ ($1 ≤ i ≤ n$) and replace element $a_{i}$ with $a_{i} & x$, where $&$ denotes the bitwise and operation.
You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices $i ≠ j$ such that $a_{i} = a_{j}$. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
|
Clearly, if it is possible then there are no more than $2$ operations needed. So we basically need to distinguish $4$ outcomes - $- 1$, $0$, $1$ and $2$. The answer is zero if there are already equal elements in the array. To check if the answer is -1 we can apply the operation to each element of the array. If all elements are still distinct, then it couldn't be helped. To check if the answer is one we can bruteforce the element $a$ to apply the operation to, and if this operation changes this element, we can check if there is an $a & x$ element in the array. In all other cases answer is two.
|
[
"greedy"
] | 1,200
| null |
1015
|
A
|
Points in Segments
|
You are given a set of $n$ segments on the axis $Ox$, each segment has integer endpoints between $1$ and $m$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le m$) — coordinates of the left and of the right endpoints.
Consider all integer points between $1$ and $m$ inclusive. Your task is to print all such points that don't belong to any segment. The point $x$ belongs to the segment $[l; r]$ if and only if $l \le x \le r$.
|
In this problem all you need is to check for each point from $1$ to $m$ if it cannot belongs to any segment. It can be done in $O(n \cdot m)$ by two nested loops or in $O(n + m)$ by easy prefix sums calculation. Both solutions are below.
|
[
"implementation"
] | 800
|
n, m = map(int, input().split())
seg = [list(map(int, input().split())) for i in range(n)]
def bad(x):
for i in range(n):
if (seg[i][0] <= x and x <= seg[i][1]): return False
return True
ans = list(filter(bad, [i for i in range(1, m + 1)]))
print(len(ans))
print(' '.join([str(x) for x in ans]))
|
1015
|
B
|
Obtaining the String
|
You are given two strings $s$ and $t$. Both strings have length $n$ and consist of lowercase Latin letters. The characters in the strings are numbered from $1$ to $n$.
You can successively perform the following move any number of times (possibly, zero):
- swap any two adjacent (neighboring) characters of $s$ (i.e. for any $i = \{1, 2, \dots, n - 1\}$ you can swap $s_i$ and $s_{i + 1})$.
You can't apply a move to the string $t$. The moves are applied to the string $s$ one after another.
Your task is to obtain the string $t$ from the string $s$. Find any way to do it with at most $10^4$ such moves.
You do not have to minimize the number of moves, just find any sequence of moves of length $10^4$ or less to transform $s$ into $t$.
|
This problem can be solved using the next greedy approach: let's iterate over all $i$ from $1$ to $n$. If $s_i = t_i$, go further. Otherwise let's find any position $j > i$ such that $s_j = t_i$ and move the character from the position $j$ to the position $i$. If there is no such position in $s$, the answer is "-1". Upper bound on time complexity (and the size of the answer) of this solution is $O(n^2)$.
|
[
"implementation"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
string s, t;
cin >> n >> s >> t;
vector<int> ans;
for (int i = 0; i < n; ++i) {
if (s[i] == t[i]) continue;
int pos = -1;
for (int j = i + 1; j < n; ++j) {
if (s[j] == t[i]) {
pos = j;
break;
}
}
if (pos == -1) {
cout << -1 << endl;
return 0;
}
for (int j = pos - 1; j >= i; --j) {
swap(s[j], s[j + 1]);
ans.push_back(j);
}
}
assert(s == t);
cout << ans.size() << endl;
for (auto it : ans) cout << it + 1 << " ";
cout << endl;
return 0;
}
|
1015
|
C
|
Songs Compression
|
Ivan has $n$ songs on his phone. The size of the $i$-th song is $a_i$ bytes. Ivan also has a flash drive which can hold at most $m$ bytes in total. Initially, his flash drive is empty.
Ivan wants to copy all $n$ songs to the flash drive. He can compress the songs. If he compresses the $i$-th song, the size of the $i$-th song reduces from $a_i$ to $b_i$ bytes ($b_i < a_i$).
Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $m$. He can compress any subset of the songs (not necessarily contiguous).
Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $m$).
If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.
|
If we will no compress songs, the sum of the sizes will be equal $\sum\limits_{i = 1}^{n} a_i$. Let it be $sum$. Now, if we will compress the $j$-th song, how do $sum$ will change? It will decrease by $a_j - b_j$. This suggests that the optimal way to compress the songs is the compress it in non-increasing order of $a_j - b_j$. Let's create the array $d$ of size $n$, where $d_j = a_j - b_j$. Let's sort it in non-increasing order, and then iterate over all $j$ from $1$ to $n$. If at the current step $sum \le m$, we print $j - 1$ and terminate the program. Otherwise we set $sum := sum - d_j$. After all we have to check again if $sum \le m$ then print $n$ otherwise print "-1". Time complexity is $O(n \log n)$ because of sorting.
|
[
"sortings"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m;
cin >> n >> m;
vector<pair<int, int>> a(n);
long long sum = 0;
for (int i = 0; i < n; ++i) {
cin >> a[i].first >> a[i].second;
sum += a[i].first;
}
sort(a.begin(), a.end(), [&](pair<int, int> a, pair<int, int> b) { return a.first - a.second > b.first - b.second; });
for (int i = 0; i < n; ++i) {
if (sum <= m) {
cout << i << endl;
return 0;
}
sum -= a[i].first - a[i].second;
}
if (sum <= m)
cout << n << endl;
else
cout << -1 << endl;
return 0;
}
|
1015
|
D
|
Walking Between Houses
|
There are $n$ houses in a row. They are numbered from $1$ to $n$ in order from left to right. Initially you are in the house $1$.
You have to perform $k$ moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house $x$ to the house $y$, the total distance you walked increases by $|x-y|$ units of distance, where $|a|$ is the absolute value of $a$. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).
Your goal is to walk exactly $s$ units of distance in total.
If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly $k$ moves.
|
The solution for this problem is very simple: at first, if $k > s$ or $k \cdot (n - 1) < s$ the answer is "NO". Otherwise let's do the following thing $k$ times: let $dist$ be $min(n - 1, s - k + 1)$ (we have to greedily decrease the remaining distance but we also should remember about the number of moves which we need to perform). We have to walk to any possible house which is located at distance $dist$ from the current house (also don't forget to subtract $dist$ from $s$). The proof of the fact that we can always walk to the house at distance $dist$ is very simple: one of the possible answers (which is obtained by the algorithm above) will looks like several moves of distance $n-1$, (possibly) one move of random distance less than $n-1$ and several moves of distance $1$. The first part of the answer can be obtained if we are stay near the leftmost or the rightmost house, second and third parts always can be obtained because distances we will walk in every of such moves is less than $n-1$. Time complexity is $O(k)$.
|
[
"constructive algorithms",
"greedy"
] | 1,600
|
def step(cur, x):
if(cur - x > 0):
return cur - x
else:
return cur + x
n, k, s = map(int, input().split())
cur = 1
if(k > s or k * (n - 1) < s):
print('NO')
else:
print('YES')
while(k > 0):
l = min(n - 1, s - (k - 1))
cur = step(cur, l)
print(cur, end = ' ')
s -= l
k -= 1
|
1015
|
E1
|
Stars Drawing (Easy Edition)
|
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $0$ are not allowed).
Let's consider empty cells are denoted by '.', then the following figures are stars:
\begin{center}
{\small The leftmost figure is a star of size $1$, the middle figure is a star of size $2$ and the rightmost figure is a star of size $3$.}
\end{center}
You are given a rectangular grid of size $n \times m$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $1$ to $n$, columns are numbered from $1$ to $m$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $n \cdot m$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.
In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $n \cdot m$ stars.
|
Since we are almost unlimited in the number of stars in the answer, the following solution will works. We iterate over all possible stars centers and try to extend rays of the current star as large as possible. It can be done by the simple iterating and checking in $O(n)$. If the size of the current star is non-zero, let's add it to the answer. It is obvious that the number of stars in such answer will not exceed $n \cdot m$. Then let's try to draw all these stars on the empty grid. Drawing of each star is also can be done in $O(n)$. If after drawing our grid equals to the input grid, the answer is "YES" and our set of stars is the correct answer. Otherwise the answer is "NO". Time complexity: $O(n^3)$.
|
[
"brute force",
"dp",
"greedy"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
const int N = 1001;
int n, m;
vector<string> f;
int d[N][N][4];
int r[N][N], a[N][N], b[N][N];
int getd(int i, int j, int k) {
int dxk = dx[k];
int dyk = dy[k];
int result = 0;
while (i >= 0 && i < n && j >= 0 && j < m && f[i][j] == '*')
result++, i += dxk, j += dyk;
return result;
}
int main() {
cin >> n >> m;
f = vector<string>(n);
forn(i, n)
cin >> f[i];
memset(d, -1, sizeof(d));
int result = 0;
for (int i = 1; i + 1 < n; i++)
for (int j = 1; j + 1 < m; j++)
if (f[i][j] == '*') {
bool around = true;
forn(k, 4)
around = around && (f[i + dx[k]][j + dy[k]] == '*');
if (around) {
r[i][j] = INT_MAX;
forn(k, 4)
r[i][j] = min(r[i][j], getd(i, j, k) - 1);
result++;
a[i][j - r[i][j]] = max(a[i][j - r[i][j]], 2 * r[i][j] + 1);
b[i - r[i][j]][j] = max(b[i - r[i][j]][j], 2 * r[i][j] + 1);
}
}
vector<string> g(n, string(m, '.'));
forn(i, n) {
int v = 0;
forn(j, m) {
v = max(v - 1, a[i][j]);
if (v > 0)
g[i][j] = '*';
}
}
forn(j, m) {
int v = 0;
forn(i, n) {
v = max(v - 1, b[i][j]);
if (v > 0)
g[i][j] = '*';
}
}
if (f == g) {
cout << result << endl;
forn(i, n)
forn(j, m)
if (r[i][j] > 0)
cout << i + 1 << " " << j + 1 << " " << r[i][j] << endl;
} else
cout << -1 << endl;
}
|
1015
|
E2
|
Stars Drawing (Hard Edition)
|
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $0$ are not allowed).
Let's consider empty cells are denoted by '.', then the following figures are stars:
\begin{center}
{\small The leftmost figure is a star of size $1$, the middle figure is a star of size $2$ and the rightmost figure is a star of size $3$.}
\end{center}
You are given a rectangular grid of size $n \times m$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $1$ to $n$, columns are numbered from $1$ to $m$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $n \cdot m$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.
In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $n \cdot m$ stars.
|
I am sorry that some $O(n^3)$ solutions pass tests in this problem also. I was supposed to increase constraints or decrease time limit. The general idea of this problem is the same as in the previous problem. But now we should do all what we were doing earlier faster. The solution is divided by two parts. The first part. Let's calculate four matrices of size $n \times m$ - $up$, $down$, $left$ and $right$. $up_{i, j}$ will denote the distance to the nearest dot character to the top from the current position. The same, $down_{i, j}$ will denote the distance to the nearest dot character to the bottom from the current position, $left_{i, j}$ - to the left and $right_{i, j}$ - to the right. We can calculate all these matrices in $O(n^2)$ using easy dynamic programming. If we will iterate over all possible $i$ from $1$ to $n$ and $j$ from $1$ to $m$, we can easy see the next: if the current character is dot, then $up_{i, j} = left_{i, j} = 0$. Otherwise if $i > 1$ then $up_{i, j} = up_{i - 1, j}$, and if $j > 1$ then $left_{i, j} = left_{i, j - 1}$. Rest two matrices can be calculated the as well as these two matrices but we should iterate over all $i$ from $n$ to $1$ and $j$ from $m$ to $1$. So, this part of the solution works in $O(n^2)$. After calculating all these matrices the maximum possible length of rays of the star with center in position $(i, j)$ is $min(up_{i, j}, down_{i, j}, left_{i, j}, right_{i, j}) - 1$. The second part is to draw all stars in $O(n^2)$. Let's calculate another two matrices of size $n \times m$ - $h$ and $v$. Let's iterate over all stars in our answer. Let the center of the current star is $(i, j)$ and its size is $s$. Let's increase $h_{i, j - s}$ by one and decrease $h_{i, j + s + 1}$ by one (if $j + s + 1 \le m$). The same with the matrix $v$. Increase $v_{i - s, j}$ and decrease $v_{i + s + 1, j}$ (if $i + s + 1 \le n$). Then let's iterate over all possible $i$ from $1$ to $n$ and $j$ from $1$ to $m$. If $i > 1$ then set $v_{i, j} := v_{i, j} + v_{i - 1, j}$ and if $j > 1$ set $h_{i, j} := h_{i, j} + h_{i, j - 1}$. How to know that the character at the position $(i, j)$ is asterisk character or dot character? If either $h_{i, j}$ or $v_{i, j}$ greater than zero, then the character at the position $(i, j)$ in our matrix will be the asterisk character. Otherwise it is the dot character. This part works also in $O(n^2)$. Time complexity of the solution: $O(n^2)$.
|
[
"binary search",
"dp",
"greedy"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<string> s;
vector<string> draw(const vector<pair<pair<int, int>, int>> &r) {
vector<string> f(n, string(m, '.'));
vector<vector<int>> h(n, vector<int>(m));
vector<vector<int>> v(n, vector<int>(m));
for (auto it : r) {
int x = it.first.first;
int y = it.first.second;
int len = it.second;
++v[x - len][y];
if (x + len + 1 < n)
--v[x + len + 1][y];
++h[x][y - len];
if (y + len + 1 < m)
--h[x][y + len + 1];
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (i > 0) v[i][j] += v[i - 1][j];
if (j > 0) h[i][j] += h[i][j - 1];
if (v[i][j] > 0 || h[i][j] > 0)
f[i][j] = '*';
}
}
return f;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> m;
s = vector<string>(n);
for (int i = 0; i < n; ++i) {
cin >> s[i];
}
vector<vector<int>> l(n, vector<int>(m));
vector<vector<int>> r(n, vector<int>(m));
vector<vector<int>> u(n, vector<int>(m));
vector<vector<int>> d(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (i > 0) {
if (s[i][j] != '.')
u[i][j] = u[i - 1][j] + 1;
} else {
u[i][j] = s[i][j] != '.';
}
if (j > 0) {
if (s[i][j] != '.')
l[i][j] = l[i][j - 1] + 1;
} else {
l[i][j] = s[i][j] != '.';
}
}
}
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
if (i < n - 1) {
if (s[i][j] != '.')
d[i][j] = d[i + 1][j] + 1;
} else {
d[i][j] = s[i][j] != '.';
}
if (j < m - 1) {
if (s[i][j] != '.')
r[i][j] = r[i][j + 1] + 1;
} else {
r[i][j] = s[i][j] != '.';
}
}
}
vector<pair<pair<int, int>, int>> ans;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (s[i][j] == '*') {
int len = min(min(u[i][j], l[i][j]), min(d[i][j], r[i][j])) - 1;
if (len != 0) {
ans.push_back(make_pair(make_pair(i, j), len));
}
}
}
}
if (draw(ans) != s) {
cout << -1 << endl;
} else {
cout << ans.size() << endl;
for (auto it : ans) {
cout << it.first.first + 1 << " " << it.first.second + 1 << " " << it.second << endl;
}
}
return 0;
}
|
1015
|
F
|
Bracket Substring
|
You are given a bracket sequence $s$ (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Your problem is to calculate the number of regular bracket sequences of length $2n$ containing the given bracket sequence $s$ as a substring (consecutive sequence of characters) modulo $10^9+7$ ($1000000007$).
|
At first, let's calculate the matrix $len$ of size $(n + 1) \times 2$. Let $len_{i, j}$ will denote the maximum length of the prefix of $s$ which equals to the suffix of the prefix of $s$ of length $i$ with the additional character '(' if $j = 0$ and ')' otherwise. In other words, $len_{i, j}$ is denote which maximum length of the prefix of $s$ we can reach if now we have the prefix of $s$ of length $i$ and want to add the character '(' if $j = 0$ and ')' otherwise, and only one possible move is to remove characters from the beginning of this prefix with an additional character. This matrix can be easily calculated in $O(n^3)$ without any dynamic programming. It can be also calculated in $O(n)$ using prefix-function and dynamic programming. Now let's calculate the following dynamic programming $dp_{i, j, k, l}$. It means that now we have gained $i$ characters of the regular bracket sequence, the balance of this sequence is $j$, the last $k$ characters of the gained prefix is the prefix of $s$ of length $k$ and $l$ equals to $1$ if we obtain the full string $s$ at least once and $0$ otherwise. The stored value of the $dp_{i, j, k, l}$ is the number of ways to reach this state. Initially, $dp_{0, 0, 0, 0} = 1$, all other values equal $0$. The following recurrence works: try to add to the current prefix character '(' if the current balance is less than $n$, then we will move to the state $dp{i + 1, j + 1, len_{k, 0}, f~ |~ (len_{k, 0} = |s|)}$. $|s|$ is the length of $s$ and $|$ is OR operation (if at least one is true then the result is true). Let's add to the number of ways to reach the destination state the number of ways to reach the current state. The same with the character ')'. Try to add to the current prefix character ')' if the current balance is greater than $0$, then we will move to the state $dp{i + 1, j - 1, len_{k, 1}, f~ |~ (len_{k, 1} = |s|)}$. Also add to the number of ways to reach the destination state the number of ways to reach the current state. After calculating this dynamic programming, the answer is $\sum\limits_{i = 0}^{|s|} dp_{2n, 0, i, 1}$. Time complexity is $O(n^3)$.
|
[
"dp",
"strings"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
const int N = 203;
const int MOD = 1e9 + 7;
int n, ssz;
string s;
int len[N][2];
int dp[N][N][N][2];
int calc(const string &t) {
int tsz = t.size();
for (int i = tsz; i > 0; --i) {
if (s.substr(0, i) == t.substr(tsz - i, i))
return i;
}
return 0;
}
void add(int &a, int b) {
a += b;
if (a >= MOD)
a -= MOD;
if (a < 0)
a += MOD;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> s;
ssz = s.size();
if (s[0] == '(')
len[0][0] = 1;
else
len[0][1] = 1;
string pref;
for (int i = 0; i < ssz; ++i) {
pref += s[i];
pref += '(';
len[i + 1][0] = calc(pref);
pref.pop_back();
pref += ')';
len[i + 1][1] = calc(pref);
pref.pop_back();
}
dp[0][0][0][0] = 1;
for (int i = 0; i < 2 * n; ++i) {
for (int j = 0; j <= n; ++j) {
for (int pos = 0; pos <= ssz; ++pos) {
for (int f = 0; f < 2; ++f) {
if (dp[i][j][pos][f] == 0) continue;
if (j + 1 <= n)
add(dp[i + 1][j + 1][len[pos][0]][f | (len[pos][0] == ssz)], dp[i][j][pos][f]);
if (j > 0)
add(dp[i + 1][j - 1][len[pos][1]][f | (len[pos][1] == ssz)], dp[i][j][pos][f]);
}
}
}
}
int ans = 0;
for (int i = 0; i <= ssz; ++i)
add(ans, dp[2 * n][0][i][1]);
cout << ans << endl;
return 0;
}
|
1016
|
A
|
Death Note
|
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $n$ consecutive days. During the $i$-th day you have to write exactly $a_i$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).
Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $m$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.
Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $1$ to $n$.
|
In this problem all we need is to maintain the variable $res$ which will represent the number of names written on the current page. Initially this number equals zero. The answer for the $i$-th day equals $\lfloor\frac{res + a_i}{m}\rfloor$. This value represents the number of full pages we will write during the $i$-th day. After the answering we need to set $res := (res + a_i) \% m$, where operation $x \% y$ is taking $x$ modulo $y$.
|
[
"greedy",
"implementation",
"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 n, m;
cin >> n >> m;
int r = 0;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
r += x;
cout << r / m << ' ';
r %= m;
}
cout << '\n';
return 0;
}
|
1016
|
B
|
Segment Occurrences
|
You are given two strings $s$ and $t$, both consisting only of lowercase Latin letters.
The substring $s[l..r]$ is the string which is obtained by taking characters $s_l, s_{l + 1}, \dots, s_r$ without changing the order.
Each of the occurrences of string $a$ in a string $b$ is a position $i$ ($1 \le i \le |b| - |a| + 1$) such that $b[i..i + |a| - 1] = a$ ($|a|$ is the length of string $a$).
You are asked $q$ queries: for the $i$-th query you are required to calculate the number of occurrences of string $t$ in a substring $s[l_i..r_i]$.
|
Let's take a look at a naive approach: for each query $[l, r]$ you iterate over positions $i \in [l, r - |m| + 1]$ and check if $s[i, i + |m| - 1] = t$. Okay, this is obviously $O(q \cdot n \cdot m)$. Now we notice that there are only $O(n)$ positions for $t$ to start from, we can calculate if there is an occurrence of $t$ starting in this position beforehand in $O(n \cdot m)$. Thus, we transition to $O(q \cdot n)$ solution. Finally, we calculate a partial sum array over this occurrence check array and answer each query in $O(1)$. Overall complexity: $O(n \cdot m + q)$.
|
[
"brute force",
"implementation"
] | 1,300
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 1000 + 7;
int pr[N];
bool ok[N];
int main() {
int n, m, q;
scanf("%d%d%d", &n, &m, &q);
string s, t;
static char buf[N];
scanf("%s", buf);
s = buf;
scanf("%s", buf);
t = buf;
pr[0] = 0;
forn(i, n - m + 1){
bool fl = true;
forn(j, m)
if (s[i + j] != t[j])
fl = false;
ok[i] = fl;
pr[i + 1] = pr[i] + ok[i];
}
for (int i = max(0, n - m + 1); i < n; ++i){
pr[i + 1] = pr[i];
}
forn(i, q){
int l, r;
scanf("%d%d", &l, &r);
--l, r -= m - 1;
printf("%d\n", r >= l ? pr[r] - pr[l] : 0);
}
return 0;
}
|
1016
|
C
|
Vasya And The Mushrooms
|
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into $n$ consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.
Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells \textbf{exactly once} and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of $0$. Note that Vasya doesn't need to return to the starting cell.
Help Vasya! Calculate the maximum total weight of mushrooms he can collect.
|
A route visiting each cell exactly once can always be denoted as follows: several (possibly zero) first columns of the glade are visited in a zigzag pattern, then Vasya goes to the right until the end of the glade, makes one step up or down and goes left until he visits all remaining cells: There are $n - 1$ such routes. To calculate the weight of collected mushrooms quickly, we will precompute three arrays for the first row of the glade - $sum123, sum321$ and $sum111$. $sum123$ will be used to compute the weight of mushrooms collected when Vasya moves to the right until the last column of the glade, $sum321$ - when Vasya moves to the left from the last column, and $sum111$ - to handle the growth of mushrooms. $s u m123_{i}=\sum_{k=i}^{n}a_{i}\cdot k$ $s u m321_{i}=\sum_{k=i}^{n}a_{i}\cdot(n-k+1)$ $s u m11_{i}=\sum_{k=i}^{n}a_{i}$ Also we have to compute the same arrays for the second row of the glade. Let's iterate on the number of columns Vasya will pass in a zigzag pattern and maintain the weight of mushrooms he will collect while doing so. Then we have to add the weight of the mushrooms Vasya will gather while moving to the right, and then - while moving to the left. The first can be handled by arrays $sum123$ and $sum111$, the second - by arrays $sum321$ and $sum111$.
|
[
"dp",
"implementation"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
const int N = 300 * 1000 + 9;
int n;
int a[2][N];
long long sum123[2][N];
long long sum321[2][N];
long long sum111[2][N];
int main() {
//freopen("input.txt", "r", stdin);
scanf("%d", &n);
for(int i = 0; i < 2; ++i)
for(int j = 0; j < n; ++j)
scanf("%d", &a[i][j]);
for(int i = 0; i < 2; ++i)
for(int j = n - 1; j >= 0; --j){
sum123[i][j] = sum123[i][j + 1] + (j + 1) * 1LL * a[i][j];
sum321[i][j] = sum321[i][j + 1] + (n - j) * 1LL * a[i][j];
sum111[i][j] = sum111[i][j + 1] + a[i][j];
}
/* for(int i = 0; i < 2; ++i)
for(int j = n - 1; j >= 0; --j){
cout << i << ' ' << j << " : ";
cout << sum123[i][j] << " " << sum321[i][j] << " " << sum111[i][j] << endl;
} */
long long res = 0, sum = 0;
for(int i = 0, j = 0; j < n; ++j, i ^= 1){
long long nres = sum;
nres += sum123[i][j] + j * 1LL * sum111[i][j];
nres += sum321[i ^ 1][j] + (j + n) * 1LL * sum111[i ^ 1][j];
res = max(res, nres);
sum += a[i][j] * 1ll * (j + j + 1);
sum += a[i ^ 1][j] * 1ll * (j + j + 2);
}
for(int j = 0; j < n; ++j) res -= a[0][j] + a[1][j];
printf("%I64d\n", res);
return 0;
}
|
1016
|
D
|
Vasya And The Matrix
|
Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!
Vasya knows that the matrix consists of $n$ rows and $m$ columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence $a_{1}, a_{2}, ..., a_{n}$ denotes the xor of elements in rows with indices $1$, $2$, ..., $n$, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence $b_{1}, b_{2}, ..., b_{m}$ denotes the xor of elements in columns with indices $1$, $2$, ..., $m$, respectively.
Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.
|
If $a_{1}\oplus a_{2}\oplus\cdot\cdot\cdot\oplus a_{n}\neq b_{1}\oplus b_{2}\oplus\cdot\cdot\cdot\oplus b_{m}$, then there is no suitable matrix. The operation $\mathbb{C}$ means xor. Otherwise, we can always construct a suitable matrix by the following method: the first element of the first line will be equal to $a_{1}\oplus b_{2}\oplus b_{3}\oplus\cdot\cdot\Leftrightarrow b_{m}$. The second element of the first line is $b_{2}$, the third element is $b_{3}$, the last one is $b_{m}$. The first element of the second line will be $a_{2}$, the first element of the third line is $a_{3}$, the first element of the last line is $a_{n}$. The rest of the elements will be zero. It is not difficult to verify that the matrix obtained satisfies all the restrictions.
|
[
"constructive algorithms",
"flows",
"math"
] | 1,800
|
#include <bits/stdc++.h>
#include "testlib.h"
using namespace std;
const int N = 109;
int n, m;
int a[N], b[N];
int res[N][N];
int main() {
int cur = 0;
cin >> n >> m;
for(int i = 0; i < n; ++i)
cin >> a[i], cur ^= a[i];
for(int i = 0; i < m; ++i)
cin >> b[i], cur ^= b[i];
if(cur != 0){
puts("NO");
return 0;
}
puts("YES");
for(int i = 1; i < m; ++i)
cur ^= b[i];
cur ^= a[0];
cout << cur << ' ';
for(int i = 1; i < m; ++i)
cout << b[i] << ' ';
cout << endl;
for(int i = 1; i < n; ++i){
cout << a[i] << ' ';
for(int j = 1; j < m; ++j)
cout << 0 << ' ';
cout << endl;
}
return 0;
}
|
1016
|
E
|
Rest In The Shades
|
There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point $(a, s_y)$ to the $(b, s_y)$ $(s_y < 0)$ with speed equal to $1$ unit per second. The trajectory of this light source is a straight segment connecting these two points.
There is also a fence on $OX$ axis represented as $n$ segments $(l_i, r_i)$ (so the actual coordinates of endpoints of each segment are $(l_i, 0)$ and $(r_i, 0)$). The point $(x, y)$ is in the shade if segment connecting $(x,y)$ and the current position of the light source intersects or touches with any segment of the fence.
You are given $q$ points. For each point calculate total time of this point being in the shade, while the light source is moving from $(a, s_y)$ to the $(b, s_y)$.
|
Let's calculate the answer for a fixed point $P$. If you project with respect of $P$ each segment of the fence to the line containing light source you can see that the answer is the length of intersection of fence projection with segment $(A, B)$ of the trajectory light source. Key idea is the fact that the length of each fence segment is multiplied by the same coefficient $k = \frac{P_y + |s_y|}{P_y}$. On the other hand, fence segments whose projections lie inside $(A, B)$ form a subsegment in the array of segments, so its total length can be obtained with partial sums. And at most two fence segment are included in the answer partially, their positions can be calculated with lower_bound if you project points $A$ and $B$ on $OX$ axis. So now you can answer the query with $O(\log{n})$ time (and quite small hidden constant) and resulting complexity is $O(n + q \log{n})$.
|
[
"binary search",
"geometry"
] | 2,400
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define x first
#define y second
typedef long long li;
typedef long double ld;
typedef pair<li, li> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
const double EPS = 1e-9;
const int N = 200 * 1000 + 555;
li sy, a, b;
int n, q;
pt s[N], p[N];
inline bool read() {
if(!(cin >> sy >> a >> b))
return false;
assert(cin >> n);
fore(i, 0, n)
assert(scanf("%lld%lld", &s[i].x, &s[i].y) == 2);
assert(cin >> q);
fore(i, 0, q)
assert(scanf("%lld%lld", &p[i].x, &p[i].y) == 2);
return true;
}
int getGE(ld x) {
for(int pos = max(int(lower_bound(s, s + n, pt(li(x), -1)) - s) - 2, 0); pos < n; pos++)
if(x <= s[pos].x)
return pos;
return n;
}
li ps[N];
li getSum(int l, int r) {
li ans = r > 0 ? ps[r - 1] : 0;
ans -= l > 0 ? ps[l - 1] : 0;
return ans;
}
inline void solve() {
fore(i, 0, n) {
ps[i] = s[i].y - s[i].x;
if(i > 0)
ps[i] += ps[i - 1];
}
fore(i, 0, q) {
ld lx = p[i].x + (a - p[i].x) * (ld(p[i].y) / (p[i].y - sy));
ld rx = p[i].x + (b - p[i].x) * (ld(p[i].y) / (p[i].y - sy));
int posL = getGE(lx);
int posR = getGE(rx) - 1;
ld sum = getSum(posL, posR);
if(posL > 0)
sum += max(ld(0.0), s[posL - 1].y - max((ld)s[posL - 1].x, lx));
if(posR >= 0)
sum += max(ld(0.0), min((ld)s[posR].y, rx) - s[posR].x);
sum *= ld(p[i].y - sy) / p[i].y;
printf("%.15f\n", double(sum));
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1016
|
F
|
Road Projects
|
There are $n$ cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from $1$ to $n$.
The travelling time between some cities $v$ and $u$ is the total length of the roads on the shortest path from $v$ to $u$.
The two most important cities in Berland are cities $1$ and $n$.
The Berland Ministry of Transport decided to build a single new road to decrease the traffic between the most important cities. However, lots of people are used to the current travelling time between the most important cities, so the new road shouldn't change it too much.
The new road can only be built between such cities $v$ and $u$ that $v \neq u$ and $v$ and $u$ aren't already connected by some road.
They came up with $m$ possible projects. Each project is just the length $x$ of the new road.
Polycarp works as a head analyst at the Berland Ministry of Transport and it's his job to deal with all those $m$ projects. For the $i$-th project he is required to choose some cities $v$ and $u$ to build the new road of length $x_i$ between such that the travelling time between the most important cities is \textbf{maximal possible}.
Unfortunately, Polycarp is not a programmer and no analyst in the world is capable to process all projects using only pen and paper.
Thus, he asks you to help him to calculate the maximal possible travelling time between the most important cities for each project. Note that the choice of $v$ and $u$ can differ for different projects.
|
The first solution (editorial by PikMike) Firtsly, we can notice that we get the most profit by placing the edge in a same position, no matter the query. Moreover, once you have calculated the minimum difference you can apply to the shortest path $dif_{min}$ by adding edge of the weight $0$, you can answer the queries in $O(1)$ each. Let the current shortest distance between $1$ and $n$ be $curd$. Then the answer to some query $x$ is $min(curd, curd - mind + x)$. Let's proceed to proofs of the following. Consider any of the optimal positions for the edge of weight $0$. Then weight $1$ will add $1$ to the answer in this position (if the path isn't $curd$ already but that is trivial). Let there be another position such that the answer in it is less than the current one. That means that the answer for weight $0$ in it is less by $1$ which is smaller than the first one we got, which leads to contradiction. The second fact can deduced from the first one. Then let me introduce the next bold statement. We root the tree with vertex $1$. Then if there exists such a vertex in that it's not an ancestor of vertex $n$ and the number of vertices in its subtree (inclusive) is greater than $1$ then $dif_{min} = 0$. That is simple: just put the edge between the parent of this vertex and any of vertices of the subtree, there always be such that the edge doesn't exist yet. That won't change the shortest path, no matter which $x$ it is. Then, we have a graph of the following kind: That is the simple path between $1$ and $n$ and some vetices on it have additional children leaves. Finally, let's proceed to the solution. We want to choose such a pair of vertices that the sum of edge on a path between them, which are also a part of the path between $1$ and $n$ plus the weights of the newly included to shortest path edges (if any) is minimal possible. Let's precalc $d_v$ - the sum of weights of edges from vertex $1$ to vertex $v$ and $p_v$ - parent of vertex $v$. Let $w(v, u)$ be the weight of an edge between $v$ and $u$. Then we end up with the four basic cases for these vertices $v$ and $u$ with $v$ having greater or equal number of edges on path to $1$ than $u$: each of the form (whether $v$ belongs to the simple path between $1$ and $n$, whether $u$ belongs to it). $u$ doesn't belong: the answer is $d_v + w(p_u, u) - d[p_u]$; $u$ belongs, $v$ doesn't: $d_u + w(p_v, v) - d[p_v]$; both belongs: $d_v - d_u$. Each of these formulas can be broken down to parts with exacly one of the vertices. Let's call them $pt_v$ and $pt_u$. That means minimizing the result is be the same as minimizing each of the parts. We run depth-first search on vertices which belong to a simple path between $1$ and $n$ inclusive. Maintain the minimum value of $pt_u$ you have already passed by. Try connecting each vertex with this $u$ and also parent of the parent of the current vertex using all the possible formulas and updating $dif_{min}$ with the resulting value. Finally, after the precalc is finished, asnwer the queries in $O(1)$ with $dif_{min}$. Overall complexity: $O(n + q)$. The second solution (editorial by BledDest) Let's denote the distance from vertex $1$ to vertex $x$ in the tree as $d_1(x)$. Similarly, denote the distance from $n$ to $x$ in the tree as $d_n(x)$. Suppose we try to add a new edge between vertices $x$ and $y$ with length $w$. Then two new paths from $1$ to $n$ are formed: one with length $d_1(x) + w + d_n(y)$, and another with length $d_1(y) + w + d_n(x)$. Then the new length of shortest path becomes $min(d_1(n), d_1(x) + w + d_n(y), d_1(y) + w + d_n(x))$. So if we find two non-adjacent vertices such that $min(d_1(x) + d_n(y), d_1(y) + d_n(x))$ is maximum possible, then it will always be optimal to add an edge between these two vertices. How can we find this pair of vertices? Firstly, let's suppose that $d_1(x) + d_n(y) \le d_1(y) + d_n(x)$ - when we pick vertex $x$, we will try to pair it only with vertices $y$ corresponding to the aforementioned constraint. This can be done by sorting vertices by the value of $d_1(x) - d_n(x)$ and then for each vertex $x$ pairing it only with vertices that are later than $x$ in the sorted order. How do we find the best pair for $x$? The best pair could be just the vertex with maximum possible $d_n(y)$, but it is not allowed to connect a vertex with itself or its neighbour. To handle it, we may maintain a set of possible vertices $y$, delete all neighbours of $x$ from it, pick a vertex with maximum $d_n$, and then insert all neighbours of $x$ back into the set. This solution works in $O(n \log n + q)$ time.
|
[
"dfs and similar",
"dp",
"trees"
] | 2,600
|
#include<bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > g;
vector<long long> d;
vector<long long> d1;
vector<long long> dn;
int n, q;
bool read()
{
scanf("%d %d", &n, &q);
g.resize(n);
d.resize(n);
for(int i = 0; i < n - 1; i++)
{
int x, y, w;
scanf("%d %d %d", &x, &y, &w);
--x;
--y;
g[x].push_back(make_pair(y, w));
g[y].push_back(make_pair(x, w));
}
return true;
}
void dfs(int x, int p = -1, long long dist = 0)
{
d[x] = dist;
for (auto e : g[x])
if (p != e.first)
dfs(e.first, x, e.second + dist);
}
void solve()
{
dfs(0);
d1 = d;
dfs(n - 1);
dn = d;
set<pair<long long, int> > dists_n;
vector<pair<long long, int> > order;
for(int i = 0; i < n; i++)
order.push_back(make_pair(d1[i] - dn[i], i));
sort(order.begin(), order.end());
for(int i = 0; i < n; i++)
dists_n.insert(make_pair(dn[i], i));
vector<int> pos(n);
for(int i = 0; i < n; i++)
pos[order[i].second] = i;
long long T = (long long)(1e18);
for(int i = 0; i < n; i++)
{
int v = order[i].second;
dists_n.erase(make_pair(dn[v], v));
for (auto e : g[v])
if (pos[e.first] > pos[v])
dists_n.erase(make_pair(dn[e.first], e.first));
if (!dists_n.empty())
T = min(T, d1[n - 1] - d1[v] - dists_n.rbegin()->first);
for (auto e : g[v])
if (pos[e.first] > pos[v])
dists_n.insert(make_pair(dn[e.first], e.first));
}
for(int i = 0; i < q; i++)
{
int x;
scanf("%d", &x);
printf("%lld\n", d1[n - 1] - max(0ll, T - x));
}
}
int main()
{
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
if (read())
{
solve();
}
}
|
1016
|
G
|
Appropriate Team
|
Since next season are coming, you'd like to form a team from two or three participants. There are $n$ candidates, the $i$-th candidate has rank $a_i$. But you have weird requirements for your teammates: if you have rank $v$ and have chosen the $i$-th and $j$-th candidate, then $GCD(v, a_i) = X$ and $LCM(v, a_j) = Y$ must be met.
You are very experienced, so you can change your rank to any non-negative integer but $X$ and $Y$ are tied with your birthdate, so they are fixed.
Now you want to know, how many are there pairs $(i, j)$ such that there exists an integer $v$ meeting the following constraints: $GCD(v, a_i) = X$ and $LCM(v, a_j) = Y$. It's possible that $i = j$ and you form a team of two.
$GCD$ is the greatest common divisor of two number, $LCM$ — the least common multiple.
|
At first, $X \mid Y$ must be met (since $X \mid v$ and $v \mid Y$). Now let $Y = p_1^{py_1} p_2^{py_2} \dots p_z^{py_z}$ and $X = p_1^{px_1} p_2^{px_2} \dots p_z^{px_z}$. From now on let's consider only $p_k$ such that $px_k < py_k$. Now let's look at $a_i$: $X \mid a_i$ must be met. Let $a_i = p_1^{pa_1} p_2^{pa_2} \dots p_l^{pa_l} \cdot a'$. Since $GCD(v, a_i) = X$, if $pa_k > px_k$ then $v$ must have $p_k$ to the power of $px_k$ in its factorization; otherwise power of $p_k$ can be any non-negative integer $\ge px_k$. It leads us to the bitmask of restrictions $min_i$ ($min_i[k] = (pa_k > px_k)$) with size equal to the number of different prime divisors of $Y$. In the same way let's process $a_j$. Of course, $a_j \mid Y$ and if $pa_k < py_k$ then $v$ must have $p_k$ to the power of $py_k$ in its factorization. This is another restriction bitmask $max_j$ ($max_j[k] = (pa_k < py_k)$). So, for any pair $(i, j)$ there exists $v$ if and only if $min_i\ \text{AND}\ max_j = 0$. Since we look only at $p_k$ where $px_k < py_k$ then $v$ can't have power of $p_k$ equal to $px_k$ and $py_k$ at the same time. For any other $p$ it is enough to have power of $p$ in $v$ equal to the power of $p$ in $Y$ (even if it's equal to $0$). So, for each $max_j$ we need to know the number of $a_i$ such that $min_i$ is a submask of $\text{NOT}\ max_j$. So we just need to calculate sum of submasks for each mask; it can be done with $O(n\cdot 2^n)$ or $O(3^n)$. Finally, how to factorize number $A$ up to $10^{18}$. Of course, Pollard algorithm helps, but there is another way, which works sometimes. Let's factorize $A$ with primes up to $10^6$. So after that if $A > 1$ there is only three cases: $A = p$, $A = p^2$ or $A = p \cdot q$. $A = p^2$ is easy to check ($\text{sqrtl}$ helps). Otherwise, just check $GCD$ with all $a_i$, $X$ and $Y$: if you have found $GCD \neq 1$ and $GCD \neq A$, then $A = p \cdot q$ and you have found $p$. Otherwise you can assume that $A = p$, because this probable mistake doesn't break anything in this task. Result complexity is $O(A^{\frac{1}{3}} + n \log{A} + z \cdot 2^z)$ where $z$ is the number of prime divisors of $Y$ $(z \le 15)$.
|
[
"bitmasks",
"math",
"number theory"
] | 2,700
|
#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<li, li> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
const int N = 200 * 1000 + 555;
int n; li x, y;
li a[N];
inline bool read() {
if(!(cin >> n >> x >> y))
return false;
fore(i, 0, n)
assert(scanf("%lld", &a[i]) == 1);
return true;
}
li gcd(li a, li b) {
while(a > 0) {
b %= a;
swap(a, b);
}
return b;
}
vector<pt> factorize(li v) {
vector<pt> f;
for(li x = 2; x <= 1'000'000 && x * x <= v; x++) {
int cnt = 0;
while(v % x == 0)
v /= x, cnt++;
if(cnt > 0)
f.emplace_back(x, cnt);
}
if(v > 1) {
for(li s = max(1ll, (li)sqrtl(v) - 2); s * s <= v; s++)
if(s * s == v) {
f.emplace_back(s, 2);
v = 1;
break;
}
if(v > 1) {
vector<li> cnd(a, a + n);
cnd.push_back(x);
cnd.push_back(y);
for(li c : cnd) {
li g = gcd(v, c);
if(g != 1 && g != v) {
li a = g, b = v / g;
if(a > b)
swap(a, b);
f.emplace_back(a, 1);
f.emplace_back(b, 1);
v = 1;
break;
}
}
if(v > 1)
f.emplace_back(v, 1), v = 1;
}
}
return f;
}
int d[(1 << 18) + 3];
inline void solve() {
if(y % x != 0) {
puts("0");
return;
}
vector<pt> fy = factorize(y);
vector<pt> fx;
li cx = x;
for(auto p : fy) {
int cnt = 0;
while(cx % p.x == 0)
cx /= p.x, cnt++;
fx.emplace_back(p.x, cnt);
}
vector<li> ps;
vector<pt> bb;
fore(i, 0, sz(fy)) {
if(fx[i].y < fy[i].y) {
ps.push_back(fy[i].x);
bb.emplace_back(fx[i].y, fy[i].y);
}
}
fore(i, 0, n) {
if(a[i] % x != 0)
continue;
int mask = 0;
li ca = a[i];
fore(j, 0, sz(ps)) {
int cnt = 0;
while(ca % ps[j] == 0)
ca /= ps[j], cnt++;
assert(cnt >= bb[j].x);
mask |= (cnt > bb[j].x) << j;
}
d[mask]++;
}
for(int i = 0; i < sz(ps); i++) {
fore(mask, 0, 1 << sz(ps))
if((mask >> i) & 1)
d[mask] += d[mask ^ (1 << i)];
}
li ans = 0;
fore(i, 0, n) {
if(y % a[i] != 0)
continue;
int mask = 0;
li ca = a[i];
fore(j, 0, sz(ps)) {
int cnt = 0;
while(ca % ps[j] == 0)
ca /= ps[j], cnt++;
assert(cnt <= bb[j].y);
mask |= (cnt < bb[j].y) << j;
}
ans += d[mask ^ ((1 << sz(ps)) - 1)];
}
cout << ans << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1017
|
A
|
The Rank
|
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.
There are $n$ students, each of them has a \textbf{unique} id (from $1$ to $n$). Thomas's id is $1$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.
In the table, the students will be sorted by \textbf{decreasing} the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by \textbf{increasing} their ids.
Please help John find out the rank of his son.
|
For each student, add his/her $4$ scores together and count how many students have strictly lower scores than Thomas. Complexity: $O(n)$ or $O(n \log n)$.
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int a, b, c, d;
cin >> a >> b >> c >> d;
int S = a + b + c + d;
int Ans = 1;
for(int i = 2; i <= n; i++)
{
cin >> a >> b >> c >> d;
if(a + b + c + d > S)
{
Ans++;
}
}
printf("%d\n",Ans);
return 0;
}
|
1017
|
B
|
The Bits
|
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:
Given two binary numbers $a$ and $b$ of length $n$. How many different ways of swapping two digits in $a$ (only in $a$, not $b$) so that bitwise OR of these two numbers will be changed? In other words, let $c$ be the bitwise OR of $a$ and $b$, you need to find the number of ways of swapping two bits in $a$ so that bitwise OR will not be equal to $c$.
Note that binary numbers can contain leading zeros so that length of each number is exactly $n$.
Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $01010_2$ OR $10011_2$ = $11011_2$.
Well, to your surprise, you are not Rudolf, and you don't need to help him$\ldots$ You are the security staff! Please find the number of ways of swapping two bits in $a$ so that bitwise OR will be changed.
|
Let $t_{xy}$ be the number of indexes $i$ such that $a_i=x$ and $b_i=y$. The answer is $t_{00}\cdot t_{10} + t_{00}\cdot t_{11} + t_{01}\cdot t_{10}$.
|
[
"implementation",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
long long ar[4];
char c1[4] = {'0', '0', '1', '1'};
char c2[4] = {'0', '1', '0', '1'};
int main() {
int n;
cin >> n;
string a, b;
cin >> a >> b;
for(int i = 0; i < n; i++){
for(int j = 0; j < 4; j++){
if(c1[j] == a[i] && c2[j] == b[i]){
ar[j]++;
}
}
}
cout << ar[0] * ar[2] + ar[0] * ar[3] + ar[1] * ar[2] << endl;
return 0;
}
|
1017
|
C
|
The Phone Number
|
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of $n$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ where $1\leq i_1 < i_2 < \ldots < i_k\leq n$ is called increasing if $a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$. If $a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation $[6, 4, 1, 7, 2, 3, 5]$, LIS of this permutation will be $[1, 2, 3, 5]$, so the length of LIS is equal to $4$. LDS can be $[6, 4, 1]$, $[6, 4, 2]$, or $[6, 4, 3]$, so the length of LDS is $3$.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
|
Show an example of $n = 22$: "' 19 20 21 22 15 16 17 18 11 12 13 14 7 8 9 10 3 4 5 6 1 2 "' You can use [Dilworth's theorem](https://en.wikipedia.org/wiki/Dilworth So assume we've already known that $LIS = L$, then we can achieve $LDS = \big\lceil\frac{n}{L}\big\rceil$. So after enumerating all possible $L$ and find the minimum of function $L \big\lceil\frac{n}{L}\big\rceil$, we can construct the sequence easily just as the case when $n = 22$. Actually, $L = \big\lfloor \sqrt n \big\rfloor$ will always work. Complexity: $O(n)$.
|
[
"constructive algorithms",
"greedy"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100000
#define rint register int
inline int rf(){int r;int s=0,c;for(;!isdigit(c=getchar());s=c);for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);return s^45?r:-r;}
int n, L, A[MAXN+5];
int main()
{
n = rf();
L = (int)sqrt(n);
for(rint i = 1, o = n, j; i <= n; i += L)
for(j = min(i+L-1,n); j >= i; A[j--] = o--);
for(rint i = 1; i <= n; i++)
printf("%d%c",A[i],"\n "[i<n]);
return 0;
}
|
1017
|
D
|
The Wu
|
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset $S$ of $m$ "01-strings".
A "01-string" is a string that contains $n$ characters "0" and "1". For example, if $n=4$, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are $5$ characters, not $4$) and "zero" (unallowed characters) are not.
\textbf{Note that the multiset $S$ can contain equal elements.}
Frequently, Mr. Kasoura will provide a "01-string" $t$ and ask Childan how many strings $s$ are in the multiset $S$ such that the "Wu" value of the pair $(s, t)$ is \textbf{not greater} than $k$.
Mrs. Kasoura and Mr. Kasoura think that if $s_i = t_i$ ($1\leq i\leq n$) then the "Wu" value of the character pair equals to $w_i$, otherwise $0$. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to $n$.
For example, if $w=[4, 5, 3, 6]$, "Wu" of ("1001", "1100") is $7$ because these strings have equal characters only on the first and third positions, so $w_1+w_3=4+3=7$.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset $S$ such that the "Wu" value of the pair is not greater than $k$.
|
We can regard a $01-string$ as a binary number. Notice that $n \le 12$, so $\frac{n}{2} \le 6$, so we can do something like meet-in-the-middle, split the numbers into higher $6$ bits and lower $6$ bits: $f[S_1][S_2][j]$ count the number of binary numbers with higher bits equal to $S_1$ and $f((\text{lower bits}) \oplus S2) = j$. Then one can easily get $g[S][k]$ stores the answer and then answer queries in $O(1)$ time. If you don't understand, see the code. Complexity: $O(|S|2^{\frac{n}{2}}+2^{\frac{3n}{2}}+q)$.
|
[
"bitmasks",
"brute force",
"data structures"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100000
#define rint register int
inline int rf(){int r;int s=0,c;for(;!isdigit(c=getchar());s=c);for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);return s^45?r:-r;}
int Wu[4096], f[64][64][104], g[4096][104], w[16], m, n, q, E, K, B = 6, L = 63, H = 4032; char _[16];
int main()
{
m = rf();
n = rf();
q = rf();
generate(w,w+m,rf);
E = 1<<m;
for(rint S = 0, j; S < E; S++)
{
for(j = 0; j < m; j++)
S&1<<j?:Wu[S]+=w[j];
Wu[S] = min(Wu[S],101);
}
for(rint i = 1, j, S; i <= n; i++)
{
scanf("%s",_+1);
for(S = 0, j = m; j; j--)
S = S<<1|(_[j]^'0');
for(j = 0; j < 64; j++)
++f[(S&H)>>B][j][Wu[((j^(S&L))|H)&~-E]];
}
for(rint S = 0, a, b, j; S < E; S++)
{
for(j = 0; j < 64; j++)
for(a = 0, b = Wu[(((j<<B)^(S&H))|L)&~-E]; b <= 100; a++, b++)
g[S][b] += f[j][S&L][a];
partial_sum(g[S],g[S]+101,g[S]);
}
for(rint i = 1, j, S; i <= q; i++)
{
scanf("%s",_+1);
for(S = 0, j = m; j; j--)
S = S<<1|(_[j]^'0');
printf("%d\n",g[S][rf()]);
}
return 0;
}
|
1017
|
E
|
The Supersonic Rocket
|
After the war, the supersonic rocket became the most common public transportation.
Each supersonic rocket consists of \textbf{two} "engines". Each engine is a set of "power sources". The first engine has $n$ power sources, and the second one has $m$ power sources. A power source can be described as a point $(x_i, y_i)$ on a 2-D plane. All points in each engine are different.
You can manipulate each engine \textbf{separately}. There are two operations that you can do with each engine. You can do each operation as many times as you want.
- For every power source as a whole in that engine: $(x_i, y_i)$ becomes $(x_i+a, y_i+b)$, $a$ and $b$ can be any real numbers. In other words, all power sources will be shifted.
- For every power source as a whole in that engine: $(x_i, y_i)$ becomes $(x_i \cos \theta - y_i \sin \theta, x_i \sin \theta + y_i \cos \theta)$, $\theta$ can be any real number. In other words, all power sources will be rotated.
The engines work as follows: after the two engines are powered, their power sources are being combined (here power sources of different engines may coincide). If two power sources $A(x_a, y_a)$ and $B(x_b, y_b)$ exist, then for all real number $k$ that $0 \lt k \lt 1$, a new power source will be created $C_k(kx_a+(1-k)x_b,ky_a+(1-k)y_b)$. \textbf{Then, this procedure will be repeated again with all new and old power sources}. After that, the "power field" from all power sources will be generated (can be considered as an infinite set of all power sources occurred).
A supersonic rocket is "safe" if and only if after you manipulate the engines, destroying any power source and then power the engine, the power field generated won't be changed (comparing to the situation where no power source erased). Two power fields are considered the same if and only if any power source in one field belongs to the other one as well.
Given a supersonic rocket, check whether it is safe or not.
|
The statement is complicated, it is actually: Given two sets of points, check whether their convex hulls are isomorphic. The standard solution is: get the convex hulls, make it into a string of traversal: "edge-angle-edge-angle-edge-...". Then double the first string and KMP them. There can be other ways to solve this problem, because there is a useful condition: all coordinates are integers. Complexity: $O(|S_1| \log |S_1| + |S_2| \log |S_2|)$.
|
[
"geometry",
"hashing",
"strings"
] | 2,400
|
#pragma comment(linker, "/STACK:512000000")
#define _CRT_SECURE_NO_WARNINGS
//#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;
#define all(a) a.begin(), a.end()
using li = long long;
using ld = long double;
void solve(bool);
void precalc();
clock_t start;
int main() {
#ifdef AIM
freopen("/home/alexandero/CLionProjects/ACM/input.txt", "r", stdin);
//freopen("/home/alexandero/CLionProjects/ACM/output.txt", "w", stdout);
//freopen("out.txt", "w", stdout);
#else
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
start = clock();
int t = 1;
#ifndef AIM
cout.sync_with_stdio(0);
cin.tie(0);
#endif
cout.precision(20);
cout << fixed;
//cin >> t;
precalc();
while (t--) {
solve(true);
}
cout.flush();
#ifdef AIM1
while (true) {
solve(false);
}
#endif
#ifdef AIM
cerr << "\n\n time: " << (clock() - start) / 1.0 / CLOCKS_PER_SEC << "\n\n";
#endif
return 0;
}
//BE CAREFUL: IS INT REALLY INT?
template<typename T>
T binpow(T q, T w, T mod) {
if (!w)
return 1 % mod;
if (w & 1)
return q * 1LL * binpow(q, w - 1, mod) % mod;
return binpow(q * 1LL * q % mod, w / 2, mod);
}
template<typename T>
T gcd(T q, T w) {
while (w) {
q %= w;
swap(q, w);
}
return q;
}
template<typename T>
T lcm(T q, T w) {
return q / gcd(q, w) * w;
}
template <typename T>
void make_unique(vector<T>& vec) {
sort(all(vec));
vec.erase(unique(all(vec)), vec.end());
}
template<typename T>
void relax_min(T& cur, T val) {
cur = min(cur, val);
}
template<typename T>
void relax_max(T& cur, T val) {
cur = max(cur, val);
}
void precalc() {
}
#define int li
//const li mod = 1000000007;
//using ull = unsigned long long;
struct Point {
int x, y;
Point() {}
Point(int x, int y) : x(x), y(y) {}
Point operator - (const Point& ot) const {
return Point(x - ot.x, y - ot.y);
}
int operator * (const Point& ot) const {
return x * ot.y - y * ot.x;
}
void scan() {
cin >> x >> y;
}
bool operator < (const Point& ot) const {
return make_pair(x, y) < make_pair(ot.x, ot.y);
}
int sqr_len() const {
return x * x + y * y;
}
long double get_len() const {
return sqrtl(sqr_len());
}
int operator % (const Point& ot) const {
return x * ot.x + y * ot.y;
}
};
struct Polygon {
vector<Point> hull;
Polygon(int n) {
vector<Point> points(n);
for (int i = 0; i < n; ++i) {
points[i].scan();
}
sort(all(points));
vector<Point> up, down;
for (auto& pt : points) {
while (up.size() > 1 && (up[up.size() - 2] - up.back()) * (pt - up.back()) >= 0) {
up.pop_back();
}
up.push_back(pt);
while (down.size() > 1 && (down[down.size() - 2] - down.back()) * (pt - down.back()) <= 0) {
down.pop_back();
}
down.push_back(pt);
}
hull = up;
for (int i = (int)down.size() - 2; i > 0; --i) {
hull.push_back(down[i]);
}
}
int sqr_len(int pos) const {
return (hull[(pos + 1) % hull.size()] - hull[pos]).sqr_len();
}
int size() const {
return (int)hull.size();
}
long double get_angle(int pos) const {
auto a = hull[(pos + 1) % hull.size()] - hull[pos], b = hull[(pos + hull.size() - 1) % hull.size()] - hull[pos];
long double co = (a % b) / a.get_len() / b.get_len();
return co;
}
};
void solve(bool read) {
vector<Polygon> polys;
int n[2];
cin >> n[0] >> n[1];
for (int i = 0; i < 2; ++i) {
polys.emplace_back(n[i]);
}
if (polys[0].size() != polys[1].size()) {
cout << "NO\n";
return;
}
vector<long double> all_lens;
int m = polys[0].size();
for (int i = 0; i < m; ++i) {
all_lens.push_back(polys[0].sqr_len(i));
all_lens.push_back(polys[0].get_angle(i));
}
all_lens.push_back(-1);
for (int j = 0; j < 2; ++j) {
for (int i = 0; i < m; ++i) {
all_lens.push_back(polys[1].sqr_len(i));
all_lens.push_back(polys[1].get_angle(i));
}
}
/*for (int x : all_lens) {
cout << x << " ";
}
cout << "\n";*/
vector<int> p(all_lens.size());
for (int i = 1; i < p.size(); ++i) {
int j = p[i - 1];
while (j > 0 && all_lens[i] != all_lens[j]) {
j = p[j - 1];
}
if (all_lens[i] == all_lens[j]) {
++j;
}
p[i] = j;
if (p[i] == 2 * m) {
cout << "YES\n";
return;
}
}
cout << "NO\n";
}
|
1017
|
F
|
The Neutral Zone
|
\textbf{Notice: unusual memory limit!}
After the war, destroyed cities in the neutral zone were restored. And children went back to school.
The war changed the world, as well as education. In those hard days, a new math concept was created.
As we all know, logarithm function can be described as: $$ \log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \log p_1 + a_2 \log p_2 + ... + a_k \log p_k $$ Where $p_1^{a_1}p_2^{a_2}...p_k^{a_2}$ is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.
So, the mathematicians from the neutral zone invented this: $$ \text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) $$
Notice that $\text{exlog}_f(1)$ is always equal to $0$.
This concept for any function $f$ was too hard for children. So teachers told them that $f$ can only be a polynomial of degree no more than $3$ in daily uses (i.e., $f(x) = Ax^3+Bx^2+Cx+D$).
"Class is over! Don't forget to do your homework!" Here it is: $$ \sum_{i=1}^n \text{exlog}_f(i) $$
Help children to do their homework. Since the value can be very big, you need to find the answer modulo $2^{32}$.
|
First forget about the memory limit part. Instead of enumerating all integers and count its $\text{exlog}_f$ value, we enumerate all primes and count its contribution. It is obvious that prime $p$'s contribution is: Brute-force this thing is actually $O(n)$: since there are only $O(\frac{n}{\ln n})$ primes less than or equal to $n$ and calculate the second part for each of them cost $O(\log_p n)$ times. Now the problem is on sieving the primes. Use Eratosthenes's sieve instead of Euler's, then the only memory cost is the cross-out table. Use a 'bitset' to store the cross-out table and you'll get a memory cost for about $37.5 MB$. Key observation: except $2$ and $3$, all primes $p$ satisfy $p \equiv \pm 1 \pmod 6$. Then just store these positions with $\frac{37.5MB}{3} = 12.5 MB$. You can also use this observation to optimize your code's running time. Complexity: $O(n \log \log n)$. That's the running time of Eratosthenes's sieve.
|
[
"brute force",
"math"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
typedef unsigned int ll;
const ll maxn=4e8;
const ll maxp=sqrt(maxn)+10;
ll f[4][maxp],g[4][maxp];
ll n,m,A,B,C,D,ans,res,tmp,rt;
ll p1(ll x){
ll y=x+1; if (x%2==0) x/=2; else y/=2;
return x*y;
}
ll p2(ll x){
long long y=x+1,z=x*2+1;
if (x%2==0) x/=2; else y/=2;
if (z%3==0) z/=3; else if (x%3==0) x/=3; else y/=3;
return (ll)x*y*z;
}
ll p3(ll x){
ll y=p1(x);
return y*y;
}
bool is_prime(ll x){
for (ll i=2;i*i<=x;i++) if (x%i==0) return false;
return true;
}
ll solve(ll n)
{
ll i,j,rt,o[4];
for (m=1;m*m<=n;m++) {
f[0][m]=(n/m-1);
f[1][m]=(p1(n/m)-1)*C;
f[2][m]=(p2(n/m)-1)*B;
f[3][m]=(p3(n/m)-1)*A;
}
for (i=1;i<=m;i++) {
g[0][i]=(i-1);
g[1][i]=(p1(i)-1)*C;
g[2][i]=(p2(i)-1)*B;
g[3][i]=(p3(i)-1)*A;
}
for (i=2;i<=m;i++) {
if (g[0][i]==g[0][i-1]) continue;
o[0]=1; for (int w=1;w<4;w++) o[w]=o[w-1]*i;
for (j=1;j<=min(m-1,n/i/i);j++)
for (int w=0;w<4;w++)
if (i*j<m) f[w][j]-=o[w]*(f[w][i*j]-g[w][i-1]);
else f[w][j]-=o[w]*(g[w][n/i/j]-g[w][i-1]);
for (j=m;j>=i*i;j--)
for (int w=0;w<4;w++)
g[w][j]-=o[w]*(g[w][j/i]-g[w][i-1]);
}
for (int i=1;i<=m+1;i++) f[0][i]*=D,g[0][i]*=D;
rt=0;
for (ll i=1;n/i>m;i++) {
for (int w=0;w<4;w++) rt+=(f[w][i]-g[w][m]);
//cout<<"H"<<rt<<endl;
}
return rt;
}
int main()
{
//freopen("input.txt","r",stdin);
ll n; cin >> n >> A >> B >> C >> D;
ans=solve(n);
for (ll i=2;i<=m;i++){
if (is_prime(i)){
res=A*i*i*i+B*i*i+C*i+D; tmp=n;
while (tmp){
ans+=res*(tmp/i);
tmp/=i;
}
}
}
cout << ans << endl;
return 0;
}
|
1017
|
G
|
The Tree
|
Abendsen assigned a mission to Juliana. In this mission, Juliana has a rooted tree with $n$ vertices. Vertex number $1$ is the root of this tree. Each vertex can be either black or white. At first, all vertices are white. Juliana is asked to process $q$ queries. Each query is one of three types:
- If vertex $v$ is white, mark it as black; otherwise, perform this operation on all direct sons of $v$ instead.
- Mark all vertices in the subtree of $v$ (including $v$) as white.
- Find the color of the $i$-th vertex.
\begin{center}
{\small An example of operation "1 1" (corresponds to the first example test). The vertices $1$ and $2$ are already black, so the operation goes to their sons instead.}
\end{center}
Can you help Juliana to process all these queries?
|
The problem can be solved using HLD or sqrt-decomposition on queries. Here, I will explain to you the second solution. Let $s$ be a constant. Let's split all queries on $\frac{n}{s}$ blocks. Each block will contain $s$ queries. In each block, since we have $s$ queries, we will have at most $s$ different vertices there. Therefore, we can squeeze the tree using only those $s$ different vertices. There will be a directed edge from $i$ to $j$ if they are both in that set of $s$ different vertices and $i$ is an ancestor of $j$ in the original tree. A weight of such edge will be the number of white vertices on the way between those two vertices (exclusively $i$ and $j$). If we want to find answers for the queries in the black, we need to make every operation in $\mathcal{O}(s)$. In each vertex, we will have $p_i$ - the number of operations of the first type that need to be processed on that vertex. Also, each vertex will have $c_i$ - the boolean variable that means that we need to clear the subtree. Obviously, when we are doing the second operation, we need to clear every $p_i$ in that subtree. After we answer the queries of the $i$-th block, we need to update the full graph. So, the complexity will be $\mathcal{O}(\frac{n}{s}\cdot n + n\cdot s)$. If you make $s = \sqrt{n}$, the complexity will be $\mathcal{O}(n\cdot \sqrt{n})$. For better understanding, you can check the code below.
|
[
"data structures"
] | 3,200
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 10;
bool black[MAX]; // is it vertex black now
vector<int> vec[MAX]; // main edges
bool old_black[MAX]; // to remember the tree before block
const int MAX_BLOCK_SIZE = 600;
int t[MAX], v[MAX]; // queries
bool used[MAX]; // is in mini-tree
vector<pair<pair<int, int>, int> > v2[MAX]; // mini-tree edges (son, number of white vertices, dist)
int push[MAX]; // push of the i-th vertex in mini-tree
bool clear[MAX]; // do we need to clear first
void dfs_1(int pos, int prev = -1, int white = 0, int dist = 0){
if(used[pos]){
if(prev != -1){
v2[prev].push_back(make_pair(make_pair(pos, white), dist));
}
for(int a : vec[pos]){
dfs_1(a, pos, 0, 0);
}
}else{
if(!black[pos]){
white++;
}
for(int a : vec[pos]){
dfs_1(a, prev, white, dist + 1);
}
}
}
void make_1(int pos){
if(!black[pos]){
black[pos] = true;
return;
}
push[pos]++;
for(auto a : v2[pos]){
if(a.first.second + 1 <= push[pos]){
make_1(a.first.first);
}
}
}
void make_2(int pos){
black[pos] = false;
push[pos] = 0;
clear[pos] = true;
for(auto &a : v2[pos]){
a.first.second = a.second;
make_2(a.first.first);
}
}
void dfs_2(int pos, int p = 0, bool cl = false){
if(used[pos]){
p = push[pos];
cl |= clear[pos];
}else{
black[pos] = old_black[pos];
if(cl){
black[pos] = false;
}
if(!black[pos] && p){
black[pos] = true;
p--;
}
}
for(int a : vec[pos]){
dfs_2(a, p, cl);
}
}
int main(){
ios_base::sync_with_stdio();
cin.tie(0);
cout.tie(0);
int n, q;
cin >> n >> q;
for(int i = 2; i <= n; i++){
int a;
cin >> a;
vec[a].push_back(i);
}
for(int i = 1; i <= q; i++){
cin >> t[i] >> v[i];
}
int root = 1;
for(int i = 1; i <= q; i += MAX_BLOCK_SIZE){
for(int j = 1; j <= n; j++){
used[j] = false;
v2[j].clear();
old_black[j] = black[j];
push[j] = 0;
clear[j] = false;
}
for(int j = 0; j < MAX_BLOCK_SIZE && i + j <= q; j++){
used[v[i + j]] = true;
}
dfs_1(root);
for(int j = 0; j < MAX_BLOCK_SIZE && i + j <= q; j++){
int t = ::t[i + j];
int v = ::v[i + j];
if(t == 1){
make_1(v);
}else if(t == 2){
make_2(v);
}else{
cout << (black[v] ? "black" : "white") << "\n";
}
}
dfs_2(root);
}
return 0;
}
|
1017
|
H
|
The Films
|
In "The Man in the High Castle" world, there are $m$ different film endings.
Abendsen owns a storage and a shelf. At first, he has $n$ ordered films on the shelf. In the $i$-th month he will do:
- Empty the storage.
- Put $k_i \cdot m$ films into the storage, $k_i$ films for each ending.
- He will think about a question: if he puts all the films from the shelf into the storage, then randomly picks $n$ films (from all the films in the storage) and rearranges them on the shelf, what is the probability that sequence of endings in $[l_i, r_i]$ on the shelf will not be changed? Notice, he just thinks about this question, so the shelf will not actually be changed.
Answer all Abendsen's questions.
Let the probability be fraction $P_i$. Let's say that the total number of ways to take $n$ films from the storage for $i$-th month is $A_i$, so $P_i \cdot A_i$ is always an integer. Print for each month $P_i \cdot A_i \pmod {998244353}$.
$998244353$ is a prime number and it is equal to $119 \cdot 2^{23} + 1$.
It is guaranteed that there will be only no more than $100$ different $k$ values.
|
First, we claim the probability is this: Proof: For each position in $[l,r]$ with ending $i$, you can choose any film with the same ending, there are $(t_i+k)$ of them for the first candidate, and $(t_i+k-1)$ of them for the second candidate, ... So you can satisfy the conditions with $\prod_{i=1}^m (t_i +k)^{\underline c_i}$ number of ways. After that, other $n-(r-l+1)$ positions can be filled arbitrarily, there are $(mk+n-(r-l+1))^{\underline{n-(r-l+1)}}$ ways of doing that. And the total number of ways is $(mk+n)^{\underline n}$ obviously. If $k = 0$, we can maintain the expression using Mo-algorithm with complexity about $O(n\sqrt n)$. More precisely, it is $O(n \sqrt q)$ or $O(n \sqrt q\log m)$. Key observation: There can only be $O(\sqrt n)$ different occuring times at most. Proof: In the worst case, the occurring times are $1 + 2 + 3 + ... + x = \frac{x(x+1)}{2} \le n$, so $x = O(\sqrt n)$. Similarly, that there are at most $O(n^\frac{2}{3})$ different combinations of $t_i$ and $c_i$. Proof: In the worst case, pairs of $(t_i,c_i)$ are like: $t_i$ : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 ... $c_i$ : 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 ... Let its length of same $c_i$ be $A$ and repeat time be $B$. Then from the total occurring times we get $\frac{A(A+1)}{2}B \le n$ , and from the occurring times in segment we get $\frac{B(B+1)}{2} A \le r-l+1$ . So around $A = B = O(n^{\frac{1}{3}})$ we achieve the minimum. Use a hash table (actually an array of size $O(m\sqrt n)$) to remember them, and brute-force them for each query. We're done. About the $\frac{(mk+n-(r-l+1))^{\underline{n-(r-l+1)}}}{(mk+n)^{\underline n}}$ part, since there are no more than $K = 100$ different $k$ value, preprocess that for each $k$. Complexity: $O(Kn + n \sqrt q + qn^{\frac{2}{3}} \log m)$. Actually, due to limit of $K$, if one simply run mo-algorithm $K$ times, it will reach a $O(n\sqrt{qK})$. Under this limit it can be faster than standard solution.
|
[
"brute force"
] | 3,300
|
#pragma comment(linker, "/STACK:512000000")
#include <bits/stdc++.h>
using namespace std;
#define all(a) a.begin(), a.end()
typedef long long li;
typedef long double ld;
void solve(__attribute__((unused)) bool);
void precalc();
clock_t start;
#define FILENAME ""
int main() {
#ifdef AIM
string s = FILENAME;
// assert(!s.empty());
freopen("/home/alexandero/ClionProjects/cryptozoology/input.txt", "r", stdin);
//freopen("/home/alexandero/ClionProjects/cryptozoology/output.txt", "w", stdout);
#else
// freopen(FILENAME ".in", "r", stdin);
// freopen(FILENAME ".out", "w", stdout);
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
start = clock();
int t = 1;
#ifndef AIM
cout.sync_with_stdio(0);
cin.tie(0);
#endif
precalc();
cout.precision(10);
cout << fixed;
//cin >> t;
int testNum = 1;
while (t--) {
//cout << "Case #" << testNum++ << ": ";
solve(true);
}
cout.flush();
#ifdef AIM1
while (true) {
solve(false);
}
#endif
#ifdef AIM
cout.flush();
auto end = clock();
usleep(10000);
print_stats(end - start);
usleep(10000);
#endif
return 0;
}
template<typename T>
T binpow(T q, T w, T mod) {
if (!w)
return 1 % mod;
if (w & 1)
return q * 1LL * binpow(q, w - 1, mod) % mod;
return binpow(q * 1LL * q % mod, w / 2, mod);
}
template<typename T>
T gcd(T q, T w) {
while (w) {
q %= w;
swap(q, w);
}
return q;
}
template<typename T>
T lcm(T q, T w) {
return q / gcd(q, w) * w;
}
template <typename T>
void make_unique(vector<T>& a) {
sort(all(a));
a.erase(unique(all(a)), a.end());
}
template<typename T>
void relax_min(T& cur, T val) {
cur = min(cur, val);
}
template<typename T>
void relax_max(T& cur, T val) {
cur = max(cur, val);
}
void precalc() {
}
#define int li
const int mod = 998244353;
struct Query {
int l, r, id;
};
vector<int> res;
vector<int> a;
int n;
int TIMER = 0;
const int C = 200500;
int used[C];
int cur_cnt[C];
int rev[C];
map<int, vector<int>> down;
vector<int> init;
void kill(vector<Query>& all_q, int block_size, int k) {
vector<vector<Query>> by_block(n / block_size + 1);
for (auto& cur_q : all_q) {
by_block[cur_q.l / block_size].push_back(cur_q);
}
for (int i = 0; i < by_block.size(); ++i) {
++TIMER;
auto& q = by_block[i];
sort(all(q), [&] (const Query& o1, const Query& o2) {
return o1.r < o2.r;
});
int cur_l = min(n, (i + 1) * block_size);
int cur_r = cur_l;
int cur_prod = 1;
auto add_item = [&] (int val) {
if (used[val] != TIMER) {
used[val] = TIMER;
cur_cnt[val] = 0;
}
int cur_k = k + init[val];
++cur_cnt[val];
cur_prod = cur_prod * (cur_k - cur_cnt[val] + 1) % mod;
};
auto remove_item = [&] (int val) {
int cur_k = k + init[val];
cur_prod = cur_prod * rev[cur_k - cur_cnt[val] + 1] % mod;
--cur_cnt[val];
};
for (auto& cur_q : q) {
while (cur_r < cur_q.r) {
add_item(a[cur_r++]);
}
while (cur_l > cur_q.l) {
add_item(a[--cur_l]);
}
while (cur_r > cur_q.r) {
remove_item(a[--cur_r]);
}
while (cur_l < cur_q.l) {
remove_item(a[cur_l++]);
}
res[cur_q.id] = cur_prod * down[k][n - cur_q.r + cur_q.l] % mod;
}
}
}
void solve(__attribute__((unused)) bool read) {
for (int i = 1; i < C; ++i) {
rev[i] = binpow(i, mod - 2, mod);
}
int m, Q;
//read = false;
if (read) {
cin >> n >> m >> Q;
} else {
n = 50000;
m = 100000;
Q = 50000;
}
a.resize(n);
init.assign(m, 0);
for (int i = 0; i < n; ++i) {
if (read) {
cin >> a[i];
--a[i];
} else {
a[i] = rand() % m;
}
++init[a[i]];
}
map<int, vector<Query>> q;
for (int i = 0; i < Q; ++i) {
int l, r, k;
if (read) {
cin >> l >> r >> k;
} else {
do {
l = rand() % n + 1;
r = rand() % n + 1;
} while (l > r);
k = rand() % 100;
}
--l;
q[k].push_back({l, r, i});
down[k] = vector<int>();
}
res.assign(Q, 0);
for (auto& item : down) {
int init_val = (item.first * m) % mod;
auto& vec = item.second;
vec.assign(n + 1, 1);
for (int i = 1; i < vec.size(); ++i) {
vec[i] = vec[i - 1] * (init_val + i) % mod;
}
}
for (auto& item : q) {
int k = item.first;
auto& cur_q = item.second;
int block_size = std::max((int)(n / sqrt((int)cur_q.size())), 1LL);
kill(cur_q, block_size, k);
}
for (int i = 0; i < Q; ++i) {
cout << res[i] << "\n";
}
}
|
1019
|
A
|
Elections
|
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.
Elections are coming. You know the number of voters and the number of parties — $n$ and $m$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $i$-th voter $c_i$ bytecoins you can ask him to vote for any other party you choose.
The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.
|
Let's iterate over final number of votes for The United Party of Berland. We can see that all opponents should get less votes than our party, and our party should get at least our chosen number of votes. We can sort all voters by their costs, and solve the problem in two passes. First, if we need to get $x$ votes, we should definitely buy all cheap votes for parties that have at least $x$ votes. Second, if we don't have $x$ votes yet, we should by the cheapest votes to get $x$ votes. We can see that this solution is optimal: consider the optimal answer, and see how many votes The United Party got. We tried such number of votes, and we tried to achieve this number of votes by cheapest way, so we couldn't miss the optimal answer. This can be implemented in $O(n^2 \log n)$ or even $O(n \log n)$.
|
[
"brute force",
"greedy"
] | 1,700
| null |
1019
|
B
|
The hat
|
\textbf{This is an interactive problem.}
Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by $n$ students, where $n$ is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant $i$ and participant $i + 1$ ($1 ≤ i ≤ n - 1$) are adjacent, as well as participant $n$ and participant $1$. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.
As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers $i$ and $i+{\frac{n}{2}}$ sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.
You can ask questions of form «which number was received by student $i$?», and the goal is to determine whether the desired pair exists in no more than $60$ questions.
|
Let $a(i)$ be a number given to the $i$-th student. Let's introduce function $b(i)=a(i)-a(i+{\frac{n}{2}})$. As $n$ is even, $\frac{n t}{2}$ is integer, and $b(i)$ is defined correctly. Notice two facts: first, $b(i)=-b(i+{\frac{n}{2}})$, and second, $|b(i)-b(i+1)|\in\{-2,0,2\}$. The problem is to find an $i$ such that $b(i) = 0$. Second note leads us to observation that all $b(i)$ have the same oddity. So, let's find $b(0)$, and if it is odd, then there is no answer, and we need to print $- 1$ - all $b(i)$ have the same oddity (odd), and zero, as a number of different oddity, won't appear in $b(i)$. Otherwise, suppose we know $b(0)$, and it is equal to $x$ (without loss of generality $x > 0$). Notice that $b(0+{\textstyle{\frac{n}{2}}})=-b(0)=-x$. As we remember from second observation that all $b(i)$ have the same oddity, and neighboring numbers differ by no more than 2, we can use discrete continuity. Lemma: if you have two indices $i$ and $j$ with values $b(i)$ and $b(j)$, then on segment between $i$ and $j$ there are all values with the same oddity from $min(b(i), b(j))$ to $max(b(i), b(j))$. Indeed, as neighboring $b$ differ by no more than 2, we couldn't skip any number with the same oddity. Now we can use a binary search. At the start $l = 0$, $r={\frac{n}{2}}$, and values $b(l)$ and $b(r)$ are even numbers with the different signs. By lemma, on segment between $l$ and $r$ there is a zero that we want to find. Let's take $m={\frac{l+r}{2}}$. If $b(m) = 0$, we found the answer. Otherwise, based on sign of $b(m)$ we can replace one of $l$, $r$ in binary search to $m$, and reduce the problem to the same with smaller size. There will be no more than $\log n$ iterations, and as calculation of $b(i)$ requires two queries, we solved the problem in $2\log n$ queries.
|
[
"binary search",
"interactive"
] | 2,000
| null |
1019
|
C
|
Sergey's problem
|
Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree. Today he celebrates his birthday again! He found a directed graph without loops as a present from his parents.
Since Sergey is a very curious boy, he immediately came up with a thing to do. He decided to find a set $Q$ of vertices in this graph, such that no two vertices $x, y \in Q$ are connected by an edge, and it is possible to reach any vertex $z \notin Q$ from some vertex of $Q$ in no more than two moves.
After a little thought, Sergey was able to solve this task. Can you solve it too?
A vertex $y$ is reachable from a vertex $x$ in at most two moves if either there is a directed edge $(x,y)$, or there exist two directed edges $(x,z)$ and $(z, y)$ for some vertex $z$.
|
Let's build the solution by induction. Suppose we have to solve the problem for $n$ vertices and we can solve this problem for all $k$ ($k < n$). Take an arbitrary vertex $A$. Remove $A$ from the graph, as well as all vertices that $A$ has an outgoing edge to. Resulting graph has less than $n$ vertices, so by induction, we can build the solution for it. Let's call the answer set for the new graph $M$. After this we have two cases: either there is an edge from set $M$ to vertex $A$ or there is not. If there is an edge from $M$ to $A$, then $M$ is a correct answer for initial graph, because every removed vertex can be reached from $M$ in at most two steps. Otherwise, we can add $A$ to $M$ and, again, this set will satisfy the required condition. This also proves the answer always exists. How to implement it? Let's iterate over all vertices in order from $1$ to $n$ and remember whether each vertex is currently present in the graph or not. Whenever we encounter a currently present vertex $u$, we save $u$ and mark $u$ and all vertices reachable from $u$ in one step as removed. After that, we go over all saved vertices in reverse order and add them to answer set if it's not reachable from the answer set in one step. This solutions works in $O(V + E)$ time and space.
|
[
"constructive algorithms",
"graphs"
] | 3,000
| null |
1019
|
D
|
Large Triangle
|
\begin{quote}
There is a strange peculiarity: if you connect the cities of Rostov, Taganrog and Shakhty, peculiarly, you get a triangle
\hfill «Unbelievable But True»
\end{quote}
Students from many different parts of Russia and abroad come to Summer Informatics School. You marked the hometowns of the SIS participants on a map.
Now you decided to prepare an interesting infographic based on this map. The first thing you chose to do is to find three cities on this map, such that they form a triangle with area $S$.
|
Let's fix one of edge of the triangle. We need to find a third point so the area of triangle is equal to $s$. Notice that area of triangle is proportional to scalar product of the normal vector to the chosen edge and radius-vector of third point. So, if we had all other points sorted by scalar product with normal to the edge, we could find the third point by binary search. It is the main goal of the solution. There are $O(n^2)$ interesting directions - two normal vectors to each of edges, defined by all pairs of points. For each pair of points you can see that for some directions one of points has larger scalar product with this direction, and for some other direction another point has larger scalar product. We can see that points $a_i$ and $a_j$ have the same scalar product with vector $rotate_{90}(a_i-a_j)$ - with normal vector edge defined by these two points. If you look at all directions on unit circle, this vector and the opposite vector change the order of points $a_i$ and $a_j$ in sorted order by scalar product. Also, as there are no three points lying on one line, these two points will be neighboring in sorting order by this direction. So, we can maintain the sorting order. Let's take all events on unit circle as all vectors of type $rotate_{90}(a_i - a_j)$, and for every such event swap two neighboring points $a_i$ and $a_j$ in sorting order. After swap we can do a binary search for third point to find a required triangle with area $s$. This works in $O(n^2 \log n)$ time.
|
[
"binary search",
"geometry",
"sortings"
] | 2,700
| null |
1019
|
E
|
Raining season
|
By the year 3018, Summer Informatics School has greatly grown. Hotel «Berendeetronik» has been chosen as a location of the school. The camp consists of $n$ houses with $n-1$ pathways between them. It is possible to reach every house from each other using the pathways.
Everything had been perfect until the rains started. The weather forecast promises that rains will continue for $m$ days. A special squad of teachers was able to measure that the $i$-th pathway, connecting houses $u_i$ and $v_i$, before the rain could be passed in $b_i$ seconds. Unfortunately, the rain erodes the roads, so with every day the time to pass the road will increase by $a_i$ seconds. In other words, on the $t$-th (from zero) day after the start of the rain, it will take $a_i \cdot t + b_i$ seconds to pass through this road.
Unfortunately, despite all the efforts of teachers, even in the year 3018 not all the students are in their houses by midnight. As by midnight all students have to go to bed, it is important to find the maximal time between all the pairs of houses for each day, so every student would know the time when he has to run to his house.
Find all the maximal times of paths between every pairs of houses after $t=0$, $t=1$, ..., $t=m-1$ days.
|
Let's use centroid decomposition on edges of the tree to solve this task. Centroid decomposition on edges is about finding an edge that divides a tree of $n$ vertices into two subtrees, each of which contains no more than $cn$ vertices for some fixed constant $c<1$. It is easy to see that such decomposition has only logarithmic depth in terms of initial number of nodes. There is a problem - it is easy to construct an example, where it is impossible to choose such edge. For example, star tree with $n$ vertices and $n-1$ leaves is fine for that - every edge has a leaf as one of its ends. To solve this problem, we can add new vertices and edges to the tree. Let's fix arbitrary root of the tree, and make tree binary: if some vertex $v$ has more than two children - $u_1, u_2, \ldots, u_k$, we may replace vertex $v$ to vertex $v_1$ with children $u_1$ and $v_2$, $v_2$ with children $u_2$ and $v_3$, and so on. Edge between $v_i$ and $u_i$ has the same length as in initial tree between $v$ and $u_i$, and edge between $v_i$ and $v_{i+1}$ has length 0. It is easy to see that the distance between any pair of vertices in new tree is the same as the distance between them in initial tree. Also, the degree of the each vertex is at most three, so we can take the centroid of the new tree, and there will be a subtree of centroid with $[{n \over 3}; {n \over 2}]$ vertices, so, we will wind an edge that we need in centroid decomposition on edges. After choosing an edge for decomposition, we should solve the problem recursively for subtrees, and find the diameters which contain the chosen edge. It is quite easy - we can calculate a linear function of length of path from . After that we need to take one linear function from both subtrees and get the sum of these functions. We can say that if length of path looks like linear function $at+b$, then we have a point $(a, b)$ on plane. Then it is obvious that we should only keep points on the convex hull of this set. Instead of choosing pairs of vertices in subtrees of edge we can just build a Minkowski sum of their convex hulls - we will get exactly the diameters that contain the chosen edge in linear time. After computing the convex hulls of diameters containing each edge in decomposition, we can put all these points in one big array and build one big convex hull for all these points again. This way we get all interesting diameters in the tree. To get the length of diameter in time $t$, we have to find the most distant point on convex hull in direction $(t, 1)$. Building the convex hull for all points for diameters containing the edge of decomposition works in $O(k \log k)$, where $k$ is size of current connected component. With knowledge that we have logarithmic depth of decomposition, overall complexity is $O(n \log^2 n)$.
|
[
"data structures",
"divide and conquer",
"trees"
] | 3,200
| null |
1020
|
A
|
New Building for SIS
|
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.
The building consists of $n$ towers, $h$ floors each, where the towers are labeled from $1$ to $n$, the floors are labeled from $1$ to $h$. There is a passage between any two adjacent towers (two towers $i$ and $i + 1$ for all $i$: $1 ≤ i ≤ n - 1$) on every floor $x$, where $a ≤ x ≤ b$. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building.
\begin{center}
{\small The picture illustrates the first example.}
\end{center}
You have given $k$ pairs of locations $(t_{a}, f_{a})$, $(t_{b}, f_{b})$: floor $f_{a}$ of tower $t_{a}$ and floor $f_{b}$ of tower $t_{b}$. For each pair you need to determine the minimum walking time between these locations.
|
In this problem you need to find a shortest path between some locations in a building. You need to look at some cases to solve this problem. First, if locations are in the same tower ($t_{a} = t_{b}$), you don't need to use a passages between two towers at all, and answer is $f_{a} - f_{b}$. In other case, you have to use some passage between towers. Obviously, you need to use only passage on one floor. The easiest way to do this is to write down interesting floors in array - the floor where you start, the floor where you end your path, first and last floors with passages. After that you can choose interesting floor $x$ where you will use a passage, check if there is a passage at this floor ($a \le x \le b$), and update answer with an expression like $|t_{a} - t_{b}| + |f_{a} - x| + |f_{b} - x|$. Another method is to choose a floor where you use a passage by case handling. If you start on the floor $f_{a}$, and there is a passage, you can just use this passage. Otherwise, you choose between floors $a$ and $b$, whichever is closer to the start.
|
[
"math"
] | 1,000
| null |
1020
|
B
|
Badge
|
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $n$ students doing yet another trick.
Let's assume that all these students are numbered from $1$ to $n$. The teacher came to student $a$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $p_a$.
After that, the teacher came to student $p_a$ and made a hole in his badge as well. The student in reply said that the main culprit was student $p_{p_a}$.
This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.
After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.
You don't know the first student who was caught by the teacher. However, you know all the numbers $p_i$. Your task is to find out for every student $a$, who would be the student with two holes in the badge if the first caught student was $a$.
|
In this problem you are given a graph, with one outgoing edge from each vertex. You are asked which vertex is first to be visited twice, if you start in some vertex, and go by outgoing edge from current vertex until you visited some vertex twice. The problem can be solved by straightforward implementation. You choose a starting vertex (which student is first to get a hole in their badge), and keep the current vertex, and for all vertices how many times it was visited. After transition to the next vertex you just check if it has been already visited, and update visited mark for it. This solution works in $O(n^2)$, and is very easy in implementation. It can be optimized to $O(n)$, but it was not necessary in this problem. It an easy and useful exercise left to reader.
|
[
"brute force",
"dfs and similar",
"graphs"
] | 1,000
| null |
1023
|
A
|
Single Wildcard Pattern Matching
|
You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and \textbf{at most one} wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$.
The wildcard character '*' in the string $s$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $s$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $s$ to obtain a string $t$, then the string $t$ matches the pattern $s$.
For example, if $s=$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string $t$ matches the given string $s$, print "YES", otherwise print "NO".
|
If there is no wildcard character in the string $s$, the answer is "YES" if and only if strings $s$ and $t$ are equal. In the other case let's do the following thing: while both strings are not empty and their last characters are equal, let's erase them. Then do the same for the first characters, i.e. while both strings are not empty and their first characters are equal, let's erase them. Now if $s$ is empty or $s=$"*" the answer is "YES", otherwise the answer is "NO".
|
[
"brute force",
"implementation",
"strings"
] | 1,200
| null |
1023
|
B
|
Pair of Toys
|
Tanechka is shopping in the toy shop. There are exactly $n$ toys in the shop for sale, the cost of the $i$-th toy is $i$ burles. She wants to choose two toys in such a way that their total cost is $k$ burles. How many ways to do that does she have?
Each toy appears in the shop exactly once. Pairs $(a, b)$ and $(b, a)$ are considered equal. Pairs $(a, b)$, where $a=b$, are not allowed.
|
The problem is to calculate the number of ways to choose two distinct integers from $1$ to $n$ with sum equals $k$. If $k \le n$ then the answer is $\lfloor\frac{k}{2}\rfloor$ because this is the number of ways to choose two distinct integers from $1$ to $k - 1$ with the sum equals $k$. Otherwise let $mn = n - k$ will be the minimum possible term in the correct pair of integers. Also let $mx = n$ will be the maximum possible term in the correct pair of integers. Then the answer is $max(0, \lfloor\frac{mx - mn + 1}{2}\rfloor)$ because this is the number of ways to choose two distinct integers from $mn$ to $mx$ with the sum equals $k$.
|
[
"math"
] | 1,000
| null |
1023
|
C
|
Bracket Subsequence
|
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You are given a regular bracket sequence $s$ and an integer number $k$. Your task is to find a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$.
It is guaranteed that such sequence always exists.
|
Let the array $used$ of $n$ boolean values describe if the corresponding bracket of string $s$ is included in answer or not. The algorithm goes like this: iterate over the string from $1$ to $n$, maintain the stack of positions of currenly unmatched opening brackets $st$. When opening bracket is met at position $i$, push $i$ to $st$, and when closing bracket is met, set $used[st.top()] = True$, $used[i] = True$ and pop the top of $st$. When $k$ values are marked True in $used$ then break, iterate from $1$ to $n$ and print the brackets at positions where $used[i] = True$. Obviously, this algorithm produces a subsequence of $s$ of length $k$. Why will it be a regular bracket sequence? The requirements for it are: no prefix contains more closing brackets than opening ones; the total number of closing bracket equals the total number of opening brackets. The first requirement is met by construction, we couldn't pop more elements from the stack than it had. The second requirement is also met as we marked brackets in pairs. Overall complexity: $O(n)$.
|
[
"greedy"
] | 1,200
| null |
1023
|
D
|
Array Restoration
|
Initially there was an array $a$ consisting of $n$ integers. Positions in it are numbered from $1$ to $n$.
Exactly $q$ queries were performed on the array. During the $i$-th query some segment $(l_i, r_i)$ $(1 \le l_i \le r_i \le n)$ was selected and values of elements on positions from $l_i$ to $r_i$ inclusive got changed to $i$. The order of the queries couldn't be changed and all $q$ queries were applied. It is also known that every position from $1$ to $n$ got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of $n$ integers with values from $1$ to $q$) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to $0$.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
|
Let's firstly solve the problem as if there are no zeroes in the given array. Let $l_i$ be the leftmost occurrence of $i$ in the array and $r_i$ be the rightmost occurrence of $i$. The main observation is that you can choose segments $(l_i; r_i)$ for the corresponding queries and this sequence will be correct if and only if there exists any answer for the given array. If there is no occurrence of some value in the array then you can put the segment for it under the segment of some greater value. If there is no occurrence of $q$ in the array then the answer doesn't exist. For sure, segment $(l_i, r_i)$ is the minimum segment you can choose. You can expand it in both directions but it will never matter: these positions either will get covered by the segments of greater values or will replace the smaller values with $i$ (and turn YES to NO if the answer existed). Finally, each position will be covered as each element is a left bound of a segment, a right bound of a segment or just covered by the segment of its value. That problem can be solved with any data structure that allows you to assign values on segment and get the value of every position (segment tree, sqrt decomposition). However, all the queries are performed offline (the resulting values are only needed after the queries) and the operation can be replaced with assigning maximum of the current value of element and the value of the query. This can also be done using set. For each position you should keep the segments which start there and end there. For each segment $(l_i, r_i)$ you push $i$ to the list for $l_i$ and push $i$ to the list for $r_i$. Now you iterate from $1$ to $n$, when entering $i$ you add all values of opening segments to the set, assign the element at position $i$ the maximum value of the set and remove all the values of closing segments from the set. The complexity of this algorithm is $O(n \log q)$. This algorithm can be easily applied to the problem with zeroes in the array. At the beginning you fill the resulting array with ones. After you performed the algorithm with set on the values from $1$ to $q$, while constructing the segments from the non-zero elements of the given array, you check if the values you assigned are less or equal than the corresponding values of the given array. If that holds then the resulting array is already the correct one. Otherwise the answer doesn't exist. The only corner case there is if no value $q$ was in array and there were some zeroes. That way you should just change any zero to $q$. Overall complexity: $O(n \log q)$.
|
[
"constructive algorithms",
"data structures"
] | 1,700
| null |
1023
|
E
|
Down or Right
|
This is an interactive problem.
Bob lives in a square grid of size $n \times n$, with rows numbered $1$ through $n$ from top to bottom, and columns numbered $1$ through $n$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $n$.
Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move \textbf{down or right} to an adjacent cell, if it is allowed.
You can ask at most $4 \cdot n$ queries of form "?$r_1$ $c_1$ $r_2$ $c_2$" ($1 \le r_1 \le r_2 \le n$, $1 \le c_1 \le c_2 \le n$). The answer will be "YES" if Bob can get from a cell $(r_1, c_1)$ to a cell $(r_2, c_2)$, and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $n - 1$, i.e. the following condition must be satisfied: $(r_2 - r_1) + (c_2 - c_1) \ge n - 1$.
It's guaranteed that Bob can get from the top-left corner $(1, 1)$ to the bottom-right corner $(n, n)$ and your task is to find a way to do it. You should print the answer in form "! S" where $S$ is a string of length $2 \cdot n - 2$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $1$, the right move increases the second coordinate by $1$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.
|
Hint: Move from $(1, 1)$ to the middle by asking queries 'query(row, col, n, n)', starting with $row = col = 1$. Similarly, move from $(n, n)$ to the middle by asking queries 'query(1, 1, row, col)'. How to ensure that we will meet in the same cell in the middle? The unusual condition in this problem is $(r_2 - r_1) + (c_2 - c_1) \ge n - 1$ that must be satisfied in every query. Without it, the following simple code would solve the problem: This program starts in $(1,1)$ and greedily moves down if after this move we could still reach the cell $(n, n)$. Otherwise, it must move right. But in this problem, we can only get half the way this method. We must stop at the antidiagonal (one of cells: $(1, n), (2, n-1), \ldots, (n, 1)$). So maybe it's a good idea to move backward from $(n, n)$ the same way, and meet at the antidiagonal? Not really :( We indeed can apply the same algorithm starting from $(n, n)$ and going towards $(1, 1)$, but possibly we will end in a different cell in the middle. It's possible even for an empty grid, without any blocked cells. We are very close to a correct solution, but let's focus on a thought process for a moment. Analyzing some other possible approach might help with that. The limitation about the distance at least $n - 1$ is just enough to ask a query between $(1, 1)$ and a cell from the antidiagonal, and also that cell and $(n, n)$. This pseudocode would print reasonable candidates for a middle cell in our path - a cell reachable from $(1, 1)$ and from which the $(n, n)$ is reachable. But after choosing some cell like this, it isn't that easy to find a way to the corner cells. In our first idea, we were able to get from $(1, 1)$ to one of the reasonable candidates and from $(n, n)$ to one of the reasonable candidates, but maybe a different one. Now a very important observation is: the first piece of code in this editorial will reach the leftmost (equivalently: downmost) reasonable candidate, because we always prefer moving down instead of right. For example, in an empty we would reach the bottom left corner. Now we see that we need to guarantee the same when moving from $(n, n)$. So we should prioritize left direction over the up direction:
|
[
"constructive algorithms",
"interactive",
"matrices"
] | 2,100
| null |
1023
|
F
|
Mobile Phone Network
|
You are managing a mobile phone network, and want to offer competitive prices to connect a network.
The network has $n$ nodes.
Your competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially $m$ connections the competitor is offering. The $i$-th connection your competitor is offering will connect nodes $fa_i$ and $fb_i$ and costs $fw_i$.
You have a list of $k$ connections that you want to offer. It is guaranteed that this set of connection does not form any cycle. The $j$-th of these connections will connect nodes $ga_j$ and $gb_j$. These connections are also bidirectional. The cost of these connections have not been decided yet.
You can set the prices of these connections to any arbitrary integer value. These prices are set independently for each connection. After setting the prices, the customer will choose such $n - 1$ connections that all nodes are connected in a single network and the total cost of chosen connections is minimum possible. If there are multiple ways to choose such networks, the customer will choose an arbitrary one that also maximizes the number of your connections in it.
You want to set prices in such a way such that \textbf{all} your $k$ connections are chosen by the customer, and the sum of prices of your connections is maximized.
Print the maximum profit you can achieve, or $-1$ if it is unbounded.
|
Consider the forest of your edges. Let's add edges into this forest greedily from our competitor's set in order of increasing weight until we have a spanning tree. Remember, we don't need to sort, the input is already given in sorted order. Now, consider the competitor's edges one by one by increasing weight. Since we have a spanning tree, each competitor edge spans some path on our tree. To process a competitor's edge, we can collapse all the nodes in the path into one single large node, and fix the cost of our edges along this path to be equal to the cost of the currently considered competitor's edge. We know this is an upper bound on cost since if any were higher, then by the cycle property of MSTs, the customer can ignore one of the higher cost edge on this cycle and choose the customer's edge instead. In addition, this still allows us to satisfy the condition of the customer choosing all of our edges, since by Kruskal's algorithm, the customer will try to greedily add our edges first into their spanning tree and won't be able to add the customer edge since it now forms a cycle). This shows that this cost is the maximum possible profit since we have an upper bound on each edge, and this upper bound also gives a valid solution. To determine if our answer can be unbounded, we can check if any of our edges remains uncollapsed after processing all competitor edges. To do this efficiently, we can just do it naively (even without needing to compute LCAs!). To show it's already fast enough, there are only a total of at most $n$ merges overall and each merge can be done in $\alpha(n)$ time, where $\alpha(n)$ is the inverse ackermann function, so the overall complexity is $O(m + (n + k)\alpha(n))$. Unfortunately, this is too hard to separate from solution with logarithms, so those were also allowed to pass (though TL might have been a bit more strict in those cases).
|
[
"dfs and similar",
"dsu",
"graphs",
"trees"
] | 2,600
| null |
1023
|
G
|
Pisces
|
A group of researchers are studying fish population in a natural system of lakes and rivers. The system contains $n$ lakes connected by $n - 1$ rivers. Each river has integer length (in kilometers) and can be traversed in both directions. It is possible to travel between any pair of lakes by traversing the rivers (that is, the network of lakes and rivers form a tree).
There is an unknown number of indistinguishable fish living in the lakes. On day $1$, fish can be at arbitrary lakes. Fish can travel between lakes by swimming the rivers. Each fish can swim a river $l$ kilometers long in any direction in $l$ days. Further, each fish can stay any number of days in any particular lake it visits. No fish ever appear or disappear from the lake system. Each lake can accomodate any number of fish at any time.
The researchers made several observations. The $j$-th of these observations is "on day $d_j$ there were at least $f_j$ distinct fish in the lake $p_j$". Help the researchers in determining the smallest possible total number of fish living in the lake system that doesn't contradict the observations.
|
First, how do we find the answer in any time complexity? Let us construct a partially ordered set where each element is a single fish in one of the observations. For two elements $x = (v_1, d_1)$ and $y = (v_2, d_2)$ we put $x < y$ if $x$ and $y$ could possibly be two occurences of the same fish one after the other, that is, there is enough time to get from one observation to another, so that $\rho(v_1, v_2) \leq d_2 - d_1$, where $\rho(v_1, v_2)$ is the distance between the tree vertices, and $d_1$ and $d_2$ are respective day numbers of the two observations. We can now see that the answer is the smallest number of chains needed to cover all the vertices (a chain is a set of pairwise comparable elements of a p.o.set). By Dilworth's theorem, this is equal to the size of the largest antichain (a set of pairwise incomparable elements). Clearly, if a largest antichain contains a fish from an observation, than it must include all fish from this observation as well. We can now solve the problem in something like $O(2^k)$ time by trying all subsets of observations. To get a better complexity we need to use the tree structure. To start, how do we check if a set of observations forms an antichain? Here's one criterion that works: Proposition. A set $S$ of observations is an antichain iff: For each subtree of the root $v$, a subset of $S$ lying in that subtree is an antichain. There exists a time moment $T$ such that it is impossible to reach $v$ at time $T$ from any observation in $S$ (possibly travelling back in time). Indeed, if both of these conditions hold, than for any two observations $(v_1, d_1)$ and $(v_2, d_2)$ happening in different subtrees we have $\rho(v_1, v_2) = \rho(v, v_1) + \rho(v, v_2) > |d_1 - T| + |d_2 - T| \geq |d_1 - d_2|$, hence these observations are incomparable. On the other hand, if $S$ is an antichain, for any observation $(v_i, d_i) \in S$ there is an interval of time moments $(l_i, r_i)$ such that we cannot reach the root at any of times in $(l_i, r_i)$. If two observations $i$ and $j$ are incomparable, then$(l_i, r_i) \cap (l_j, r_j) \neq \varnothing$. But since we have a set of intervals with pairwise non-empty intersections, they must all share a common point, hence our time moment $T$ exists. Note that in some cases $T$ is necessarily a non-integer: if there are two vertices at distance $1$ from the root, and there are observations happening at days $1$ and $2$ respectively at these vertices, than any $T \in (1, 2)$ will suffice. However, $T$ can always be either an integer or a half-integer, hence we can multiply all times and distances by $2$ and assume $T$ is integer. The solution is going to be subtree dynamic programming $dp_{v, t}$ - the total weight of the largest antichain in the subtree of $v$ such that no observation can reach $v$ at time $t$. Recalculation is a bit tricky, so let's go step by step. First, if we have values of $dp_{v, t}$, and no observations take place at $v$, how do we change $dp_{v, t}$ as we travel up the edge to the top of $v$? If the length of this edge is $l$, then the new values $dp'_{v, t}$ satisfy $dp'_{v, t} = \max_{t' = t - l}^{t + l} dp_{v, t'}$. Let's call this procedure "advancing $l$ steps forward". How do we account for observations at $v$? For an observation $(v, t)$ with $f$ fishes we cannot simply add $f$ to $dp_{v, t}$ since we can obviously reach $v$ at time $t$ from this observation. Instead, the correct procedure is: advance the values $1$ step; apply $dp'_{v, t} = \max(dp'_{v, t}, dp_{v, t} + f)$ for all observations; advance the new values $l - 1$ steps. Finally, to combine the answers from the subtrees $u_1, \ldots, u_k$ of a vertex $v$ (after the advancements were made in them), we simply add them element-wise for each $t$: $dp_{v, t} = \sum_{u_i} dp_{u_i, t}$. Of course, we cannot store the DP values themselves since there are too much of them to store. Instead, we will need to use a data structure that will maintain a piecewise constant function. More specifically, let us maintain the positions where the function changes values: for each $t$ such that $dp_{v, t} \neq dp_{v, t + 1}$ we store the pair $(t, dp_{v, t + 1} - dp_{v, t})$. How all of the above manipulations look like in terms of this difference structure? Element-wise sum of two functions is simply the union of the difference sets. (We may want to combine the differences with the same $t$ value, but for most implementations this is not necessary) When we advance $l$ steps forward, the borders with positive differences will more $l$ units to the left, and negative differences will move to the right. When two borders collide, then some of them get eliminated. Consider the function $10, 1, 5$, with two differences $(1, -9)$ and $(2, 4)$. After advancing this one step, the new function is $10, 10, 5$, so there is now a single difference $(2, -5)$. If we keep track of when and where these collisions take place, we can make changes to the structure accordingly. The structure of choice here is a treap of differences. When we add two functions, we insert all elements of the smaller treap into the larger one; a standard argument shows that at most $O(k \log k)$ insertions will take place overall. To keep track of collisions, we'll have to maintain collision times for all adjacent border pairs, and store the minimal value in the root of each subtree. This may seem cumbersome, but every adjacent pair of elements occurs either as (the rightmost vertex in the left subtree of $v$, $v$), or ($v$, the leftmost vertex in the right subtree of $v$), hence the standard relax function in the treap implementation can handle this. One further detail is that we don't want to change the time values in our treaps. Instead, we'll use "lazy" time shifting, that is, we'll keep an additional value $\Delta$ associated with each treap, and assume that for entries $(t, d)$ with $d > 0$ the actual time should be $t - \Delta$, and with $d < 0$ the time should be $t + \Delta$. This way, we won't need to actually change anything in the treap when advancing (apart from resolving collisions). The total complexity of this solution is $O(n + k \log^2 k)$.
|
[
"data structures",
"flows",
"trees"
] | 3,400
| null |
1025
|
A
|
Doggo Recoloring
|
Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.
The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.
Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $x$ such that there are currently \textbf{at least two} puppies of color $x$ and recolor \textbf{all} puppies of the color $x$ into some arbitrary color $y$. Luckily, this operation can be applied multiple times (including zero).
For example, if the number of puppies is $7$ and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose $x$='c' right now, because currently only one puppy has the color 'c'.
Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.
|
It's easy to see that, if there exists such a color $x$ that at least two puppies share this color, the answer is "Yes" as we can eliminate colors one by one by taking the most numerous color and recoloring all puppies of this color into some other (the number of colors will decrease, but the more-than-one property for the most numerous color will hold, so apply induction). If all puppies' colors are distinct, the answer is "No" except for the case when $n = 1$ (since there's no need to recolor the only puppy).
|
[
"implementation",
"sortings"
] | 900
| null |
1025
|
B
|
Weakened Common Divisor
|
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.
For a given list of pairs of integers $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ their WCD is arbitrary integer greater than $1$, such that it divides at least one element in each pair. WCD may not exist for some lists.
For example, if the list looks like $[(12, 15), (25, 18), (10, 24)]$, then their WCD can be equal to $2$, $3$, $5$ or $6$ (each of these numbers is strictly greater than $1$ and divides at least one number in each pair).
You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.
|
The obvious solution of finding all divisors of all numbers in $\mathcal{O}(n \cdot \sqrt{a_{max}})$ definitely won't pass, so we have to come up with a slight optimization. One may notice that is's sufficient to take a prime WCD (because if some value is an answer, it can be factorized without losing the answer property). To decrease the number of primes to check, let's get rid of the redundant ones. Take an arbitrary pair of elements ($a_i$, $b_i$) and take the union of their prime factorizations. It's easy to see at this point that the cardinality of this union doesn't exceed $2 \cdot \log{a_{max}}$. The rest is to check whether there exists such prime that divides at least one element in each pair in $\mathcal{O}(n \cdot \log{a_{max}})$ time.
|
[
"brute force",
"greedy",
"number theory"
] | 1,600
| null |
1025
|
C
|
Plasticine zebra
|
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras.
Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let's call the number of selected pieces the length of the zebra.
Before assembling the zebra Grisha can make the following operation $0$ or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order "bwbbw" (here 'b' denotes a black strip, and 'w' denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain "wbwbb".
Determine the maximum possible length of the zebra that Grisha can produce.
|
Imagine just for a second, that in reality our string is cyclic with a cut at point $0$ and clockwise traversal direction. Now let's apply the cut & reverse operation at point $i$. The key fact here is that nothing happens to the cyclic string - it's just the traversal direction and the cut point (now $i$ instead of $0$) that change. Here's an example. Let the string be $bwwbwbbw$ and we cut it after the $2$-nd letter ($1$-indexed). It's easy to see that it transforms to $wbwbbwbw$, which equals the initial one after shifting it to the left by $2$ and inverting the traversal direction. This observation helps us see that all strings obtained within these operations are in fact just cuts of one cyclic strings with precision up to traversal direction. In other words, it's enough to find the longest zebra inside the cyclic string - this value will be the answer to the problem.
|
[
"constructive algorithms",
"implementation"
] | 1,600
| null |
1025
|
D
|
Recovering BST
|
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!
Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset.
To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed $1$.
Help Dima construct such a \textbf{binary search tree} or determine that it's impossible. The definition and properties of a binary search tree can be found here.
|
Let $\mathcal{dp}(l, r, root)$ be a dp determining whether it's possible to assemble a tree rooted at $root$ from the subsegment $[l..r]$. It's easy to see that calculating it requires extracting such $root_{left}$ from $[l..root - 1]$ and $root_{right}$ from $[root + 1..right]$ that: $\mathcal{gcd}(a_{root}, a_{root_{left}}) > 1$; $\mathcal{gcd}(a_{root}, a_{root_{right}}) > 1$; $\mathcal{dp}(l, root - 1, root_{left}) = 1$; $\mathcal{dp}(root + 1, r, root_{right}) = 1$. This can be done in $\mathcal{O}(r - l)$ provided we are given all $\mathcal{dp}(x, y, z)$ values for all subsegments of $[l..r]$. Considering a total of $\mathcal{O}(n^3)$ dp states, the final complexity is $\mathcal{O}(n^4)$. That's too much. Let's turn our dp into $\mathcal{dp_{new}}(l, r, side)$ where $side$ can be either $0$ or $1$ - is it possible to make a tree from $[l..r]$ rooted at $l - 1$ or $r + 1$ respectively. It immediately turns out that $\mathcal{dp}(l, r, root)$ is inherited form $\mathcal{dp_{new}}(l, root - 1, 1)$ and $\mathcal{dp_{new}}(root + 1, r, 0)$. Now we have $\mathcal{O}(n^2)$ states, but at the same time all transitions are performed in linear time; thus final complexity is $\mathcal{O}(n^3)$ which is sufficient to pass.
|
[
"brute force",
"dp",
"math",
"number theory",
"trees"
] | 2,100
| null |
1025
|
E
|
Colored Cubes
|
Vasya passes all exams! Despite expectations, Vasya is not tired, moreover, he is ready for new challenges. However, he does not want to work too hard on difficult problems.
Vasya remembered that he has a not-so-hard puzzle: $m$ colored cubes are placed on a chessboard of size $n \times n$. The fact is that $m \leq n$ and all cubes have distinct colors. Each cube occupies exactly one cell. Also, there is a designated cell for each cube on the board, the puzzle is to place each cube on its place. The cubes are fragile, so in one operation you only can move one cube onto one of four neighboring by side cells, if only it is empty. Vasya wants to be careful, so each operation takes exactly one second.
Vasya used to train hard for VK Cup Final, so he can focus his attention on the puzzle for at most $3$ hours, that is $10800$ seconds. Help Vasya find such a sequence of operations that all cubes will be moved onto their designated places, and Vasya won't lose his attention.
|
We're gonna show how to turn an arbitrary arrangement of cubes into the arrangement where $i$-th cube is located at $(i, i)$ (we call such an arrangement basic) in no more than $2*n^{2}$ operations. For simplicity, we imply that we have exactly $n$ cubes where $n$ is even. Say we have some arrangement where $i$-th cube occupies some cell $(x_i, y_i)$. On the first step, we turn it into the arrangement where all cubes have distinct $x$ coordinates. In order to do this, we sort cubes in ascending order of their $x$ coordinates $x$ (with ties broken arbitrarily) . If cube $i$ is at position $j$ in the sorted list, we say that its desired coordinates are $(j, y_i)$. It's easy to check that such choice always allows to move at least one cube from its current position to the desired one through the $y = y_i$ line. If we perform this operation $n$ times, we'll move all cubes to their desired positions. In addition, the maximum number of operations will occur if all the cubes were initially located on the line $x = 1$ or $x = n$, and in this case the number of operations will be equal to $0 + 1 + ... + (n-1)$ < $n^{2}/2$. The formal proof of this inequality can be given using the induction principle. Indeed, the base ($n = 1$) is obvious. Now let the statement be true for all $k \leq n$. Let's prove that if the number of cubes (and the size of the board) changes from $n$ to $(n+1)$, the upper limit of the number of operations increases by no more than $n$. Consider the cube $i$ with maximum $x$ coordinate which we have to move to $x_i = n$. If initially $x_i$ is less than $n$, we move this cube to the desired position in no more than $n$ operations, and other $n$ cubes have coordinates $x_j \leq n$ which implies the upper limit of $n*(n-1)/2$ operations by definition. But if $x_i$ is initially $n$, we don't have to move it whereas each of the remaining $n$ cubes requires one more additional (i.e $n$ total) operation since we added only one diagonal. In total we'll make a total of $n + n*(n-1)/2 = n*(n+1)/2$ operations. Now all $x$ coordinates are distinct and that means that nothing restricts us from changing their $y$ coordinates. Let's move the cubes in such a way that $i$-th cube ends at position $y_i = i$. One cube can be processed in no more than $min(i-1, n-i)$ operations. According to this, we need at most $(n-1) + (n-2) + ... + n/2 + n/2 + ... + (n-1) = 2*((n/2)*(n/2 + n - 1)/2) = 3*n*(n-2)/4 \leq 3*n^{2}/4$ operations in total. Now we obtain an arrangement where all $y$ coordinates are also distinct. If we apply the same operation to cubes' $x$ coordinates, we will end up with $i$-th cube at position $(i, i)$. This requires no more than $n^{2}/2 + 2*(3*n^{2}/4) = 2*n^{2}$ operations. Now we can switch any arrangement to the basic one. Let's get the list of operations for turning the initial position to basic and the final position to basic. Now it's sufficient to reverse one of the lists and concatenate these actions. This yields no more than $4*n^{2} \leq 10000$ operations in total. Note that this estimate is quite rough; however, this is enough under given constraints.
|
[
"constructive algorithms",
"implementation",
"matrices"
] | 2,700
| null |
1025
|
F
|
Disjoint Triangles
|
A point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles are disjoint if there is no point on the plane that belongs to both triangles.
You are given $n$ points on the plane. No two points coincide and no three points are collinear.
Find the number of different ways to choose two disjoint triangles with vertices in the given points. Two ways which differ only in order of triangles or in order of vertices inside triangles are considered equal.
|
The most challenging part of the problem is to think of the way how to count each pair of triangles exactly once. It turns out, that this can be done in a nice and geometrical way. Each pair of triangles has exactly two inner tangents between them. Moreover, exactly one of them (if we direct tangent from point of the first polygon to the point of the second polygon) leaves the first rectangle on the right side and the other tangent leaves it on the left side. So let's brute-force the inner tangent. If we continue the tangent to draw the line and count the number of points on the left and on the right of it, say $k_1$ and $k_2$ respectively, then we simply need to add $\frac{k_1 (k_1 - 1)}{2} \frac{k_2 (k_2 - 1)}{2}$ to our answer, since if we select arbitrary pair of vertices on each halfplanes, together with tangent points we will form a pair of triangles with such a tangent. The question is how to count $k_1$ and $k_2$ for each tangent efficiently. If the points would be sorted by direction, perpendicular to the tangent, we could have answered this query with binary search (since points of one halfplane form a prefix of the sorted array and the other - suffix). However, if we wrote down all the interesting directions, sort them by angle, and make a scanline on it, we could maintain the points in sorted order. Basically, points $a_i$ and $a_j$ change their order in the sorted array at the direction $rotate_{90}(a_i - a_j)$, and, since there are no three points on one line, these points are neighbours in the sorted array at the moment of the swap. The complexity is $\mathcal{O}(n^2 \log(n))$ since we need to sort all $n^2$ directions and for each direction make a binary search on the sorted array.
|
[
"geometry"
] | 2,700
| null |
1025
|
G
|
Company Acquisitions
|
There are $n$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup.
The following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day.
- Two distinct active startups $A$, $B$, are chosen uniformly at random.
- A fair coin is flipped, and with equal probability, $A$ acquires $B$ or $B$ acquires $A$ (i.e. if $A$ acquires $B$, then that means $B$'s state changes from active to acquired, and its starts following $A$).
- When a startup changes from active to acquired, all of its previously acquired startups become active.
For example, the following scenario can happen: Let's say $A$, $B$ are active startups. $C$, $D$, $E$ are acquired startups under $A$, and $F$, $G$ are acquired startups under $B$:
\begin{center}
{\small Active startups are shown in red.}
\end{center}
If $A$ acquires $B$, then the state will be $A$, $F$, $G$ are active startups. $C$, $D$, $E$, $B$ are acquired startups under $A$. $F$ and $G$ have no acquired startups:
If instead, $B$ acquires $A$, then the state will be $B$, $C$, $D$, $E$ are active startups. $F$, $G$, $A$ are acquired startups under $B$. $C$, $D$, $E$ have no acquired startups:
You are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following.
You're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end.
It can be shown the expected number of days can be written as a rational number $P/Q$, where $P$ and $Q$ are co-prime integers, and $Q \not= 0 \pmod{10^9+7}$. Return the value of $P \cdot Q^{-1}$ modulo $10^9+7$.
|
You can solve this most likely by brute forcing small cases and looking for a pattern. Here's a proof of the pattern. Let's define a potential of a startup with $k$ followers to be equal to $2^k - 1$. For example, an active startup with zero followers has potential zero. Now, in one day, if we choose a startup with $p$ followers, and a startup with $q$ followers, the expected change in sum of potentials is equal to $\frac{1}{2}((2^{p+1} - 1 - 2^p + 1) - 2^q + 1) + \frac{1}{2}((2^{q+1} - 1 - 2^q + 1) - 2^p + 1) = 1$, regardless of the values of $p$ and $q$. The potential of the final state is $2^{n-1} - 1$, and we can compute the current potential in linear time, so the expected number of turns is the difference between them. To prove this more rigorously, we can use show that this process is a martingale, so we can use https://en.wikipedia.org/wiki/Optional_stopping_theorem to show that the expected number of days is exactly equal to this difference.
|
[
"constructive algorithms",
"math"
] | 3,200
| null |
1027
|
A
|
Palindromic Twist
|
You are given a string $s$ consisting of $n$ lowercase Latin letters. $n$ is even.
For each position $i$ ($1 \le i \le n$) in string $s$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed \textbf{exactly once}.
For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.
That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' $\rightarrow$ 'd', 'o' $\rightarrow$ 'p', 'd' $\rightarrow$ 'e', 'e' $\rightarrow$ 'd', 'f' $\rightarrow$ 'e', 'o' $\rightarrow$ 'p', 'r' $\rightarrow$ 'q', 'c' $\rightarrow$ 'b', 'e' $\rightarrow$ 'f', 's' $\rightarrow$ 't').
String $s$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.
Your goal is to check if it's possible to make string $s$ a palindrome by applying the aforementioned changes to every position. Print "YES" if string $s$ can be transformed to a palindrome and "NO" otherwise.
Each testcase contains several strings, for each of them you are required to solve the problem separately.
|
If some string can't be transformed to palindrom then it has some pair of positions $(i, n - i + 1)$ with different letters on them (as no such pair affects any other pair). Thus you need to check each pair for $i$ from $1$ to $\frac n 2$ and verify that the distance between the corresponding letters is either $0$ or $2$. Overall complexity: $O(T \cdot n)$.
|
[
"implementation",
"strings"
] | 1,000
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
int main() {
int T;
cin >> T;
int n;
string s;
forn(_, T){
cin >> n >> s;
bool ok = true;
forn(i, n){
int k = abs(s[i] - s[n - i - 1]);
if (k > 2 || k % 2 == 1){
ok = false;
break;
}
}
cout << (ok ? "YES" : "NO") << endl;
}
return 0;
}
|
1027
|
B
|
Numbers on the Chessboard
|
You are given a chessboard of size $n \times n$. It is filled with numbers from $1$ to $n^2$ in the following way: the first $\lceil \frac{n^2}{2} \rceil$ numbers from $1$ to $\lceil \frac{n^2}{2} \rceil$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $n^2 - \lceil \frac{n^2}{2} \rceil$ numbers from $\lceil \frac{n^2}{2} \rceil + 1$ to $n^2$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $\lceil\frac{x}{y}\rceil$ means division $x$ by $y$ rounded up.
For example, the left board on the following picture is the chessboard which is given for $n=4$ and the right board is the chessboard which is given for $n=5$.
You are given $q$ queries. The $i$-th query is described as a pair $x_i, y_i$. The answer to the $i$-th query is the number written in the cell $x_i, y_i$ ($x_i$ is the row, $y_i$ is the column). Rows and columns are numbered from $1$ to $n$.
|
Let's see the following fact: if we will decrease $\lceil \frac{n^2}{2} \rceil$ from all numbers written in cells with an odd sum of coordinates and write out the numbers obtained on the board from left to right from top to bottom, the sequence will looks like $1, 1, 2, 2, \dots, \lceil \frac{n^2}{2} \rceil, \lceil \frac{n^2}{2} \rceil$ for even $n$ (for odd $n$ there is only one number $\lceil \frac{n^2}{2} \rceil$ at the end of the sequence, but, in general, it does not matter). Let's try to find out the answer for some query ($x, y$). Let $cnt=(x - 1) \cdot n + y$ (1-indexed). There $cnt$ is the position of our cell in order of the written sequence. The first approximation of the answer is $\lceil\frac{cnt}{2}\rceil$. But now we are remember that we decreased $\lceil \frac{n^2}{2} \rceil$ from all numbers written in cells with an odd sum of coordinates. So if $x + y$ is even then the answer is $\lceil\frac{cnt}{2}\rceil$, otherwise the answer is $\lceil\frac{cnt}{2}\rceil + \lceil\frac{n^2}{2}\rceil$. Note that you should be careful with integer overflow in C++, Java or similar languages. 64-bit datatype is quite enough. Time complexity: $O(q)$.
|
[
"implementation",
"math"
] | 1,200
|
import sys
lst = sys.stdin.readlines()
n, q = map(int, lst[0].split())
for i in range(q):
x, y = map(int, lst[i + 1].split())
cnt = (x - 1) * n + y
ans = (cnt + 1) // 2
if ((x + y) % 2 == 1): ans += (n * n + 1) // 2
sys.stdout.write(str(ans) + '\n')
|
1027
|
C
|
Minimum Value Rectangle
|
You have $n$ sticks of the given lengths.
Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.
Let $S$ be the area of the rectangle and $P$ be the perimeter of the rectangle.
The chosen rectangle should have the value $\frac{P^2}{S}$ minimal possible. The value is taken without any rounding.
If there are multiple answers, print any of them.
Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately.
|
Let's work with the formula a bit: $\frac{P^2}{s}$ $=$ $\frac{4(x + y)^2}{xy}$ $=$ $4(2 + \frac x y + \frac y x)$ $=$ $8 + 4(\frac x y + \frac y x)$ Let $a = \frac x y$, then the formula becomes $8 + 4(a + \frac 1 a)$. Considering $x \ge y$, $a = \frac x y \ge 1$, thus $(a + \frac 1 a)$ is strictly increasing and has its minimum at $a = 1$. So the solution will be to sort the list, extract the pairs of sticks of equal length and check only neighbouring pairs in sorted order for the answer. Overall complexity: $O(n \log n)$.
|
[
"greedy"
] | 1,600
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long li;
using namespace std;
const int N = 1000 * 1000 + 13;
int n, m;
int a[N];
int b[N];
int main() {
int T;
scanf("%d", &T);
forn(_, T){
scanf("%d", &n);
forn(i, n)
scanf("%d", &a[i]);
sort(a, a + n);
m = 0;
forn(i, n - 1){
if (a[i] == a[i + 1]){
b[m++] = a[i];
++i;
}
}
int A = b[0], B = b[1];
li P2 = (A + B) * li(A + B);
li S = A * li(B);
forn(i, m - 1){
li p2 = (b[i] + b[i + 1]) * li(b[i] + b[i + 1]);
li s = b[i] * li(b[i + 1]);
if (s * P2 > S * p2){
A = b[i];
B = b[i + 1];
S = s;
P2 = p2;
}
}
printf("%d %d %d %d\n", A, A, B, B);
}
}
|
1027
|
D
|
Mouse Hunt
|
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $80\%$ of applicants are girls and majority of them are going to live in the university dormitory for the next $4$ (hopefully) years.
The dormitory consists of $n$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $i$ costs $c_i$ burles. Rooms are numbered from $1$ to $n$.
Mouse doesn't sit in place all the time, it constantly runs. If it is in room $i$ in second $t$ then it will run to room $a_i$ in second $t + 1$ without visiting any other rooms inbetween ($i = a_i$ means that mouse won't leave room $i$). It's second $0$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.
That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $1$ to $n$ at second $0$.
What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?
|
Mouse jumps on a cycle at some point, no matter the starting vertex, thus it's always the most profitable to set traps on cycles. The structure of the graph implies that there are no intersecting cycles. Moreover, mouse will visit each vertex of the cycle, so it's enough to set exactly one trap on each cycle. The only thing left is to find the cheapest vertex of each cycle. This can be done by a simple dfs. Overall complexity: $O(n)$.
|
[
"dfs and similar",
"graphs"
] | 1,700
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) fore(i, 0, n)
#define mp make_pair
#define pb push_back
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define sqr(a) ((a) * (a))
#define x first
#define y second
typedef long long li;
typedef long double ld;
typedef pair<li, li> pt;
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
return out << "(" << p.x << ", " << p.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 << "]";
}
const int INF = int(1e9);
const li INF64 = li(1e18);
const ld EPS = 1e-9;
int n;
vector<int> a, c;
inline bool read() {
if(!(cin >> n))
return false;
c.assign(n, 0);
a.assign(n, 0);
forn(i, n)
assert(scanf("%d", &c[i]) == 1);
forn(i, n) {
assert(scanf("%d", &a[i]) == 1);
a[i]--;
}
return true;
}
vector< vector<int> > cycles;
vector<char> used;
vector<int> path;
void dfs(int v) {
path.push_back(v);
used[v] = 1;
int to = a[v];
if(used[to] != 2) {
if(used[to] == 1) {
cycles.emplace_back();
int id = sz(path) - 1;
while(path[id] != to)
cycles.back().push_back(path[id--]);
cycles.back().push_back(to);
} else
dfs(to);
}
path.pop_back();
used[v] = 2;
}
inline void solve() {
used.assign(n, 0);
forn(i, n) {
if (!used[i])
dfs(i);
}
li ans = 0;
for(auto &cur : cycles) {
int mn = c[cur[0]];
for(int v : cur)
mn = min(mn, c[v]);
ans += mn;
}
cout << ans << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1027
|
E
|
Inverse Coloring
|
You are given a square board, consisting of $n$ rows and $n$ columns. Each tile in it should be colored either white or black.
Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well.
Let's call some coloring suitable if it is beautiful and there is no \textbf{rectangle} of the single color, consisting of at least $k$ tiles.
Your task is to count the number of suitable colorings of the board of the given size.
Since the answer can be very large, print it modulo $998244353$.
|
You can notice that every coloring can be encoded by the two binary strings of length $n$. You firstly generate one string to put as a first row and then use the second string to mark if you put the first string as it is or inverting each color. That way, you can also guess that the area of maximum rectangle of a single color you will get in you coloring is the product of maximum lengths of segments of a single color in both of the strings. Let's consider the following dynamic programming solution: $dp[i][j][k]$ is the number of binary strings of length $i$, such the current last segment of a single color has length $j$ and the maximum segment of a single color has length $k$. The transitions are: $dp[i + 1][j + 1][max(k, j + 1)]$ += $dp[i][j][k]$ - color the new tile the same as the previous one; $dp[i + 1][1][max(k, 1)]$ += $dp[i][j][k]$ - color the new tile the opposite from the previous one. The starting state is $dp[0][0][0] = 1$. Let's sum the values of this dp to an array $cnt[i]$ - the number of binary strings of length $n$ such that the maximum segment of a single color in them has length $i$. You can also do another dp to calculate this not in $O(n^3)$ but in $O(n^2)$ using some partial sums in it. Finally, you iterate over the first side of the resulting rectangle (the maximum length of segment of a single color in a first binary string) and multiply the number of ways to get it by the total number of ways to get the second side of the resulting rectangle, so that the area doesn't $(k - 1)$. Overall complexity: $O(n^3)$ or $O(n^2)$.
|
[
"combinatorics",
"dp",
"math"
] | 2,100
|
def norm(x):
return (x % 998244353 + 998244353) % 998244353
n, k = map(int, input().split())
dp1 = [0]
dp2 = [0]
for i in range(n):
l = [1]
cur = 0
for j in range(n + 1):
cur += l[j]
if(j > i):
cur -= l[j - i - 1]
cur = norm(cur)
l.append(cur)
dp1.append(l[n])
dp2.append(norm(dp1[i + 1] - dp1[i]))
ans = 0
for i in range(n + 1):
for j in range(n + 1):
if(i * j < k):
ans = norm(ans + dp2[i] * dp2[j])
ans = norm(ans * 2)
print(ans)
|
1027
|
F
|
Session in BSU
|
Polycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly $n$ exams.
For the each exam $i$ there are known two days: $a_i$ — day of the first opportunity to pass the exam, $b_i$ — day of the second opportunity to pass the exam ($a_i < b_i$). Polycarp can pass at most one exam during each day. For each exam Polycarp chooses by himself which day he will pass this exam. He has to pass all the $n$ exams.
Polycarp wants to pass all the exams as soon as possible. Print the minimum index of day by which Polycarp can pass all the $n$ exams, or print -1 if he cannot pass all the exams at all.
|
This problem has many approaches (as Hall's theorem, Kuhn algorithm (???) and so on), I will explain one (or two) of them. Let's find the answer using binary search. It is obvious that if we can pass all the exams in $k$ days we can also pass them in $k+1$ days. For the fixed last day $k$ let's do the following thing: firstly, if there exists some exam with the day of the first opportunity to pass it greater than $k$, then the answer for the day $k$ is false. Next, while there exist exams having only one possibility to pass them (because of the upper bound of the maximum possible day or constraints imposed by the other exams), we choose this day for this exam and continue (after choosing such day there can appear some new exams with the same property). Now there are no exams having only one day to pass them. Let's take a look on the graph where vertices represent days and edges represent exams (the edge between some vertices $u$ and $v$ ($u < v$) exists iff there is an exam with the first day to pass it equal to $u$ and the second day to pass it equal to $v$). Let's remove all the exams for which we identified the answer. Now let's take a look on the connected components of this graph and analyze the problem which we have now. Our problem is to choose exactly one vertex incident to each edge of the connected component such that no vertex is chosen twice (and we have to do this for all the connected components we have). Let $cntv$ be the number of vertices in the current connected component and $cnte$ be the number of edges in the current connected component. The answer for the connected component is true iff $cnte \le cntv$, for obvious reasons. There is very easy constructive method to see how we can do this. If $cnte < cntv$ then the current connected component is a tree. Let's remove some leaf of this tree and set it as the chosen vertex for the edge incident to this leaf (and remove this edge too). If $cnte = cntv$ then let's remove all leaves as in the algorithm for the tree. For the remaining cycle let's choose any edge and any vertex incident to it, set this vertex as the chosen to this edge and remove them. Now we have a chain. Chain is a tree, so let's apply the algorithm for the tree to this chain. So, if for some connected component $c$ holds $cnte_c > cntv_c$ then the answer for the day $k$ is false. Otherwise the answer is true. Overall complexity $O(n \log n)$ because of numbers compressing or using logarithmic data structures to maintain the graph. Also there is another solution (which can be too slow, I don't know why it works). It is well-known fact that if we will apply Kuhn algorithm to the some bipartite graph in order of increasing indices of vertices of the left part, then the last vertex in the left part of this graph which is in the matching will be minimum possible. Oh, that's what we need! Let the left part of this graph consist of days and the right part consist of exams. The edge between some vertices $u$ from the left part and $v$ from the right part exists iff $u$ is one of two days to pass the exam $v$. Let's apply Kuhn algorithm to this graph, considering days in increasing order. The first day when matching becomes $n$ (all exams are in the matching) will be the answer. I don't know its complexity, really. Maybe it works too fast because of the special properties of the graph... If someone can explain in which time it works I will very happy!
|
[
"binary search",
"dfs and similar",
"dsu",
"graph matchings",
"graphs"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
mt19937 rnd(time(NULL));
const int N = 2 * 1000 * 1000 + 11;
const int INF = 1e9;
int n;
int a[N][2];
vector<int> nums;
int m;
vector<int> g[N];
int mt[N];
int used[N];
int T = 1;
bool try_kuhn(int v) {
if (used[v] == T)
return false;
used[v] = T;
for (auto to : g[v]) {
if (mt[to] == -1) {
mt[to] = v;
return true;
}
}
for (auto to : g[v]) {
if (try_kuhn(mt[to])) {
mt[to] = v;
return true;
}
}
return false;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &a[i][j]);
nums.push_back(a[i][j]);
}
}
sort(nums.begin(), nums.end());
nums.resize(unique(nums.begin(), nums.end()) - nums.begin());
m = nums.size();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < 2; ++j) {
a[i][j] = lower_bound(nums.begin(), nums.end(), a[i][j]) - nums.begin();
}
}
for (int i = 0; i < n; ++i) {
g[a[i][0]].push_back(i);
g[a[i][1]].push_back(i);
}
memset(mt, -1, sizeof(mt));
int match = 0;
for (int i = 0; i < m; ++i) {
if (try_kuhn(i)) {
++T;
++match;
if (match == n) {
printf("%d\n", nums[i]);
return 0;
}
}
}
puts("-1");
return 0;
}
|
1027
|
G
|
X-mouse in the Campus
|
The campus has $m$ rooms numbered from $0$ to $m - 1$. Also the $x$-mouse lives in the campus. The $x$-mouse is not just a mouse: each second $x$-mouse moves from room $i$ to the room $i \cdot x \mod{m}$ (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the $x$-mouse is unknown.
You are responsible to catch the $x$-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the $x$-mouse enters a trapped room, it immediately gets caught.
And the only observation you made is $\text{GCD} (x, m) = 1$.
|
Some notes: At first, there is $x^{-1} \mod{m}$ since $(x, m) = 1$ (lets define $\text{GCD}(a,b)$ as $(a, b)$). That means that for each $v = 0..m-1$ there is exactly one $u$ that $u \cdot x = v$. So if we look at this problem as the graph then it consists of cycles (consider loops as cycles of length one). So we need to know number of cycles in this graph. At second, $(v, m) = (v \cdot x \mod{m}, m)$ since $(x, m) = 1$, $v \cdot x \mod{m} = v \cdot x - m \cdot k$ and $(v, m) \mid v$ and $(v, m) \mid m$. So all $v$ can be divided in groups by its $(v,m)$. And we can calculate number of cylces in each group independently. Let fix some $\text{GCD}$ equal to $g$. All numbers $v$ such that $(v, m) = g$ can be represented as $v = g \cdot v'$ and $(v', m) = 1$. Number of such $v$ equals to $\varphi(\frac{m}{g})$. Moreover $gv' \cdot x \equiv gv' \cdot (x \mod{\frac{m}{g}}) \mod{m}$. Here we can shift from $v$, $x$ and $m$ to $v'$, $(x \mod{\frac{m}{g}})$ and $\frac{m}{g}$. In result we need for each $d \mid m$ calculate number of cycles created by $x \mod{d}$ from numbers $v$, that $1 \le v < d$ and $(v, d) = 1$. Lets set $x = x \mod{d}$. Next step is to find minimal $k > 0$ such that $x^k \equiv 1 \mod{d}$, let's name it order of $x$ or $\text{ord}(x)$. Then for each $0 \le i,j < k$ if $i \neq j$ then $x^i \not\equiv x^j$ and $v \cdot x^i \not\equiv v \cdot x^j$, so each cycle will have length equal to $\text{ord}(x)$ and number of cycles will be equal to $\frac{\varphi(d)}{\text{ord}(x \mod d)}$. Last step is calculate $\text{ord}(x)$ for each $d \mid m$. There is a fact that $\text{ord}(x) \mid \varphi(d)$ so can try to iterate over all divisors $df$ of $\varphi(d)$ and check $x^{df} \equiv 1$ by binary exponentiation (It seems as $O(divs(m)^2 \log{m})$ but it's faster and author's version work around 2 seconds. It doesn't pass but somebody can write better). But we'll speed it up. Let $\varphi(d) = p_1^{a_1} p_2^{a_2} \dots p_k^{a_k}$. So we can independently for each $p_i$ find its minimal power $b_i \le a_i$ such that $x^{\varphi(d) \cdot p_i^{b_i - a_i}} \equiv 1$. We can just iterate over all $p_i$ and $a_i$ since $\sum{a_i} = O(\log{m})$. Some words about finding $\varphi(d)$ - its factorization differs from factorization of $d$ just by lowering degrees of primes and adding factorizations of some $(p_i - 1)$. But we can manually find factorization of $(p_i - 1)$ with memorization (or even without it) since $\sum{\sqrt{p_i}} \le \prod{\sqrt{p_i}} = O(\sqrt{m})$. So our steps are next: factorize $m$, recursively iterate over all divisors of $m$, find $\varphi(d)$ and $\text{ord}(x \mod d)$, and add to the answer $\frac{\varphi(d)}{\text{ord}(x \mod d)}$. Result complexity is $O(\sqrt{m} + \text{divs}(m) \cdot \log^2{m})$. And the last note is how to multiply $a, b < 10^{14}$ modulo $mod \le 10^{14}$. You can use binary multiplification which will give you extra $\log{m}$ what is not critically in this task (in C++, of course). Or you can use multiplification from hashes, which will work with 64 bit double, since it's only $10^{14}$.
|
[
"bitmasks",
"math",
"number theory"
] | 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 long double ld;
typedef pair<li, li> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
const ld EPS = 1e-9;
li m, x;
inline bool read() {
if(!(cin >> m >> x))
return false;
return true;
}
map< li, vector<pt> > dFact;
vector<pt> fact(li v) {
if(dFact.count(v))
return dFact[v];
li oldv = v;
vector<pt> fs;
for(li d = 2; d * d <= v; d++) {
int cnt = 0;
while(v % d == 0)
v /= d, cnt++;
if(cnt > 0)
fs.emplace_back(d, cnt);
}
if(v > 1)
fs.emplace_back(v, 1), v = 1;
return dFact[oldv] = fs;
}
vector<pt> merge(const vector<pt> &a, const vector<pt> &b) {
vector<pt> ans;
int u = 0, v = 0;
while(u < sz(a) && v < sz(b)) {
if(a[u].x < b[v].x)
ans.push_back(a[u++]);
else if(a[u].x > b[v].x)
ans.push_back(b[v++]);
else {
ans.emplace_back(a[u].x, a[u].y + b[v].y);
u++, v++;
}
}
while(u < sz(a))
ans.push_back(a[u++]);
while(v < sz(b))
ans.push_back(b[v++]);
return ans;
}
li getPw(li a, li b) {
li ans = 1;
fore(i, 0, b)
ans *= a;
return ans;
}
li mul(li a, li b, li mod) {
li m = li(ld(a) * b / mod);
li rem = a * b - m * mod;
while(rem < 0)
rem += mod;
while(rem >= mod)
rem -= mod;
return rem;
}
li binPow(li a, li k, li mod) {
li ans = 1 % mod;
while(k > 0) {
if(k & 1)
ans = mul(ans, a, mod);
a = mul(a, a, mod);
k >>= 1;
}
return ans;
}
li findOrder(li x, li mod, const vector<pt> &f) {
li phi = 1;
fore(i, 0, sz(f)) fore(k, 0, f[i].y)
phi *= f[i].x;
if(phi == 1 || x == 0)
return 1;
li ord = 1;
fore(i, 0, sz(f)) {
li basePw = phi;
fore(k, 0, f[i].y)
basePw /= f[i].x;
li curV = binPow(x, basePw, mod);
int curPw = -1;
fore(k, 0, f[i].y + 1) {
if(curV != 1)
curPw = k;
curV = binPow(curV, f[i].x, mod);
}
ord *= getPw(f[i].x, curPw + 1);
}
return ord;
}
vector<pt> fm;
vector<int> pw;
li calc(int pos, li dv) {
if(pos >= sz(fm)) {
vector<pt> cf = fm;
fore(i, 0, sz(fm))
cf[i].y = max(pw[i] - 1, 0);
li phi = dv;
fore(i, 0, sz(fm)) {
if(pw[i] > 0) {
cf = merge(cf, fact(fm[i].x - 1));
phi -= phi / fm[i].x;
}
}
li k = findOrder(x % dv, dv, cf);
return phi / k;
}
li ans = 0;
fore(i, 0, fm[pos].y + 1) {
pw[pos] = i;
ans += calc(pos + 1, dv);
dv *= fm[pos].x;
}
return ans;
}
inline void solve() {
fm = fact(m);
pw.assign(sz(fm), 0);
li ans = calc(0, 1);
cout << ans << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1028
|
A
|
Find Square
|
Consider a table of size $n \times m$, initially fully white. Rows are numbered $1$ through $n$ from top to bottom, columns $1$ through $m$ from left to right. Some square inside the table with \textbf{odd} side length was painted black. Find the center of this square.
|
There are lots of possible solutions. For example, run through rows from the top until you find one with at least one 'B'. Do the same for the bottom. Average of the two row numbers is the number of the middle row. Now find the first and last 'B' in that row, their average value is the number of the middle column. Alternative approach is to print $\dfrac{\sum\limits_{i=1}^{cnt}x_i}{cnt}, \dfrac{\sum\limits_{i=1}^{cnt}y_i}{cnt}$, where $cnt$ is the number of black points and $\{(x_i, y_i)\}_{i=1}^{cnt}$ is a list of black points.
|
[
"implementation"
] | 800
|
static class SquareInside {
final int inf = (int) 1e9;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt(), m = in.readInt();
char[][] s = new char[n][];
for (int i = 0; i < n; i++) {
s[i] = in.readWord().toCharArray();
}
int minX = inf, maxX = -inf, minY = inf, maxY = -inf;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s[i][j] == 'B') {
minX = Math.min(minX, i);
minY = Math.min(minY, j);
maxX = Math.max(maxX, i);
maxY = Math.max(maxY, j);
}
}
}
out.print((minX + maxX) / 2 + 1);
out.print(' ');
out.println((minY + maxY) / 2 + 1);
}
}
|
1028
|
B
|
Unnatural Conditions
|
Let $s(x)$ be sum of digits in decimal representation of positive integer $x$. Given two integers $n$ and $m$, find some positive integers $a$ and $b$ such that
- $s(a) \ge n$,
- $s(b) \ge n$,
- $s(a + b) \le m$.
|
First note, that if some output is correct for test with $n = 1129$ and $m = 1$, then it's correct for any valid test. After noticing this, we don't need to read input and output one answer for any test. One of many possible answers is $a = 99..9900..001$ (200 nines, 199 zeroes, 1 one) $b = 99..99$ (200 nines) $a + b = 10^{400}$ $s(a) = 1801, s(b) = 1800, s(a+b) = 1$
|
[
"constructive algorithms",
"math"
] | 1,200
|
int len = 400;
cout << string(len, '5') << "\n";
cout << (string(len - 1, '4') + '5') << "\n";
|
1028
|
C
|
Rectangles
|
You are given $n$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $(n-1)$ of the given $n$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.
Find any point with integer coordinates that belongs to at least $(n-1)$ given rectangles.
|
Note that intersection of any number of rectangles is a rectangle too (possibly, empty). Calculate $pref(i)$ - intersection of rectangles with numbers $1, 2, \ldots, i$, and $suf(i)$ - intersection of rectangles with numbers $i, i + 1, \ldots, n$. If $i$ is the index of the rectangle not included in the answer, then intersection of $pref(i-1)$ and $suf(i+1)$ must be non-empty. So, for some $i$ this condition is held, and we can print any integer point inside this rectangle.
|
[
"geometry",
"implementation",
"sortings"
] | 1,600
|
static class Rectangle {
public Point topLeft, bottomRight;
public Rectangle(Point topLeft, Point bottomRight) {
this.topLeft = topLeft;
this.bottomRight = bottomRight;
}
public Rectangle intersect(Rectangle other) {
if (other == null) {
return null;
}
int x0 = Math.max(topLeft.x, other.topLeft.x);
int y0 = Math.max(topLeft.y, other.topLeft.y);
int x1 = Math.min(bottomRight.x, other.bottomRight.x);
int y1 = Math.min(bottomRight.y, other.bottomRight.y);
if (x0 > x1 || y0 > y1) {
return null;
}
return new Rectangle(new Point(x0, y0), new Point(x1, y1));
}
}
private void solve() throws IOException {
int rectanglesCount = nextInt();
Rectangle[] rectangles = new Rectangle[rectanglesCount];
for (int i = 0; i < rectanglesCount; i++) {
Point topLeft = new Point(nextInt(), nextInt());
Point bottomRight = new Point(nextInt(), nextInt());
rectangles[i] = new Rectangle(topLeft, bottomRight);
}
Rectangle[] prefixIntersection = new Rectangle[rectanglesCount + 1];
Rectangle[] suffixIntersection = new Rectangle[rectanglesCount + 1];
prefixIntersection[0] = suffixIntersection[0] = new Rectangle(
new Point(Integer.MIN_VALUE, Integer.MIN_VALUE),
new Point(Integer.MAX_VALUE, Integer.MAX_VALUE)
);
for (int i = 1; i <= rectanglesCount; i++) {
prefixIntersection[i] = rectangles[i - 1].intersect(prefixIntersection[i - 1]);
suffixIntersection[i] = rectangles[rectanglesCount - i].intersect(suffixIntersection[i - 1]);
}
for (int i = 0; i <= rectanglesCount; i++) {
if (prefixIntersection[i] != null) {
Rectangle intersection = prefixIntersection[i].intersect(suffixIntersection[rectanglesCount - i - 1]);
if (intersection != null) {
out.println(intersection.topLeft);
return;
}
}
}
throw new AssertionError();
}
|
1028
|
D
|
Order book
|
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
\textbf{In this problem no two ever existed orders will have the same price.}
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
\begin{center}
{\small The presented order book says that someone wants to sell the product at price $12$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $10$.}
\end{center}
There are two possible actions in this orderbook:
- Somebody adds a new order of some direction with some price.
- Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL $20$" if there is already an offer "BUY $20$" or "BUY $25$" — in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
- "ADD $p$" denotes adding a new order with price $p$ and unknown direction. The order must not contradict with orders still not removed from the order book.
- "ACCEPT $p$" denotes accepting an existing best offer with price $p$ and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $10^9 + 7$. If it is impossible to correctly restore directions, then output $0$.
|
Keep track of a lower bound for the best sell $s_{best}$ and an upper bound for the best buy $b_{best}$ in the order book. If we have ACCEPT $p$ with $p > s_{best}$ or $p < b_{best}$, it's a contradiction and the answer does not exist. If either $b_{best} = p$ or $s_{best} = p$, then the answer stay the same, and if $b_{best} < p < s_{best}$, the answer is multiplied by $2$, because the removed order could've had any direction. After an ACCEPT $p$, the price of the order above it is the new $s_{best}$ and the price of the order below it is the new $b_{best}$. If in the end there are $m$ orders with undetermined direction, the answer is multiplied by $m+1$. To maintain sets of orders with determined direction (i.e. with prices $p \le b_{best}$ or $p \ge s_{best}$) one can use std::set or std::priority_queue in C++ or TreeSet or PriorityQueue in Java.
|
[
"combinatorics",
"data structures",
"greedy"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const int mod = 1e9 + 7;
signed main() {
#ifdef LOCAL
assert(freopen("test.in", "r", stdin));
#endif
int n;
cin >> n;
map<int, int> a{{INT_MIN, 1}, {INT_MAX, 0}};
set<int*> non0{&a.begin()->second};
for (int i = 0; i < n; ++i) {
string t;
int x;
cin >> t >> x;
if (t == "ADD") {
auto it = a.lower_bound(x);
assert(it != a.begin());
--it;
int ways = it->second;
auto m = a.emplace(x, ways).first;
non0.insert(&m->second);
} else {
auto m = a.find(x);
assert(m != a.end() && m != a.begin());
auto it = prev(m);
auto& w = it->second;
w = (w + m->second) % mod;
non0.insert(&it->second);
non0.erase(&m->second);
a.erase(m);
for (auto it2 = non0.begin(); it2 != non0.end(); ) {
if (*it2 == &it->second) {
++it2;
} else {
*(*it2) = 0;
it2 = non0.erase(it2);
}
}
}
}
int res = 0;
for (auto p : a) {
res = (res + p.second) % mod;
}
cout << res << '\n';
}
|
1028
|
E
|
Restore Array
|
While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $a_1, a_2, \ldots, a_n$. Since the talk was long and not promising, Kostya created a new cyclic array $b_1, b_2, \ldots, b_{n}$ so that $b_i = (a_i \mod a_{i + 1})$, where we take $a_{n+1} = a_1$. Here $mod$ is the modulo operation. When the talk became interesting, Kostya completely forgot how array $a$ had looked like. Suddenly, he thought that restoring array $a$ from array $b$ would be an interesting problem (unfortunately, not A).
|
Let's consider a special case at first: all numbers are equal to $M$. Then the answer exists only if $M = 0$ (prove it as an exercise). Now let $M$ be the maximum value in array $b$. Then there exists an index $i$ such that $b_i = M$ and $b_{i-1} < M$ (we assume $b_0 = b_n$). We assume it's $b_n$, otherwise we just shift the array to make this happen. Then $a_n = b_n$ and $a_n < a_1$, $a_i - a_{i+1} = b_i$ for $i < n$, $b_i < a_{i+1}$ for $i < n - 1$ because $b_n$ is maximum value, which is greater than $0$, $b_{n-1} < b_n = M$, $b_n < a_1$ because $b_n < 2 b_n$. Note that without multiplier $2$ before $b_n$ in the formula solution won't work if all numbers in the array except for one are zeroes, because in this case $a_n \mod a_{1} = 0$. Also instead of $2b_n$ it's possible to use something like $b_n + 10^{10}$, the proof doesn't change much in this case.
|
[
"constructive algorithms"
] | 2,400
|
void solve(__attribute__((unused)) bool read) {
int n;
cin >> n;
vector<int> b(n, 0);
for (int i = 0; i < n; ++i) {
cin >> b[i];
}
int mx = *max_element(all(b));
int start_pos = -1;
for (int i = 0; i < n; ++i) {
if (b[i] == mx && b[(i - 1 + n) % n] != mx) {
start_pos = i;
break;
}
}
if (start_pos == -1) {
if (mx == 0) {
cout << "YES\n";
for (int i = 0; i < n; ++i) {
cout << 1 << " \n"[i + 1 == n];
}
return;
}
cout << "NO\n";
return;
}
auto a = b;
for (int i = 1; i < n; ++i) {
int pos = (start_pos - i + n) % n, prev_pos = (start_pos + 1 - i + n) % n;
a[pos] += a[prev_pos];
if (i == 1) {
a[pos] += mx;
}
}
cout << "YES\n";
for (int x : a) {
cout << x << " ";
}
cout << "\n";
}
|
1028
|
F
|
Make Symmetrical
|
Consider a set of points $A$, initially it is empty. There are three types of queries:
- Insert a point $(x_i, y_i)$ to $A$. It is guaranteed that this point does not belong to $A$ at this moment.
- Remove a point $(x_i, y_i)$ from $A$. It is guaranteed that this point belongs to $A$ at this moment.
- Given a point $(x_i, y_i)$, calculate the minimum number of points required to add to $A$ to make $A$ symmetrical with respect to the line containing points $(0, 0)$ and $(x_i, y_i)$. Note that these points are not actually added to $A$, i.e. these queries are independent from each other.
|
The key idea is the fact that the number of points $(x, y)$, where $x, y \ge 0$, with fixed $x^2 + y^2 = C$ is not large. Actually it is equal to the number of divisors of $C$ after removing all prime divisors of $4k+3$ form (because if $C$ has such prime divisor, then both $x, y$ are divisible by it). For the problem constraints it can be checked by brute force that maximum number of points with fixed $C \le 2 \cdot 10^{10}$ is $M = 144$. Since the circumference with the center in origin is symmetrical with respect to any line containing origin, let's solve the problem for each circumference independently. We maintain two maps: $L$ holds the number of points for each line containing origin, $S$ holds the number of pairs of points that are symmetrical with respect to each line containing origin. When the point $p$ is added or removed on some circumference, we iterate over points $q_i$ lying on it and add or remove $1$ to $S[l(p + q_i)]$, as well as add or remove $1$ to $L[l(p)]$ (where $l(p)$ is the line through $(0, 0)$ and $p$). The answer for query $l$ is $n - L[l] - 2 \cdot H[l]$, where $n$ is the number of points at the moment. This solution makes $O(q_{changes} \cdot M + q_{asks})$ queries to map or unordered_map, which is fast enough since $M = 144$.
|
[
"brute force"
] | 2,900
|
struct Point {
int x, y;
Point() {}
Point(int x, int y) : x(x), y(y) {}
void scan() {
cin >> x >> y;
}
auto key() const {
return make_pair(x, y);
}
bool operator < (const Point& ot) const {
return key() < ot.key();
}
bool operator == (const Point& ot) const {
return key() == ot.key();
}
Point operator + (const Point& ot) const {
return Point(x + ot.x, y + ot.y);
}
li sqr_dist() {
return x * 1LL * x + y * 1LL * y;
}
void normalize() {
auto g = gcd(x, y);
x /= g;
y /= g;
}
};
struct Hasher {
size_t operator () (const Point& pt) const {
return pt.x * 2352345 + pt.y;
}
};
enum Type {
INSERT = 1,
REMOVE = 2,
QUERY = 3
};
struct Query {
Type type;
Point pt;
int dist_id;
void scan() {
int type1;
cin >> type1;
type = Type(type1);
pt.scan();
}
};
void solve(__attribute__((unused)) bool read) {
int Q;
cin >> Q;
vector<Query> queries(Q);
map<li, vector<Point>> all_points;
vector<li> dists;
set<Point> have;
for (int i = 0; i < Q; ++i) {
queries[i].scan();
auto& pt = queries[i].pt;
if (queries[i].type != QUERY) {
all_points[pt.sqr_dist()].push_back(pt);
dists.push_back(pt.sqr_dist());
} else {
pt.normalize();
}
}
make_unique(dists);
for (auto& q : queries) {
q.dist_id = (int)(lower_bound(all(dists), q.pt.sqr_dist()) - dists.begin());
}
vector<vector<char>> has_point(dists.size());
vector<vector<Point>> points_by_dist_id(dists.size());
vector<vector<vector<Point>>> sum_points(dists.size());
unordered_map<Point, pair<int, int>, Hasher> point_position;
for (auto& item : all_points) {
make_unique(item.second);
int dist_id = (int)(lower_bound(all(dists), item.first) - dists.begin());
has_point[dist_id].assign(item.second.size(), false);
points_by_dist_id[dist_id] = item.second;
sum_points[dist_id].assign(item.second.size(), vector<Point>(item.second.size()));
for (int i = 0; i < item.second.size(); ++i) {
point_position[item.second[i]] = {dist_id, i};
for (int j = 0; j < item.second.size(); ++j) {
sum_points[dist_id][i][j] = item.second[i] + item.second[j];
sum_points[dist_id][i][j].normalize();
}
}
}
unordered_map<Point, int, Hasher> on_line;
unordered_map<Point, int, Hasher> good_pairs;
auto change_on_line = [&] (Point pt, bool add) {
pt.normalize();
if (add) {
++on_line[pt];
} else {
assert(on_line[pt] > 0);
--on_line[pt];
}
};
int n_points = 0;
for (auto& cur_q : queries) {
auto& pt = cur_q.pt;
int dist_id = cur_q.dist_id;
if (cur_q.type == INSERT) {
++n_points;
int pos = point_position[pt].second;
assert(!has_point[dist_id][pos]);
change_on_line(pt, true);
for (int i = 0; i < points_by_dist_id[dist_id].size(); ++i) {
if (i == pos || !has_point[dist_id][i]) {
continue;
}
++good_pairs[sum_points[dist_id][i][pos]];
}
has_point[dist_id][pos] = true;
} else if (cur_q.type == REMOVE) {
--n_points;
int pos = point_position[pt].second;
assert(has_point[dist_id][pos]);
change_on_line(pt, false);
for (int i = 0; i < points_by_dist_id[dist_id].size(); ++i) {
if (i == pos || !has_point[dist_id][i]) {
continue;
}
--good_pairs[sum_points[dist_id][i][pos]];
}
has_point[dist_id][pos] = false;
} else if (cur_q.type == QUERY) {
pt.normalize();
cout << n_points - 2 * good_pairs[pt] - on_line[pt] << "\n";
}
}
}
|
1028
|
G
|
Guess the number
|
This problem is interactive.
You should guess hidden number $x$ which is between $1$ and $M = 10004205361450474$, inclusive.
You could use up to $5$ queries.
In each query, you can output an increasing sequence of $k \leq x$ integers, each between $1$ and $M$, inclusive, and you will obtain one of the following as an answer:
- either the hidden number belongs to your query sequence, in this case you immediately win;
- or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $i$ that the hidden number $x$ is between the $i$-th and the $(i+1)$-st numbers of your sequence.
See the interaction section for clarity.
Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.
Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between $1$ and $M$. In all pretests the hidden number is fixed as well.
|
Although it looks strange, the bound on the number from the problem statement is actually tight for $5$ queries of length up to $10^4$. Let's find out how to obtain this number. Let $dp(l, q)$ is the maximum $(r - l)$ such that we can guess the number which is known to be in $[l; r)$ using $q$ queries. The number $l$ is the bound for the number of guesses in the next query, except for the case $l > 10^4$ - then $dp(l, q) = dp(10^4, q)$, since from that time the bound for this number will be $10^4$. The following process calculates $dp(l,q)$: $r_0 = l$ $r_{i + 1} = r_i + dp(r_i, q - 1) + 1$ $dp(l,q) = r_{l + 1} - l$. The complexity of the solution can be estimated as $O(M_q \cdot M_{guesses}^2)$, where $M_q = 5$ and $M_{guesses} = 10^4$, but actually it's much faster if we calculate $dp$ only for reachable states.
|
[
"dp",
"interactive"
] | 3,000
|
private static final int MAX_WIDTH = 10000;
private static final int QUERIES = 5;
public static final long INF = 20000000000000000L;
long[][] memo = new long[QUERIES + 1][MAX_WIDTH + 1];
long dp(int guesses, long l) {
if (guesses == 0) {
return l;
}
if (l > MAX_WIDTH) {
return Math.min(INF, dp(guesses, MAX_WIDTH) + l - MAX_WIDTH);
}
if (memo[guesses][(int) l] != 0) {
return memo[guesses][(int) l];
}
long ans = l;
for (int i = 0; i < l; ++i) {
ans = dp(guesses - 1, ans);
++ans;
}
ans = dp(guesses - 1, ans);
return memo[guesses][(int) l] = Math.min(ans, INF);
}
private void run() throws IOException {
long l = 1;
long r = dp(QUERIES, 1);
for (int queriesNext = QUERIES - 1; queriesNext >= 0; --queriesNext) {
List<Long> query = new ArrayList<>();
long curL = l;
for (int i = 0, e = (int)Math.min(l, MAX_WIDTH); i < e; ++i) {
long end = dp(queriesNext, curL);
query.add(end);
curL = end + 1;
}
assert r == dp(queriesNext, curL);
out.print(query.size());
for (long x: query) {
out.print(" ");
out.print(x);
}
out.println();
out.flush();
System.out.flush();
int ans = readInt();
if (ans < 0) {
return;
}
if (ans > 0) {
l = query.get(ans - 1) + 1;
}
if (ans != query.size()) {
r = query.get(ans);
}
assert dp(queriesNext, l) == r;
}
}
|
1028
|
H
|
Make Square
|
We call an array $b_1, b_2, \ldots, b_m$ good, if there exist two indices $i < j$ such that $b_i \cdot b_j$ is a perfect square.
Given an array $b_1, b_2, \ldots, b_m$, in one action you can perform one of the following:
- multiply any element $b_i$ by any prime $p$;
- divide any element $b_i$ by prime $p$, if $b_i$ is divisible by $p$.
Let $f(b_1, b_2, \ldots, b_m)$ be the minimum number of actions needed to make the array $b$ good.
You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$ and $q$ queries of the form $l_i, r_i$. For each query output $f(a_{l_i}, a_{l_i + 1}, \ldots, a_{r_i})$.
|
Firstly, we can divide out all squares from the $a_i$, since they make no difference. Thus, each $a_i$ is then a product of unique primes. If we want to transform $a_i$ and $a_j$ so that their product becomes a square, the cost is the number of primes that appear in one but not in another. Each $a_i$ can have at most $7$ primes ($2 \cdot 3 \cdot 5 \cdot 7 \cdot 11 \cdot 13 \cdot 17 \cdot 19$ is too big), so at most $128$ divisors. Sweep from left to right, maintaining $dp[val][dist]$ - the rightmost index $i$ so far that $a_i$ can be expressed as $val \cdot x$, where $x$ has $dist$ primes in its factorization. Also maintain $best[D]$ - the rightmost $l$ such that the answer for the segment $[l; i]$ is $D$, for current index $i$. To add a new $a_i$ in $dp$, consider each divisor $val$ in it, calculate $dist$ as the number of primes in $\dfrac{a_i}{val}$ and relax $dp[val][dist]$ with $i$. Before doing this for $i$, we need to update $best$ array: for each $val~|~a_i$ and $\dfrac{a_i}{val}$ having $dist$ primes in factorization and for each $k \le 7$ relax $best[k + dist]$ with $dp[val][dist]$. Then all queries with right border equal to $i$ can be answered in $O(M_{ans})$ time, where $M_{ans} \le 14$. The complexity of this solution is $O(n \cdot M_{primes} \cdot 2^{M_{primes}} + q \cdot M_{ans})$, where $M_{primes} = 7$, $M_{ans} \le 2 M_{primes}$. Actually, the maximum possible answer for a query in this problem is $11$. You can find two numbers generating it as an exercise.
|
[
"math"
] | 2,900
|
const int C = 5032107 + 1;
int lp[C];
int fred[C];
int num_primes[C];
const int MAX_DIVISORS = 7;
const int MAX_ANS = 2 * MAX_DIVISORS;
int max_left[MAX_DIVISORS + 1][C];
int max_border[MAX_ANS + 1];
vector<int> cur_primes;
vector<int> divs;
void get_divisors(int n) {
divs = {1};
while (n > 1) {
int p = lp[n];
n /= p;
int sz = divs.size();
for (int i = 0; i < sz; ++i) {
divs.push_back(divs[i] * p);
}
}
}
void solve(bool read) {
vector<int> pr;
for (int i = 2; i < C; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.push_back(i);
}
for (int j = 0; j < pr.size() && pr[j] <= lp[i] && i * pr[j] < C; ++j) {
lp[i * pr[j]] = pr[j];
}
}
fred[1] = 1;
for (int i = 2; i < C; ++i) {
int p = lp[i];
int cur = i / p;
if (cur % p == 0) {
fred[i] = fred[cur / p];
num_primes[i] = num_primes[cur / p];
} else {
fred[i] = p * fred[cur];
num_primes[i] = num_primes[cur] + 1;
}
}
for (int i = 0; i < C; ++i) {
for (int j = 0; j <= MAX_DIVISORS; ++j) {
max_left[j][i] = -1;
}
}
memset(max_border, -1, sizeof(max_border));
int n;
cin >> n;
int Q;
cin >> Q;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
a[i] = fred[a[i]];
}
vector<vector<pair<int, int>>> queries(n);
vector<int> res(Q);
for (int i = 0; i < Q; ++i) {
int l, r;
cin >> l >> r;
--l; --r;
queries[r].push_back({l, i});
}
for (int i = 0; i < n; ++i) {
get_divisors(a[i]);
for (int d : divs) {
int first_add = num_primes[a[i]] - num_primes[d];
for (int prev_ans = 0; prev_ans <= MAX_DIVISORS; ++prev_ans) {
int cur_left = max_left[prev_ans][d];
int cur_ans = first_add + prev_ans;
if (cur_ans <= MAX_ANS) {
relax_max(max_border[cur_ans], cur_left);
}
}
}
for (int d : divs) {
int first_add = num_primes[a[i]] - num_primes[d];
relax_max(max_left[first_add][d], i);
}
for (auto q : queries[i]) {
res[q.second] = MAX_ANS + 1;
for (int cur_ans = 0; cur_ans <= MAX_ANS; ++cur_ans) {
if (max_border[cur_ans] >= q.first) {
res[q.second] = cur_ans;
break;
}
}
assert(res[q.second] <= MAX_ANS);
}
}
int sum_ans = 0;
for (int i = 0; i < Q; ++i) {
cout << res[i] << '\n';
}
}
|
1029
|
A
|
Many Equal Substrings
|
You are given a string $t$ consisting of $n$ lowercase Latin letters and an integer number $k$.
Let's define a substring of some string $s$ with indices from $l$ to $r$ as $s[l \dots r]$.
Your task is to construct such string $s$ of minimum possible length that there are exactly $k$ positions $i$ such that $s[i \dots i + n - 1] = t$. In other words, your task is to construct such string $s$ of minimum possible length that there are exactly $k$ substrings of $s$ equal to $t$.
It is guaranteed that the answer is always unique.
|
Let's carry the current answer as $ans$, the last position we're checked as $pos$ and the number of occurrences as $cnt$. Initially, the answer is $t$, $cnt$ is $1$ and $pos$ is $1$ (0-indexed). We don't need to check the position $0$ because there is the beginning of the occurrence of $t$ at this position. Also $cnt$ is $1$ by the same reason. Let's repeat the following algorithm while $cnt < k$: if $pos >= |ans|$, where |ans| is the length of the answer, let's add $t$ to the answer, increase $cnt$ and $pos$ by $1$. In the other case let's check if there is a prefix of $t$ starting from $pos$. If it is, let $len$ be its length. Then we need to add the suffix of $t$ starting from $len$ till the end of $t$, increase $cnt$ and $pos$ by $1$. If there is no prefix of $t$ starting from $pos$ the we just increase $pos$. The other idea is the following: we have to find the period of the string $t$. Let this period will be $p$. Then the answer is $p$ repeated $k-1$ times and $t$. The period of the string $s$ is the minimum prefix of this string such that we can repeat this prefix infinite number of times so the prefix of this infinite string will be $s$. For example, the period of the string $ababa$ is $ab$, the period of the string $abc$ is $abc$ and the period of the string $aaaaa$ is $a$. The period of the string can be found using prefix-function of the string or in $O(n^2)$ naively.
|
[
"implementation",
"strings"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
#define sz(a) int((a).size())
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, k;
string t;
cin >> n >> k >> t;
vector<int> p(n);
for (int i = 1; i < sz(t); ++i) {
int j = p[i - 1];
while (j > 0 && t[j] != t[i])
j = p[j - 1];
if (t[i] == t[j])
++j;
p[i] = j;
}
int len = sz(t) - p[n - 1];
for (int i = 0; i < k - 1; ++i)
cout << t.substr(0, len);
cout << t << endl;
return 0;
}
|
1029
|
B
|
Creating the Contest
|
You are given a problemset consisting of $n$ problems. The difficulty of the $i$-th problem is $a_i$. It is guaranteed that all difficulties are distinct and are given in the increasing order.
You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $a_{i_1}, a_{i_2}, \dots, a_{i_p}$ be the difficulties of the selected problems in increasing order. Then for each $j$ from $1$ to $p-1$ $a_{i_{j + 1}} \le a_{i_j} \cdot 2$ should hold. It means that the contest consisting of only one problem is always valid.
Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.
|
The answer is always a segment of the initial array. The authors solution uses two pointers technique: let's iterate over all left bounds of the correct contests and try to search maximum by inclusion correct contest. Let's iterate over all $i$ from $0$ to $n-1$ and let the current left bound be $i$. Let $j$ be the maximum right bound of the correct contest starting from the position $i$. Initially $j=i$. Now while $j + 1 < n$ and $a_{j + 1} \le a_j \cdot 2$ let's increase $j$. Try to update the answer with the value $j - i + 1$. It is obvious that all positions from $i + 1$ to $j$ cannot be left bounds of the maximum by inclusion correct contests, so let's set $i=j$ and go on. Because each element will be processed once, time complexity is $O(n)$.
|
[
"dp",
"greedy",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
#endif
int n;
scanf("%d", &n);
vector<int> a(n);
for (int i = 0; i < n; ++i)
scanf("%d", &a[i]);
int ans = 0;
for (int i = 0; i < n; ++i) {
int j = i;
while (j + 1 < n && a[j + 1] <= a[j] * 2)
++j;
ans = max(ans, j - i + 1);
i = j;
}
printf("%d\n", ans);
}
|
1029
|
C
|
Maximal Intersection
|
You are given $n$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.
The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $0$ in case the intersection is an empty set.
For example, the intersection of segments $[1;5]$ and $[3;10]$ is $[3;5]$ (length $2$), the intersection of segments $[1;5]$ and $[5;7]$ is $[5;5]$ (length $0$) and the intersection of segments $[1;5]$ and $[6;6]$ is an empty set (length $0$).
Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $(n - 1)$ segments has the maximal possible length.
|
Intersection of some segments $[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$ is $[\max \limits_{i = 1}^n l_i; \min \limits_{i = 1}^n r_i]$. If this segment has its left bound greater than its right bound then the intersection is empty. Removing some segment $i$ makes the original sequence equal to $[l_1, r_1], \dots, [l_{i - 1}, r_{i - 1}], \dots [l_{i + 1}, r_{i + 1}], \dots, [l_n, r_n]$. That can be split up to a prefix of length $i - 1$ and a suffix of length $n - i$. Intersections for them can be precalced separately and stored in some partial sum-like arrays. Finally, you have to iterate over the position of the removed segment and calculate the intersection of prefix and suffix without this segment. Overall complexity: $O(n)$.
|
[
"greedy",
"math",
"sortings"
] | 1,600
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int N = 300 * 1000 + 13;
const int INF = int(1e9);
int n;
int prl[N], prr[N], sul[N], sur[N];
int l[N], r[N];
int main() {
scanf("%d", &n);
forn(i, n)
scanf("%d%d", &l[i], &r[i]);
prl[0] = sul[n] = 0;
prr[0] = sur[n] = INF;
forn(i, n){
prl[i + 1] = max(prl[i], l[i]);
prr[i + 1] = min(prr[i], r[i]);
}
for (int i = n - 1; i >= 0; --i){
sul[i] = max(sul[i + 1], l[i]);
sur[i] = min(sur[i + 1], r[i]);
}
int ans = 0;
forn(i, n)
ans = max(ans, min(prr[i], sur[i + 1]) - max(prl[i], sul[i + 1]));
printf("%d\n", ans);
return 0;
}
|
1029
|
D
|
Concatenated Multiples
|
You are given an array $a$, consisting of $n$ positive integers.
Let's call a concatenation of numbers $x$ and $y$ the number that is obtained by writing down numbers $x$ and $y$ one right after another without changing the order. For example, a concatenation of numbers $12$ and $3456$ is a number $123456$.
Count the number of ordered pairs of positions $(i, j)$ ($i \neq j$) in array $a$ such that the concatenation of $a_i$ and $a_j$ is divisible by $k$.
|
Let's rewrite concatenation in a more convenient form. $conc(a_i, a_j) = a_i \cdot 10^{len_j} + a_j$, where $len_j$ is the number of digits in $a_j$. Then this number is divisible by $k$ if and only if the sum of ($a_{j}~ mod~ k$) and ($(a_i \cdot 10^{len_j})~ mod~ k$) is either $0$ or $k$. Let's calculate $10$ arrays of remainders $rem_1, rem_2, \dots, rem_{10}$. For each $i$ $a_i$ adds ($a_{i}~ mod~ k$) to $rem_{len_i}$. That's the first term of the sum. Now iterate over the second term, for $i \in [1..n]$ and for $j \in [1..10]$ you binary search for ($k - ((a_i \cdot 10^j)~ mod~ k)$) in $rem_j$. The number of its occurrences should be added to answer. You also might have calculated some pairs $(i, i)$, iterate over them and subtract them naively. Overall complexity: $O(10 \cdot n \log n)$.
|
[
"implementation",
"math"
] | 1,900
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long li;
using namespace std;
const int N = 200 * 1000 + 13;
const int LOGN = 11;
int n, k;
int a[N];
int len[N];
vector<int> rems[LOGN];
int pw[LOGN];
int main() {
scanf("%d%d", &n, &k);
forn(i, n) scanf("%d", &a[i]);
pw[0] = 1;
forn(i, LOGN - 1)
pw[i + 1] = pw[i] * 10 % k;
forn(i, n){
int x = a[i];
while (x > 0){
++len[i];
x /= 10;
}
rems[len[i]].push_back(a[i] % k);
}
forn(i, LOGN)
sort(rems[i].begin(), rems[i].end());
li ans = 0;
forn(i, n){
for (int j = 1; j < LOGN; ++j){
int rem = (a[i] * li(pw[j])) % k;
int xrem = (k - rem) % k;
auto l = lower_bound(rems[j].begin(), rems[j].end(), xrem);
auto r = upper_bound(rems[j].begin(), rems[j].end(), xrem);
ans += (r - l);
if (len[i] == j && (rem + a[i] % k) % k == 0)
--ans;
}
}
printf("%lld\n", ans);
return 0;
}
|
1029
|
E
|
Tree with Small Distances
|
You are given an undirected tree consisting of $n$ vertices. An undirected tree is a connected undirected graph with $n - 1$ edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $1$ to any other vertex is at most $2$. Note that you are not allowed to add loops and multiple edges.
|
The first idea is the following: it is always profitable to add the edges from the vertex $1$ to any other vertex. The proof is the following: if we will add two edges $(1, u)$ and $(u, v)$ then the distance to the vertex $u$ will be $1$, the distance to the vertex $v$ will be $2$. But we can add edges $(1, u)$ and $(1, v)$ and this will be better (in fact, you cannot obtain the less answer by adding two edges in the other way). The main idea is the following. Let's carry all vertices of the tree with the distance more than $2$ in the set. Let the vertex with the maximum distance be $v$. What we will obtain if we will add the edge $(1, v)$? The distance to the vertex $v$ will be $1$ and the distance to the vertex $p_v$ (where $p_v$ is the parent of the vertex $v$ if we will root the tree by the vertex $1$) will be $2$. So we will make reachable at most two vertices (if the vertex $p_v$ is already reachable then it will be not counted in the answer). Now what we will obtain if we will add the edge $(1, p_v)$? We will make reachable all the vertices adjacent to the vertex $p_v$ and the vertex $p_v$ (the number of such vertices is not less than $1$ so this move won't make the answer greater instead of any other way to add the edge). After adding such edge let's remove the vertex $p_v$ and all vertices adjacent to it from the set. We need to repeat this algorithm until the set will not become empty. Time complexity is $O(n \log n)$. I sure that there exists the solution with the dynamic programming in the linear time, I will be very happy if someone will explain it to other participants.
|
[
"dp",
"graphs",
"greedy"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int N = 200 * 1000 + 11;
int p[N];
int d[N];
vector<int> g[N];
void dfs(int v, int pr = -1, int dst = 0) {
d[v] = dst;
p[v] = pr;
for (auto to : g[v]) {
if (to != pr) {
dfs(to, v, dst + 1);
}
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
#endif
int n;
scanf("%d", &n);
for (int i = 0; i < n - 1; ++i) {
int x, y;
scanf("%d %d", &x, &y);
--x, --y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(0);
set<pair<int, int>> st;
for (int i = 0; i < n; ++i) {
if (d[i] > 2) {
st.insert(make_pair(-d[i], i));
}
}
int ans = 0;
while (!st.empty()) {
int v = st.begin()->second;
v = p[v];
++ans;
auto it = st.find(make_pair(-d[v], v));
if (it != st.end()) {
st.erase(it);
}
for (auto to : g[v]) {
auto it = st.find(make_pair(-d[to], to));
if (it != st.end()) {
st.erase(it);
}
}
}
printf("%d\n", ans);
}
|
1029
|
F
|
Multicolored Markers
|
There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly $a$ red tiles and exactly $b$ blue tiles across the board.
Vova wants to color such a set of tiles that:
- they would form a \textbf{rectangle}, consisting of exactly $a+b$ colored tiles;
- all tiles of at least one color would also form a \textbf{rectangle}.
Here are some examples of correct colorings:
Here are some examples of incorrect colorings:
Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?
It is guaranteed that there exists at least one correct coloring.
|
$a+b$ should be area of the outer rectangle. It means that its sides are divisors of $a+b$. The same holds for the inner rectangle. Let's assume that red color forms a rectangle, we'll try it and then swap $a$ with $b$ and solve the same problem again. Write down all the divisors of $a$ up to $\sqrt a$, these are the possible smaller sides of the inner rectangle. Divisors of $a+b$ up to $\sqrt{a+b}$ are possible smaller sides of the outer rectangle. Let's put inner rectangle to the left bottom corner of the outer rectangle and choose smaller sides of both of them as bottom and top ones. Iterate over the divisors $d1$ of $a+b$, for each of them choose the greatest divisor $d2$ of $a$ smaller or equal to it and check that $\frac{a+b}{d1} \ge \frac{a}{d2}$. Update the answer with $2(d1 + \frac{a+b}{d1})$ if it holds. You can use both binary search or two pointers, both get AC pretty easily. The number of divisors of $n$ can usually be estimated as $n^{\frac 1 3}$. Overall complexity: $O(\sqrt{a+b})$.
|
[
"binary search",
"brute force",
"math",
"number theory"
] | 2,000
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
typedef long long li;
using namespace std;
const int N = 1000 * 1000;
int lens[N];
int k;
li solve(li a, li b){
k = 0;
for (li i = 1; i * i <= b; ++i)
if (b % i == 0)
lens[k++] = i;
li ans = 2 * (a + b) + 2;
li x = a + b;
int l = 0;
for (li i = 1; i * i <= x; ++i){
if (x % i == 0){
while (l + 1 < k && lens[l + 1] <= i)
++l;
if (b / lens[l] <= x / i)
ans = min(ans, (i + x / i) * 2);
}
}
return ans;
}
int main() {
li a, b;
scanf("%lld%lld", &a, &b);
printf("%lld\n", min(solve(a, b), solve(b, a)));
return 0;
}
|
1030
|
A
|
In Search of an Easy Problem
|
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked $n$ people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these $n$ people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.
|
Codebait. Comforting problem. Find $\max\limits_{i=1..n}{(\text{answer}_i)}$, if it's equal to $1$ then answer is HARD, otherwise - EASY.
|
[
"implementation"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
int curMax = 0;
for(int i = 0; i < n; i++) {
int curAns; cin >> curAns;
curMax = max(curMax, curAns);
}
puts(curMax > 0 ? "HARD" : "EASY");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.