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
⌀ |
|---|---|---|---|---|---|---|---|
1151
|
B
|
Dima and a Bad XOR
|
Student Dima from Kremland has a matrix $a$ of size $n \times m$ filled with non-negative integers.
He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!
Formally, he wants to choose an integers sequence $c_1, c_2, \ldots, c_n$ ($1 \leq c_j \leq m$) so that the inequality $a_{1, c_1} \oplus a_{2, c_2} \oplus \ldots \oplus a_{n, c_n} > 0$ holds, where $a_{i, j}$ is the matrix element from the $i$-th row and the $j$-th column.
Here $x \oplus y$ denotes the bitwise XOR operation of integers $x$ and $y$.
|
Let's take the first number in each array. Then, if we have current XOR strictly greater than zero we can output an answer. And if there is some array, such that it contains at least two distinct numbers, you can change the first number in this array to number, that differs from it, and get XOR $0 \oplus x > 0$. Else, each array consists of the same numbers, so all possible XORs are equal to $0$, and there is no answer. Complexity is $\mathcal{O}(n \cdot m)$.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"dp"
] | 1,600
| null |
1151
|
C
|
Problem for Nazar
|
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.
Consider two infinite sets of numbers. The first set consists of odd positive numbers ($1, 3, 5, 7, \ldots$), and the second set consists of even positive numbers ($2, 4, 6, 8, \ldots$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out \textbf{two times more} numbers than at the previous one, and also \textbf{changes the set} from which these numbers are written out \textbf{to another}.
The ten first written numbers: $1, 2, 4, 3, 5, 7, 9, 6, 8, 10$. Let's number the numbers written, starting \textbf{with one}.
The task is to find the sum of numbers with numbers from $l$ to $r$ for given integers $l$ and $r$. The answer may be big, so you need to find the remainder of the division by $1000000007$ ($10^9+7$).
Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.
|
At first let's simplify the problem. Let's denote as $f(x)$ function that returns sum of the elements that are on positions from $1$ to $x$ inclusive. How to implement function $f(x)$? To find the answer we can find the sum of even and sum of odd numbers and add them. Let's find how many there are even and odd numbers. Let's call them $cur_{even}$ and $cur_{odd}$. Iterate through the powers of two. If current power is even, then add minimum from $x$ and current power of two to $cur_{odd}$, otherwise add minimum from $x$ and current power of two to $cur_{even}$, after that reduce $x$ by current power of two. If $x$ becomes less than or equal to $0$ break. Now our task is reduced to twos: for given number $n$ find the sum of first $n$ even numbers and for given number $m$ find the sum of first $m$ odd numbers. The answer for first task is $n \cdot (n + 1)$. The answer for second task is $m^2$. Now the answer for the problem is $f(r)-f(l-1)$. Don't forget about modulo :) Complexity is $\mathcal{O}(\log{N})$.
|
[
"constructive algorithms",
"math"
] | 1,800
| null |
1151
|
D
|
Stas and the Queue at the Buffet
|
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $n$ high school students numbered from $1$ to $n$. Initially, each student $i$ is on position $i$. Each student $i$ is characterized by two numbers — $a_i$ and $b_i$. Dissatisfaction of the person $i$ equals the product of $a_i$ by the number of people standing to the left of his position, add the product $b_i$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $i$, which is on the position $j$, equals $a_i \cdot (j-1) + b_i \cdot (n-j)$.
The director entrusted Stas with the task: rearrange the people in the queue so that \textbf{minimize the total} dissatisfaction.
Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
|
Firstly, open the brackets: $a_i \cdot (j-1) + b_i \cdot (n-j)$ = $(a_i - b_i) \cdot j + b_i \cdot n - a_i$. As you can see $b_i \cdot n - a_i$ is not depending on $j$, so we can sum these values up and consider them as constants. Now we must minimize the sum of $(a_i - b_i) \cdot j$. Let's denote two integers arrays each of length $n$: array $c$ such that $c_i=a_i-b_i$ and array $d$ such that $d_i=i$ (for each $i$ from $1$ to $n$). Now we must solve the following task: minimize the value $\sum_{i=1}^{n} c_i \cdot d_i$ if we can rearrange the elements of array $c$ as we want. To solve this problem we must sort array $c$ in non-increasing order. You can use an exchange argument to prove it. Complexity is $\mathcal{O}(n\log{n})$.
|
[
"greedy",
"math",
"sortings"
] | 1,600
| null |
1151
|
E
|
Number of Components
|
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of $n$ vertices. Each vertex $i$ has its own value $a_i$. All vertices are connected in series by edges. Formally, for every $1 \leq i < n$ there is an edge between the vertices of $i$ and $i+1$.
Denote the function $f(l, r)$, which takes two integers $l$ and $r$ ($l \leq r$):
- We leave in the tree only vertices whose values range from $l$ to $r$.
- The value of the function will be the number of connected components in the new graph.
Your task is to calculate the following sum: $$\sum_{l=1}^{n} \sum_{r=l}^{n} f(l, r) $$
|
First of all assign $0$ to $a_0$. How to find the value of $f(l, r)$ in $\mathcal{O}(n)$? For each $i$ from $0$ to $n$ set $b_i$ to $1$ if $l \leq a_i \leq r$, otherwise set it to $0$. Now we can see that the value of $f(l, r)$ is equal to the number of adjacent pairs $(0, 1)$ in array $b$. So now we can find the answer in $\mathcal{O}(n)$ using technique contribution to the sum. For every adjacent pair of elements in array $a$ (including zero-indexed element) we must find it contribution to the overall answer. Considering the thoughts above about $f(l,r)$, we must find the number of pairs $(l, r)$ such that $a_i$ is on the range $[l, r]$ and $a_{i-1}$ is not on the range $[l, r]$. There are two cases: What if $a_i$ is greater than $a_{i-1}$? Then $l$ must be on range from $a_{i-1}+1$ to $a_i$ and $r$ must be on range from $a_i$ to $n$. The contribution is $(a_i-a_{i-1}) \cdot (n-a_i+1)$. What if $a_i$ is less than $a_{i-1}$? Then $l$ must be on range from $1$ to $a_i$ and $r$ must be on range from $a_i$ to $a_{i-1}-1$. The contribution is $a_i \cdot (a_{i-1} - a_i)$. Sum up the contributions of all adjacent pairs to find the answer. Complexity is $\mathcal{O}(n)$.
|
[
"combinatorics",
"data structures",
"dp",
"math"
] | 2,100
| null |
1151
|
F
|
Sonya and Informatics
|
A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.
Given an array $a$ of length $n$, \textbf{consisting only of the numbers $0$ and $1$}, and the number $k$. \textbf{Exactly $k$ times} the following happens:
- Two numbers $i$ and $j$ are chosen equiprobable such that ($1 \leq i < j \leq n$).
- The numbers in the $i$ and $j$ positions are swapped.
Sonya's task is to find the probability that after all the operations are completed, the $a$ array will be \textbf{sorted in non-decreasing order}. She turned to you for help. Help Sonya solve this problem.
It can be shown that the desired probability is either $0$ or it can be represented as $\dfrac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \not\equiv 0~\pmod {10^9+7}$.
|
How to solve this problem in $\mathcal{O}(n\cdot k)$? Let's find the answer using dynamic programming. Denote $cur$ as the number of zeroes in array $a$, and $dp_{i,j}$ as the number of rearrangements of array $a$ after $i$ operations and $j$ is equal to the number of zeroes on prefix of length $cur$. Denote $x$ as the number of zeroes on prefix of length $cur$. The initial state will be $dp_{0,x}=1$. Notice that the answer will be $\dfrac{dp_{k, cur}}{\sum_{i=0}^{cur}dp_{k, i}}$. The transitions are not so hard. You must know the following values: the number of ones on prefix of length $cur$, the number of zeroes on prefix of length $cur$, the number of ones NOT on prefix of length $cur$ and the number of zeroes NOT on prefix of length $cur$. For example, you can find the number of pairs such that after we swap them the number of zeroes on prefix of length $cur$ is increased by one: the number of ones on prefix of length $cur$ multiply by the number of zeroes NOT on prefix of length $cur$. Also there are transitions when the number of zeroes on prefix of length $cur$ remains the same, and when it decreased by one (you can find them by yourself). To solve the original problem we must create the transition matrix and find the answer using matrix multiplication with binary exponentiation. Also you must know how to find the modular multiplicative inverse to find the answer. Complexity is $\mathcal{O}(n^3\cdot \log{k})$.
|
[
"combinatorics",
"dp",
"matrices",
"probabilities"
] | 2,300
| null |
1152
|
A
|
Neko Finds Grapes
|
On a random day, Neko found $n$ treasure chests and $m$ keys. The $i$-th chest has an integer $a_i$ written on it and the $j$-th key has an integer $b_j$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The $j$-th key can be used to unlock the $i$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $a_i + b_j \equiv 1 \pmod{2}$. One key can be used to open at most one chest, and one chest can be opened at most once.
Find the maximum number of chests Neko can open.
|
The most important observation is that: Key with odd id can only be used to unlock chest with even id Key with even id can only be used to unlock chest with odd id Let: $c_0, c_1$ be the number of chests with even and odd id, respectively $k_0, k_1$ be the number of keys with even and odd id, respectively With $c_0$ even-id chests and $k_1$ odd-id keys, you can unlock at most $\min(c_0, k_1)$ chests. With $c_1$ odd-id chests and $k_0$ even-id keys, you can unlock at most $\min(c_1, k_0)$ chests. Therefore, the final answer is $\min(c_0, k_1) + \min(c_1, k_0)$. Complexity: $O(n + m)$
|
[
"greedy",
"implementation",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char* argv[])
{
int n, m;
scanf("%d%d", &n, &m);
vector<int> a(n), b(m);
for(int i = 0; i < n; ++i)
scanf("%d", &a[i]);
for(int i = 0; i < m; ++i)
scanf("%d", &b[i]);
int c0 = 0, c1 = 0;
for(int i = 0; i < n; ++i)
if (a[i]%2 == 0)
++c0;
else
++c1;
int k0 = 0, k1 = 0;
for(int i = 0; i < m; ++i)
if (b[i]%2 == 0)
++k0;
else
++k1;
int ans = min(c1, k0) + min(c0, k1);
printf("%d", ans);
return 0;
}
|
1152
|
B
|
Neko Performs Cat Furrier Transform
|
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.
Assume that we have a cat with a number $x$. A perfect longcat is a cat with a number equal $2^m - 1$ for some non-negative integer $m$. For example, the numbers $0$, $1$, $3$, $7$, $15$ and so on are suitable for the perfect longcats.
In the Cat Furrier Transform, the following operations can be performed on $x$:
- (Operation A): you select any non-negative integer $n$ and replace $x$ with $x \oplus (2^n - 1)$, with $\oplus$ being a bitwise XOR operator.
- (Operation B): replace $x$ with $x + 1$.
The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.
Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $40$ operations. Can you help Neko writing a transformation plan?
Note that it is \textbf{not required} to minimize the number of operations. You just need to use no more than $40$ operations.
|
There are various greedy solutions possible. I'll only cover one of them. We'll perform a loop as follows: If $x \le 1$, stop the process (since it's already correct). If $x = 2^m$ ($m \ge 1$), perform operation A with $2^m-1$. Obviously, the resulting $x$ will be $2^{m+1}-1$, which satisfies the criteria, so we stop the process. Otherwise, let's denote $MSB(x)$ as the position/exponential of the most significant bit of $x$ (for example, $MSB(4) = MSB(7) = 2$). We'll perform operation A with $2^{MSB(x)+1} - 1$. If $x$ after this phase is not a valid number, we'll then perform operation B and return to the beginning of the loop. This will never take more than $40$ queries, since each iteration removes the most significant bit (and it would never reappear after later steps), and $x$ can only have at most $20$ bits initially. Also, it is possible to solve this problem by finding exactly shortest operation sequence by using a BFS. However, this was not required.
|
[
"bitmasks",
"constructive algorithms",
"dfs and similar",
"math"
] | 1,300
|
#pragma comment(linker, "/stack:247474112")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int x; vector<vector<int>> vis(2, vector<int>(1048576, INT_MAX));
vector<vector<pair<int, int>>> Last(2, vector<pair<int, int>>(1048576, {-1LL, -1LL}));
int isCompletion(int z) {
int bitval = 0;
z += 1; while (z % 2 == 0) {z /= 2; bitval++;}
if (z != 1) return -1;
return bitval;
}
void Input() {
cin >> x;
}
void Solve() {
queue<pair<int, int>> Q;
vis[0][x] = 0; Q.push({0, x});
int p1 = -1, p2 = -1;
while (!Q.empty()) {
pair<int, int> Token = Q.front();
int p = Token.first, z = Token.second; Q.pop();
if (isCompletion(z) != -1) {p1 = p; p2 = z; break;}
if (p == 1) {
if (vis[0][z+1] == INT_MAX) {
vis[0][z+1] = vis[1][z] + 1;
Last[0][z+1] = {1, z}; Q.push({0, z+1});
}
}
else {
for (int i=0; i<20; i++) {
int t = (z ^ ((1 << i) - 1));
if (vis[1][t] != INT_MAX) continue;
vis[1][t] = vis[0][z] + 1;
Last[1][t] = {0, z}; Q.push({1, t});
}
}
}
cout << vis[p1][p2] << endl;
vector<int> xorCmd;
while (Last[p1][p2] != make_pair(-1, -1)) {
pair<int, int> Token = Last[p1][p2];
int z = Token.first, t = Token.second;
if (p1 == 1) xorCmd.push_back(isCompletion(p2 ^ t));
p1 = z; p2 = t;
}
reverse(xorCmd.begin(), xorCmd.end());
for (auto z: xorCmd) cout << z << " ";
}
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(NULL); Input(); Solve();
return 0;
}
|
1152
|
C
|
Neko does Maths
|
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers $a$ and $b$. His goal is to find a non-negative integer $k$ such that the least common multiple of $a+k$ and $b+k$ is the smallest possible. If there are multiple optimal integers $k$, he needs to choose the smallest one.
Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?
|
The $lcm(a + k, b + k)$ is equal to $\frac{(a + k) \cdot (b + k)}{\gcd(a + k, b + k)}$. In fact, there are not much possible values for the denominator of this fraction. Without losing generality, let's assume $a \le b$. Applying one step of Euclid's algorithm we can see, that $\gcd(a + k, b + k) = \gcd(b - a, a + k)$. So the $\gcd$ is a divisor of $b - a$. Let's iterate over all divisors $q$ of $b - a$. That also means that $a \pmod{q} = b \pmod{q}$. In case $a \pmod{q} = 0$, we can use $k = 0$. Otherwise, the corresponding $k$ should be $q - a \pmod{q}$. Lastly, we need to check whether the value of $lcm(a + k, b + k)$ is the smallest found so far. Also, one has to be careful when dealing with $k = 0$ answer, which was the reason why many solutions got WA 63. The complexity is $O(\sqrt{b - a})$.
|
[
"brute force",
"math",
"number theory"
] | 1,800
|
#pragma comment(linker, "/stack:247474112")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int a, b;
void Input() {
cin >> a >> b;
}
void Solve() {
if (a == b) {cout << "0\n"; return;}
vector<int> Divisors;
for (int i=1; i<=sqrt(max(a,b) - min(a,b)); i++) {
if ((max(a,b) - min(a,b)) % i != 0) continue;
int j = (max(a,b) - min(a,b)) / i;
Divisors.push_back(i);
if (i != j) Divisors.push_back(j);
}
pair<long long, int> Token = make_pair(LLONG_MAX, INT_MAX);
for (auto d: Divisors) {
int k = (d - a % d) % d;
pair<long long, int> NewToken = make_pair(1LL * (0LL + a + k) / __gcd(0LL+a+k, 0LL+b+k) * (0LL + b + k), k);
Token = min(Token, NewToken);
}
cout << Token.second << endl;
}
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(NULL); Input(); Solve();
return 0;
}
|
1152
|
D
|
Neko and Aki's Prank
|
Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...
It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a trie of all correct bracket sequences of length $2n$.
The definition of correct bracket sequence is as follows:
- The empty sequence is a correct bracket sequence,
- If $s$ is a correct bracket sequence, then $(\,s\,)$ is a correct bracket sequence,
- If $s$ and $t$ are a correct bracket sequence, then $st$ is also a correct bracket sequence.
For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.
Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo $10^9 + 7$.
|
Note, that many subtrees of the trie are equal. Basically, if we consider two vertices on the same depth and having the same balance from root to them (that is, the number of opening brackets minus the number of closing brackets), than their subtrees will be entirely same. For example, the subtrees after following $((())$, $()()($ and $(())($ are all the same. We will use this observation to consider the tree in "compressed" form. Clearly, this way there are only $O(n^2)$ different vertices types (basically a vertex is described by $(depth, balance)$). Now let's get back to finding a maximum matching in the tree. There are two approaches to this problem. One of them is greedy. Basically if you find a matching in a tree you can always greedily take the edge between a leaf and its parent (since this adds one edge to the answer and destroys at most one edge you would've chosen). This idea can transform into the following algorithm (for the problem of the maximum matching in the tree). Do a dynamic programming on the subtrees, the result of $dp[v]$ is a pair of "number of edges taken in subtree, whether the root of this subtree is free (so we can start a new edge upwards)". Combining this with the idea that there are little ($n^2$) number of vertex types, we get a dp solution.
|
[
"dp",
"greedy",
"trees"
] | 2,100
|
// Dmitry _kun_ Sayutin (2019)
#include <bits/stdc++.h>
using std::cin;
using std::cout;
using std::cerr;
using std::vector;
using std::map;
using std::array;
using std::set;
using std::string;
using std::pair;
using std::make_pair;
using std::tuple;
using std::make_tuple;
using std::get;
using std::min;
using std::abs;
using std::max;
using std::swap;
using std::unique;
using std::sort;
using std::generate;
using std::reverse;
using std::min_element;
using std::max_element;
#ifdef LOCAL
#define LASSERT(X) assert(X)
#else
#define LASSERT(X) {}
#endif
template <typename T>
T input() {
T res;
cin >> res;
LASSERT(cin);
return res;
}
template <typename IT>
void input_seq(IT b, IT e) {
std::generate(b, e, input<typename std::remove_reference<decltype(*b)>::type>);
}
#define SZ(vec) int((vec).size())
#define ALL(data) data.begin(),data.end()
#define RALL(data) data.rbegin(),data.rend()
#define TYPEMAX(type) std::numeric_limits<type>::max()
#define TYPEMIN(type) std::numeric_limits<type>::min()
const int mod = 1000 * 1000 * 1000 + 7;
int add(int a, int b) {
return (a + b >= mod ? a + b - mod : a + b);
}
const int max_n = 1001;
pair<int, bool> dp[2 * max_n][2 * max_n];
int main() {
std::iostream::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// code here
int n = input<int>();
n *= 2;
assert(n / 2 < max_n);
dp[0][0] = make_pair(0, true);
for (int len = 1; len <= n; ++len) {
for (int bal = 0; bal <= n; ++bal) {
// (len, bal) -> (len - 1, bal + 1)
// (len, bal) -> (len - 1, bal - 1)
int sum = 0;
bool has = false;
if (bal != 0) {
sum = add(sum, dp[len - 1][bal - 1].first);
has = has or dp[len - 1][bal - 1].second;
}
if (bal + 1 <= len - 1) {
sum = add(sum, dp[len - 1][bal + 1].first);
has = has or dp[len - 1][bal + 1].second;
}
if (has)
dp[len][bal] = make_pair(add(sum, 1), false);
else
dp[len][bal] = make_pair(sum, true);
}
}
cout << dp[n][0].first << "\n";
return 0;
}
|
1152
|
E
|
Neko and Flashback
|
A permutation of length $k$ is a sequence of $k$ integers from $1$ to $k$ containing each integer exactly once. For example, the sequence $[3, 1, 2]$ is a permutation of length $3$.
When Neko was five, he thought of an array $a$ of $n$ positive integers and a permutation $p$ of length $n - 1$. Then, he performed the following:
- Constructed an array $b$ of length $n-1$, where $b_i = \min(a_i, a_{i+1})$.
- Constructed an array $c$ of length $n-1$, where $c_i = \max(a_i, a_{i+1})$.
- Constructed an array $b'$ of length $n-1$, where $b'_i = b_{p_i}$.
- Constructed an array $c'$ of length $n-1$, where $c'_i = c_{p_i}$.
For example, if the array $a$ was $[3, 4, 6, 5, 7]$ and permutation $p$ was $[2, 4, 1, 3]$, then Neko would have constructed the following arrays:
- $b = [3, 4, 5, 5]$
- $c = [4, 6, 6, 7]$
- $b' = [4, 5, 3, 5]$
- $c' = [6, 7, 4, 6]$
Then, he wrote two arrays $b'$ and $c'$ on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays $b'$ and $c'$ written on it. However he can't remember the array $a$ and permutation $p$ he used.
In case Neko made a mistake and there is no array $a$ and permutation $p$ resulting in such $b'$ and $c'$, print -1. Otherwise, help him recover any possible array $a$.
|
Obviously, if $b'_i > c'_i$ for some $i$, then the answer is "-1". From the statement, we have $b_i = \min(a_i, a_{i+1})$ and $c_i = \max(a_i, a_{i+1})$. For this to happen, either one of the following must happen: $a_i = b_i$ and $a_{i+1} = c_i$ $a_i = c_i$ and $a_{i+1} = b_i$ In order word, one of the two following pairs - $(b_i, c_i)$ or $(c_i, b_i)$ - will match the pair $(a_i, a_{i+1})$. From the statement, we also have $b'_i = b_{p_i}$ and $c'_i = c_{p_i}$. Therefore, one of the two following pairs - $(b'_i, c'_i)$ or $(c'_i, b'_i)$ - will match the pair $(a_{p_i}, a_{p_{i+1}})$ Consider a graph $G$ with $10^9$ vertices. For each $i$ from $1$ to $n-1$, we will add an undirected edge between $b'_i$ and $c'_i$. The following figure show such graph $G$ for the third example. Consider the path $P = a_1 \rightarrow a_2 \rightarrow a_3 \rightarrow \ldots \rightarrow a_n$. Each edge $(b'_i, c'_i)$ will correspond to exactly one edge between $a_j$ and $a_{j+1}$ for some j. In other word, $P$ correspond to an Eulerian path on the graph $G$. The following figure show the path $P = 3 \rightarrow 4 \rightarrow 5 \rightarrow 2 \rightarrow 1 \rightarrow 4 \rightarrow 3 \rightarrow 2$ for the third example. For implementation, we need to do the following step: For all elements of $b'$ and $c'$, we need to replace them with corresponding value from $1$ to $k$ (where $k$ is the number of distinct value in $b'$ and $c'$). This part can be done using an balanced BST (C++ 'map' or Java 'TreeMap') or by sorting in $O(n \log n)$. Build the graph $G$ as above Finding an Eulerian path in $G$ using Hierholzer's_algorithm in $O(n)$, or detect that such path does not exists. Complexity: $O(n \log n)$
|
[
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
class Indexer {
private:
map<int, int> id;
vector<int> num;
public:
int getId(int x) {
if (!id.count(x)) {
id[x] = num.size();
num.push_back(x);
}
return id[x];
}
int getNum(int id) {
return num[id];
}
int size() {
return id.size();
}
};
struct Edge {
int u, v;
bool avail;
};
class Graph {
private:
int n;
vector<Edge> e;
vector<vector<int> > adj;
vector<int> pos;
list<int> path;
void dfs(list<int>::iterator it, int u) {
for(; pos[u] < adj[u].size(); ++pos[u]) {
int id = adj[u][pos[u]];
if (e[id].avail) {
e[id].avail = false;
int v = e[id].u + e[id].v - u;
dfs(path.insert(it, u), v);
}
}
}
public:
Graph(int n): n(n) {
adj.assign(n, vector<int>());
}
void addEdge(int u, int v) {
adj[u].push_back(e.size());
adj[v].push_back(e.size());
e.push_back({u, v, false});
}
vector<int> eulerPath() {
for(Edge &p: e)
p.avail = true;
path.clear();
pos.assign(n, 0);
vector<int> odd;
for(int u = 0; u < n; ++u)
if (adj[u].size() % 2 == 1)
odd.push_back(u);
if (odd.empty()) {
odd.push_back(0);
odd.push_back(0);
}
if (odd.size() > 2)
return vector<int>();
dfs(path.begin(), odd[0]);
path.insert(path.begin(), odd[1]);
return vector<int>(path.begin(), path.end());
}
};
int main() {
int n;
scanf("%d", &n);
vector<int> bprime(n-1);
for(int i = 0; i < n-1; ++i)
scanf("%d", &bprime[i]);
vector<int> cprime(n-1);
for(int i = 0; i < n-1; ++i)
scanf("%d", &cprime[i]);
Indexer ind;
for(int i = 0; i < n-1; ++i) {
if (bprime[i] > cprime[i]) {
puts("-1");
return 0;
}
bprime[i] = ind.getId(bprime[i]);
cprime[i] = ind.getId(cprime[i]);
}
int k = ind.size();
Graph g(k);
for(int i = 0; i < n-1; ++i)
g.addEdge(bprime[i], cprime[i]);
vector<int> a = g.eulerPath();
if (a.size() < n)
puts("-1");
else {
for(int i = 0; i < n; ++i)
printf("%d ", ind.getNum(a[i]));
puts("");
}
return 0;
}
|
1152
|
F1
|
Neko Rules the Catniverse (Small Version)
|
This problem is same as the next one, but has smaller constraints.
Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.
There are $n$ planets in the Catniverse, numbered from $1$ to $n$. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs $k - 1$ moves, where in each move Neko is moved from the current planet $x$ to some other planet $y$ such that:
- Planet $y$ is not visited yet.
- $1 \leq y \leq x + m$ (where $m$ is a fixed constant given in the input)
This way, Neko will visit exactly $k$ different planets. Two ways of visiting planets are called different if there is some index $i$ such that the $i$-th planet visited in the first way is different from the $i$-th planet visited in the second way.
What is the total number of ways to visit $k$ planets this way? Since the answer can be quite large, print it modulo $10^9 + 7$.
|
As the problem stated, from planet $x$ we can go backwards any to any planet $y$ such that $y < x$. This implies an idea of considering the planets from $n$ to $1$, then deciding whether to insert each planet to the current path or not. Formally, if our current path is $v_1, v_2, \dots, v_p$ and we are going to insert planet $x$ somewhere ($x < v_i$ for all $i$), we can either insert it into the back, or insert it before some planet $v_i$ such that $v_i \le x + m$. Therefore, we can use dynamic programming with the parameters being: the planet being considered, the number of planets chosen so far, and the bitmask of the last $m$ planets (whether each of them is chosen or not). The transition is straightforward: either we don't choose the planet, or we choose it and there are $1 + bitcount(mask)$ ways to insert the planet into the path. Total complexity: $\mathcal{O} \left( nk \cdot 2^m \right)$.
|
[
"bitmasks",
"dp",
"matrices"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
void add(int &a, long long b) {
a = (a + b) % MOD;
}
int main() {
int n, k, m;
scanf("%d%d%d", &n, &k, &m);
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(k+1, vector<int>(1<<m, 0)));
dp[0][0][0] = 1;
for(int i = 0; i < n; ++i) {
for(int j = 0; j <= k; ++j) {
for(int mask = 0; mask < (1<<m); ++mask) {
int newMask = (mask << 1) % (1<<m);
// Not visit planet i+1
add(dp[i+1][j][newMask], dp[i][j][mask]);
// Visit planet i+1
if (j < k) {
int insertWays = __builtin_popcount(mask) + 1;
add(dp[i+1][j+1][newMask|1], 1LL*insertWays*dp[i][j][mask]);
}
}
}
}
int ans = 0;
for(int mask = 0; mask < (1<<m); ++mask)
add(ans, dp[n][k][mask]);
printf("%d", ans);
}
|
1152
|
F2
|
Neko Rules the Catniverse (Large Version)
|
This problem is same as the previous one, but has larger constraints.
Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.
There are $n$ planets in the Catniverse, numbered from $1$ to $n$. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs $k - 1$ moves, where in each move Neko is moved from the current planet $x$ to some other planet $y$ such that:
- Planet $y$ is not visited yet.
- $1 \leq y \leq x + m$ (where $m$ is a fixed constant given in the input)
This way, Neko will visit exactly $k$ different planets. Two ways of visiting planets are called different if there is some index $i$ such that, the $i$-th planet visited in the first way is different from the $i$-th planet visited in the second way.
What is the total number of ways to visit $k$ planets this way? Since the answer can be quite large, print it modulo $10^9 + 7$.
|
The core idea is similar to F1, however there is one crucial observation. We can see that all DP transitions are just linear transformations, thus we can construct a transition matrix of size $k \cdot 2^m$, then use fast matrix exponentiation as a replacement of the original DP transitions. Total complexity: $\mathcal{O} \left( \log(n) \cdot {\left( k \cdot 2^m \right)}^3 \right)$.
|
[
"bitmasks",
"dp",
"matrices"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
void add(int &a, long long b) {
a = (a + b) % MOD;
}
struct Matrix {
vector<vector<int>> a;
int n, m;
Matrix(int n, int m): n(n), m(m) {
a.assign(n, vector<int>(m, 0));
}
friend Matrix operator * (Matrix a, Matrix b) {
Matrix c(a.n, b.m);
for(int i = 0; i < a.n; ++i)
for(int j = 0; j < b.m; ++j)
for(int k = 0; k < a.m; ++k)
add(c.a[i][j], 1LL * a.a[i][k] * b.a[k][j]);
return c;
}
};
Matrix identity(int n) {
Matrix res(n, n);
for(int i = 0; i < n; ++i)
res.a[i][i] = 1;
return res;
}
void power(Matrix &a, int n, Matrix &b) {
while (n > 0) {
if (n&1) b = a * b;
a = a * a;
n >>= 1;
}
}
int n, k, m;
int toId(int j, int mask) {
return j * (1<<m) + mask;
}
int main() {
scanf("%d%d%d", &n, &k, &m);
Matrix dp((k+1) * (1<<m), 1);
dp.a[0][0] = 1;
Matrix f((k+1) * (1<<m), (k+1) * (1<<m));
for(int j = 0; j <= k; ++j) {
for(int mask = 0; mask < (1<<m); ++mask) {
int newMask = (mask << 1) % (1<<m);
int cur = toId(j, mask);
f.a[toId(j, newMask)][cur] = 1;
if (j < k)
f.a[toId(j+1, newMask|1)][cur] = __builtin_popcount(mask) + 1;
}
}
power(f, n, dp);
int ans = 0;
for(int mask = 0; mask < (1<<m); ++mask)
add(ans, dp.a[toId(k, mask)][0]);
printf("%d", ans);
}
|
1153
|
A
|
Serval and Bus
|
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.
Serval will go to the bus station at time $t$, and there are $n$ bus routes which stop at this station. For the $i$-th bus route, the first bus arrives at time $s_i$ minutes, and each bus of this route comes $d_i$ minutes later than the previous one.
As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
|
Find the first bus Serval can see in each route and find the earliest one. For each route, finding the first bus Serval sees can work in $O(1)$. Or mark all the time no more than $\max(s_i,t+\max(d_i))$ which bus would come or there will be no bus, then search the nearest one.
|
[
"brute force",
"math"
] | 1,000
| null |
1153
|
B
|
Serval and Toy Bricks
|
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.
He has a special interest to create difficult problems for others to solve. This time, with many $1 \times 1 \times 1$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $n \times m$ matrix, such that in each cell $(i,j)$, there are $h_{i,j}$ bricks standing on the top of each other.
However, Serval doesn't give you any $h_{i,j}$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $m$ columns, and in the $i$-th of them, the height is the maximum of $h_{1,i},h_{2,i},\dots,h_{n,i}$. It is similar for the left view, where there are $n$ columns. And in the top view, there is an $n \times m$ matrix $t_{i,j}$, where $t_{i,j}$ is $0$ or $1$. If $t_{i,j}$ equals $1$, that means $h_{i,j}>0$, otherwise, $h_{i,j}=0$.
However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?
|
Fill in all the bricks, and then remove all bricks you must remove (which in some view, there is empty). This can be solved in $O(nm)$.
|
[
"constructive algorithms",
"greedy"
] | 1,200
| null |
1153
|
C
|
Serval and Parenthesis Sequence
|
Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.
In his favorite math class, the teacher taught him the following interesting definitions.
A parenthesis sequence is a string, containing only characters "(" and ")".
A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, parenthesis sequences "()()", "(())" are correct (the resulting expressions are: "(1+1)+(1+1)", "((1+1)+1)"), while ")(" and ")" are not. Note that the empty string is a correct parenthesis sequence by definition.
We define that $|s|$ as the length of string $s$. A strict prefix $s[1\dots l]$ $(1\leq l< |s|)$ of a string $s = s_1s_2\dots s_{|s|}$ is string $s_1s_2\dots s_l$. Note that the empty string and the whole string are not strict prefixes of any string by the definition.
Having learned these definitions, he comes up with a new problem. He writes down a string $s$ containing only characters "(", ")" and "?". And what he is going to do, is to replace each of the "?" in $s$ independently by one of "(" and ")" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.
After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.
|
First let ( be $+1$, ) be $-1$ and ? be a missing place, so we will replace all the missing places in the new $+1$,$-1$ sequence by $+1$ and $-1$. Obviously, for each prefix of a correct parenthesis sequence, the sum of the new $+1$,$-1$ sequence is not less than $0$. And for the correct parenthesis sequence itself, the sum of the new sequence should be $0$. So we can calculate how many $+1$ (let $a$ denotes it) and how many $-1$ (let $b$ denotes it) that we should fill in the missing places. According to the problem, our goal is to fill the missing place with $+1$ and $-1$ to make sure there is no strict prefix (prefixes except the whole sequence itself) exists with the sum equal to $0$. This can be solved in greedy. We want the sum of prefixes as large as possible to avoid the sum touching $0$. So let the first $a$ missing places be filled with $+1$ and the last $b$ missing places be filled with $-1$. Check it whether it is a correct parenthesis sequence or not at last. The complexity is $O(n)$.
|
[
"greedy",
"strings"
] | 1,700
| null |
1153
|
D
|
Serval and Rooted Tree
|
Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before.
As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. Children of vertex $v$ are all nodes for which $v$ is the parent. A vertex is a leaf if it has no children.
The rooted tree Serval owns has $n$ nodes, node $1$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $\max$ or $\min$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively.
Assume that there are $k$ leaves in the tree. Serval wants to put integers $1, 2, \ldots, k$ to the $k$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?
|
If we want to check whether $x$ is the answer (I didn't say I want to do binary search), then we can set all the numbers no less than $x$ as $1$, and the numbers less than $x$ as $0$. Then we can use $dp_i$ to represent that the maximum number on node $i$ is the $dp_i$-th smallest number of leaves within subtree of $i$. There should be at least $dp_i$ ones in the subtree of $i$ such that the number on $i$ is one. Then $k+1-dp_1$ is the final answer. Complexity $O(n)$. We can solve this problem in greedy. At first we use $leaf_u$ to represent the number of leaves in the subtree whose root is $u$, and $f_u$ to represent the maximum number we can get on the node $u$. Note that since we are concidering the subtree of $u$, we just number those $leaf_u$ nodes from $1$ to $leaf_u$, and $f_u$ is between $1$ and $leaf_u$, too. Let's think how to find the maximum number a node can get. If the operation of the node $u$ we concerned is $\max$, for all the nodes $v$ whose father or parent is $u$, we can find the minimum $leaf_v-f_v$. Let $v_{min}$ denotes the node reaches the minimum. And we can construct an arrangement so that the number written in the node $u$ can be $leaf_u-(leaf_{v_{min}}-f_{v_{min}})$. When we number the leaves in the subtree of $u$ from $1$ to $leaf_u$, we number the leaves in other subtrees of children of $u$ first, and then number the leaves in subtree of $v_{min}$. It can be proved this arrangement is optimal. If the operation of the node $u$ we concerned is $\max$, for all the nodes $v$ whose father or parent is $u$, we can find the minimum $leaf_v-f_v$. Let $v_{min}$ denotes the node reaches the minimum. And we can construct an arrangement so that the number written in the node $u$ can be $leaf_u-(leaf_{v_{min}}-f_{v_{min}})$. When we number the leaves in the subtree of $u$ from $1$ to $leaf_u$, we number the leaves in other subtrees of children of $u$ first, and then number the leaves in subtree of $v_{min}$. It can be proved this arrangement is optimal. If the operation of the node $u$ is $\min$, we can construct an arrangement of the numbers written in the leaves to make the number written in $u$ be as large as possible. For all sons or children $v$ of $u$, we number the first $f_v-1$ leaves in subtree of $v$ first according to the optimal arrangement of the node $v$. And then no matter how we arrange the remaining numbers, the number written in $u$ is $1+\sum_{v \text{ is a son of } u} (f_v-1)$. This is the optimal arrangement. If the operation of the node $u$ is $\min$, we can construct an arrangement of the numbers written in the leaves to make the number written in $u$ be as large as possible. For all sons or children $v$ of $u$, we number the first $f_v-1$ leaves in subtree of $v$ first according to the optimal arrangement of the node $v$. And then no matter how we arrange the remaining numbers, the number written in $u$ is $1+\sum_{v \text{ is a son of } u} (f_v-1)$. This is the optimal arrangement. We can use this method and get the final answer $f_1$.
|
[
"binary search",
"dfs and similar",
"dp",
"greedy",
"trees"
] | 1,900
|
#include <cstdio>
using namespace std;
const int N=1000005;
int n,p;
int h[N],nx[N];
int t[N],sz[N];
void getsize(int u)
{
if (!h[u])
sz[u]++;
for (int i=h[u];i;i=nx[i])
{
getsize(i);
sz[u]+=sz[i];
}
}
int getans(int u)
{
if (!h[u])
return 1;
int ret=0,tmp;
if (t[u])
{
for (int i=h[u];i;i=nx[i])
{
tmp=getans(i)+sz[u]-sz[i];
if (tmp>ret)
ret=tmp;
}
return ret;
}
for (int i=h[u];i;i=nx[i])
ret+=getans(i)-1;
return ret+1;
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%d",&t[i]);
for (int i=2;i<=n;i++)
{
scanf("%d",&p);
nx[i]=h[p];
h[p]=i;
}
getsize(1);
printf("%d\n",getans(1));
return 0;
}
|
1153
|
E
|
Serval and Snake
|
This is an interactive problem.
Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a $n \times n$ grid. The snake has a head and a tail in different cells, and its body is a series of adjacent cells connecting the head and the tail without self-intersecting. If Serval hits its head or tail, the snake will bite him and he will die.
Luckily, he has a special device which can answer the following question: you can pick a rectangle, it will tell you the number of times one needs to cross the border of the rectangle walking cell by cell along the snake from the head to the tail. The pictures below show a possible snake and a possible query to it, which will get an answer of $4$.
Today Serval got up too late and only have time to make $2019$ queries. As his best friend, can you help him find the positions of the head and the tail?
Note that two cells are adjacent if and only if they have a common edge in the grid, and a snake can have a body of length $0$, that means it only has adjacent head and tail.
Also note that the snake is sleeping, so it won't move while Serval using his device. And what's obvious is that the snake position does not depend on your queries.
|
If the answer to a rectangle is odd, there must be exactly one head or tail in that rectangle. Otherwise, there must be even number ($0$ or $2$) of head and tail in the given rectangle. We make queries for each of the columns except the last one, then we can know for each column whether there are odd number of head and tails in it or not. Because the sum is even, we can know the parity of the last column. If the head and tail are in different columns, we can find two columns with odd answer and get them. Then we can do binary search for each of those two columns separately and get the answer in no more than $999+10+10=1019$ queries totally. If the head and tail are in the same column, we will get all even answer and know that fact. Then we apply the same method for rows. Then we can just do binary search for one of the rows, and use the fact that the other is in the same column as this one. In this case, we have made no more than $999+999+10=2008$ queries. How to save one more query? We first make queries for row $2$ to row $n-1$. If we find any ones, make the last query for row, and use the method above. If we cannot find any ones, we make $n-1$ queries for columns. If none of them provide one, we know that for row $1$ and row $n$, there must be exactly one head or tail in them, and they are in the same column. In this case, we do binary search for one of the rows, then the total number of queries is $998+999+10=2007$. If we can find two ones in the columns, we know that: if one of them is in row $2$ to row $n-1$, the other must be in the same row, because for row $2$ to row $n$, we know that there are even number of head and tails, and them can't appear in the other columns. Then we do binary search, when we divide the length into two halves, we let the one close the the middle to be the longer one, and the one close to one end to be the shorter one. Then, if it turns out that, the answer is in row $1$ (or row $n$), the number of queries must be $\log n$ rounded down, and we can use one more query to identify, whether the head or tail in the other column is in row $1$ or row $n$. If it turns out that, the answer is in one of the rows in row $2$ to row $n$, we may used $\log n$ queries rounded up, but in this case, we don't need that extra query. So the total number of queries is $999+998+9+1=2007$ (or $999+998+10=2007$). In fact, if the interactor is not adaptive and we query for columns and rows randomly, we can use far less than $2007$ queries. And if we query for rows and columns alternatively, we can save more queries.
|
[
"binary search",
"brute force",
"interactive"
] | 2,200
| null |
1153
|
F
|
Serval and Bonus Problem
|
Getting closer and closer to a mathematician, Serval becomes a university student on math major in Japari University. On the Calculus class, his teacher taught him how to calculate the expected length of a random subsegment of a given segment. Then he left a bonus problem as homework, with the award of a garage kit from IOI. The bonus is to extend this problem to the general case as follows.
You are given a segment with length $l$. We randomly choose $n$ segments by choosing two points (maybe with non-integer coordinates) from the given segment equiprobably and the interval between the two points forms a segment. You are given the number of random segments $n$, and another integer $k$. The $2n$ endpoints of the chosen segments split the segment into $(2n+1)$ intervals. Your task is to calculate the expected total length of those intervals that are covered by at least $k$ segments of the $n$ random segments.
You should find the answer modulo $998244353$.
|
Without loss of generality, assume that $l=1$. For a segment covering, the total length of the legal intervals is the probability that we choose another point $P$ on this segment randomly such that it is in the legal intervals. Since all $2n+1$ points ($P$ and the endpoints of each segment) are chosen randomly and independently, we only need to find the probability that point $P$ is in the legal intervals. Note that only the order of these $2n+1$ points make sense. Because the points are chosen in the segment, the probability that some of them coincide is $0$, so we can assume that all points do not coincide. Now the problem is, how to calculate the number of arrangements that $P$ is between at least $k$ pairs of endpoints. It can be solved by dynamic programming in time complexity of $O(n^2)$. We define $f(i,j,x)$ as the number of arrangements for the first $i$ positions, with $j$ points haven't been matched, and $P$ appeared $x$ times (obviously $x=0$ or $1$). So we can get three different types of transition for the $i$-th position below: Place $P$ at $i$-th position (if $j\geq k$): $f(i-1,j,0)\rightarrow f(i,j,1)$ Start a new segment (if $i+j+x<2n$): $f(i-1,j-1,x)\rightarrow f(i,j,x)$ Match a started segment, note that we have $j$ choices of segments: $f(i-1,j+1,x)\times (j+1)\rightarrow f(i,j,x)$ Then $f(2n+1,0,1)$ is the number of legal arrangements. Obviously, the total number of arrangements is $(2n+1)!$. However, there are $n$ pairs of endpoints whose indices can be swapped, and the indices $n$ segments can be rearranged. So the final answer is $\frac{f(2n+1,0,1)\times n! \times 2^n}{(2n+1)!}$.
|
[
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,600
|
#include <cstdio>
using namespace std;
const int mod=998244353;
const int N=4005;
const int K=2005;
int n,k,l;
int fac,ans;
int f[N][K][2];
int fpw(int b,int e=mod-2)
{
if (!e)
return 1;
int ret=fpw(b,e>>1);
ret=1ll*ret*ret%mod;
if (e&1)
ret=1ll*ret*b%mod;
return ret;
}
int main()
{
scanf("%d%d%d",&n,&k,&l);
f[0][0][0]=1;
for (int i=1;i<=2*n+1;i++)
for (int j=0;j<=n;j++)
for (int x=0;x<=1;x++)
if (f[i-1][j][x])
{
if (j)
f[i][j-1][x]=(f[i][j-1][x]+1ll*f[i-1][j][x]*j)%mod;
if (i+j-1<2*n+x)
f[i][j+1][x]=(f[i][j+1][x]+f[i-1][j][x])%mod;
if (j>=k&&!x)
f[i][j][1]=(f[i][j][1]+f[i-1][j][x])%mod;
}
fac=1;
for (int i=n+1;i<=2*n+1;i++)
fac=1ll*fac*i%mod;
ans=f[2*n+1][0][1];
ans=1ll*ans*fpw(2,n)%mod;
ans=1ll*ans*fpw(fac)%mod*l%mod;
printf("%d\n",ans);
return 0;
}
|
1154
|
A
|
Restoring Three Numbers
|
Polycarp has guessed three positive integers $a$, $b$ and $c$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $a+b$, $a+c$, $b+c$ and $a+b+c$.
You have to guess three numbers $a$, $b$ and $c$ using given numbers. Print three guessed integers in any order.
Pay attention that some given numbers $a$, $b$ and $c$ can be equal (it is also possible that $a=b=c$).
|
Let $x_1 = a + b$, $x_2 = a + c$, $x_3 = b = c$ and $x_4 = a + b + c$. Then we can construct the following answer: $c = x_4 - x_1$, $b = x_4 - x_2$ and $a = x_4 - x_3$. Because all numbers in the answer are positive, we can assume that the maximum element of $x$ is $a + b + c$. So let's sort the input array $x$ consisting of four elements and just print $x_4 - x_1, x_4 - x_2$ and $x_4 - x_3$.
|
[
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
vector<int> a(4);
for (int i = 0; i < 4; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
cout << a[3] - a[0] << " " << a[3] - a[1] << " " << a[3] - a[2] << endl;
return 0;
}
|
1154
|
B
|
Make Them Equal
|
You are given a sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers.
You can choose any non-negative integer $D$ (i.e. $D \ge 0$), and for each $a_i$ you can:
- add $D$ (only once), i. e. perform $a_i := a_i + D$, or
- subtract $D$ (only once), i. e. perform $a_i := a_i - D$, or
- leave the value of $a_i$ unchanged.
It is possible that after an operation the value $a_i$ becomes negative.
Your goal is to choose such \textbf{minimum non-negative integer} $D$ and perform changes in such a way, that all $a_i$ are equal (i.e. $a_1=a_2=\dots=a_n$).
Print the required $D$ or, if it is impossible to choose such value $D$, print -1.
For example, for array $[2, 8]$ the value $D=3$ is minimum possible because you can obtain the array $[5, 5]$ if you will add $D$ to $2$ and subtract $D$ from $8$. And for array $[1, 4, 7, 7]$ the value $D=3$ is also minimum possible. You can add it to $1$ and subtract it from $7$ and obtain the array $[4, 4, 4, 4]$.
|
Let's leave only unique values of the given array in the array $b$ (i. e. construct an array $b$ that is actually array $a$ without duplicate element) and sort it in ascending order. Then let's consider the following cases: If the length of $b$ is greater than $3$ then the answer is -1; if the length of $b$ is $3$ then there are two cases: if $b_3 - b_2 = b_2 - b_1$ then the answer is $b_2 - b_1$; otherwise the answer is -1; if $b_3 - b_2 = b_2 - b_1$ then the answer is $b_2 - b_1$; otherwise the answer is -1; if the length of $b$ is $2$ then there are also two cases: if $b_2 - b_1$ is even then the answer is $\frac{b_2 - b_1}{2}$; otherwise the answer is $b_2 - b_1$; if $b_2 - b_1$ is even then the answer is $\frac{b_2 - b_1}{2}$; otherwise the answer is $b_2 - b_1$; and if the length of $b$ is $1$ then the answer is $0$.
|
[
"math"
] | 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;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
a.resize(unique(a.begin(), a.end()) - a.begin());
if (a.size() > 3) {
cout << -1 << endl;
} else {
if (a.size() == 1) {
cout << 0 << endl;
} else if (a.size() == 2) {
if ((a[1] - a[0]) % 2 == 0) {
cout << (a[1] - a[0]) / 2 << endl;
} else {
cout << a[1] - a[0] << endl;
}
} else {
if (a[1] - a[0] != a[2] - a[1]) {
cout << -1 << endl;
} else {
cout << a[1] - a[0] << endl;
}
}
}
return 0;
}
|
1154
|
C
|
Gourmet Cat
|
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
- on Mondays, Thursdays and Sundays he eats fish food;
- on Tuesdays and Saturdays he eats rabbit stew;
- on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already packed his backpack. His backpack contains:
- $a$ daily rations of fish food;
- $b$ daily rations of rabbit stew;
- $c$ daily rations of chicken stakes.
Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.
|
Let the number of rations of fish food be $a_1$, the number of rations of rabbit stew be $a_2$ and the number of rations of chicken stakes be $a_3$ (so we have an array $a$ consisting of $3$ elements). Let $full$ be the maximum number of full weeks cat can eat if the starting day of the trip can be any day of the week. The value of $full$ is $min(\lfloor\frac{a_1}{3}\rfloor, \lfloor\frac{a_2}{2}\rfloor, \lfloor\frac{a_3}{2}\rfloor)$. Let's subtract the value $3 \cdot full$ from $a_1$, and $2 \cdot full$ from $a_2$ and $a_3$. We can see that we cannot feed the cat at least one more full week. So the final answer is $7 \cdot full + add$, where $add < 7$. Now it's time for some good implementation! Of course, you can try to analyze all cases and handle them using ifs or something similar, but I will try to suggest you a good enough way to implement the remaining part of the problem: Let's create an array $idx$ of length $7$, where $idx_i$ means the type of the food cat eats during the $i$-th day of the week ($1$ for fish food, $2$ for rabbit stew and $3$ for chicken stake). It will be $idx = [1, 2, 3, 1, 3, 2, 1]$. Now let's iterate over the day we will start our trip. Let it be $start$. For the current starting day let $cur$ be the number of rations cat has eaten already (initially it is zero), $day$ be the current day of the trip (initially it is $start$) and the array $b$ be the copy of the array $a$. Then let's do the following sequence of the operations, while $b_{idx_{day}}$ is greater than zero: decrease $b_{idx_{day}}$ by one, increase $cur$ by one and set $day := day \% 7 + 1$ (take it modulo $7$ and add one). After this cycle we can update the answer with the value of $7 \cdot full + cur$.
|
[
"implementation",
"math"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
vector<int> a(3);
cin >> a[0] >> a[1] >> a[2];
vector<int> idx({0, 1, 2, 0, 2, 1, 0});
int full = min({a[0] / 3, a[1] / 2, a[2] / 2});
a[0] -= full * 3;
a[1] -= full * 2;
a[2] -= full * 2;
int ans = 0;
for (int start = 0; start < 7; ++start) {
int day = start;
vector<int> b = a;
int cur = 0;
while (b[idx[day]] > 0) {
--b[idx[day]];
day = (day + 1) % 7;
++cur;
}
ans = max(ans, full * 7 + cur);
}
cout << ans << endl;
return 0;
}
|
1154
|
D
|
Walking Robot
|
There is a robot staying at $X=0$ on the $Ox$ axis. He has to walk to $X=n$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.
The $i$-th segment of the path (from $X=i-1$ to $X=i$) can be exposed to sunlight or not. The array $s$ denotes which segments are exposed to sunlight: if segment $i$ is exposed, then $s_i = 1$, otherwise $s_i = 0$.
The robot has one battery of capacity $b$ and one accumulator of capacity $a$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).
If the current segment is \textbf{exposed to sunlight} and the robot goes through it \textbf{using the battery}, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).
If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.
You understand that it is not always possible to walk to $X=n$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.
|
Let's simulate the process of walking and maintain the current charges of the battery and the accumulator, carefully choosing which to use each time we want to pass a segment. Obviously, if at the beginning of some segment our battery is exhausted (its current charge is $0$), we must use the accumulator to continue, and vice versa. What if we can use both types of energy storage? If we can recharge the accumulator (the current segment is exposed and the current charge of accumulator is lower than its initial charge), let's do it - because it only consumes one charge of the battery, and there is no better way to spend it. And if we cannot recharge the accumulator, it's optimal to use it instead of the battery (suppose it's not right: our solution uses the accumulator during current moment of time $t$ and the battery during some moment in future $t_2$, but optimal solution does vice versa. Then the usage of the battery in optimal solution does not grant us any additional charges, so we can instead swap our decisions in these moments, use the accumulator right now and the battery later, and the answer won't get worse). So, what's left is to carefully implement the simulation, keeping track of charges and choosing what to use according to aforementioned rules.
|
[
"greedy"
] | 1,500
|
#include<bits/stdc++.h>
using namespace std;
int a, b, maxa;
void use_battery(int s)
{
if(s == 1) a = min(a + 1, maxa);
--b;
}
void use_accum()
{
--a;
}
int main()
{
int ans = 0;
int n;
cin >> n >> b >> a;
maxa = a;
vector<int> s(n);
for(int i = 0; i < n; i++) cin >> s[i];
for(int i = 0; i < n; i++)
{
if(a == 0 && b == 0)
break;
else if(a == 0)
use_battery(s[i]);
else if(b == 0)
use_accum();
else if(s[i] == 1 && a < maxa)
use_battery(s[i]);
else use_accum();
ans++;
}
cout << ans << endl;
}
|
1154
|
E
|
Two Teams
|
There are $n$ students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.
The $i$-th student has integer programming skill $a_i$. All programming skills are \textbf{distinct} and between $1$ and $n$, inclusive.
Firstly, the first coach will choose the student with maximum programming skill among all students not taken into any team, \textbf{and} $k$ closest students to the left of him and $k$ closest students to the right of him (if there are less than $k$ students to the left or to the right, all of them will be chosen). All students that are chosen leave the row and join the first team. Secondly, the second coach will make the same move (but all students chosen by him join the second team). Then again the first coach will make such move, and so on. This repeats until the row becomes empty (i. e. the process ends when each student becomes to some team).
Your problem is to determine which students will be taken into the first team and which students will be taken into the second team.
|
Let's maintain two data structures: a queue with positions of students in order of decreasing their programming skill and a set (std::set, note that we need exactly ordered set) with positions of students not taken in any team. To construct the first data structure we need to sort pairs $(a_i, i)$ in decreasing order of the first element and after that push second elements in order from left to right. The second data structure can be constructed even easier - we just need to insert all values from $[1, n]$ into it. Also let's maintain an array $ans$, where $ans_i = 1$ if the $i$-th student belongs to the first team and $ans_i = 2$ otherwise, and the variable $who$ to determine whose turn is now (initially it is $1$). While our set is not empty, let's repeat the following algorithm: firstly, while the head (the first element) of the queue is not in the set, pop it out. This is how we determine which student will be taken now. Let his position be $pos$. And don't forget to pop him out too. Create the additional dynamic array $add$ which will contain all students we will add to the team during this turn. Let's find the iterator to the student with the position $pos$. Then make the following sequence of moves $k+1$ times: add the element the current iterator is pointing at to the array $add$, then if the current iterator is pointing at the first element, break the cycle, otherwise go to the iterator pointing at the previous element. Then let's find the iterator to the student next to the student with position $pos$. And then let's make almost the same sequence of moves $k$ times: if the current iterator is pointing to the end of the set, break the cycle, otherwise add the element the current iterator is pointing at to the array $add$ and advance to the iterator pointing at the next element. Then let's remove all values from the array $add$ from the set, and for each student $st$ we delete let's set $ans_{st} = who$. And change the variable $who$ to $2$ if it is $1$ now and to $1$ otherwise. Time complexity: $O(n \log n)$.
|
[
"data structures",
"implementation",
"sortings"
] | 1,800
|
#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>> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i].first;
a[i].second = i;
}
sort(a.rbegin(), a.rend());
queue<int> q;
for (int i = 0; i < n; ++i) {
q.push(a[i].second);
}
set<int> idx;
for (int i = 0; i < n; ++i) {
idx.insert(i);
}
string ans(n, '0');
int who = 0;
while (!idx.empty()) {
while (!idx.count(q.front())) {
q.pop();
}
int pos = q.front();
q.pop();
vector<int> add;
auto it = idx.find(pos);
for (int i = 0; i <= k; ++i) {
add.push_back(*it);
if (it == idx.begin()) break;
--it;
}
it = next(idx.find(pos));
for (int i = 0; i < k; ++i) {
if (it == idx.end()) break;
add.push_back(*it);
++it;
}
for (auto it : add) {
idx.erase(it);
ans[it] = '1' + who;
}
who ^= 1;
}
cout << ans << endl;
return 0;
}
|
1154
|
F
|
Shovels Shop
|
There are $n$ shovels in the nearby shop. The $i$-th shovel costs $a_i$ bourles.
Misha has to buy \textbf{exactly} $k$ shovels. Each shovel can be bought \textbf{no more than once}.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also $m$ special offers in the shop. The $j$-th of them is given as a pair $(x_j, y_j)$, and it means that if Misha buys \textbf{exactly} $x_j$ shovels \textbf{during one purchase} then $y_j$ \textbf{most cheapest} of them are for free (i.e. he will not pay for $y_j$ most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use \textbf{more than one} offer during \textbf{one purchase} (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying $k$ shovels, if Misha buys them optimally.
|
First of all, since we are going to buy exactly $k$ shovels, we may discard $n - k$ most expensive shovels from the input and set $n = k$ (and solve the problem which requires us to buy all the shovels). Also, let's add an offer which allows us to buy $1$ shovel and get $0$ cheapest of them for free, to simulate that we can buy shovels without using offers. Now we claim that if we sort all the shovels by their costs, it's optimal to divide the array of costs into some consecutive subarrays and buy each subarray using some offer. Why should the sets of shovels for all purchases be consecutive subarrays? Suppose it's not so: let's pick two purchases such that they are "mixed" in the array of costs, i. e. there exists at least one shovel $A$ bought in the first purchase such that there exists a shovel $B$ cheaper than it and a shovel $C$ more expensive than it, both bought in the second purchase. If shovel $A$ is for free, then we may "swap" shovels $A$ and $C$, otherwise we may swap shovels $A$ and $B$, and the answer won't become worse. So, we can do it until all purchases correspond to subsegments in the array of costs. Then it's easy to see that we can make purchases in such a way that we always buy some amount of cheapest shovels. And now the problem can be solved by knapsack-like dynamic programming: let $dp_i$ be the minimum cost to buy exactly $i$ cheapest shovels. $dp_0$ is $0$, and for each offer $(x, y)$ we can update $dp_{i + x}$ by the value of $dp_i + sum(i + y + 1, i + x)$, where $sum(l, r)$ is the sum of costs of all shovels in the sorted order from shovel on position $l$ to shovel on position $r$, inclusive (these sums can be calculated in $O(1)$ using partial sums method).
|
[
"dp",
"greedy",
"sortings"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, m, k;
cin >> n >> m >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
a.resize(k);
reverse(a.begin(), a.end());
vector<int> offers(k + 1);
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
if (x <= k) {
offers[x] = max(offers[x], y);
}
}
vector<int> pref(k + 1);
for (int i = 0; i < k; ++i) {
pref[i + 1] = pref[i] + a[i];
}
vector<int> dp(k + 1, INF);
dp[0] = 0;
for (int i = 0; i < k; ++i) {
dp[i + 1] = min(dp[i + 1], dp[i] + a[i]);
for (int j = 1; j <= k; ++j) {
if (offers[j] == 0) continue;
if (i + j > k) break;
dp[i + j] = min(dp[i + j], dp[i] + pref[i + j - offers[j]] - pref[i]);
}
}
cout << dp[k] << endl;
return 0;
}
|
1154
|
G
|
Minimum Possible LCM
|
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$.
Your problem is to find such pair of indices $i, j$ ($1 \le i < j \le n$) that $lcm(a_i, a_j)$ is minimum possible.
$lcm(x, y)$ is the least common multiple of $x$ and $y$ (minimum positive number such that both $x$ and $y$ are divisors of this number).
|
I've heard about some very easy solutions with time complexity $O(a \log a)$, where $a$ is the maximum value of $a_i$, but I will describe my solution with time complexity $O(nd)$, where $d$ is the maximum number of divisors of $a_i$. A very good upper-bound approximation of the number of divisors of $x$ is $\sqrt[3]{x}$ so my solution works in $O(n \sqrt[3]{a})$. Firstly, let's talk about the idea. The main idea is the following: for each number from $1$ to $10^7$, we want to find two minimum numbers in the array which are divisible by this number. Then we can find the answer among all such divisors that have at least two multiples in the array. Let's write a function $add(idx)$ which will try to add the number $a_{idx}$ to all its divisors. The easiest way to do it is iterate over all divisors in time $O(\sqrt{a_{idx}})$ and add it somehow. But it is too slow. Let's improve it somehow. How can we skip numbers that aren't divisors of $a_{idx}$? Let's build an Eratosthenes sieve (I highly recommended one with time complexity $O(n)$ because the sieve with time complexity $O(n \log \log n)$ is about twice slower on such constraints) which will maintain the minimum divisor for each number from $1$ to $10^7$ (the linear sieve builds this array automatically in its implementation). Then we can factorize the number in $O(\log a_{idx})$ and iterate over all its divisors using simple recursive function. And the last thing I should notice - this solution can give TLE and require some constant optimizations. I recommended to use pair of integers (or arrays of size two) for each divisor and to add numbers using a few if-statements.
|
[
"brute force",
"greedy",
"math",
"number theory"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int N = 10 * 1000 * 1000 + 11;
int n;
vector<int> a;
int mind[N];
pair<int, int> mins[N];
vector<pair<int, int>> divs;
void build_sieve() {
vector<int> pr;
mind[0] = mind[1] = 1;
for (int i = 2; i < N; ++i) {
if (mind[i] == 0) {
pr.push_back(i);
mind[i] = i;
}
for (int j = 0; j < int(pr.size()) && pr[j] <= mind[i] && i * pr[j] < N; ++j) {
mind[i * pr[j]] = pr[j];
}
}
}
void add_to_mins(int curd, int idx) {
if(mins[curd].first == -1)
mins[curd].first = idx;
else if(mins[curd].second == -1)
mins[curd].second = idx;
}
void rec(int pos, int curd, int idx) {
if (pos == int(divs.size())) {
add_to_mins(curd, idx);
return;
}
int curm = 1;
for (int i = 0; i <= divs[pos].second; ++i) {
rec(pos + 1, curd * curm, idx);
curm *= divs[pos].first;
}
}
void add(int idx) {
int value = a[idx];
divs.clear();
while (value > 1) {
int d = mind[value];
if (!divs.empty() && divs.back().first == d) {
++divs.back().second;
} else {
divs.push_back(make_pair(d, 1));
}
value /= d;
}
rec(0, 1, idx);
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n;
a.resize(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for(int i = 0; i < N; i++)
mins[i] = make_pair(-1, -1);
build_sieve();
vector<pair<int, int> > vals;
for(int i = 0; i < n; i++)
vals.push_back(make_pair(a[i], i));
sort(vals.begin(), vals.end());
for (int i = 0; i < n; ++i) {
if(i > 1 && vals[i].first == vals[i - 2].first) continue;
add(vals[i].second);
}
long long l = INF * 1ll * INF;
int ansi = -1, ansj = -1;
for (int i = 1; i < N; ++i) {
pair<int, int> idxs = mins[i];
if (idxs.second == -1) continue;
long long curl = a[idxs.first] * 1ll * a[idxs.second] / i;
if (l > curl) {
l = curl;
ansi = min(idxs.first, idxs.second);
ansj = max(idxs.first, idxs.second);
}
}
cout << ansi + 1 << " " << ansj + 1 << endl;
return 0;
}
|
1155
|
A
|
Reverse a Substring
|
You are given a string $s$ consisting of $n$ lowercase Latin letters.
Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $3$ and ends in position $6$), but "aa" or "d" aren't substrings of this string. So the substring of the string $s$ from position $l$ to position $r$ is $s[l; r] = s_l s_{l + 1} \dots s_r$.
You have to choose \textbf{exactly} one of the substrings of the given string and reverse it (i. e. make $s[l; r] = s_r s_{r - 1} \dots s_l$) to obtain a string that is \textbf{less} lexicographically. Note that it \textbf{is not necessary} to obtain the minimum possible string.
If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and \textbf{any} suitable substring.
String $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x \ne y$), or there exists such $i$ ($1 \le i \le min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.
|
If the answer is "YES" then we always can reverse a substring of length $2$. So we need to check only pairs of adjacent characters in $s$. If there is no such pair of characters $s_i > s_{i + 1}$ for all $i$ from $1$ to $n-1$ then the answer is "NO". Why is it so? Consider the substring $s[l; r] = s_l s_{l+1} \dots s_r$ we have to reverse. It is obvious that $s_l > s_r$, otherwise it is pointless to reverse this substring. Then consider two cases: $s_l \le s_{l+1}$ then $s_{l+1} > s_r$ (by transitivity) and then we can go to a smaller substring ($s[l + 1; r]$); otherwise $s_l > s_{l + 1}$ and it means that we can take the substring $s[l; l + 1]$.
|
[
"implementation",
"sortings",
"strings"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
string s;
cin >> n >> s;
for (int i = 1; i < int(s.size()); ++i) {
if (s[i] < s[i - 1]) {
cout << "YES" << endl;
cout << i << " " << i + 1 << endl;
return 0;
}
}
cout << "NO" << endl;
return 0;
}
|
1155
|
B
|
Game with Telephone Numbers
|
A telephone number is a sequence of \textbf{exactly} $11$ digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string $s$ of length $n$ ($n$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player \textbf{must} choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $s$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.
You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
|
Let's understand how players should act. Vasya needs to delete the first digit that is not equal to $8$, because the first digit of telephone number should be $8$, and the first digit not equal to $8$ is preventing it. Petya needs to delete the first digit equal to $8$, for the same reasons. So, all that we need to do is delete first $\frac{n-11}{2}$ digits not equal to $8$ (if they exist), and first $\frac{n-11}{2}$ digits equal to $8$ (again if they exist). It's enough to stop when there is either no $8$'s left or no non-$8$'s because the latter moves won't change the result of the game anyway. Finally, if first digit of resulting string is $8$, then Vasya wins, otherwise Petya. Overall complexity: $O(n)$.
|
[
"games",
"greedy",
"implementation"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
int n;
string s;
int main(){
cin >> n >> s;
int cnt1 = (n - 11) / 2;
int cnt2 = cnt1;
string res = "";
for(int i = 0; i < n; ++i){
if(s[i] == '8'){
if(cnt1 > 0) --cnt1;
else res += s[i];
}
else{
if(cnt2 > 0) --cnt2;
else res += s[i];
}
}
if(res[0] == '8') cout << "YES\n";
else cout << "NO\n";
return 0;
}
|
1155
|
C
|
Alarm Clocks Everywhere
|
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $i$-th of them will start during the $x_i$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $x_1, x_2, \dots, x_n$, so he will be awake during each of these minutes (\textbf{note that it does not matter if his alarm clock will ring during any other minute}).
Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as $y$) and the interval between two consecutive signals (let's denote it by $p$). After the clock is set, it will ring during minutes $y, y + p, y + 2p, y + 3p$ and so on.
Ivan can choose \textbf{any} minute as the first one, but he cannot choose any arbitrary value of $p$. He has to pick it among the given values $p_1, p_2, \dots, p_m$ (his phone does not support any other options for this setting).
So Ivan has to choose the first minute $y$ when the alarm clock should start ringing and the interval between two consecutive signals $p_j$ in such a way that it will ring during all given minutes $x_1, x_2, \dots, x_n$ (and it does not matter if his alarm clock will ring in any other minutes).
Your task is to tell the first minute $y$ and the index $j$ such that if Ivan sets his alarm clock with properties $y$ and $p_j$ it will ring during all given minutes $x_1, x_2, \dots, x_n$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.
|
It is obvious that we can always take $x_1$ as $y$. But we don't know which value of $p$ we can take. Let $d_i$ be $x_{i + 1} - x_i$ for all $i$ from $1$ to $n-1$. The value of $p$ should be divisor of each value of $d_i$. The maximum possible divisor of each $d_i$ is $g = gcd(d_1, d_2, \dots, d_{n-1})$ (greatest common divisor). And then it is obvious that the value of $p$ should be the divisor of $g$. So we have to find any divisor of $g$ among all values $p_j$. If there is no such value then the answer is "NO". Time complexity: $O(n \log n)$.
|
[
"math",
"number theory"
] | 1,300
|
#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<long long> x(n), p(m);
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
for (int i = 0; i < m; ++i) {
cin >> p[i];
}
long long g = x[1] - x[0];
for (int i = 2; i < n; ++i) {
g = __gcd(g, x[i] - x[i - 1]);
}
for (int i = 0; i < m; ++i) {
if (g % p[i] == 0) {
cout << "YES" << endl;
cout << x[0] << " " << i + 1 << endl;
return 0;
}
}
cout << "NO" << endl;
return 0;
}
|
1155
|
D
|
Beautiful Array
|
You are given an array $a$ consisting of $n$ integers. Beauty of array is the maximum sum of some \textbf{consecutive subarray} of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.
You may choose \textbf{at most one consecutive subarray} of $a$ and multiply all values contained in this subarray by $x$. You want to maximize the beauty of array after applying at most one such operation.
|
The first intuitive guess one's probably made is multiplying the segment of maximum sum for positive $x$. That thing is correct. Unfortunately, there is no similar strategy for non-positive $x$, simple greedy won't work there. Thus, dynamic programming is our new friend. Let's introduce the following state: $dp[pos][state_{max}][state_{mul}]$, where $pos$ is the length of the currently processed prefix, $state_{max}$ is the state of maximum sum segment ($0$ is not reached, it'll appear later, $1$ is open, current elements are added to it, $2$ is passed, the segment appeared earlier) and $state_{mul}$ is the state of segment multiplied by $x$ with the same values. This $dp$ will store the maximum segment sum we can achieve. The only base state is $dp[0][0][0] = 0$ - the prefix of length $0$ is processed and both segments are not open yet. The rest of values in $dp$ are $-\infty$. There are two main transitions. At any moment we can change the state of each segment to the next one without moving to the next position. From state $0$ (not reached) we can go to state $1$ (opened) and from state $1$ we can go to state $2$ (passed). Note that this easily covers the case where optimal segment is empty. We can also move to the next position updating the value of $dp$ with correspondance to the current states of segments. The answer will be stored in $dp[n][2][2]$ - the state where all the array is processed and both segments are closed. Overall complexity: $O(n)$.
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
typedef long long li;
const int N = 300 * 1000 + 13;
const li INF64 = 1e18;
int n, x;
int a[N];
li dp[N][3][3];
int main() {
scanf("%d%d", &n, &x);
forn(i, n) scanf("%d", &a[i]);
forn(i, n + 1) forn(j, 3) forn(k, 3)
dp[i][j][k] = -INF64;
dp[0][0][0] = 0;
forn(i, n + 1) forn(j, 3) forn(k, 3){
if (k < 2)
dp[i][j][k + 1] = max(dp[i][j][k + 1], dp[i][j][k]);
if (j < 2)
dp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k]);
if (i < n)
dp[i + 1][j][k] = max(dp[i + 1][j][k], dp[i][j][k] + (j == 1 ? a[i] : 0) * li(k == 1 ? x : 1));
}
printf("%lld\n", dp[n][2][2]);
}
|
1155
|
E
|
Guess the Root
|
Jury picked a polynomial $f(x) = a_0 + a_1 \cdot x + a_2 \cdot x^2 + \dots + a_k \cdot x^k$. $k \le 10$ and all $a_i$ are integer numbers and $0 \le a_i < 10^6 + 3$. It's guaranteed that there is at least one $i$ such that $a_i > 0$.
Now jury wants you to find such an integer $x_0$ that $f(x_0) \equiv 0 \mod (10^6 + 3)$ or report that there is not such $x_0$.
You can ask no more than $50$ queries: you ask value $x_q$ and jury tells you value $f(x_q) \mod (10^6 + 3)$.
Note that printing the answer doesn't count as a query.
|
Since $10^6 + 3$ is a prime and degree $k$ of the polynomial is small enough, we can get this polynomial in our hands asking $k + 1$ queries in different points. Knowing values $f(x_i)$ for $x_1, x_2, \dots, x_{k + 1}$, we can interpolate $f$ by various ways. For example, we can construct a system of linear equations thinking of $a_i$ as variables. In other words, we know, that $a_0 \cdot x_i^0 + a_1 \cdot x_i^1 + \dots + a_k \cdot x_i^k = f(x_i)$ for $i = 1 \dots (k+1)$, also we know $x_i^l$ and $f(x_i)$. So we can solve this system using Gaussian elimination in $O(k^3)$. Now, knowing the polynomial $f(x)$ we can locally brute force all possible candidates for $x_0$, since there is only $10^6 + 3$ such candidates, and print the one we found.
|
[
"brute force",
"interactive",
"math"
] | 2,200
|
#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<int, int> pt;
const int MOD = 1000 * 1000 + 3;
int norm(int a) {
while(a >= MOD) a -= MOD;
while(a < 0) a += MOD;
return a;
}
int mul(int a, int b) {
return int(a * 1ll * b % MOD);
}
int binPow(int a, int k) {
int ans = 1;
while(k > 0) {
if(k & 1)
ans = mul(ans, a);
a = mul(a, a);
k >>= 1;
}
return ans;
}
int inv(int a) {
return binPow(a, MOD - 2);
}
int k = 10;
vector<int> f;
int main() {
f.resize(k + 1);
fore(i, 0, sz(f)) {
cout << "? " << i << endl;
cout.flush();
cin >> f[i];
}
vector< vector<int> > mat(sz(f), vector<int>(sz(f) + 1));
fore(i, 0, sz(mat)) {
mat[i][0] = 1;
mat[i][sz(f)] = f[i];
fore(j, 1, sz(mat[i]) - 1)
mat[i][j] = mul(mat[i][j - 1], i);
}
/*
fore(i, 0, sz(mat)) {
fore(j, 0, sz(mat[i]))
cerr << mat[i][j] << " ";
cerr << endl;
}
*/
fore(j, 0, sz(mat)) {
int nid = -1;
fore(i, j, sz(mat)) {
if(mat[i][j] != 0) {
nid = i;
break;
}
}
if(nid == -1)
continue;
swap(mat[j], mat[nid]);
fore(i, 0, sz(mat)) {
if(i == j) continue;
int cf = mul(mat[i][j], inv(mat[j][j]));
fore(cj, j, sz(mat[i]))
mat[i][cj] = norm(mat[i][cj] - mul(cf, mat[j][cj]));
}
}
vector<int> a(sz(f), 0);
fore(i, 0, sz(a)) {
if(mat[i][i] == 0)
continue;
a[i] = mul(mat[i][sz(a)], inv(mat[i][i]));
}
fore(x0, 0, MOD) {
int val = 0;
for(int i = sz(a) - 1; i >= 0; i--)
val = norm(mul(val, x0) + a[i]);
if(val == 0) {
cout << "! " << x0 << endl;
return 0;
}
}
cout << "! -1" << endl;
return 0;
}
|
1155
|
F
|
Delivery Oligopoly
|
The whole delivery market of Berland is controlled by two rival companies: BerEx and BerPS. They both provide fast and reliable delivery services across all the cities of Berland.
The map of Berland can be represented as an \textbf{undirected} graph. The cities are vertices and the roads are edges between them. Each pair of cities has no more than one road between them. Each road connects different cities.
BerEx and BerPS are so competitive that for each pair of cities $(v, u)$ they have set up their paths from $v$ to $u$ in such a way that \textbf{these two paths don't share a single road}. It is guaranteed that it was possible.
Now Berland government decided to cut down the road maintenance cost by abandoning some roads. Obviously, they want to maintain as little roads as possible. However, they don't want to break the entire delivery system. So BerEx and BerPS should still be able to have their paths between every pair of cities non-intersecting.
What is the minimal number of roads Berland government can maintain?
More formally, given a 2-edge connected undirected graph, what is the minimum number of edges that can be left in it so that the resulting graph is also 2-edge connected?
|
Let's use dynamic programming to solve this problem. We will start with a single biconnected component consisting of vertex $0$, and connect other vertices to it. So, the state of our dynamic programming will be a $mask$ of vertices that are in the same biconnected component with $0$. How can we extend a biconnected component in such a way that some other vertices are added into it, but it is still biconnected? We will add a path (possibly cyclic) that starts in some vertex $x$ belonging to the $mask$, goes through some vertices not belonging to the $mask$, and ends in some vertex $y$ belonging to the $mask$ (possibly $x = y$). If for every triple ($x$, $y$, $addmask$) we precalculate some path that starts in $x$, goes through vertices from $addmask$ and ends in $y$ (and $addmask$ does not contain neither $x$ nor $y$), then we can solve the problem in $O(3^n n^2)$: there will be $2^n$ states, for every state we will iterate on two vertices $x$ and $y$ belonging to the $mask$, and the number of possible pairs of non-intersecting masks $mask$ and $addmask$ is $O(3^n)$. The only thing that's left is precalculating the paths for triples ($x$, $y$, $addmask$). That can be done with auxiliary dynamic programming $dp_2[x][y][addmask]$ which will denote whether such a path exists. For every edge $(u, v)$ of the original graph, $dp_2[u][v][0]$ is true, and we can go from $dp_2[x][y][addmask]$ to some state $dp_2[x][z][addmask']$, where $addmask'$ will contain all vertices from $addmask$ and vertex $y$ (and we should ensure that there is an edge $(y, z)$ in the graph and the $addmask$ didn't contain vertex $y$ earlier). We should also somehow be able to restore the paths from this dp, and we also should be careful not to choose the same edge twice (for example, if we start a path by edge $(x, y)$, we should not use the same edge to return to $x$) - both these things can be done, for example, by storing next-to-last vertex in the path.
|
[
"brute force",
"dp",
"graphs"
] | 2,800
|
#include<bits/stdc++.h>
using namespace std;
const int N = 14;
const int INF = int(1e9);
int dp[1 << N];
int par[1 << N];
int last[1 << N];
pair<int, int> last_pair[1 << N];
int dp2[N][N][1 << N];
int lastv[N][N][1 << N];
vector<int> bits[1 << N];
int n;
int m;
vector<int> g[N];
int main()
{
cin >> n >> m;
for(int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
--x;
--y;
g[x].push_back(y);
g[y].push_back(x);
}
for(int i = 0; i < (1 << n); i++)
dp[i] = INF;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
for(int z = 0; z < (1 << n); z++)
dp2[i][j][z] = INF;
for(int i = 0; i < n; i++)
for(auto x : g[i])
{
dp2[i][x][0] = 1;
lastv[i][x][0] = i;
}
for(int mask = 0; mask < (1 << n); mask++)
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
if((mask & (1 << i)) || (mask & (1 << j)) || (i == j) || (dp2[i][j][mask] == INF))
continue;
for(auto z : g[j])
{
if(mask & (1 << z)) continue;
if(z == lastv[i][j][mask]) continue;
int nmask = mask ^ (1 << j);
if(dp2[i][z][nmask] == INF)
{
dp2[i][z][nmask] = 1;
lastv[i][z][nmask] = j;
}
}
}
for(int mask = 0; mask < (1 << n); mask++)
for(int j = 0; j < n; j++)
if(mask & (1 << j))
bits[mask].push_back(j);
dp[1] = 0;
for(int mask = 0; mask < (1 << n); mask++)
for(int addmask = mask; addmask; addmask = (addmask - 1) & mask)
{
int lastmask = mask ^ addmask;
int cnt = __builtin_popcount(addmask) + 1;
if(dp[lastmask] + cnt >= dp[mask])
continue;
bool f = false;
for(auto x : bits[lastmask])
{
for(auto y : bits[lastmask])
{
if(dp2[x][y][addmask] == 1)
{
dp[mask] = dp[lastmask] + cnt;
last_pair[mask] = make_pair(x, y);
last[mask] = addmask;
}
if(f) break;
}
if(f) break;
}
}
if(dp[(1 << n) - 1] == INF)
cout << -1 << endl;
else
{
cout << dp[(1 << n) - 1] << endl;
int cur = (1 << n) - 1;
while(cur != 1)
{
int lst = last[cur];
int x = last_pair[cur].first;
int y = last_pair[cur].second;
cur ^= lst;
while(lst)
{
int ny = lastv[x][y][lst];
cout << y + 1 << " " << ny + 1 << endl;
lst ^= (1 << ny);
y = ny;
}
cout << x + 1 << " " << y + 1 << endl;
}
}
}
|
1156
|
A
|
Inscribed Figures
|
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.
Future students will be asked just a single question. They are given a sequence of integer numbers $a_1, a_2, \dots, a_n$, each number is from $1$ to $3$ and $a_i \ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure:
- circle;
- isosceles triangle with the length of height equal to the length of base;
- square.
The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:
- $(i + 1)$-th figure is inscribed into the $i$-th one;
- each triangle base is parallel to OX;
- the triangle is oriented in such a way that the vertex opposite to its base is at the top;
- each square sides are parallel to the axes;
- for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle.
Note that the construction is unique for some fixed position and size of just the first figure.
The task is to calculate the number of \textbf{distinct} points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?
So can you pass the math test and enroll into Berland State University?
|
Firstly, let's find out when the answer is infinite. Obviously, any point of intersection is produced by at least a pair of consecutive figures. Take a look at every possible pair and you'll see that only square inscribed in triangle and vice verse produce infinite number of points in intersection. The other cases are finite. From now we assume that initial sequence has no 2 and 3 next to each other. Basically, it's all triangles and squares separated by circles. If the task was to count all pairs of intersecting figures, the solution will be the following. Square next to circle gives 4 points, triangle next to circle gives 3 points. Unfortunately, the task asked for distinct points. Notice that there is a single subsegment which can produce coinciding points (square $\rightarrow$ circle $\rightarrow$ triangle). So you have to find each triplet (3 1 2) and subtract their count from the sum. Overall complexity: $O(n)$.
|
[
"geometry"
] | 1,400
|
#include <bits/stdc++.h>
#define forn(i, n) for(int i = 0; i < int(n); i++)
using namespace std;
int main(){
int n;
scanf("%d", &n);
int sum = 0;
int lst = 1;
vector<int> figs;
forn(i, n){
int x;
scanf("%d", &x);
if (lst != 1 && x != 1){
puts("Infinite");
return 0;
}
if (x != 1){
figs.push_back(x);
sum += x + 1;
if (i != 0 && i != n - 1)
sum += x + 1;
}
lst = x;
}
forn(i, int(figs.size()) - 1) if (figs[i] == 3 && figs[i + 1] == 2)
--sum;
printf("Finite\n%d\n", sum);
}
|
1156
|
B
|
Ugly Pairs
|
You are given a string, consisting of lowercase Latin letters.
A pair of \textbf{neighbouring} letters in a string is considered ugly if these letters are also \textbf{neighbouring} in a alphabet. For example, string "abaca" contains ugly pairs at positions $(1, 2)$ — "ab" and $(2, 3)$ — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer $T$ separate queries.
|
To be honest, the solution to this problem is easier to code than to prove. Let's follow the next strategy. Write down all the letters of the string which have odd positions in alphabet ("aceg$\dots$") and even positions in alphabet ("bdfi$\dots$"). Sort both of these lists in non-decreasing order. The answer is either concatenation of the lists (odd + even or even + odd) or "No answer". Now for the proof part. Let's establish that we don't care about equal letters and leave just a single copy of each letter of the string. Let's check some cases: There is just a single letter. That's trivial. There are two letters of the same parity. There is no incorrect arrangement for this. There are two letters of different parity. If they differ by one then no answer exists. Otherwise any arrangement works. There are three letters and they are consecutive in alphabet. No answer exists. There are other types of three letters. Then the one of the different parity can put on the side (e.g. "acd" and "dac"). As the difference between at least one of these letters and that one isn't 1, that arrangement will be ok. Finally, there are at least 4 letters. It means that the difference between either the smallest odd and the largest even or between the smallest even and the largest odd isn't 1. The only thing you need to do is to implement the check function the most straightforward way possible and check both arrangements. Overall complexity: $O(n \log n)$.
|
[
"dfs and similar",
"greedy",
"implementation",
"sortings",
"strings"
] | 1,800
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
bool check(string s){
bool ok = true;
forn(i, int(s.size()) - 1)
ok &= (abs(s[i] - s[i + 1]) != 1);
return ok;
}
int main() {
int T;
scanf("%d", &T);
static char buf[120];
forn(_, T){
scanf("%s", buf);
string s = buf;
string odd = "", even = "";
forn(i, s.size()){
if (s[i] % 2 == 0)
odd += s[i];
else
even += s[i];
}
sort(odd.begin(), odd.end());
sort(even.begin(), even.end());
if (check(odd + even))
printf("%s\n", (odd + even).c_str());
else if (check(even + odd))
printf("%s\n", (even + odd).c_str());
else
puts("No answer");
}
return 0;
}
|
1156
|
C
|
Match Points
|
You are given a set of points $x_1$, $x_2$, ..., $x_n$ on the number line.
Two points $i$ and $j$ can be matched with each other if the following conditions hold:
- neither $i$ nor $j$ is matched with any other point;
- $|x_i - x_j| \ge z$.
What is the maximum number of pairs of points you can match with each other?
|
Let's denote the points that have greater coordinates in their matched pairs as $R$-points, and the points that have smaller coordinates as $L$-points. Suppose we have an $R$-point that has smaller coordinate than some $L$-point. Then we can "swap" them, and the answer won't become worse. Also, if some $R$-point has smaller coordinate than some point that doesn't belong to any pair, or some $L$-point has greater coordinate than some point that doesn't belong to any pair, we can swap them too. So, if the answer is $k$, we choose $k$ leftmost points as $L$-points, and $k$ rightmost ones as $R$-points. For a fixed value of $k$, it's easy to see that we should match the leftmost $L$-point with the leftmost $R$-point, the second $L$-point with the second $R$-point, and so on, in order to maximize the minimum distance in a pair. This fact allows us to check whether it is possible to construct at least $k$ pairs, and we can use binary search to compute the answer to the problem.
|
[
"binary search",
"greedy",
"sortings",
"ternary search",
"two pointers"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
const int N = 200043;
int n, z;
int a[N];
int main()
{
scanf("%d", &n);
scanf("%d", &z);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
sort(a, a + n);
int l = 0;
int r = n / 2 + 1;
while(r - l > 1)
{
int m = (l + r) / 2;
bool good = true;
for(int i = 0; i < m; i++)
good &= (a[n - m + i] - a[i] >= z);
if(good)
l = m;
else
r = m;
}
cout << l << endl;
}
|
1156
|
D
|
0-1-Tree
|
You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices and $n - 1$ edges. A number is written on each edge, each number is either $0$ (let's call such edges $0$-edges) or $1$ (those are $1$-edges).
Let's call an ordered pair of vertices $(x, y)$ ($x \ne y$) \textbf{valid} if, while traversing the simple path from $x$ to $y$, we never go through a $0$-edge after going through a $1$-edge. Your task is to calculate the number of \textbf{valid} pairs in the tree.
|
Let's divide all valid pairs into three categories: the ones containing only $0$-edges on the path, the ones containing only $1$-edges, and the ones containing both types of edges. To calculate the number of pairs containing only $0$-edges, we may build a forest on the vertices of the original graph and $0$-edges, and choose all pairs of vertices belonging to the same connected components of this forest (we can find all connected components with DSU or any graph traversal algorithm). The same can be done for the pairs containing only $1$-edges. If a path from $x$ to $y$ is valid and contains both types of edges, then there exists a vertex $v$ such that the simple path from $x$ to $v$ goes only through $0$-edges, and the simple path from $v$ to $y$ goes only through $1$-edges. So, let's iterate on this vertex $v$, and choose some other vertex from its component in $0$-graph as $x$, and some other vertex from its component in $1$-graph as $y$, and add the number of ways to choose them to the answer.
|
[
"dfs and similar",
"divide and conquer",
"dp",
"dsu",
"trees"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
const int N = 200043;
int p[2][N];
int siz[2][N];
int get(int x, int c)
{
if(p[c][x] == x)
return x;
return p[c][x] = get(p[c][x], c);
}
void merge(int x, int y, int c)
{
x = get(x, c);
y = get(y, c);
if(siz[c][x] < siz[c][y])
swap(x, y);
p[c][y] = x;
siz[c][x] += siz[c][y];
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
p[0][i] = p[1][i] = i;
siz[0][i] = siz[1][i] = 1;
}
for(int i = 0; i < n - 1; i++)
{
int x, y, c;
scanf("%d %d %d", &x, &y, &c);
--x;
--y;
merge(x, y, c);
}
long long ans = 0;
for(int i = 0; i < n; i++)
{
if(p[0][i] == i)
ans += siz[0][i] * 1ll * (siz[0][i] - 1);
if(p[1][i] == i)
ans += siz[1][i] * 1ll * (siz[1][i] - 1);
ans += (siz[0][get(i, 0)] - 1) * 1ll * (siz[1][get(i, 1)] - 1);
}
cout << ans << endl;
}
|
1156
|
E
|
Special Segments of Permutation
|
You are given a permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).
Let's call some subsegment $p[l, r]$ of this permutation special if $p_l + p_r = \max \limits_{i = l}^{r} p_i$. Please calculate the number of special subsegments.
|
Let's fix the maximum element on segment and iterate on either the elements to the left of it or to the right of it, and if the current maximum is $x$, and the element we found is $y$, check whether the element $x - y$ can form a special subsegment with $y$ (that is, $x$ is the maximum value on the segment between $y$ and $x - y$). That obviously works in $O(n^2)$, yes? Well, not exactly. If we can precompute the borders of the segment where $x$ is the maximum element (this can be done with some logarithmic data structure, or just by processing the array with a stack forwards and backwards) and always choose to iterate on the smaller part of the segment, it's $O(n \log n)$. Why is it so? Every element will be processed no more than $\log n$ times because, if we process it in a segment of size $m$, the smaller part of it contains no more than $\frac{m}{2}$ elements (which we will process later, and the smaller part of this segment contains no more than $\frac{m}{4}$ elements, and so on). Checking whether the element belongs to the segment we are interested in can be done in $O(1)$ if we precompute inverse permutation for $p$.
|
[
"data structures",
"divide and conquer",
"dsu",
"two pointers"
] | 2,200
|
#include<bits/stdc++.h>
using namespace std;
const int N = 200043;
int lf[N];
int rg[N];
int n;
int ans = 0;
int p[N];
int q[N];
void update(int l, int r, int l2, int r2, int sum)
{
for(int i = l; i <= r; i++)
{
int o = sum - p[i];
if(o >= 1 && o <= n && l2 <= q[o] && q[o] <= r2)
ans++;
}
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%d", &p[i]);
q[p[i]] = i;
}
stack<pair<int, int> > s;
s.push(make_pair(n + 1, -1));
for(int i = 0; i < n; i++)
{
while(s.top().first < p[i])
s.pop();
lf[i] = s.top().second;
s.push(make_pair(p[i], i));
}
while(!s.empty())
s.pop();
s.push(make_pair(n + 1, n));
for(int i = n - 1; i >= 0; i--)
{
while(s.top().first < p[i])
s.pop();
rg[i] = s.top().second;
s.push(make_pair(p[i], i));
}
for(int i = 0; i < n; i++)
{
// cerr << i << " " << lf[i] << " " << rg[i] << endl;
int lenl = i - lf[i] - 1;
int lenr = rg[i] - i - 1;
if(lenl == 0 || lenr == 0)
continue;
if(lenl < lenr)
update(lf[i] + 1, i - 1, i + 1, rg[i] - 1, p[i]);
else
update(i + 1, rg[i] - 1, lf[i] + 1, i - 1, p[i]);
}
cout << ans << endl;
}
|
1156
|
F
|
Card Bag
|
You have a bag which contains $n$ cards. There is a number written on each card; the number on $i$-th card is $a_i$.
You are playing the following game. During each turn, you choose and remove a random card from the bag (all cards that are still left inside the bag are chosen equiprobably). Nothing else happens during the first turn — but during the next turns, after removing a card (let the number on it be $x$), you compare it with the card that was removed during the previous turn (let the number on it be $y$). Possible outcomes are:
- if $x < y$, the game ends and you lose;
- if $x = y$, the game ends and you win;
- if $x > y$, the game continues.
If there are no cards left in the bag, you lose. \textbf{Cards are not returned into the bag after you remove them.}
You have to calculate the probability of winning in this game. It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \neq 0$, $P \le Q$. Output the value of $P \cdot Q^{−1} ~(mod ~~ 998244353)$.
|
Let's solve the problem by dynamic programming. Let $dp_{i, j}$ be the probability of winning if the last taken card has number $i$ on it and the number of taken cards is $j$. We win immediately next turn if we take card with number $i$ on it. The probability of this is $\frac{cnt_{i} - 1}{n - j}$, where $cnt_i$ is number of cards with $i$. Also we can win if we take a greater card next turn. We take a card with number $i + 1$ with probability $\frac{cnt_{i + 1}}{n - j}$, with number $i+2$ - with probability $\frac{cnt_{i + 2}}{n - j}$, and so on. The probability of winning in this case will be $\frac{cnt_{i + 1}}{n - j} \cdot dp_{i + 1, j + 1}$ and $\frac{cnt_{i + 2}}{n - j} \cdot dp_{i + 2, j + 1}$ respectively. So the probability of winning for $dp_{i, j}$ is $\frac{cnt_{i} - 1}{n - j} + \sum\limits_{k = i + 1}^{n} (\frac{cnt_{k}}{n - j} \cdot dp_{k, j + 1}$) = $\frac{cnt_{i} - 1}{n - j} + \frac{1}{n - j} \cdot \sum\limits_{k = i + 1}^{n} (cnt_{k} \cdot dp_{k, j + 1}$). Therefore, all we need is to maintain the sum $\sum\limits_{i = x}^{n} (cnt_{i} \cdot dp_{i, j})$ while calculating our dynamic programming.
|
[
"dp",
"math",
"probabilities"
] | 2,300
|
#include<bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int N = 5005;
void upd(int &a, int b){
a += b;
a %= MOD;
}
int mul(int a, int b){
return (a * 1LL * b) % MOD;
}
int bp(int a, int n){
int res = 1;
for(; n > 0; n >>= 1){
if(n & 1) res = mul(res, a);
a = mul(a, a);
}
return res;
}
int getInv(int a){
int ia = bp(a, MOD - 2);
assert(mul(a, ia) == 1);
return ia;
}
int n;
int cnt[N];
int suf[N];
int dp[N][N];
int sum[N][N];
int inv[N];
int main(){
for(int i = 1; i < N; ++i)
inv[i] = getInv(i);
cin >> n;
for(int i = 0; i < n; ++i){
int x;
cin >> x;
++cnt[x];
}
cnt[0] = 1;
for(int i = N - 2; i >= 0; --i)
suf[i] = suf[i + 1] + cnt[i];
for(int x = n; x >= 0; --x)
for(int y = n; y >= 0; --y){
if(cnt[x] == 0){
upd(sum[x][y], sum[x + 1][y]);
continue;
}
int s = n - y;
if(s <= 0){
upd(sum[x][y], sum[x + 1][y]);
continue;
}
upd(dp[x][y], mul(cnt[x] - 1, inv[s]));
upd(dp[x][y], mul(sum[x + 1][y + 1], inv[s]));
upd(sum[x][y], sum[x + 1][y]);
upd(sum[x][y], mul(cnt[x], dp[x][y]));
}
cout << dp[0][0] << endl;
return 0;
}
|
1156
|
G
|
Optimizer
|
Let's analyze a program written on some strange programming language. The variables in this language have names consisting of $1$ to $4$ characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.
There are four types of operations in the program, each denoted by one of the characters: $, ^, # or &.
Each line of the program has one of the following formats:
- <lvalue>=<rvalue>, where <lvalue> and <rvalue> are valid variable names;
- <lvalue>=<arg1><op><arg2>, where <lvalue>, <arg1> and <arg2> are valid variable names, and <op> is an operation character.
The program is executed line-by-line, and the result of execution is stored in a variable having the name res. If res is never assigned in the program, then the result will be equal to the value of res before running the program.
Two programs are called equivalent if no matter which operations do characters $, ^, # and & denote (but, obviously, performing the same operation on the same arguments gives the same result) and which values do variables have before execution of program, the value of res after running the first program is equal to the value of res after running the second program (the programs are executed independently).
You are given a program consisting of $n$ lines. Your task is to write a program consisting of minimum possible number of lines that is equivalent to the program you are given.
|
Let's restate the problem in a more convinient way. Initially we are given some directed acyclic graph. Let there be nodes of two kinds: For a direct set operation. These will have a single outgoing edge to another node. For a binary operation. These will have two outgoing edges to other nodes. However, it's important which edge is the "left" one and which is the "right" one. We also have to make dummy vertices for the variables which only appeared at the right side of some operation. We are allowed to remove any direct set operations, we will simulate this by compressing the edges of the graph. Instead of doing ($b=a, c=b$), we'll do ($b=a, c=a$). Value-wise this is the same but variable $c$ don't rely on $b$ anymore, so $b$ might be deleted. We'll build the entire graph line by line. Let's maintain array $var2node$ which will keep the current value of each variable. It will store the node itself. It's probably better to store both kinds of nodes in a separate array so that $var2node$ and the pointers to the ends of the edges could be integers. If we encountered no "res" variable getting set, then the answer is 0. Otherwise let's traverse from the node representing the current value of "res" to every reachable node. While building the graph we were compressing every unoptimal operation, thus all reachable nodes matter. Finally, the last operation on "res" might have been just a direct set. That's unoptimal, so we'll handle that case separately.
|
[
"graphs",
"greedy",
"hashing",
"implementation"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef pair<ll,ll> pll;
typedef vector<bool> vb;
const ll oo = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-9;
#define sz(c) ll((c).size())
#define all(c) begin(c), end(c)
#define FOR(i,a,b) for (ll i = (a); i < (b); i++)
#define FORD(i,a,b) for (ll i = (b)-1; i >= (a); i--)
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define xx first
#define yy second
#define TR(X) ({ if(1) cerr << "TR: " << (#X) << " = " << (X) << endl; })
bool is_op(char c) {
for (char d: "$^#&") if (c == d) return true;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
map<string,ll> var2node;
ll m = 0;
vector<tuple<char,ll,ll>> nodes;
vector<string> original_var;
map<tuple<char,ll,ll>,ll> operations;
auto add_node = [&](string a) {
original_var.pb(a);
nodes.eb('=',-1,m);
var2node[a] = m++;
};
ll n; cin >> n;
while (n--) {
string asn; cin >> asn;
ll ii = 0;
while (asn[ii] != '=') ii++;
string a = asn.substr(0,ii);
asn = asn.substr(ii+1), ii = 0;
while (ii < sz(asn) && !is_op(asn[ii])) ii++;
if (ii == sz(asn)) {
string b = asn;
if (!var2node.count(b)) {
add_node(b);
}
var2node[a] = var2node[b];
} else {
string b = asn.substr(0,ii), c = asn.substr(ii+1);
char op = asn[ii];
if (!var2node.count(b)) {
add_node(b);
}
if (!var2node.count(c)) {
add_node(c);
}
tuple<char,ll,ll> tpl = make_tuple(op,var2node[b],var2node[c]);
if (!operations.count(tpl)) {
nodes.pb(tpl);
original_var.pb(a);
operations[tpl] = m++;
}
var2node[a] = operations[tpl];
}
}
if (!var2node.count("res")) {
cout << 0 << endl;
return 0;
}
auto fresh = [&]() {
string s = "aaaa";
while (var2node.count(s)) {
FOR(i,0,4) s[i] = 'a' + rand() % 26;
}
var2node[s] = -1;
return s;
};
vector<string> res;
map<ll,string> new_var;
function<string(ll)> rec = [&](ll cur) {
if (new_var.count(cur)) return new_var[cur];
char op;
ll a, b;
tie(op,a,b) = nodes[cur];
if (op == '=') return original_var[cur];
string stra = rec(a), strb = rec(b);
string str = (cur == var2node["res"]) ? "res" : fresh();
res.pb(str + "=" + stra + op + strb);
return new_var[cur] = str;
};
string lst = rec(var2node["res"]);
if (lst != "res") res.pb("res=" + lst);
cout << sz(res) << endl;
for (string str: res) cout << str << endl;
}
|
1157
|
A
|
Reachable Numbers
|
Let's denote a function $f(x)$ in such a way: we add $1$ to $x$, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
- $f(599) = 6$: $599 + 1 = 600 \rightarrow 60 \rightarrow 6$;
- $f(7) = 8$: $7 + 1 = 8$;
- $f(9) = 1$: $9 + 1 = 10 \rightarrow 1$;
- $f(10099) = 101$: $10099 + 1 = 10100 \rightarrow 1010 \rightarrow 101$.
We say that some number $y$ is \textbf{reachable} from $x$ if we can apply function $f$ to $x$ some (possibly zero) times so that we get $y$ as a result. For example, $102$ is reachable from $10098$ because $f(f(f(10098))) = f(f(10099)) = f(101) = 102$; and any number is reachable from itself.
You are given a number $n$; your task is to count how many different numbers are reachable from $n$.
|
The key fact in this problem is that the answer is not very large (in fact, it's not greater than $91$). Why is it so? Every $10$ times we apply function $f$ to our current number, it gets divided by $10$ (at least), and the number of such divisions is bounded as $O(\log n)$. So we can just do the following: store all reachable numbers somewhere, and write a loop that adds current number $n$ to reachable numbers, and sets $n = f(n)$ (we should end this loop when $n$ already belongs to reachable numbers). The most convenient way to store reachable numbers is to use any data structure from your favourite programming language that implemenets a set, but, in fact, the constrains were so small that it was possible to store all reachable numbers in an array.
|
[
"implementation"
] | 1,100
|
def f(x):
x += 1
while(x % 10 == 0):
x //= 10
return x
a = set()
n = int(input())
while(not(n in a)):
a.add(n)
n = f(n)
print(len(a))
|
1157
|
B
|
Long Number
|
You are given a long decimal number $a$ consisting of $n$ digits from $1$ to $9$. You also have a function $f$ that maps every digit from $1$ to $9$ to some (possibly the same) digit from $1$ to $9$.
You can perform the following operation \textbf{no more than once}: choose a non-empty \textbf{contiguous subsegment} of digits in $a$, and replace each digit $x$ from this segment with $f(x)$. For example, if $a = 1337$, $f(1) = 1$, $f(3) = 5$, $f(7) = 3$, and you choose the segment consisting of three rightmost digits, you get $1553$ as the result.
What is the maximum possible number you can obtain applying this operation no more than once?
|
Let's find the first digit in $a$ that becomes strictly greater if we replace it (obviously, if there is no such digit, then the best solution is to leave $a$ unchanged). In the optimal solution we will replace this digit and maybe some digits after this. Why is it so? It is impossible to make any of the previous digits greater (since we found the first digit that can be replaced with a greater one). Then let's analyze all digits to the right of it. We should not replace any digit with a lower digit (because it is better not to replace it and all digits to the right of it at all), but there's nothing wrong with replacing any other digits. So, the segment we need to replace begins with the first digit that can become greater after replacing (and includes this digit) and goes to the right until the first digit that becomes less after replacing (and this digit is excluded).
|
[
"greedy"
] | 1,300
|
#include<bits/stdc++.h>
using namespace std;
int f[10];
string s;
int main()
{
int n;
cin >> n;
cin >> s;
for(int i = 1; i <= 9; i++)
cin >> f[i];
vector<int> diff;
for(int i = 0; i < n; i++)
diff.push_back(f[s[i] - '0'] - (s[i] - '0'));
for(int i = 0; i < n; i++)
if(diff[i] > 0)
{
while(i < n && diff[i] >= 0)
{
s[i] = char(f[s[i] - '0'] + '0');
i++;
}
break;
}
cout << s << endl;
}
|
1157
|
C1
|
Increasing Subsequence (easy version)
|
\textbf{The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2)}.
You are given a sequence $a$ consisting of $n$ integers. \textbf{All these integers are distinct, each value from $1$ to $n$ appears in the sequence exactly once.}
You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a \textbf{strictly} increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).
For example, for the sequence $[2, 1, 5, 4, 3]$ the answer is $4$ (you take $2$ and the sequence becomes $[1, 5, 4, 3]$, then you take the rightmost element $3$ and the sequence becomes $[1, 5, 4]$, then you take $4$ and the sequence becomes $[1, 5]$ and then you take $5$ and the sequence becomes $[1]$, the obtained increasing sequence is $[2, 3, 4, 5]$).
|
In this problem the following greedy solution works: let's maintain the last element of the increasing sequence we got and on each turn choose the minimum element greater than this last element among the leftmost and the rightmost. Such turns will maximize the answer. You can find details of implementation in the authors solution.
|
[
"greedy"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
string res;
int l = 0, r = n - 1;
int lst = 0;
while (l <= r) {
vector<pair<int, char>> cur;
if (lst < a[l]) cur.push_back(make_pair(a[l], 'L'));
if (lst < a[r]) cur.push_back(make_pair(a[r], 'R'));
sort(cur.begin(), cur.end());
if (int(cur.size()) == 2) {
cur.pop_back();
}
if (int(cur.size()) == 1) {
if (cur[0].second == 'L') {
res += 'L';
lst = a[l];
++l;
} else {
res += 'R';
lst = a[r];
--r;
}
} else {
break;
}
}
cout << res.size() << endl << res << endl;
return 0;
}
|
1157
|
C2
|
Increasing Subsequence (hard version)
|
\textbf{The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2)}.
You are given a sequence $a$ consisting of $n$ integers.
You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a \textbf{strictly} increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).
For example, for the sequence $[1, 2, 4, 3, 2]$ the answer is $4$ (you take $1$ and the sequence becomes $[2, 4, 3, 2]$, then you take the rightmost element $2$ and the sequence becomes $[2, 4, 3]$, then you take $3$ and the sequence becomes $[2, 4]$ and then you take $4$ and the sequence becomes $[2]$, the obtained increasing sequence is $[1, 2, 3, 4]$).
|
The solution of the previous problem works for this problem also. Almost works. What if the leftmost element is equal the rightmost element? Which one should we choose? Let's analyze it. If we take the leftmost element then we will nevertake any other element from the right, and vice versa. So we can't meet this case more than once because after meeting it once we can take only leftmost elements or only rightmost elements. The only thing we should understand is which of these two cases is better (take the leftmost element or take the rightmost element). To do it we can just iterate from left to right and calculate the number of elements we can take if we will take the leftmost element each time. If we cannot take the current element then just stop the cycle. And do the same thing for the rightmost element and take the best case.
|
[
"greedy"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
string res;
int l = 0, r = n - 1;
int lst = 0;
while (l <= r) {
vector<pair<int, char>> cur;
if (lst < a[l]) cur.push_back(make_pair(a[l], 'L'));
if (lst < a[r]) cur.push_back(make_pair(a[r], 'R'));
sort(cur.begin(), cur.end());
if (int(cur.size()) == 2 && cur[0].first != cur[1].first) {
cur.pop_back();
}
if (int(cur.size()) == 1) {
if (cur[0].second == 'L') {
res += 'L';
lst = a[l];
++l;
} else {
res += 'R';
lst = a[r];
--r;
}
} else if (int(cur.size()) == 2) {
int cl = 1, cr = 1;
while (l + cl <= r && a[l + cl] > a[l + cl - 1]) ++cl;
while (r - cr >= l && a[r - cr] > a[r - cr + 1]) ++cr;
if (cl > cr) {
res += string(cl, 'L');
} else {
res += string(cr, 'R');
}
break;
} else {
break;
}
}
cout << res.size() << endl << res << endl;
return 0;
}
|
1157
|
D
|
N Problems During K Days
|
Polycarp has to solve exactly $n$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $k$ days. It means that Polycarp has exactly $k$ days for training!
Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $k$ days. He also doesn't want to overwork, so if he solves $x$ problems during some day, he should solve no more than $2x$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $x$ problems during some day, he should solve at least $x+1$ problem during the next day.
More formally: let $[a_1, a_2, \dots, a_k]$ be the array of numbers of problems solved by Polycarp. The $i$-th element of this array is the number of problems Polycarp solves during the $i$-th day of his training. Then the following conditions must be satisfied:
- sum of all $a_i$ for $i$ from $1$ to $k$ should be $n$;
- $a_i$ should be \textbf{greater than zero} for each $i$ from $1$ to $k$;
- the condition $a_i < a_{i + 1} \le 2 a_i$ should be satisfied for each $i$ from $1$ to $k-1$.
Your problem is to find \textbf{any} array $a$ of length $k$ satisfying the conditions above or say that it is impossible to do it.
|
I suppose there are some solutions without cases handling, but I'll describe my own, it handling approximately $5$ cases. Firstly, let $nn = n - \frac{k(k+1)}{2}$. If $nn < 0$ then the answer is "NO" already. Otherwise let's construct the array $a$, where all $a_i$ are $\lfloor\frac{nn}{k}\rfloor$ (except rightmost $nn \% k$ values, they are $\lceil\frac{nn}{k}\rceil$). It is easy to see that the sum of this array is $nn$, it is sorted in non-decreasing order and the difference between the maximum and the minimum elements is not greater than $1$. Let's add $1$ to $a_1$, $2$ to $a_2$ and so on (this is what we subtract from $n$ at the beginning of the solution). Then if $nn \ne k - 1$ or $k = 1$ then this answer is correct. Otherwise we got some array of kind $1, 3, \dots, a_k$. How do we fix that? For $k=2$ or $k=3$ there is no answer for this case (you can try to prove it or try to find answers for cases $n=4, k=2$ and $n=8, k=3$). Otherwise $k > 3$ and we can subtract one from $a_2$ and add it to $a_k$ and this answer will be correct (this also can be proved with some easy formulas). Time complexity: $O(k)$.
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,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, k;
cin >> n >> k;
if (n < k * 1ll * (k + 1) / 2) {
cout << "NO" << endl;
return 0;
}
int nn = n - k * (k + 1) / 2;
vector<int> a(k);
for (int i = 0; i < k; ++i) {
a[i] = i + 1 + (nn / k) + (i >= k - nn % k);
}
if (nn != k - 1) {
cout << "YES" << endl;
for (int i = 0; i < k; ++i) cout << a[i] << " ";
cout << endl;
} else {
if (k > 3) {
--a[1];
++a[k - 1];
}
if (k == 2 || k == 3) {
cout << "NO" << endl;
} else {
cout << "YES" << endl;
for (int i = 0; i < k; ++i) cout << a[i] << " ";
cout << endl;
}
}
return 0;
}
|
1157
|
E
|
Minimum Array
|
You are given two arrays $a$ and $b$, both of length $n$. All elements of both arrays are from $0$ to $n-1$.
You can reorder elements of the array $b$ (if you want, you may leave the order of elements as it is). After that, let array $c$ be the array of length $n$, the $i$-th element of this array is $c_i = (a_i + b_i) \% n$, where $x \% y$ is $x$ modulo $y$.
Your task is to reorder elements of the array $b$ to obtain the \textbf{lexicographically} minimum possible array $c$.
Array $x$ of length $n$ is lexicographically less than array $y$ of length $n$, if there exists such $i$ ($1 \le i \le n$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$.
|
Let's maintain all elements of the array $b$ in a set that allows multiple copies of equal elements (std::multiset for C++). Then let's iterate from left to right over the array $a$ and try to minimize the current element in array $c$. This order will minimize the resulting array by lexicographical comparing definition. So for the $i$-th element $a_i$ let's find the minimum element greater than or equal to $n - a_i$ in the set because $n - a_i$ will give us remainder $0$, $n - a_i + 1$ will give us remainder $1$ and so on. If there is no greater or equal element in the set then let's take the minimum element of the set and take it as a pair for $a_i$ otherwise let's take this greater or equal element and remove it from the set. Time complexity: $O(n \log n)$.
|
[
"binary search",
"data structures",
"greedy"
] | 1,700
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
multiset<int> b;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
b.insert(x);
}
for (int i = 0; i < n; ++i) {
auto it = b.lower_bound(n - a[i]);
if (it == b.end()) it = b.begin();
cout << (a[i] + *it) % n << " ";
b.erase(it);
}
cout << endl;
return 0;
}
|
1157
|
F
|
Maximum Balanced Circle
|
There are $n$ people in a row. The height of the $i$-th person is $a_i$. You can choose \textbf{any} subset of these people and try to arrange them into a \textbf{balanced circle}.
A \textbf{balanced circle} is such an order of people that the difference between heights of any adjacent people is no more than $1$. For example, let heights of chosen people be $[a_{i_1}, a_{i_2}, \dots, a_{i_k}]$, where $k$ is the number of people you choose. Then the condition $|a_{i_j} - a_{i_{j + 1}}| \le 1$ should be satisfied for all $j$ from $1$ to $k-1$ and the condition $|a_{i_1} - a_{i_k}| \le 1$ should be also satisfied. $|x|$ means the absolute value of $x$. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a \textbf{balanced circle} consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
|
Let's realize what we need to construct the minimum balanced circle with heights from $l$ to $r$. We can represent it as $l, l + 1, \dots, r - 1, r, r - 1, \dots, l + 1$. As we can see, we need one occurrence of $l$ and $r$ and two occurrences of all other heights from $l + 1$ to $r - 1$. How can we find the maximum balanced circle using this information? We can find the maximum by inclusion segment of neighboring heights with at least two occurrences using the array of frequencies $cnt$, sorted array of unique heights $b$ and two pointers technique. For the current left border $l$ we should increase $r$ (initially it is $l + 1$ and it is an excluded border) while $b_r - b_{r - 1}=1$ and $cnt_{b_r} \ge 2$. Then for the current left and right borders we can try to extend the segment to the left if $b_l - b_{l - 1} = 1$ and to the right if $b_{r + 1} - b_r = 1$ and try to update the answer with the the current segment (and go to the next segment). There may be some corner cases like $n = 1$ or all $cnt$ are $1$, but you can avoid them if you will implement the solution carefully. There are almost no corner cases in my solution, you can see details of implementation in authors code. Time complexity: $O(n \log n)$ or $O(n)$ (depends on sorting method).
|
[
"constructive algorithms",
"dp",
"greedy",
"two pointers"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
vector<int> cnt(200 * 1000 + 1);
for (int i = 0; i < n; ++i) {
cin >> a[i];
++cnt[a[i]];
}
sort(a.begin(), a.end());
a.resize(unique(a.begin(), a.end()) - a.begin());
int l = 0, r = 0;
int ans = cnt[a[0]];
for (int i = 0; i < int(a.size()); ++i) {
int j = i + 1;
int sum = cnt[a[i]];
while (a[j] - a[j - 1] == 1 && cnt[a[j]] > 1) {
sum += cnt[a[j]];
++j;
}
int cr = j - 1;
if (j < n && a[j] - a[j - 1] == 1) {
sum += cnt[a[j]];
cr = j;
}
if (ans < sum) {
ans = sum;
l = i;
r = cr;
}
i = j - 1;
}
cout << ans << endl;
for (int c = 0; c < cnt[a[l]]; ++c) cout << a[l] << " ";
for (int i = l + 1; i < r; ++i) {
for (int c = 0; c < cnt[a[i]] - 1; ++c) cout << a[i] << " ";
}
for (int c = 0; l != r && c < cnt[a[r]]; ++c) cout << a[r] << " ";
for (int i = r - 1; i > l; --i) cout << a[i] << " ";
cout << endl;
return 0;
}
|
1157
|
G
|
Inverse of Rows and Columns
|
You are given a binary matrix $a$ of size $n \times m$. A binary matrix is a matrix where each element is either $0$ or $1$.
You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in this row to the opposite ($0$ to $1$, $1$ to $0$). Inverting a column is changing all values in this column to the opposite.
Your task is to sort the initial matrix by some sequence of such operations. The matrix is considered \textbf{sorted} if the array $[a_{1, 1}, a_{1, 2}, \dots, a_{1, m}, a_{2, 1}, a_{2, 2}, \dots, a_{2, m}, \dots, a_{n, m - 1}, a_{n, m}]$ is sorted in non-descending order.
|
The first observation: if we have an answer where the first row is inverted, we can inverse all rows and columns, then the matrix will remain the same, and the first row is not inverted in the new answer. So we can suppose that the first row is never inverted. Note that this will be true only for slow solution. The second observation: if we consider a sorted matrix, its first row either consists only of '0's, or has at least one '1' and then all other rows consist only of '1's. This observation can be extended to the following (one user wrote a comment about it and I pinned the link to it above) which can improve time complexity of the solution a lot: in the sorted matrix either the first row consists only of '0's, or the last row consists only of '1's (the corner case is $n = 1$, but for $n=1$ we can obtain both answers). So what should we do with these observations? I will explain a slow solution, a faster solution can be obtained by mirroring one of cases of this one. Let's iterate over the number of '0's in the first row. Let it be $cnt$. Then the first $cnt$ elements of the first string should be '0's, and all others should be '1's. We can do it by inverting the columns with elements '1' among first $cnt$ elements of the first row and columns with elements '0' among remaining elements. So, it's case handling time! The first case (when $cnt < m$) is pretty easy. We have to check if all rows from $2$ to $n$ that they consist only of '0's or only of '1's (and if some row consists of '0's then we should invert it). If it is true then we found the answer. Otherwise the first row consists only of '0's. So we have to find the "transitional" row (the row with some '0's on the prefix and '1's on the suffix or vice versa). If the number of such rows among all rows from $2$ to $n$ is greater than $1$ then this configuration is bad. If the number of such rows is $1$ then let $idx$ be the index of this row. Then we should inverse all rows above it consisting only of '1's and all rows consisting only of '0's below it. And we have to check if the current row is really transitional. We know that its sum is neither $0$ nor $m$ so there is at least one '1' and at least '0' in it. If the first element is '1' then let's inverse it. Then we just should check if this row is sorted, and if it is then we found the answer. And the last case is if there are no transitional rows in the matrix. Then we should invert all rows from $2$ to $n$ consisting only of '0's (or only of '1's, it does not matter). So, we have a solution with time complexity $O(n^3)$. Each number of '0's in the first row is processed in $O(n^2)$ and there are $O(n)$ such numbers. But we can see that if we apply the last case (when the number of '0' is $m$) to the first row and then do the same, but with the last row consisting of $m$ '1', we can get a solution in $O(n^2)$.
|
[
"brute force",
"constructive algorithms"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
void invRow(vector<vector<int>> &a, int idx) {
for (int pos = 0; pos < m; ++pos) {
a[idx][pos] ^= 1;
}
}
void invCol(vector<vector<int>> &a, int idx) {
for (int pos = 0; pos < n; ++pos) {
a[pos][idx] ^= 1;
}
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> m;
vector<vector<int>> a(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> a[i][j];
}
}
for (int cnt0 = 0; cnt0 <= m; ++cnt0) {
string r(n, '0');
string c(m, '0');
vector<vector<int>> b = a;
for (int j = 0; j < m; ++j) {
if ((j < cnt0 && b[0][j] == 1) || (j >= cnt0 && b[0][j] == 0)) {
invCol(b, j);
c[j] = '1';
}
}
bool ok = true;
if (cnt0 < m) {
for (int i = 1; i < n; ++i) {
int sum = accumulate(b[i].begin(), b[i].end(), 0);
if (sum != 0 && sum != m) {
ok = false;
} else if (sum == 0) {
invRow(b, i);
r[i] = '1';
}
}
} else {
int idx = -1;
for (int i = 1; i < n; ++i) {
int sum = accumulate(b[i].begin(), b[i].end(), 0);
if (sum != 0 && sum != m) {
if (idx != -1) ok = false;
else idx = i;
}
}
if (idx == -1) {
for (int i = 1; i < n; ++i) {
int sum = accumulate(b[i].begin(), b[i].end(), 0);
if (sum == 0) {
invRow(b, i);
r[i] = '1';
}
}
} else {
for (int i = 1; i < idx; ++i) {
int sum = accumulate(b[i].begin(), b[i].end(), 0);
if (sum == m) {
invRow(b, i);
r[i] = '1';
}
}
if (b[idx][0] == 1) {
invRow(b, idx);
r[idx] = '1';
}
for (int j = 1; j < m; ++j) {
if (b[idx][j] < b[idx][j - 1]) {
ok = false;
}
}
for (int i = idx + 1; i < n; ++i) {
int sum = accumulate(b[i].begin(), b[i].end(), 0);
if (sum == 0) {
invRow(b, i);
r[i] = '1';
}
}
}
}
if (ok) {
cout << "YES" << endl << r << endl << c << endl;
return 0;
}
}
cout << "NO" << endl;
return 0;
}
|
1158
|
A
|
The Party and Sweets
|
$n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \leq i \leq n$ the minimal number of sweets, which $i$-th boy presented to some girl is equal to $b_i$ and for all $1 \leq j \leq m$ the maximal number of sweets, which $j$-th girl received from some boy is equal to $g_j$.
More formally, let $a_{i,j}$ be the number of sweets which the $i$-th boy give to the $j$-th girl. Then $b_i$ is equal exactly to the minimum among values $a_{i,1}, a_{i,2}, \ldots, a_{i,m}$ and $g_j$ is equal exactly to the maximum among values $b_{1,j}, b_{2,j}, \ldots, b_{n,j}$.
You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $a_{i,j}$ for all $(i,j)$ such that $1 \leq i \leq n$ and $1 \leq j \leq m$. You are given the numbers $b_1, \ldots, b_n$ and $g_1, \ldots, g_m$, determine this number.
|
Let's note, that for all $1 \leq i \leq n, 1 \leq j \leq m$ is is true, that $b_i \leq g_j$, because $b_i \leq a_{{i}{j}} \leq g_j$. So $max(b_1, b_2, \ldots, b_n) \leq min(g_1, g_2, \ldots, g_m)$. If it is not true, the answer is $-1$. Let's prove, that if $max(b_1, b_2, \ldots, b_n) \leq min(g_1, g_2, \ldots, g_m)$ the answer always exists and let's find it. Let's make all $a_{{i}{j}} = b_i$. Let's note, that $b_i = min(a_{{i}{1}}, a_{{i}{2}}, \ldots, a_{{i}{m}})$. But in this case maximums in each column can be wrong. To make them correct we should place $1 \leq j \leq m$ into the $j$-th column of the table $a$ the number $g_j$. To make the sum as small as possible we want to place all $g_j$ into the row with maximal $b_i$. If we will make it the minimal in this row will be equal $min(g_1, g_2, \ldots, g_m)$. But the number $b$ for this row is equal to $max(b_1, b_2, \ldots, b_n)$. So, if $max(b_1, b_2, \ldots, b_n) = min(g_1, g_2, \ldots, g_m)$ the answer is equal to $(b_1 + b_2 + \ldots + b_n) m + g_1 + g_2 + \ldots + g_m - max(b_1, b_2, \ldots, b_n) m$. But if $max(b_1, b_2, \ldots, b_n) < min(g_1, g_2, \ldots, g_m)$ we should place some of the $g_j$ in the other row. Let's place $g_1$ into the row there $b_i$ is second maximum in the array $b$. It's easy to check in this case, that all minimums, maximums will be correct in this case. In this case the answer is equal to $(b_1 + b_2 + \ldots + b_n) m + g_1 + g_2 + \ldots + g_m - max(b_1, b_2, \ldots, b_n) (m - 1) - max_2(b_1, b_2, \ldots, b_n)$. So: If $max(b_1, b_2, \ldots, b_n) > min(g_1, g_2, \ldots, g_m)$ the answer is $-1$; If $max(b_1, b_2, \ldots, b_n) = min(g_1, g_2, \ldots, g_m)$ the answer is $(b_1 + b_2 + \ldots + b_n) m + g_1 + g_2 + \ldots + g_m - max(b_1, b_2, \ldots, b_n) m$; If $max(b_1, b_2, \ldots, b_n) < min(g_1, g_2, \ldots, g_m)$ the answer is $(b_1 + b_2 + \ldots + b_n) m + g_1 + g_2 + \ldots + g_m - max(b_1, b_2, \ldots, b_n) (m - 1) - max_2(b_1, b_2, \ldots, b_n)$. Maximum, second maximum in the array $b$, minimum in the array $g$ and the sums in the arrays $b$ and $g$ can be easily computed in the linear time. So, we have a linear time solution. Complexity: $O(n + m)$.
|
[
"binary search",
"constructive algorithms",
"greedy",
"implementation",
"math",
"sortings",
"two pointers"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n, m;
ll r_max, c_min, x, r_max2, r_sum, c_sum, ans;
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m;
r_max = 0;
r_max2 = 0;
r_sum = 0;
for (int i = 0; i < n; i++)
{
cin >> x;
if (r_max <= x)
{
r_max2 = r_max;
r_max = x;
}
else if (r_max2 <= x)
r_max2 = x;
r_sum += x;
}
c_min = (int)(1e8);
c_sum = 0;
for (int i = 0; i < m; i++)
{
cin >> x;
if (c_min >= x)
c_min = x;
c_sum += x;
}
if (r_max > c_min)
{
cout << "-1";
return 0;
}
ans = r_sum * (ll)m;
ans += c_sum;
ans -= r_max * (ll)m;
if (r_max < c_min)
ans += r_max - r_max2;
cout << ans;
return 0;
}
|
1158
|
B
|
The minimal unique substring
|
Let $s$ be some string consisting of symbols "0" or "1". Let's call a string $t$ a substring of string $s$, if there exists such number $1 \leq l \leq |s| - |t| + 1$ that $t = s_l s_{l+1} \ldots s_{l + |t| - 1}$. Let's call a substring $t$ of string $s$ unique, if there exist only one such $l$.
For example, let $s = $"1010111". A string $t = $"010" is an unique substring of $s$, because $l = 2$ is the only one suitable number. But, for example $t = $"10" isn't a unique substring of $s$, because $l = 1$ and $l = 3$ are suitable. And for example $t =$"00" at all isn't a substring of $s$, because there is no suitable $l$.
Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.
You are given $2$ positive integers $n$ and $k$, such that $(n \bmod 2) = (k \bmod 2)$, where $(x \bmod 2)$ is operation of taking remainder of $x$ by dividing on $2$. Find any string $s$ consisting of $n$ symbols "0" or "1", such that the length of its minimal unique substring is equal to $k$.
|
Let's define the value $a = \frac {n-k} 2$. We know, that $(k \bmod 2) = (n \bmod 2)$ so $a$ is integer number. Let's construct this string $s$: $a$ symbols "0", $1$ symbol "1", $a$ symbols "0", $1$ symbol "1", $\ldots$ Let's prove, that this string satisfy the conditions. Let's note, that it's period is equal to $(a+1)$. Let the substring $t$ be unique. Let's look at the only $l$ for this substring. But if $l > a + 1$, then $l - (a + 1)$ satisfy (as the left border of the string $t$ occurrence), if $l \leq n - (a + |t|)$ then $l + (a + 1)$ satisfy (because the period of $s$ is equal to $(a + 1)$, so shift on $(a + 1)$ don't change anything). So $l \leq a + 1$ and $n - (a + |t|) < l$, because in other case $l$ can't be the only. So $n - (a + |t|) < l \leq a + 1$ so $n - (a + |t|) < a + 1$ so $n - (a + |t|) \leq a$ so $n - 2 \cdot a \leq |t|$ so $k \leq |t|$. As the example of the unique substring of length $k$ we can take $t = s_{a+1} \ldots s_{n-a}$. Complexity: $O(n)$. Bonus: How to solve the problem without condition, that $(k \bmod 2) = (n \bmod 2)$? For what $k$ the answer exists?
|
[
"constructive algorithms",
"math",
"strings"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k, a;
cin >> n >> k;
a = (n - k) / 2;
for (int i = 0; i < n; i++)
cout << ((i + 1) % (a + 1) == 0);
return 0;
}
|
1158
|
C
|
Permutation recovery
|
Vasya has written some permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, so for all $1 \leq i \leq n$ it is true that $1 \leq p_i \leq n$ and all $p_1, p_2, \ldots, p_n$ are different. After that he wrote $n$ numbers $next_1, next_2, \ldots, next_n$. The number $next_i$ is equal to the minimal index $i < j \leq n$, such that $p_j > p_i$. If there is no such $j$ let's let's define as $next_i = n + 1$.
In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values $next_i$ are completely lost! If for some $i$ the value $next_i$ is lost, let's say that $next_i = -1$.
You are given numbers $next_1, next_2, \ldots, next_n$ (maybe some of them are equal to $-1$). Help Vasya to find such permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, that he can write it to the notebook and all numbers $next_i$, which are not equal to $-1$, will be correct.
|
Note that if there are indices $i < j$ for which the values $next_i$ and $next_j$ are defined and $i < j < next_i < next_j$ are satisfied, then there is no answer. Suppose that this is not true and there exists permutation $p_1, p_2, \ldots, p_n$. Note that since $j < next_i$ we get that $p_i > p_j$ (otherwise $next_i$ would not be the minimum position in which the number is greater than $p_i$). But then $p_j < p_i < p_{next_i}$, so $next_j$ is not the minimum position for $j$. Contradiction. Now we prove that if for any pair of indices $i < j$ such condition is not satisfied, then the permutation always exists. First, let's get rid of $next_i = -1$. If $next_i = -1$ let's say $next_i = i + 1$. Note that for any pair $i < j$ the condition $i < j < next_i < next_j$ is still not satisfied (since $next_i = i + 1$ cannot take part in such inequality). Consider the following rooted tree with $n + 1$ vertices: the vertex with index $n + 1$ will be the root, and the ancestor of the vertex with index $i$ will be $next_i$. Since it is always $i < next_i$ we get the rooted tree. Let's run the depth first search algorithm ($dfs$) from the vertex $n + 1$ in this tree. In this case, we will bypass the sons of each vertex in order from the smaller number to the larger one. Let's make some global variable $timer = n + 1$. Each time we come to the vertex $i$, we will make $p_i = timer$ and reduce $timer$ by $1$. Note that $p_1, p_2, \ldots, p_n$ will form a permutation of numbers from $1$ to $n$. We prove that this permutation is the answer. First of all, for all $i$ due to $next_i$ was the ancestor of $i$, we'll go there early and so $p_{next_i} > p_i$. Let $i < j < next_i$. We need to prove that we will come to the vertex $j$ later than to the vertex $i$. Note that then the vertex $next_i$ will be a descendant of $j$ in the tree, because if you start go from $j$ by $next$, you cannot jump over $next_i$, because otherwise there is an index $x$, for which the inequality $i < x < next_i < next_x$ is satisfied. But such pair of indexes $i$, $x$ cannot exist. We'll get to $j$ later because the son of $next_i$, which is the ancestor of $j$ will be $\geq j$, and thus $> i$. That is, we understood what is the criterion of the answer and learned how to quickly build an answer, if this criterion is satisfied. But we still need to check that this criterion is satisfied. This can be done by some simple linear algorithm. But we will do this: let's make an algorithm for constructing the answer (without checking the criterion) and find the permutation $p$. Now, using the stack and the standard algorithm, we find the $next_i$ values for it. If they match the given $next_i$, then we have found the answer, otherwise, let's say that there is no answer. If the criterion is satisfied we will find the answer and if not satisfied after checking $p$ we will say there are no answers. Complexity: $O(n)$ time and memory.
|
[
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"math",
"sortings"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int M = 5e5 + 239;
int n, a[M], p[M], timer;
vector<int> v[M];
vector<int> q;
void dfs(int t)
{
p[t] = timer--;
for (int i : v[t])
dfs(i);
}
void solve()
{
cin >> n;
for (int i = 0; i <= n; i++) v[i].clear();
for (int i = 0; i < n; i++)
{
cin >> a[i];
a[i]--;
if (a[i] == -2) a[i] = i + 1;
v[a[i]].push_back(i);
}
timer = n;
dfs(n);
q.clear();
for (int i = n - 1; i >= 0; i--)
{
while (!q.empty() && p[q.back()] < p[i])
q.pop_back();
if ((q.empty() && a[i] != n) || (!q.empty() && q.back() != a[i]))
{
cout << "-1\n";
return;
}
q.push_back(i);
}
for (int i = 0; i < n; i++)
cout << p[i] + 1 << " ";
cout << "\n";
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int T;
cin >> T;
while (T--) solve();
return 0;
}
|
1158
|
D
|
Winding polygonal line
|
Vasya has $n$ different points $A_1, A_2, \ldots A_n$ on the plane. No three of them lie on the same line He wants to place them in some order $A_{p_1}, A_{p_2}, \ldots, A_{p_n}$, where $p_1, p_2, \ldots, p_n$ — some permutation of integers from $1$ to $n$.
After doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all $1 \leq i \leq n-1$ he will draw oriented segment from point $A_{p_i}$ to point $A_{p_{i+1}}$. He wants to make this polygonal line satisfying $2$ conditions:
- it will be non-self-intersecting, so any $2$ segments which are not neighbors don't have common points.
- it will be \textbf{winding}.
Vasya has a string $s$, consisting of $(n-2)$ symbols "L" or "R". Let's call an oriented polygonal line \textbf{winding}, if its $i$-th turn left, if $s_i = $ "L" and right, if $s_i = $ "R". More formally: $i$-th turn will be in point $A_{p_{i+1}}$, where oriented segment from point $A_{p_i}$ to point $A_{p_{i+1}}$ changes to oriented segment from point $A_{p_{i+1}}$ to point $A_{p_{i+2}}$. Let's define vectors $\overrightarrow{v_1} = \overrightarrow{A_{p_i} A_{p_{i+1}}}$ and $\overrightarrow{v_2} = \overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}$. Then if in order to rotate the vector $\overrightarrow{v_1}$ by the smallest possible angle, so that its direction coincides with the direction of the vector $\overrightarrow{v_2}$ we need to make a turn counterclockwise, then we say that $i$-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns:
\begin{center}
{\small There are left turns on this picture}
\end{center}
\begin{center}
{\small There are right turns on this picture}
\end{center}
You are given coordinates of the points $A_1, A_2, \ldots A_n$ on the plane and string $s$. Find a permutation $p_1, p_2, \ldots, p_n$ of the integers from $1$ to $n$, such that the polygonal line, drawn by Vasya satisfy two necessary conditions.
|
Let's describe the algorithm, which is always finding the answer: Let's find any point $A_i$, lying at the convex hull of points $A_1, A_2, \ldots, A_n$. We don't need to construct the convex hull for this, we can simply take the point with the minimal $y$. This point will be the first in the permutation. Let's construct the polygonal line one by one. Let the last added point to the polygonal line be $A_{p_i}$. The point $A_{p_i}$ should always lie at the convex hull of remaining points and $A_{p_i}$ (at the beginning it is true). If $s_i =$ "L" the next point be the most right point (sorted by angle) and if $s_i =$ "R"the next point be the most left point (sorted by angle) from the remaining. This is the picture for this: It is easy to see, that the new point lies at the convex hull. The next rotation at the point $A_{p_{i+1}}$ will be to the right side, because if $s_i =$ "L" all other points lies from the left of the vector $\overrightarrow{A_{p_i} A_{p_{i+1}}}$ and if $s_i =$ "R" all other points lies from the right of the vector $\overrightarrow{A_{p_i} A_{p_{i+1}}}$. To take the most left or right point, sorted by the angle from the remaining we will simply take minimum or maximum using the linear search. The point $X$ lies to the right of the point $Y$ from the point $A_{p_i}$, if $\overrightarrow{A_{p_i} X} \times \overrightarrow{A_{p_i} Y} > 0$. The operation $\times$ is vectors multiply. Complexity: $O(n^2)$.
|
[
"constructive algorithms",
"geometry",
"greedy",
"math"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M = 2e3 + 239;
int n, x[M], y[M];
bool used[M];
string s;
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> x[i] >> y[i];
cin >> s;
s += 'L';
int id = -1;
for (int i = 0; i < n; i++)
if (id == -1 || x[id] > x[i] || (x[id] == x[i] && y[id] > y[i]))
id = i;
used[id] = true;
cout << (id + 1) << " ";
for (int it = 1; it < n; it++)
{
int to = -1;
for (int i = 0; i < n; i++)
if (!used[i])
{
if (to == -1)
to = i;
else
{
ll now = (ll)(x[i] - x[id]) * (ll)(y[to] - y[id]) - (ll)(y[i] - y[id]) * (ll)(x[to] - x[id]);
if (s[it - 1] == 'R') now = -now;
if (now > 0) to = i;
}
}
used[to] = true;
id = to;
cout << (id + 1) << " ";
}
return 0;
}
|
1158
|
E
|
Strange device
|
\textbf{It is an interactive problem.}
Vasya enjoys solving quizzes. He found a strange device and wants to know how it works.
This device encrypted with the tree (connected undirected graph without cycles) with $n$ vertices, numbered with integers from $1$ to $n$. To solve this quiz you should guess this tree.
Fortunately, this device can make one operation, using which you should guess the cipher. You can give the device an array $d_1, d_2, \ldots, d_n$ of non-negative integers. On the device, there are $n$ lamps, $i$-th of them is connected with $i$-th vertex of the tree. For all $i$ the light will turn on the $i$-th lamp, if there exist such vertex of the tree with number $j \neq i$ that $dist(i, j) \leq d_j$. Let's define $dist(i, j)$ as the distance between vertices $i$ and $j$ in tree or number of edges on the simple path between vertices $i$ and $j$.
Vasya wants to solve this quiz using $\leq 80$ operations with the device and guess the tree. Help him!
|
The solution will consist of two parts. 1 part Let's divide all points into sets with equal distance to the vertex $1$. To do this, we will do the following algorithm. How to understand what set of points lies at a distance $\lfloor \frac{n}{2} \rfloor$ from the top of $1$? Let's fill $d$ with zeros and make $d_1 = \lfloor \frac{n}{2} \rfloor$ for the first operation and $d_1 = \lfloor \frac{n}{2} \rfloor - 1$ for the second operation. After that we will make $2$ operations with such $d$ arrays. Those vertices whose bulbs did not light up during the first operation lie at a distance of $> \lfloor \frac{n}{2} \rfloor$. Those that caught fire at the first, but did not catch fire at the second operation lie at a distance of $\lfloor \frac{n}{2} \rfloor$. Finally, those who caught fire during the second operation lie at a distance of $< \lfloor \frac{n}{2} \rfloor$. Generalize this idea. We will store the set of distances for which we already know the set of vertices at lying such distance from $1$ (we will call them good distances). Initially it is $0$ (only vertex $1$ at distance $0$) and $n$ (empty vertex set at distance $n$). We will also store between each pair of adjacent good distances $l_1 < l_2$ those vertices for which the distance is greater than $l_1$, but less than $l_2$. Now let's iterate over pairs of adjacent good distances $l_1 < l_2$. Take $m = \lfloor \frac{l_1 + l_2}{2} \rfloor$. Now the sets of vertices lying at distances greater than $l_1$, but less than $m$, exactly $m$ and more than $m$, but less than $l_2$ can be obtained using the two operations described at the beginning. With this action, we make $m$ a good distance. To do this in parallel for several pairs of adjacent good distances just iterate over pairs with even numbers and odd ones. Then as each of the cases would not be adjacent pairs, you can make two common operations. Thus, with the help of $4$ operations, we will make the middle between all pairs of adjacent good distances also a good distance. If we divide in half, then for $\lceil \log{n} \rceil$ of divisions we will make all distances good. At this part we will spend $4 \lceil \log{n} \rceil$ operations. 2 part For each vertex at the distance of $l > 0$ let's find the index of the ancestor vertex lying at a distance of $l-1$ (which is the only one). Suppose we want to do this for only one distance $l > 0$. Note that if we make $d_v = 1$ for all $v \in S$, for some subset of vertices $S$ lying at a distance $l-1$, and for all other vertices $0$, then among the vertices at a distance $l$ will include those whose ancestor belongs to $S$. Then let's for all $i$ such that $2^i < n$ choose $S$ as the set of vertices $v$ such that $v - 1$ contains $i$-th bit in binary notation and lies at a distance of $l-1$. Then, for each vertex at a distance of $l$, we will know all the bits in the binary representation of its ancestor, that is, we will find this number. This process can also be done in parallel, if we take the distance $l$, giving the same remainder of dividing by $3$. Then, since these distances are not close, they will not interfere with each other. At this part we will spend $3 \lceil \log{n} \rceil$ operations. In total we get a solution using $7 \lceil \log{n} \rceil$ operations. Complexity: $O(n \log{n})$. Number of operations: $7 \lceil \log{n} \rceil$.
|
[
"binary search",
"interactive",
"math",
"trees"
] | 3,400
|
#include <bits/stdc++.h>
using namespace std;
const int M = 1010;
vector<bool> ask(vector<int> d)
{
cout << "? ";
for (int i : d)
cout << i << " ";
cout << endl;
string s;
cin >> s;
vector<bool> ans((int)d.size());
for (int i = 0; i < (int)d.size(); i++)
ans[i] = (bool)(s[i] - '0');
return ans;
}
int n;
vector<int> in[M], nxt[M];
vector<int> pos;
bool used[M];
int pr[M];
int main()
{
cin >> n;
in[0].push_back(0);
for (int i = 1; i < n; i++)
nxt[0].push_back(i);
used[0] = true;
used[n] = true;
while (true)
{
bool stop = true;
pos.clear();
for (int i = 0; i <= n; i++)
if (used[i])
pos.push_back(i);
for (int st = 0; st < 2; st++)
{
vector<int> r1(n, 0), r2(n, 0);
for (int s = st; s < (int) pos.size() - 1; s += 2)
{
if (in[pos[s]].empty()) continue;
if (pos[s + 1] == pos[s] + 1) continue;
if (pos[s + 1] == pos[s] + 2)
{
in[pos[s] + 1] = nxt[pos[s]];
nxt[pos[s]].clear();
used[pos[s] + 1] = true;
continue;
}
stop = false;
int mid = (pos[s] + pos[s + 1] + 1) >> 1;
for (int x : in[pos[s]])
{
r1[x] = mid - pos[s] - 1;
r2[x] = r1[x] + 1;
}
}
vector<bool> a1 = ask(r1);
vector<bool> a2 = ask(r2);
for (int s = st; s < (int) pos.size() - 1; s += 2)
{
if (in[pos[s]].empty()) continue;
if (pos[s + 1] <= pos[s] + 2) continue;
int mid = (pos[s] + pos[s + 1] + 1) >> 1;
vector<int> now = nxt[pos[s]];
nxt[pos[s]].clear();
for (int x : now)
{
if (a1[x])
nxt[pos[s]].push_back(x);
else if (a2[x])
in[mid].push_back(x);
else
nxt[mid].push_back(x);
}
used[mid] = true;
}
}
if (stop)
break;
}
for (int st = 1; st <= 3; st++)
{
for (int i = 0; (1 << i) < n; i++)
{
vector<int> r(n, 0);
bool need = false;
for (int x = st; x < n; x += 3)
if (!in[x].empty())
for (int t : in[x - 1])
if ((t >> i) & 1)
{
r[t] = 1;
need = true;
}
if (!need) continue;
vector<bool> res = ask(r);
for (int x = st; x < n; x += 3)
if (!in[x].empty())
for (int t : in[x])
if (res[t])
pr[t] ^= (1 << i);
}
}
cout << "!" << endl;
for (int i = 1; i < n; i++)
cout << pr[i] + 1 << " " << i + 1 << endl;
return 0;
}
|
1158
|
F
|
Density of subarrays
|
Let $c$ be some positive integer. Let's call an array $a_1, a_2, \ldots, a_n$ of positive integers $c$-array, if for all $i$ condition $1 \leq a_i \leq c$ is satisfied. Let's call $c$-array $b_1, b_2, \ldots, b_k$ a \textbf{subarray} of $c$-array $a_1, a_2, \ldots, a_n$, if there exists such set of $k$ indices $1 \leq i_1 < i_2 < \ldots < i_k \leq n$ that $b_j = a_{i_j}$ for all $1 \leq j \leq k$. Let's define \textbf{density} of $c$-array $a_1, a_2, \ldots, a_n$ as maximal non-negative integer $p$, such that any $c$-array, that contains $p$ numbers is a subarray of $a_1, a_2, \ldots, a_n$.
You are given a number $c$ and some $c$-array $a_1, a_2, \ldots, a_n$. For all $0 \leq p \leq n$ find the number of sequences of indices $1 \leq i_1 < i_2 < \ldots < i_k \leq n$ for all $1 \leq k \leq n$, such that density of array $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ is equal to $p$. Find these numbers by modulo $998\,244\,353$, because they can be too large.
|
We have some $c$-array $a$. Let's find the criterion, that any $c$-array of length $p$ is its subsequence. To check that $c$-array $b$ is a subsequence of $a$, we should iterate all elements of $b$ and take the most left occurrence of this symbol in $a$, starting from the current moment. Because any $c$-array should be a subsequence of $a$ on each step we can take the symbol the most left occurrence of such is the most right. Let's denote the positions, which we have taken on each step $l_1, l_2, \ldots, l_p$. So if we will look to the array $a[l_i+1 \ldots l_{i+1}]$, in this arrays each of the $c$ symbols exists and the symbol $a_{l_{i+1}}$ occurs exactly $1$ time. Let's name such array "critical block". So the density of $a \geq p$, if $a$ is the concatenation of $p$ consecutive critical blocks and some other symbols at the end. Let's note, that the density of any array of length $n$ won't be more than $k = \frac{n}{c}$. It is obvious, because in any critical block at least $c$ symbols. Let's find $dp_{{t},{i}}$ as the number of subsequences of the array prefix $a[1 \ldots i]$ that contain the position $i$, which are divided into exactly $t$ critical arrays (and no other characters). We will consider it for all $1 \leq t \leq k$ and $1 \leq i \leq n$. Let's first understand how to get an answer from these values, and then show how to calculate them. If we denote by $f_t$ the number of subsequences whose density is $\geq t$, then $f_t = \sum\limits_{i=1}^n{dp_ {t},{i}} \cdot 2^{n - i}$. Next, note that the number of density subsequences exactly $t$ is $ans_t = f_{t+1} - f_t$. Here are $2$ different ways to calculate $dp_{{t},{i}}$: 1) denote by $num_{{i},{j}}$ the number of subsequences of array $a[i \ldots j]$ that contain $j$ and are critical. Then $num_{{i},{j}} = \prod\limits_{x=1, x \neq a_j}^{c}{(2^{cnt_{{x},{i},{j}}} - 1)}$, where $cnt_{{x},{i},{j}}$ - is the number of characters $x$ among $a[i \ldots j]$. Then we can calculate $num$ for $O(n^2 c)$. To speed up this calculation to $O(n^2)$ we will fix $i$ and increase $j$ by $1$, supporting $\prod\limits_{x=1}^{c}{(2^{cnt_{{x},{i},{j}}} - 1)}$. Then in such a product $1$ multiplier will be changed and it can be recalculated by $O(1)$. To get $num_{{i},{j}}$, you simply divide the supported product by $2^{cnt_{{a_j},{i},{j}}} - 1$. Then note that $dp_{{t},{i}} = \sum\limits_{j=0}^{i - 1}{dp_{{t-1},{j}}} \cdot num_{{j+1},{i}}$ (iterate over $j$ - the end of the previous critical block). This allows us to calculate the values of $dp$ in time $O(n^2 k)$. 2) We will need an auxiliary dinamical programming values $u_{{i},{t},{mask}}$ (where $mask$ is a mask of characters, that is $0 \leq mask < 2^c$), which means the number of ways to choose a subsequence from the prefix $a[1 \ldots i]$, in which there will be first $t$ critical blocks and then several characters that are in $mask$, but each character from $mask$ will be at the several symbols at least once. Then $dp_{{t},{i}} = u_{{i-1},{t-1},{2^c - 1 - 2^{a_i}}}$, which follows from the definition. Conversion formulas are as follows: $u_{{i},{t},{mask}} = u_{{i-1},{t},{mask}}$, if $a_i$ is not contained in $mask$ and $u_{{i},{t},{mask}} = 2 u_{{i-1},{t},{mask}} + u_{{i-1},{t},{mask - 2^{a_i}}}$, if $a_i$ is contained in $mask$ (if you take $a_i$ in the subsequence and if not). For $mask = 0$ it is true, that $u_{{i},{t},{0}} = u_{{i-1},{t},{0}} + dp_{{I},{t}}$. These formulas can be used to calculate the values of $u$ and $dp$ by iterating $i$ in increasing order over time $O(n k 2^c)$. The $i$ parameter can be omitted from memory because the recalculation is only from the previous layer. In total, we get $2$ ways to calculate $dp$ working for $O(n^2 k)$ and $O(n k 2^c)$. Recall that $k = \frac{n}{c}$. That is, our solutions work at the time $O(\frac{n^3}{c})$ and $O(\frac{n^2 2^c}{c})$. If $c > \log{n}$, then let's run the first solution and it will work for $O(\frac{n^3}{\log{n}})$, otherwise if $c \leq \log{n}$ and $\frac{2^c}{c} \leq \frac{n}{\log{n}}$, so let's run the second solution, which will then work, too, in $O(\frac{n^3}{\log{n}})$ time. If we carefully implement these $2$ solutions and run them depending on $c$, we get a solution with $O(\frac{n^3}{\log{n}})$ complexity and it is working fast enough. Complexity: $O(\frac{n^3}{\log{n}})$ or $O(\frac{n^2}{c} \cdot min(n, 2^c))$.
|
[
"dp",
"math"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int M = 3010;
const int MOD = 998244353;
const ll MOD2 = (ll)MOD * (ll)MOD;
const int MG = 10;
const int MS = (1 << MG);
inline int power(int a, int k)
{
if (k == 0) return 1;
int t = power(a, k >> 1);
t = 1LL * t * t % MOD;
if (k & 1) t = 1LL * a * t % MOD;
return t;
}
int n, c, a[M], kol[M][M], pw[M], inv[M], k, cnt, now, dp[M][M], ans[M], cost[M][M], pr, f[M][MS], to;
ll sum;
bool used[M];
inline void solve_n2k()
{
for (int i = 0; i <= n; i++) inv[i] = power(pw[i] - 1, MOD - 2);
for (int i = 0; i < n; i++)
{
cnt = c;
pr = 1;
for (int j = i; j < n; j++)
{
if (kol[a[j]][i] == kol[a[j]][j])
cnt--;
else
pr = 1LL * pr * inv[kol[a[j]][j] - kol[a[j]][i]] % MOD;
if (cnt != 0)
cost[i][j] = 0;
else
cost[i][j] = pr;
pr = 1LL * pr * (pw[kol[a[j]][j] - kol[a[j]][i] + 1] - 1) % MOD;
}
}
for (int i = 0; i <= n; i++) dp[0][i] = 0;
dp[0][0] = 1;
for (int r = 1; r <= k; r++)
{
dp[r][0] = 0;
for (int i = r * c - 1; i < n; i++)
{
sum = 0;
for (int j = i; j >= (r - 1) * c; j--)
{
sum += 1LL * cost[j][i] * dp[r - 1][j];
if (sum >= MOD2) sum -= MOD2;
}
dp[r][i + 1] = (sum % (ll)MOD);
}
}
}
inline void solve_nk2powc()
{
dp[0][0] = 1;
f[0][0] = 1;
for (int i = 0; i < n; i++)
{
for (int x = 1; x <= k; x++) dp[x][i + 1] = f[x - 1][((1 << c) - 1) ^ (1 << a[i])];
to = min(k - 1, (i / c));
for (int ms = (1 << c) - 1; ms >= 0; ms--)
if ((ms >> a[i]) & 1)
for (int x = 0; x <= to; x++)
{
f[x][ms] += f[x][ms];
if (f[x][ms] >= MOD) f[x][ms] -= MOD;
f[x][ms] += f[x][ms ^ (1 << a[i])];
if (f[x][ms] >= MOD) f[x][ms] -= MOD;
}
for (int x = 0; x < k; x++)
{
f[x][0] += dp[x][i + 1];
if (f[x][0] >= MOD) f[x][0] -= MOD;
}
}
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> c;
for (int i = 0; i < n; i++)
{
cin >> a[i];
a[i]--;
}
for (int i = 0; i < c; i++)
{
kol[i][0] = 0;
for (int x = 0; x < n; x++)
{
kol[i][x + 1] = kol[i][x];
if (a[x] == i) kol[i][x + 1]++;
}
}
pw[0] = 1;
for (int i = 0; i < n; i++)
{
pw[i + 1] = pw[i] + pw[i];
if (pw[i + 1] >= MOD) pw[i + 1] -= MOD;
}
for (int i = 0; i < c; i++) used[i] = false;
k = 0;
cnt = 0;
for (int i = 0; i < n; i++)
{
if (!used[a[i]])
{
used[a[i]] = true;
cnt++;
}
if (cnt == c)
{
cnt = 0;
for (int i = 0; i < c; i++) used[i] = false;
k++;
}
}
if (c <= MG)
solve_nk2powc();
else
solve_n2k();
for (int i = 0; i <= n; i++) ans[i] = 0;
for (int i = 0; i <= k; i++)
for (int j = 0; j <= n; j++)
{
ans[i] += 1LL * dp[i][j] * pw[n - j] % MOD;
if (ans[i] >= MOD) ans[i] -= MOD;
}
for (int i = 0; i < n; i++)
{
ans[i] -= ans[i + 1];
if (ans[i] < 0) ans[i] += MOD;
}
ans[0]--;
if (ans[0] < 0) ans[0] += MOD;
for (int i = 0; i <= n; i++)
cout << ans[i] << " ";
return 0;
}
|
1159
|
A
|
A pile of stones
|
Vasya has a pile, that consists of some number of stones. $n$ times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given $n$ operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
|
Let's consider an array $a$, there $a_i=1$, if $s_i=$"+" and $a_i=-1$, if $s_i=$"-". Let's notice, that the answer $\geq a_{k+1} + \ldots + a_n$ for all $k$. It is true, because after making the first $k$ operations the number of stones will be $\geq 0$, so at the end the number of stones will be $\geq a_{k+1} + \ldots + a_n$. Let's prove, that the answer is equal to $ans = \max\limits_{0 \leq k \leq n} (a_{k+1} + \ldots + a_n)$. We proved that it should be at least that number of stones. It's easy to see, that if we will take $a_1 + \ldots + a_n - ans$ stones at the beginning, the pile will be non-empty each time when Vasya should take a stone and at the end, the number of stones will be equal to $ans$. Complexity: $O(n)$.
|
[
"implementation",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int n;
string s;
int main()
{
cin >> n >> s;
int m = 0;
int a = 0;
for (int i = n - 1; i >= 0; i--)
{
if (s[i] == '+')
m++;
else
m--;
a = max(a, m);
}
cout << a;
return 0;
}
|
1159
|
B
|
Expansion coefficient of the array
|
Let's call an array of non-negative integers $a_1, a_2, \ldots, a_n$ a $k$-extension for some non-negative integer $k$ if for all possible pairs of indices $1 \leq i, j \leq n$ the inequality $k \cdot |i - j| \leq min(a_i, a_j)$ is satisfied. The expansion coefficient of the array $a$ is the maximal integer $k$ such that the array $a$ is a $k$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.
You are given an array of non-negative integers $a_1, a_2, \ldots, a_n$. Find its expansion coefficient.
|
Let our array be a $k$-extension. All inequalities $k \cdot |i - j| \leq min(a_i, a_j)$ for $i \neq j$ can be changed to $k \leq \frac{min(a_i, a_j)}{|i - j|}$. For all $i = j$ inequalities are always true, because all numbers are non-negative. So, the maximum possible value of $k$ is equal to the minimum of $\frac{min(a_i, a_j)}{|i - j|}$ for all $i < j$. Let's note, that $\frac{min(a_i, a_j)}{|i - j|} = min(\frac{a_i}{|i-j|}, \frac{a_j}{|i-j|})$. So, we need to take a minimum of $\frac{a_i}{|i-j|}$ for all $i \neq j$. If we will fix $i$ the minimum value for all $j$ is equal to $\frac{a_i}{max(i - 1, n - i)}$ and it is reached at the maximum denominator value, because $a_i \geq 0$. So the answer is equal to $\min\limits_{1 \leq i \leq n} \frac{a_i}{max(i - 1, n - i)}$ and it can be simply found by linear time. Complexity: $O(n)$.
|
[
"implementation",
"math"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
const int M = 1e5;
int n, a, m = 1e9;
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
m = min(m, a / max(i, n - 1 - i));
}
cout << m;
return 0;
}
|
1162
|
A
|
Zoning Restrictions Again
|
You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$.
In each spot, if a house has height $a$, you will gain $a^2$ dollars from it.
The city has $m$ zoning restrictions. The $i$-th restriction says that the tallest house from spots $l_i$ to $r_i$ (inclusive) must be at most $x_i$.
You would like to build houses to maximize your profit. Determine the maximum profit possible.
|
This problem can be done by processing the restrictions one by one. Let's keep an array $a$ of length $n$, where the $i$-th value in this array represents the maximum possible height for house $i$. Initially, we have processed no restrictions, so we fill $a_i = h$ for all $i$. For a restriction $k$, we can loop through the elements $j$ between $l_k$ and $r_k$ and update $a_j = \min(a_j, x_k)$. This is because the new house must be at most height $x_k$, and we know previously it had to be at most $a_j$, so we take the min of the two. After processing all restrictions, we can greedily choose the height of the $i$-th house to be $a_i$. The answer is the sum of $a_i^2$ for all $i$. The time complexity for processing one restriction is $O(n)$, so the total time complexity is $O(nm)$.
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
int32_t main()
{
int n, h, m;
cin>>n>>h>>m;
int a[n+1];
for(int i=1;i<=n;i++)
a[i]=h;
for(int i=0;i<m;i++)
{
int l, r, x;
cin>>l>>r>>x;
for(int j=l;j<=r;j++)
{
a[j]=min(a[j],x);
}
}
int ans=0;
for(int i=1;i<=n;i++)
ans+=a[i]*a[i];
cout<<ans<<endl;
return 0;
}
|
1162
|
B
|
Double Matrix
|
You are given \textbf{two} $n \times m$ matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing \textbf{and} all columns are strictly increasing.
For example, the matrix $\begin{bmatrix} 9&10&11\\ 11&12&14\\ \end{bmatrix}$ is increasing because each individual row and column is strictly increasing. On the other hand, the matrix $\begin{bmatrix} 1&1\\ 2&3\\ \end{bmatrix}$ is not increasing because the first row is not strictly increasing.
Let a position in the $i$-th row (from top) and $j$-th column (from left) in a matrix be denoted as $(i, j)$.
In one operation, you can choose any two numbers $i$ and $j$ and swap the number located in $(i, j)$ in the first matrix with the number in $(i, j)$ in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.
You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print "Possible", otherwise, print "Impossible".
|
There are too many possibilities to try a brute force, and a dp solution also might be too slow (e.g. some bitmask dp). There is a solution that uses 2sat but that is a bit hard to code so I won't go into details in this tutorial. Let's instead look at a greedy solution. First, let's swap $a_{i,j}$ with $b_{i,j}$ if $a_{i,j} > b_{i,j}$. At the end, for every $i$ and $j$, we have $a_{i,j} \leq b_{i,j}$. We now claim that there is a solution if and only if this configuration is valid. We can guess this intuitively and by trying a few examples, or we can do the proof below. <start of formal proof for why this works> If this configuration is valid, then obviously this solution works, so we're done with this side of the implication. The other way is to show if there exists a solution, then this configuration is also valid. We do this by contradiction. We show if this configuration is not valid, then there is no solution. If this configuration is not valid, without loss of generality, let $b_{i,j} \geq b_{i,j+1}$. $b_{i,j}$ must go somewhere in the matrix and it needs to be before either $b_{i,j+1}$ or $a_{i,j+1}$, but we have $a_{i,j+1} \leq b_{i, j+1} \leq b_{i,j}$, so we have nowhere that we can put $b_{i,j}$, thus this shows there is no solution. We can also extend this argument to the other cases. <end of proof for why this works> So, given the above claim, the solution is simple. Do the swaps so $a_{ij} \leq b_{ij}$. Then, check if the two matrices are increasing, and print "Possible" if so and "Impossible" otherwise. The runtime is $O(n^2)$ to read in the input, do the swaps, then do the checks that the matrices are valid.
|
[
"brute force",
"greedy"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
int32_t main()
{
int n,m;
cin>>n>>m;
int a[n][m], b[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>a[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>b[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int flag=0;
if(a[i][j]>=b[i][j])
flag=1;
if(flag)
swap(a[i][j], b[i][j]);
}
}
int flag=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(j && a[i][j]<=a[i][j-1])
flag=1;
if(j && b[i][j]<=b[i][j-1])
flag=1;
if(i && a[i][j]<=a[i-1][j])
flag=1;
if(i && b[i][j]<=b[i-1][j])
flag=1;
}
}
if(flag==0)
{
cout<<"Possible"<<endl;
}
else
{
cout << "Impossible" << endl;
}
return 0;
}
|
1163
|
A
|
Eating Soup
|
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party...
What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now $n$ cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone having finished their soup leaves the circle.
Katie suddenly notices that whenever a cat leaves, the place where she was sitting becomes an empty space, which means the circle is divided into smaller continuous groups of cats sitting next to each other. At the moment Katie observes, there are $m$ cats who left the circle. This raises a question for Katie: what is the maximum possible number of groups the circle is divided into at the moment?
Could you help her with this curiosity?
You can see the examples and their descriptions with pictures in the "Note" section.
|
We can prove that the first one to leave the circle does not make any difference to our answer. So after trying some tests, you will probably come up with an idea of selecting the cats that are sitting right between the other two to be the prior ones to leave because, in this way, those vacancies will definitely be useful for creating more separate groups. Therefore, if $m - 1 < \lfloor \frac{n}{2} \rfloor$, the answer is $m$ since each cat to leave (after the first cat) increases the number of groups. Otherwise, if $m + 1 \geq \lfloor \frac{n}{2} \rfloor$, each independent cat to leave decreases the number of groups so the answer is $n - m$. Summarily, the answer is $\min(m, n - m)$. Be careful with $m = 0$. Complexity: $O(1)$.
|
[
"greedy",
"math"
] | 900
|
#include <iostream>
using namespace std;
int main ()
{
int n, m;
cin >> n >> m;
cout << (m ? min(m, n - m) : 1) << endl;
return 0;
}
|
1163
|
B2
|
Cat Party (Hard Edition)
|
This problem is same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove \textbf{exactly one} day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.
For example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.
Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.
|
We can iterate over all streaks and check for each streak if we can remove one day so that each color has the same number of cats. There are 4 cases where we can remove a day from the streak to satisfy the condition: There is only one color in this streak. All appeared colors in this streak have the occurrence of $1$ (i.e. every color has exactly $1$ cat with that color). Every color has the same occurrence of cats, except for exactly one color which has the occurrence of $1$. Every color has the same occurrence of cats, except for exactly one color which has the occurrence exactly $1$ more than any other color. All of these four conditions can be checked using counting techniques. Complexity: $O(n)$.
|
[
"data structures",
"implementation"
] | 1,600
|
#include <iostream>
#include <stdio.h>
using namespace std;
const int N = 1e5 + 10;
int n, color, ans, mx, f[N], cnt[N];
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &color);
cnt[f[color]]--;
f[color]++;
cnt[f[color]]++;
mx = max(mx, f[color]);
bool ok = false;
if (cnt[1] == i) // every color has occurence of 1
ok = true;
else if (cnt[i] == 1) // only one color has the maximum occurence and the occurence is i
ok = true;
else if (cnt[1] == 1 && cnt[mx] * mx == i - 1) // one color has occurence of 1 and other colors have the same occurence
ok = true;
else if (cnt[mx - 1] * (mx - 1) == i - mx && cnt[mx] == 1) // one color has the occurence 1 more than any other color
ok = true;
if (ok)
ans = i;
}
printf("%d", ans);
return 0;
}
|
1163
|
C2
|
Power Transmission (Hard Edition)
|
This problem is same as the previous one, but has larger constraints.
It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.
At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $(x_i, y_i)$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane \textbf{infinite in both directions}. If there are more than two poles lying on the same line, they are connected by a single common wire.
Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?
|
First, we will divide the problem into several parts: 1) construct the wires, 2) remove duplicates, and 3) count the number of pairs that intersect. The first part is relatively simple: note that each wire is simply a line that goes through two distinct points (poles) on the $Oxy$ plane. Suppose this line goes through point $A(x_1,y_1)$ and point $B(x_2,y_2)$, then it can be described by the equation $ax - by = c$ where $a = y_1 - y_2$, $b = x_1 - x_2$, $c = y_1x_2 - y_2x_1$. For step two, we will simplify the equation for each line by dividing each coefficient by their greatest common divisor. Now each equation uniquely identifies a line, and vice versa - so we can sort the wires by their values of a, b, and c; then remove adjacent duplicates. The final part of the solution also makes use of this sorted list. As any pair of lines on the plane must intersect unless they are parallel, we only need to count the number of parallel pairs and subtract these from the total number of pairs. These are the pairs with the same slope (i.e. same value of a and b), and they already are next to each other in our list. We now iterate over these "blocks" of parallel lines and count the number of pairs each block contributes - a block of size $s$ gives $\frac{s(s-1)}{2}$ pairs. Complexity: $O(n^2\log{n})$.
|
[
"data structures",
"geometry",
"implementation",
"math"
] | 1,900
|
#include <cstdio>
#include <map>
#include <set>
#include <utility>
const int N = 1001;
int x[N], y[N];
std::map<std::pair<int,int>,std::set<long long>> slope_map;
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
int main()
{
int n; scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d%d", &x[i], &y[i]);
long long total = 0, res = 0;
for (int i = 1; i <= n - 1; ++i)
for (int j = i + 1; j <= n; ++j)
{
int x1 = x[i], y1 = y[i], x2 = x[j], y2 = y[j];
// construct a line passing through (x1, y1) and (x2, y2)
// line is expressed as equation ax - by = c with constant a, b, c
int a = y1 - y2, b = x1 - x2;
// simplify equation
int d = gcd(a, b); a /= d, b /= d;
if (a < 0 || (a == 0 && b < 0))
{
a = -a;
b = -b;
}
// lines with the same slope (same a, b) are stored in a map
std::pair<int,int> slope(a, b);
long long c = 1LL * a * x1 - 1LL * b * y1;
if (!slope_map[slope].count(c))
{
++total;
slope_map[slope].insert(c);
// if this line is new, it intersects every line with different slope
res += total - slope_map[slope].size();
}
}
printf("%lld\n", res);
}
|
1163
|
D
|
Mysterious Code
|
During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string $c$ consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).
Katie has a favorite string $s$ and a not-so-favorite string $t$ and she would love to recover the mysterious code so that it has as many occurrences of $s$ as possible and as little occurrences of $t$ as possible. Formally, let's denote $f(x, y)$ as the number of occurrences of $y$ in $x$ (for example, $f(aababa, ab) = 2$). Katie wants to recover the code $c'$ conforming to the original $c$, such that $f(c', s) - f(c', t)$ is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.
|
Firstly, we will find the maximal value of $f(c', s) - f(c', t)$ via dynamic programming. Denote 'dp[i][ks][kt]' as the maximal value of the said value when replacing the first $i$-th character of $c$, and the KMP state for the replaced sub-code to be $ks$ and $kt$. The maximal value of $f(c', s) - f(c', t)$ for the whole code will lie among all end states $dp[n][ks][kt]$ for all values of $ks$ and $kt$. Complexity: $O(|c| \cdot |s| \cdot |t|)$.
|
[
"dp",
"strings"
] | 2,100
|
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int K = 1005, N = 55, M = 55, INF = 1E9 + 7;
int k, n, m;
int kmp_s[N], nxt_s[N][26], kmp_t[M], nxt_t[M][26];
int dp[K][N][M];
char code[K], s[N], t[M];
void init(char s[], int n, int kmp[], int nxt[][26])
{
kmp[1] = 0;
for (int i = 2; i <= n; i++)
{
int cur = kmp[i - 1];
while (cur > 0 && s[cur + 1] != s[i])
cur = kmp[cur];
if (s[cur + 1] == s[i])
++cur;
kmp[i] = cur;
}
for (int i = 0; i <= n; i++)
for (char c = 'a'; c <= 'z'; c++)
{
int cur = i;
while (cur > 0 && s[cur + 1] != c)
cur = kmp[cur];
if (s[cur + 1] == c)
++cur;
nxt[i][c - 'a'] = cur;
}
}
int main()
{
scanf("%s%s%s", code + 1, s + 1, t + 1);
k = strlen(code + 1); n = strlen(s + 1); m = strlen(t + 1);
init(s, n, kmp_s, nxt_s); init(t, m, kmp_t, nxt_t);
for (int i = 0; i <= k; i++)
for (int ks = 0; ks <= n; ks++)
for (int kt = 0; kt <= m; kt++)
dp[i][ks][kt] = -INF;
dp[0][0][0] = 0;
for (int i = 0; i < k; i++)
for (int ks = 0; ks <= n; ks++)
for (int kt = 0; kt <= m; kt++)
for (char c = 'a'; c <= 'z'; c++)
if (code[i + 1] == '*' || code[i + 1] == c) // we now add/replace the (i + 1)-th character
{
int ns = nxt_s[ks][c - 'a'], nt = nxt_t[kt][c - 'a'];
int tmp = dp[i][ks][kt] + (ns == n) - (nt == m); // add the new occurrences if any
dp[i + 1][ns][nt] = max(dp[i + 1][ns][nt], tmp);
}
int ma = -INF;
for (int ks = 0; ks <= n; ks++)
for (int kt = 0; kt <= m; kt++)
ma = max(ma, dp[k][ks][kt]);
printf("%d\n", ma);
}
|
1163
|
E
|
Magical Permutation
|
Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen $n$ distinct positive integers and put all of them in a set $S$. Now he defines a magical permutation to be:
- A permutation of integers from $0$ to $2^x - 1$, where $x$ is a non-negative integer.
- The bitwise xor of any two consecutive elements in the permutation is an element in $S$.
Since Kuro is really excited about magical permutations, he wants to create the longest magical permutation possible. In other words, he wants to find the largest non-negative integer $x$ such that there is a magical permutation of integers from $0$ to $2^x - 1$. Since he is a newbie in the subject, he wants you to help him find this value of $x$ and also the magical permutation for that $x$.
|
The idea here is iterate $x$ and check if it is possible to create a magical permutation for the current $x$ we are iterating through. An observation to be made is that if it is possible to create a magical permutation $P$ from $0$ to $2^x - 1$, then it must be possible to express each integer from $0$ to $2^x - 1$ as the xor value of elements in one subset of $S$. This is because $0$ is represented as the xor value of the empty subset of $S$. Because of that, every element to the left of $0$ in $P$ is also the xor value of one subset of $S$, and so is every element to the right of $0$ in $P$. Because of that, we first check that if we can create every integer from $0$ to $2^x - 1$ using only the xor values of every subset of $S$. This is possible by creating a basis for integers from $0$ to $2^x - 1$ - $x$ integers such that each integer from $0$ to $2^x - 1$ is the xor value of a subset of these $x$ integers - from $S$ using Gaussian elimination. Now, if it is possible to create such a basis for integers from $0$ to $2^x - 1$ using only elements of $S$, is it possible to create a magic permutation then? Recall that each integer from $0$ to $2^x - 1$ corresponds to the xor value of a subset of the basis, or in other words, corresponds to a bitmask of the basis. We can also narrow down the original condition, such that the xor value of any two consecutive elements belongs to the basis; or in other words, the corresponding bitmask of any two consecutive elements in the magical permutation differs by exactly 1 bit. The problem now becomes creating a permutation of integers from $0$ to $2^x - 1$ such that any two consecutive elements in this permutation differs by 1 bit, and then convert this permutation to a magical permutation using the created basis. It turns out that we can always do this using Gray codes, although DFS works just as well. It also turns out that the basis for integers from $0$ to $2^x - 1$ does not exceed $2^x - 1$, we can sort $S$ and create the basis along with checking the aforementioned condition. Complexity: $O(n \log n + n \log MAX + MAX)$ if Gray codes are used, or $O(n \log n + n \log MAX + MAX \log MAX)$ is DFS is used instead, where $MAX$ denotes the maximum value of elements in $S$.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"data structures",
"graphs",
"math"
] | 2,400
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 200005, MX = 1E6 + 5;
int n, x = 0, a[N];
bool vis[MX];
vector<int> basis, vec, ans;
void add(int u)
{
int tmp = u;
for (int &v : basis)
u = min(u, u ^ v);
if (u > 0)
{
basis.push_back(u);
vec.push_back(tmp);
for (int i = basis.size() - 1; i > 0; i--)
if (basis[i] > basis[i - 1])
swap(basis[i], basis[i - 1]);
else
break;
}
}
void DFS(int u, int it = 0)
{
ans.push_back(u);
vis[u] = true;
if (it == (1 << x) - 1)
return;
for (int &v : vec)
if (!vis[u ^ v])
{
DFS(u ^ v, it + 1);
return;
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", a + i);
sort(a, a + n);
int pt = 0;
for (int i = 1; i < 20; i++)
{
for (; pt < n && a[pt] < (1 << i); pt++)
add(a[pt]);
if (basis.size() == i)
x = i;
}
basis.clear();
vec.clear();
for (int i = 0; i < n && a[i] < (1 << x); i++)
add(a[i]);
printf("%d\n", x);
DFS(0);
for (int &v : ans)
printf("%d ", v);
}
|
1163
|
F
|
Indecisive Taxi Fee
|
In the city of Capypaland where Kuro and Shiro resides, there are $n$ towns numbered from $1$ to $n$ and there are $m$ bidirectional roads numbered from $1$ to $m$ connecting them. The $i$-th road connects towns $u_i$ and $v_i$. Since traveling between the towns is quite difficult, the taxi industry is really popular here. To survive the harsh competition, each taxi company has to find a distinctive trait for their customers.
Kuro is the owner of a taxi company. He has decided to introduce a new fee model for his taxi brand, where the fee for each ride is not calculated based on the trip length, but on the sum of the prices of the roads traveled. The price for each of the $m$ roads has been decided by Kuro himself.
As of now, the price for the road $i$ is $w_i$ and hence the fee for a taxi ride traveling through roads $e_1, e_2, \ldots, e_k$ is $\sum_{i=1}^k w_{e_i}$.
However, Kuro himself is an indecisive person, so he has drafted $q$ plans to change the road price. Each of the plans will be based on the original prices $w_i$, except for a single road $t_j$, the price of which is changed to $x_j$. Note, that the plans are independent of each other.
Shiro is a regular customer of the Kuro's taxi brand since she uses the taxi to travel from town $1$ to town $n$ every day. Since she's so a regular customer, Kuro decided to show her all his $q$ plans before publishing them to the public. Now, Shiro wants to know the lowest fee she must pay to travel from the town $1$ to the town $n$ for each Kuro's plan.
|
Firstly, we will find and trace out one shortest path from vertex $1$ to vertex $n$ in the graph. Let's call this path main path, and we will number the edges on the main path as $E_1$, $E_2$, .., $E_k$ respectively. We will also call all of the other edges that does not belong to this main path candidate edges. During the procedure, we can also calculate the shortest path from $1$ to every vertex $u$, and the shortest path from every vertex $u$ to $n$. After calculating all of these values, we can now query the shortest path from $1$ to $n$ that must pass through each edge $(u, v)$ in either direction. We have a few observations to be made here: Observation 1: Apart of the vertices belong to the main path, for each vertex $u$, the shortest path from $1$ to $u$ uses a prefix of the main path. More formally, there exists an index $l_u$ ($0 \leq l_u \leq k$) such that the shortest path from $1$ to $u$ must use the edges $E_1$, $E_2$, ..., $E_{l_u}$ at its beginning. Using the same analogy, we can say that for each vertex $u$, the shortest path from $u$ to $n$ uses a suffix of the main path; or in other words, there exists an index $r_u$ ($1 \leq r_u \leq k + 1$) such that the shortest path from $u$ to $n$ must use the edges $E_{r_u}$, $E_{r_{u + 1}}$, ..., $E_k$ at its end. Note that if $l_u = 0$, the shortest path from $1$ to $u$ does not use a prefix of the main path, and if $r_u = k + 1$, the shortest path from $u$ to $n$ does not use a suffix of the main path. For every vertex $v$ that belongs to the main path however, we will set $l_v = t, r_v = t + 1$, where $t$ is the position where $v$ appears on the main path. What does this imply? This implies that the shortest from $1$ to $n$ that passes through $u$ does not rely on the edges $E_{l_u + 1}$, $E_{l_u + 2}$, ..., $E_{r_u - 1}$. Observation 2: For each candidate edge $(u, v)$, the shortest path from $1$ to $n$ passing through this edge in the order $u \rightarrow v$ does not rely on the edges $E_{l_u + 1}$, $E_{l_u + 2}$, ..., $E_{r_v - 1}$. This is because, the shortest path passing through this order $u \rightarrow v$ will consist of the shortest path from $1$ to $u$, the edge $(u, v)$, and the shortest path from $v$ to $n$. With the same analogy, the shortest path from $1$ to $n$ passing through this edge in the order $v \rightarrow u$ does not rely on the edges $E_{l_v + 1}$, $E_{l_v + 2}$, ..., $E_{r_u - 1}$. Using the observations, we can now answer the queries. There are three cases that we should consider when answering the shortest path with the modified edge: The modified edge is a candidate edge (i.e. it does not belong to the main path): we will take the minimal of the main path and the shortest path that goes through this modified edge. The modified edge belongs to the main path, and its value decreases: the new shortest path is still the main path, and its new value is the old value subtracting the difference between the original and the modified weight of that edge. The modified edge belongs to the main path, and its value increases: the new shortest path is either one of these two options: The main path, its new value being the old value adding the weight-difference of the modified edge. The shortest path from $1$ to $n$ that does not use the modified edge. This shortest path must use a candidate edge, since we cannot reuse the main path anymore; more specifically, this shortest path uses a candidate edge that does not rely on the modified edge. To get the value of this option, recall in observation 2 that for each candidate edge $(u, v)$ and with its direction, we know the range of edges belonging to the main path that this candidate edge does not rely on. Hence, we can use a segment tree to manage and query the shortest path that does not rely on this edge. The main path, its new value being the old value adding the weight-difference of the modified edge. The shortest path from $1$ to $n$ that does not use the modified edge. This shortest path must use a candidate edge, since we cannot reuse the main path anymore; more specifically, this shortest path uses a candidate edge that does not rely on the modified edge. To get the value of this option, recall in observation 2 that for each candidate edge $(u, v)$ and with its direction, we know the range of edges belonging to the main path that this candidate edge does not rely on. Hence, we can use a segment tree to manage and query the shortest path that does not rely on this edge. Complexity: $O((m + n)\log{n})$.
|
[
"data structures",
"graphs",
"shortest paths"
] | 3,000
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int N = 2E5 + 5, M = 2E5 + 5;
const long long INF = 1E18 + 7;
int n, m, q, ed, nw, mx, u[M], v[M], w[M], ind[M];
int tr[N], le[N], ri[N];
bool on_path[N];
long long dis[2][N];
struct TNode
{
int u;
long long val;
TNode(int _u, long long _val)
{
u = _u;
val = _val;
}
inline bool operator>(const TNode &oth) const
{
return val > oth.val;
}
};
priority_queue<TNode, vector<TNode>, greater<TNode>> pq;
struct TEdge
{
int v, w, ind;
TEdge(int _v, int _w, int _ind)
{
v = _v;
w = _w;
ind = _ind;
}
};
vector<TEdge> adj[N];
struct TTree
{
#define m (l + r) / 2
#define lc i * 2
#define rc i * 2 + 1
long long tr[4 * M];
void build(int l, int r, int i)
{
tr[i] = INF;
if (l == r)
return;
build(l, m, lc);
build(m + 1, r, rc);
}
void upd(int l, int r, int i, int L, int R, long long v)
{
if (l > R || r < L || L > R)
return;
if (L <= l && r <= R)
{
tr[i] = min(tr[i], v);
return;
}
upd(l, m, lc, L, R, v);
upd(m + 1, r, rc, L, R, v);
}
long long que(int l, int r, int i, int u)
{
if (l == r)
return tr[i];
return min(tr[i], u <= m ? que(l, m, lc, u) : que(m + 1, r, rc, u));
}
#undef m
#undef lc
#undef rc
} seg;
void dijkstra(int st, long long dis[], int get = 0)
{
fill(dis + 1, dis + n + 1, INF);
pq.push(TNode(st, dis[st] = 0));
while (!pq.empty())
{
TNode u = pq.top(); pq.pop();
if (u.val > dis[u.u])
continue;
for (TEdge &v : adj[u.u])
if (dis[v.v] > u.val + v.w)
{
tr[v.v] = v.ind;
if (get == 1 && !on_path[v.v])
le[v.v] = le[u.u];
else if (get == 2 && !on_path[v.v])
ri[v.v] = ri[u.u];
pq.push(TNode(v.v, dis[v.v] = u.val + v.w));
}
}
}
void trace()
{
on_path[1] = true; le[1] = ri[1] = 0;
for (int i = 1, cur = 1; cur != n; i++)
{
int edge = tr[cur];
ind[edge] = mx = i;
cur = u[edge] ^ v[edge] ^ cur;
on_path[cur] = true;
le[cur] = ri[cur] = i;
}
}
int main()
{
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= m; i++)
{
scanf("%d%d%d", u + i, v + i, w + i);
ind[i] = -1;
adj[u[i]].push_back(TEdge(v[i], w[i], i));
adj[v[i]].push_back(TEdge(u[i], w[i], i));
}
dijkstra(n, dis[1]); // reverse the initial dijkstra for the trace to increase from 1 -> n
trace();
dijkstra(1, dis[0], 1);
dijkstra(n, dis[1], 2);
seg.build(1, mx, 1);
for (int i = 1; i <= m; i++)
if (ind[i] == -1)
{
seg.upd(1, mx, 1, le[u[i]] + 1, ri[v[i]], dis[0][u[i]] + w[i] + dis[1][v[i]]);
seg.upd(1, mx, 1, le[v[i]] + 1, ri[u[i]], dis[0][v[i]] + w[i] + dis[1][u[i]]);
}
while (q--)
{
scanf("%d%d", &ed, &nw);
long long ans;
if (ind[ed] > 0)
{
ans = dis[0][n] - w[ed] + nw;
if (nw > w[ed])
ans = min(ans, seg.que(1, mx, 1, ind[ed]));
}
else
{
ans = dis[0][n];
if (nw < w[ed])
{
ans = min(ans, dis[0][u[ed]] + nw + dis[1][v[ed]]);
ans = min(ans, dis[0][v[ed]] + nw + dis[1][u[ed]]);
}
}
printf("%lld\n", ans);
}
}
|
1165
|
A
|
Remainder
|
You are given a huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.
You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.
You are also given two integers $0 \le y < x < n$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$.
|
As we can see, last $x$ digits of the resulting number will be zeros except the $n-y$-th. So we need to change all ones to zeros (if needed) among last $x$ digits, if the position of the digit is not $n-y$, and change zero to one (if needed) otherwise. It can be done with simple cycle.
|
[
"implementation",
"math"
] | 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, x, y;
string s;
cin >> n >> x >> y >> s;
int ans = 0;
for (int i = n - x; i < n; ++i) {
if (i == n - y - 1) ans += s[i] != '1';
else ans += s[i] != '0';
}
cout << ans << endl;
return 0;
}
|
1165
|
B
|
Polycarp Training
|
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $1$ problem, during the second day — exactly $2$ problems, during the third day — exactly $3$ problems, and so on. During the $k$-th day he should solve $k$ problems.
Polycarp has a list of $n$ contests, the $i$-th contest consists of $a_i$ problems. During each day Polycarp has to choose \textbf{exactly one} of the contests he didn't solve yet and solve it. He solves \textbf{exactly $k$ problems from this contest}. Other problems are discarded from it. If there are no contests consisting of at least $k$ problems that Polycarp didn't solve yet during the $k$-th day, then Polycarp stops his training.
How many days Polycarp can train if he chooses the contests optimally?
|
After sorting the array, we can maintain the last day Polycarp can train, in the variable $pos$. Initially it is $1$. Let's iterate over all elements of the sorted array in non-decreasing order and if the current element $a_i \ge pos$ then let's increase $pos$ by one. The answer will be $pos - 1$.
|
[
"data structures",
"greedy",
"sortings"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a.begin(), a.end());
int pos = 1;
for (int i = 0; i < n; ++i) {
if (a[i] >= pos) ++pos;
}
cout << pos - 1 << endl;
return 0;
}
|
1165
|
C
|
Good String
|
Let's call (yet again) a string \textbf{good} if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. \textbf{Note that the empty string is considered good}.
You are given a string $s$, you have to delete minimum number of characters from this string so that it becomes good.
|
The following greedy solution works: let's iterate over all characters of the string from left to right, and if the last block of two consecutive characters in the resulting string is full, just add the current character to the resulting string, otherwise add this character if it is not equal to the first character of the last block. And don't forget about the parity of length (remove last character if the length is odd).
|
[
"greedy"
] | 1,300
|
#include<bits/stdc++.h>
using namespace std;
string s;
int n;
string res;
int main()
{
cin >> n >> s;
for(int i = 0; i < n; i++)
{
if(res.size() % 2 == 0 || res.back() != s[i])
res.push_back(s[i]);
}
if(res.size() % 2 == 1) res.pop_back();
cout << n - int(res.size()) << endl << res << endl;
return 0;
}
|
1165
|
D
|
Almost All Divisors
|
We guessed some integer number $x$. You are given a list of \textbf{almost all} its divisors. \textbf{Almost all} means that there are \textbf{all divisors except $1$ and $x$} in the list.
Your task is to find the minimum possible integer $x$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.
You have to answer $t$ independent queries.
|
Suppose the given list of divisors is a list of almost all divisors of some $x$ (in other words, suppose that the answer exists). Then the minimum divisor multiplied by maximum divisor should be $x$. This is true because if we have a divisor $i$ we also have a divisor $\frac{n}{i}$. Let's sort all divisors and let $x = d_1 \cdot d_n$. Now we need to check if all divisors of $x$ except $1$ and $x$ are the permutation of the array $d$ (check that our answer is really correct). We can find all divisors of $x$ in $O(\sqrt{x})$, sort them and compare with the array $d$. If arrays are equal then the answer is $x$ otherwise the answer is -1.
|
[
"math",
"number theory"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int n;
cin >> n;
vector<long long> d(n);
for (int i = 0; i < n; ++i) {
cin >> d[i];
}
sort(d.begin(), d.end());
long long x = d[0] * d[n - 1];
vector<long long> dd;
for (int i = 2; i * 1ll * i <= x; ++i) {
if (x % i == 0) {
dd.push_back(i);
if (i != x / i) {
dd.push_back(x / i);
}
}
}
sort(dd.begin(), dd.end());
if (dd == d) {
cout << x << endl;
} else {
cout << -1 << endl;
}
}
return 0;
}
|
1165
|
E
|
Two Arrays and Sum of Functions
|
You are given two arrays $a$ and $b$, both of length $n$.
Let's define a function $f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array $b$ to minimize the value of $\sum\limits_{1 \le l \le r \le n} f(l, r)$. Since the answer can be very large, you have to print it modulo $998244353$. Note that you should \textbf{minimize the answer but not its remainder}.
|
Let's use contribution to the sum technique to solve this problem. How many times the value $a_i \cdot b_i$ will occur in the answer? It will occur $i \cdot (n - i + 1)$ times. Okay, now we can see that for each position $i$ we have the value $a_i \cdot b_i \cdot i \cdot (n - i + 1)$. The only non-constant value there is $b_i$. So let $val_i = a_i \cdot i \cdot (n - i + 1)$. Note that you cannot take this value modulo 998244353 here because then you can't compare these values correctly. We should pair the minimum $b_i$ with the maximum $val_i$, the second minimum with the second maximum and so on. So, let's sort the array $val$ and the array $b$, reverse the array $b$ and calculate the sum of values $val_i \cdot b_i$ (don't forget about modulo here!).
|
[
"greedy",
"math",
"sortings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector<int> a(n), b(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
cin >> b[i];
}
sort(b.begin(), b.end());
vector<pair<long long, int>> val(n);
for (int i = 0; i < n; ++i) {
val[i].first = (i + 1) * 1ll * (n - i) * a[i];
val[i].second = i;
}
sort(val.rbegin(), val.rend());
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = (ans + (val[i].first % MOD * 1ll * b[i]) % MOD) % MOD;
}
cout << ans << endl;
return 0;
}
|
1165
|
F1
|
Microtransactions (easy version)
|
\textbf{The only difference between easy and hard versions is constraints}.
Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.
Each day (during the \textbf{morning}) Ivan earns exactly one burle.
There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the \textbf{evening}).
Ivan can order \textbf{any} (possibly zero) number of microtransactions of \textbf{any} types during any day (of course, \textbf{if he has enough money to do it}). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.
There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.
Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.
|
Let's iterate over all possible answers. Obviously, this value is always in the range $[1, 2 \cdot \sum\limits_{i=1}^{n}k_i]$. The first day when Ivan can order all microtransactions he wants will be the answer. How to check if the current day $ansd$ is enough to order everything Ivan wants? If we had several sale days for some type of microtransaction (of course, we can use only such days that are not greater than the fixed last day $ansd$), let's use the last one, it is always not worse than some of the previous days. Then let's iterate over all days from $1$ to $ansd$ and do the following: firstly, let's increase our balance by one burle. Then let's try to order all microtransactions for which the current day is the last sale day (and pay one burle per copy). If we are out of money at some moment then just say that we should order all microtransactions that remain in this sale day during the last day for two burles per copy. It is true because it does not matter which types will remain because this day is the last sale day for all of these types. So, after all, we had some remaining microtransactions that we cannot buy during sales, and the current balance. And the current day is good if the number of such microtransactions multiplied by two is not greater than the remaining balance.
|
[
"binary search",
"greedy"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> k;
vector<pair<int, int>> q(1001);
bool can(int day) {
vector<int> lst(n, -1);
for (int i = 0; i < m; ++i) {
if (q[i].first <= day) {
lst[q[i].second] = max(lst[q[i].second], q[i].first);
}
}
vector<vector<int>> off(1001);
for (int i = 0; i < n; ++i) {
if (lst[i] != -1) {
off[lst[i]].push_back(i);
}
}
vector<int> need = k;
int cur_money = 0;
for (int i = 0; i <= day; ++i) {
++cur_money;
if (i > 1000) continue;
for (auto it : off[i]) {
if (cur_money >= need[it]) {
cur_money -= need[it];
need[it] = 0;
} else {
need[it] -= cur_money;
cur_money = 0;
break;
}
}
}
return accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> m;
k = vector<int>(n);
for (int i = 0; i < n; ++i) {
cin >> k[i];
}
for (int i = 0; i < m; ++i) {
cin >> q[i].first >> q[i].second;
--q[i].first;
--q[i].second;
}
for (int l = 0; l <= 2000; ++l) {
if (can(l)) {
cout << l + 1 << endl;
return 0;
}
}
assert(false);
return 0;
}
|
1165
|
F2
|
Microtransactions (hard version)
|
\textbf{The only difference between easy and hard versions is constraints}.
Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.
Each day (during the \textbf{morning}) Ivan earns exactly one burle.
There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the \textbf{evening}).
Ivan can order \textbf{any} (possibly zero) number of microtransactions of \textbf{any} types during any day (of course, \textbf{if he has enough money to do it}). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.
There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.
Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.
|
The main idea of this problem is the same as in the easy version. The only thing we should replace is the search method. Replacing linear search with binary search leads to reducing time complexity from $O(n^2)$ to $O(n \log n)$. And it is obvious that we can apply binary search here because if we can order all microtransactions during some day $d$ then we can order all of them during day $d+1$ (even using the answer for $d$ days and doing nothing during day $d+1$).
|
[
"binary search",
"greedy",
"implementation"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> k;
vector<pair<int, int>> q(200001);
bool can(int day) {
vector<int> lst(n, -1);
for (int i = 0; i < m; ++i) {
if (q[i].first <= day) {
lst[q[i].second] = max(lst[q[i].second], q[i].first);
}
}
vector<vector<int>> off(200001);
for (int i = 0; i < n; ++i) {
if (lst[i] != -1) {
off[lst[i]].push_back(i);
}
}
vector<int> need = k;
int cur_money = 0;
for (int i = 0; i <= day; ++i) {
++cur_money;
if (i > 200000) continue;
for (auto it : off[i]) {
if (cur_money >= need[it]) {
cur_money -= need[it];
need[it] = 0;
} else {
need[it] -= cur_money;
cur_money = 0;
break;
}
}
}
return accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
cin >> n >> m;
k = vector<int>(n);
for (int i = 0; i < n; ++i) {
cin >> k[i];
}
for (int i = 0; i < m; ++i) {
cin >> q[i].first >> q[i].second;
--q[i].first;
--q[i].second;
}
int l = 0, r = 400000;
while (r - l > 1) {
int mid = (l + r) >> 1;
if (can(mid)) r = mid;
else l = mid;
}
for (int i = l; i <= r; ++i) {
if (can(i)) {
cout << i + 1 << endl;
return 0;
}
}
assert(false);
return 0;
}
|
1166
|
A
|
Silent Classroom
|
There are $n$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $x$ be the number of such pairs of students in a split. Pairs $(a, b)$ and $(b, a)$ are the same and counted only once.
For example, if there are $6$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:
- splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $x=4$ ($3$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom),
- splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $x=1$ ($0$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom).
You are given the list of the $n$ names. What is the minimum $x$ we can obtain by splitting the students into classrooms?
Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.
|
First, note that we can solve the problem for each starting letter independently, because two students whose name starts with a different letter never form a chatty pair. How do we solve the problem when all the students' names start with the same letter? We claim that it's best to split as evenly as possible. If one classroom has $a$ students, and the other has $b$ students with $a > b + 1$, then by moving one of the students from the first classroom into the second we remove $a - 1$ chatty pairs from the first classroom and create $b$ new chatty pairs in the second, for a net result of $(a - 1) - b > 0$ chatty pairs removed. So in the best splitting we have $\vert a - b \vert \leq 1$, meaning we split as evenly as possible. Then, if $cnt_a$ denotes the number of students whose name starts with $a$, we will split them into a classroom containing $\lfloor \frac{cnt_a}{2} \rfloor$ students and one containing $\lceil \frac{cnt_a}{2} \rceil$ students. So the total number of chatty pairs among students whose name starts with $a$ is $\binom{\lfloor \frac{cnt_a}{2} \rfloor}{2} + \binom{\lceil \frac{cnt_a}{2} \rceil}{2}$ The expression is the same for the other letters in the alphabet, and adding them all up gives us our answer. We can also solve the problem without determining what the best splitting is. If, for each starting letter, we try all the possible number of students to send into the first classroom, and choose the one that gives the minimal $x$, then we will only have to do $\mathcal{O}(n)$ checks in total, which is more than fast enough to solve the problem. Complexity: $\mathcal{O}(n)$.
|
[
"combinatorics",
"greedy"
] | 900
| null |
1166
|
B
|
All the Vowels Please
|
Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $k$ is vowelly if there are positive integers $n$ and $m$ such that $n\cdot m = k$ and when the word is written by using $n$ rows and $m$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.
You are given an integer $k$ and you must either print a vowelly word of length $k$ or print $-1$ if no such word exists.
In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.
|
First, which boards could we feasibly fill with characters satisfying that every row and column contains one vowel at least once? Well, if we have a board with less than $5$ rows, then each column contains less than $5$ characters, so we cannot have every vowel on each column, and we can't fill the board. Similarly, we can't fill a board with less than $5$ columns. Ok, so say now that we have a board with at least $5$ rows and at least $5$ columns. Can we fill it? Yes we can! It's enough to fill it by diagonals, as shown in the following picture: Now we can easily solve the problem. If $n \cdot m = k$, then $n$ must divide $k$ and $m = \frac{k}{n}$. So we can iterate over all possible $n$ from $5$ to $k$, check whether $n$ divides $k$ and in that case, check whether $m = \frac{k}{n}$ is at least $5$. If this works for at least one value of $n$ then we can fill the $n \cdot m$ board by diagonals as shown before, and obtain our vowelly word by reading the characters row by row. If we don't find any values of $n$ satisfying this, then no vowelly word exists. Complexity: $\mathcal{O}(k)$.
|
[
"constructive algorithms",
"math",
"number theory"
] | 1,100
| null |
1166
|
C
|
A Tale of Two Lands
|
The legend of the foundation of Vectorland talks of two integers $x$ and $y$. Centuries ago, the array king placed two markers at points $|x|$ and $|y|$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $|x - y|$ and $|x + y|$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.
Here $|z|$ denotes the absolute value of $z$.
Now, Jose is stuck on a question of his history exam: "What are the values of $x$ and $y$?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $n$ integers $a_1, a_2, \dots, a_n$. Now, he wants to know the number of \textbf{unordered} pairs formed by two \textbf{different} elements from these $n$ integers such that the legend could be true if $x$ and $y$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.
|
Formally, the condition for the legend being true reads $\min(\vert x - y \vert, \vert x + y \vert) \le \vert x \vert, \vert y \vert \le \max(\vert x - y \vert, \vert x + y \vert)$ Now, it is possible to characterize when this condition happens through casework on the signs and sizes of $x$ and $y$, but this can be tricky to do right. However, there is a neat trick that allows us to solve the problem without any casework. What happens if we change $x$ into $-x$? The values of $\vert x \vert$ and $\vert y \vert$ stay the same, while $\vert x - y \vert$ and $\vert x + y \vert$ will swap values. This means that the pair $\{x, y\}$ works if and only if $\{-x, y\}$ works. Similarly we can switch the sign of $y$. This means that we can replace $x$ and $y$ by their absolute values, and the original pair works if and only if the new one works. If $x \ge 0$ and $y \ge 0$ then the condition becomes $\vert x - y \vert \le x, y \le x + y$. The upper bound obviously always holds, while the lower bound is equivalent by some simple algebra to $x \le 2y \text{ and } y \le 2x$ So the problem reduces to counting the number of pairs $\{x, y\}$ with $\vert x \vert \le 2 \vert y \vert$ and $\vert y \vert \le 2 \vert x \vert$. To solve this we now take the absolute values of all the $a_i$ and sort them into an array $b_1 \le b_2 \le \dots \le b_n$. The answer to the problem is the number of pairs $(l, r)$ with $l < r$ and $b_r \leq 2b_l$. For each fixed $l$ we calculate the largest $r$ that satisfies this condition, and just add $r - l$ to the answer, as the values $l + 1, l + 2, \dots, r$ are all the ones that work for this $l$. We can either do a binary search for the best $r$ at each $l$, or calculate the optimal $r$'s for all of the $l$'s in $\mathcal{O}(n)$ using two pointers. Either way, our final complexity is $\mathcal{O}(n \log n)$ as this is the time required to sort the array. Complexity: $\mathcal{O}(n \log n)$
|
[
"binary search",
"sortings",
"two pointers"
] | 1,500
| null |
1166
|
D
|
Cute Sequences
|
Given a positive integer $m$, we say that a sequence $x_1, x_2, \dots, x_n$ of positive integers is $m$-cute if for every index $i$ such that $2 \le i \le n$ it holds that $x_i = x_{i - 1} + x_{i - 2} + \dots + x_1 + r_i$ for some positive integer $r_i$ satisfying $1 \le r_i \le m$.
You will be given $q$ queries consisting of three positive integers $a$, $b$ and $m$. For each query you must determine whether or not there exists an $m$-cute sequence whose first term is $a$ and whose last term is $b$. If such a sequence exists, you must additionally find an example of it.
|
We will first deal with determining when the sequence doesn't exist. To do this, we place some bounds on the values of $x_n$. If we choose all values of the $r_i$ to be equal to $1$ then we can calculate that $x_n = 2^{n - 2}(x_1 + 1)$. Reciprocally if we choose all $r_i$ to be equal to $m$ then we find $x_n = 2^{n - 2}(x_1 + m)$. All other values give something inbetween, so we get $2^{n - 2}(x_1 + 1) \le x_n \le 2^{n - 2}(x_1 + m)$ Therefore, if $b$ doesn't lie on any of the intervals $[2^{n - 2}(a + 1), 2^{n - 2}(a + m)]$ for some value of $n$, then it is impossible for $b$ to be a term of an $m$-cute sequence starting at $a$. This can be checked naively in $\mathcal{O}(\log(10^{14}))$ since there are this many relevant values of $n$. We can convince ourselves that all values in these intervals are feasible through some experimentation, so we now turn to the more difficult problem of actually constructing a sequence. First, notice that we can rearrange the definition of the sequence as follows: $x_n = x_1 + x_2 + \dots + x_{n - 1} + r_n = (x_1 + \dots + x_{n - 2}) + x_{n - 1} + r_n \\ = (x_{n - 1} - r_{n - 1}) + x_{n - 1} + r_n = 2x_{n - 1} + r_n - r_{n - 1}$ Now, we can try to find a pattern. We see that $x_2 = a + r_1$, $x_3 = 2a + r_1 + r_2$, $x_4 = 4a + 2r_1 + r_2 + r_3$, and in general it would seem that. $x_n = 2^{n - 2}a + 2^{n - 3}r_2 + 2^{n - 4}r_3 + \dots + 2r_{n - 2} + r_{n - 1} + r_n$ This is actually very easy to prove inductively using $x_n = 2x_{n - 1} + r_n - r_{n - 1}$: All coefficients double from one term to the next, but we substract $r_{n - 1}$ once, so that coefficient becomes $1$ instead. Now we can also find an explicit solution: Write $b$ as $2^{n - 2}(a + k) + r$ where $r < 2^{n - 2}$, and consider the binary representation $r = d_{n - 3}d_{n - 4} \dots d_0$ of $r$. Then choosing $r_i = k + d_{n - 1 - i}$ (where $d_{-1} = 0$) works, because $2^{n - 2}a + 2^{n - 3}(k + d_{n - 3}) + \dots + 2(k + d_1) + (k + d_0) + k \\ = 2^{n - 2}a + (2^{n - 3} + 2^{n - 4} + \dots + 2 + 1 + 1)k + 2^{n - 3}d_{n - 3} + 2^{n - 4}d_{n - 4} + \dots + d_0 \\ = 2^{n - 2}a + 2^{n - 2}k + r \\ = 2^{n - 2}(a + k) + r$ Alternatively, after getting the formula, we can iterate on $i$ from $2$ to $k$ and greedily choose the values of $r_i$ to be as large as we can without exceeding $b$. This can be easily shown to work using that the coefficients are consecutive powers of two. Both of these approaches can be implemented in $\mathcal{O}(\log(10^{14}))$ per query. Complexity: $\mathcal{O}(q\log(10^{14}))$
|
[
"binary search",
"brute force",
"greedy",
"math"
] | 2,200
| null |
1166
|
E
|
The LCMs Must be Large
|
Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?
There are $n$ stores numbered from $1$ to $n$ in Nlogonia. The $i$-th of these stores offers a \textbf{positive integer} $a_i$.
Each day among the last $m$ days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.
Dora considers Swiper to be her rival, and she considers that she beat Swiper on day $i$ if and only if the least common multiple of the numbers she bought on day $i$ is strictly greater than the least common multiple of the numbers that Swiper bought on day $i$.
The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.
However, Dora forgot the values of $a_i$. Help Dora find out if there are positive integer values of $a_i$ such that she beat Swiper on \textbf{every} day. You don't need to find what are the possible values of $a_i$ though.
Note that it is possible for some values of $a_i$ to coincide in a solution.
|
We denote by $\textrm{lcm}\; A$ the $\textrm{lcm}$ of all elements in a collection $A$. Also, denote by $D_i$ and $S_i$ the collections that Dora and Swiper bought on day $i$, respectively. First, when can we say for sure that the values of $a_i$ cannot exist? Well, suppose that $D_i = S_j$ for some $i$ and $j$. Then we also have $D_j = S_i$, so if the condition were true we would have $\textrm{lcm}\; D_i > \textrm{lcm}\; S_i = \textrm{lcm}\; D_j > \textrm{lcm}\; S_j = \textrm{lcm}\; D_i$ Which is of course impossible. What now? We can actually make our impossibility condition a bit stronger by noticing that $\textrm{lcm}\; B \le \textrm{lcm}\; A$ whenever $B$ is a collection contained in $A$, which happens because $\textrm{lcm}\; B$ actually divides $\textrm{lcm}\; A$. Then, if the stores Dora bought from on day $i$ are completely disjoint from the stores Dora bought from on day $j$, then $D_j$ would be completely contained in $S_i$ and vice-versa, so $\textrm{lcm}\; D_i > \textrm{lcm}\; S_i \geq \textrm{lcm}\; D_j > \textrm{lcm}\; S_j \geq \textrm{lcm}\; D_i$ Which is again a contradiction. Ok, any two days must have a common store for the statement to be possible, so what? The remarkable fact here is that this is the only condition we need to check: i.e., the solution exists if and only if the sets of stores that Dora visited on days $i$ and $j$ intersect for all $i$ and $j$. How do we get a valid solution? We will take $m$ different prime numbers $p_1, p_2, \dots, p_m$ and set $a_i$ to be the product of $p_j$ for all the $j$'s such that Dora visited store $i$ on day $j$. Then $p_j$ is a divisor of $a_i$ if and only if Dora visited store $i$ on day $j$. Now proving that this works is easy: We know that on day $i$, Dora bought an integer from a store that she also visited on day $j$, and this number must be a multiple of $p_j$. So $\textrm{lcm}\; D_i = p_1p_2 \dots p_m$ for all $i$. On the other hand, $S_i$ contains no multiples of $p_i$, because they are all in $D_i$. So the $\textrm{lcm}$ of $S_i$ is strictly smaller. Now we just need to check that any two days have a common store, which can be done in $\mathcal{O}(nm^2)$ by checking each pair of days and determining for each $i$ whether Dora visited both stores on day $i$ in $\mathcal{O}(n)$. You can achieve a slight speedup if you check this using a bitset, but this wasn't necessary to solve the problem. Complexity: $\mathcal{O}(nm^2)$.
|
[
"bitmasks",
"brute force",
"constructive algorithms",
"math",
"number theory"
] | 2,100
| null |
1166
|
F
|
Vicky's Delivery Service
|
In a magical land there are $n$ cities conveniently numbered $1, 2, \dots, n$. Some pairs of these cities are connected by magical colored roads. Magic is unstable, so at any time, new roads may appear between two cities.
Vicky the witch has been tasked with performing deliveries between some pairs of cities. However, Vicky is a beginner, so she can only complete a delivery if she can move from her starting city to her destination city through a double rainbow. A double rainbow is a sequence of cities $c_1, c_2, \dots, c_k$ satisfying the following properties:
- For each $i$ with $1 \le i \le k - 1$, the cities $c_i$ and $c_{i + 1}$ are connected by a road.
- For each $i$ with $1 \le i \le \frac{k - 1}{2}$, the roads connecting $c_{2i}$ with $c_{2i - 1}$ and $c_{2i + 1}$ have the same color.
For example if $k = 5$, the road between $c_1$ and $c_2$ must be the same color as the road between $c_2$ and $c_3$, and the road between $c_3$ and $c_4$ must be the same color as the road between $c_4$ and $c_5$.
Vicky has a list of events in chronological order, where each event is either a delivery she must perform, or appearance of a new road. Help her determine which of her deliveries she will be able to complete.
|
Let $G$ be the graph with cities as vertices and roads as edges. Note that the edges originally in $G$ can be regarded as $m$ queries of the "add edge" type, so we will just describe a solution that can handle $m + q$ queries of any type. We need a way to capture the idea of going through two roads of the same color in a row. To do this, consider a graph $G^*$ with the same vertices as $G$, in which vertices $u$ and $v$ are connected by an edge if $uw$ and $vw$ are edges of the same color for some vertex $w$. Then any path in this graph corresponds to a double rainbow in the original. However, this doesn't solve the problem yet, because of the condition that the final edge of a double rainbow can be of any color. To help in solving this issue, consider $n$ sets $S_v$ such that $S_v$ has all of the $G^*$-connected components of both $v$ and any neighbor of $v$. Then we can see that we have a double rainbow from $u$ to $v$ if and only if the connected component of $u$ is in $S_v$ (either we reach $v$ directly, or we reach one of its neighbors and then use our final edge to go to $v$). So as long as we can mantain these sets, we have a $\mathcal{O}(\log n)$ time way to answer queries of the second type. Now we need to deal with adding edges. To do this, we will store the connectivity of $G^*$ using a DSU. When we connect two connected components in $G^*$, we do the merges from small to large. If we merge component $b$ into component $a$ then for each vertex $u$ in component $b$ and every neighbor $v$ of $u$ we remove $b$ from $S_v$ and insert $a$ instead. By merging from small to large we guarantee that each vertex changes component at most $\mathcal{O}(\log n)$ times, and thus we also update $S_v$ through the edge $uv$ at most $\mathcal{O}(\log n)$ times. Each update is just two $\mathcal{O}(\log n)$ operations, so over all updates this amortizes to $\mathcal{O}((m + q)\log(n)^2)$ (because we have $\mathcal{O}(m + q)$ edges), plus $\mathcal{O}(n \log n)$ for actually moving the vertices. There's an easy to fix, but important note, which is that the number of edges in $G^*$ can be quadratically large. However, we can check that for each edge $uv$ of color $x$ that we add, we only need to add two edges to $G^*$. Namely, if $u'$ and $v'$ are neighbors of $u$ and $v$ respectively through an edge of color $x$, then it is enough to add edges $uv'$ and $u'v$. (If one of $u'$ or $v'$ doesn't exist then we just don't add the corresponding edge). We can store these $x$-colored neighbors of each vertex in sets which have total size at most $m + q$, so we can find in $\mathcal{O}(\log n)$ which updates we need to perform, and we perform a constant number of updates per added edge. Complexity: $\mathcal{O}(n \log(n) + (m + q)\log(n)^2)$, or $\mathcal{O}((n + m + q)\log(n))$ using hash tables.
|
[
"data structures",
"dsu",
"graphs",
"hashing"
] | 2,400
| null |
1167
|
A
|
Telephone Number
|
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string $s$ of length $n$, consisting of digits.
In one operation you can delete any character from string $s$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.
You need to determine whether there is such a sequence of operations (possibly empty), after which the string $s$ becomes a telephone number.
|
To solve this problem, we just need to find the first occurrence of the digit $8$, let's denote it as $x$. Now if $n - x \ge 10$ then answer is $YES$, otherwise $NO$.
|
[
"brute force",
"greedy",
"strings"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
int n;
string s;
int main(){
int tc;
cin >> tc;
for(int t = 0; t < tc; ++t){
cin >> n >> s;
int pos = n;
for(int i = 0; i < n; ++i)
if(s[i] == '8'){
pos = i;
break;
}
if(n - pos >= 11)
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}
|
1167
|
B
|
Lost Numbers
|
\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.
The jury guessed some array $a$ consisting of $6$ integers. There are $6$ special numbers — $4$, $8$, $15$, $16$, $23$, $42$ — and each of these numbers occurs in $a$ exactly once (so, $a$ is some permutation of these numbers).
You don't know anything about their order, but you are allowed to ask \textbf{up to $4$ queries}. In each query, you may choose two indices $i$ and $j$ ($1 \le i, j \le 6$, $i$ and $j$ are not necessarily distinct), and you will get the value of $a_i \cdot a_j$ in return.
Can you guess the array $a$?
\textbf{The array $a$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries}.
|
The key fact that allows us to solve this problem is that if we analyze the pairwise products of special numbers, we will see that all of them (considering that we always multiply two different numbers) are unique. So, if we, for example, know that $a_i \cdot a_j = x$, then there are only two possibilities for the values of $a_i$ and $a_j$: $x$ is uniquely expressed as the product of two distinct special numbers $A$ and $B$, and either $a_i = A$, $a_j = B$, or $a_i = B$, $a_j = A$. This allows us to guess three numbers using two queries: we ask $a_i \cdot a_j$ and $a_j \cdot a_k$, we uniquely determine $a_j$ as the only number that is suitable for the both pairs, and then we express $a_i = \frac{a_i \cdot a_j}{a_j}$ and $a_k = \frac{a_j \cdot a_k}{a_j}$. Of course, there are easier ways to solve this problem, considering there are only $6$ special numbers. For example, you could use four queries $a_i \cdot a_{i + 1}$ (for all $i \in [1, 4]$) and try all $6!$ permutations, and the model solution uses exactly this approach.
|
[
"brute force",
"divide and conquer",
"interactive",
"math"
] | 1,400
|
#include<bits/stdc++.h>
using namespace std;
vector<int> p = {4, 8, 15, 16, 23, 42};
int ans[4];
int main()
{
for(int i = 0; i < 4; i++)
{
cout << "? " << i + 1 << " " << i + 2 << endl;
cout.flush();
cin >> ans[i];
}
do
{
bool good = true;
for(int i = 0; i < 4; i++)
good &= (p[i] * p[i + 1] == ans[i]);
if(good) break;
}
while(next_permutation(p.begin(), p.end()));
cout << "!";
for(int i = 0; i < 6; i++)
cout << " " << p[i];
cout << endl;
cout.flush();
return 0;
}
|
1167
|
C
|
News Distribution
|
In some social network, there are $n$ users communicating with each other in $m$ groups of friends. Let's analyze the process of distributing some news between users.
Initially, some user $x$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.
For each user $x$ you have to determine what is the number of users that will know the news if initially only user $x$ starts distributing it.
|
The first intention after reading the problem is to reformulate it in graph theory terms. Let people be vertices, edge between two vertices $x$ and $y$ exists if $x$ and $y$ have some group in common. Basically, if person $x$ starts distributing the news, everyone in his connectivity component recieves it. Thus, the task is to calculate the number of vertices of each vertex component. As of now, the graph can have up to $O(n^2)$ edges (consider the case where everyone is in the same group). Let's reduce the number of edges without changing connectivity components. For each group you know for sure that people in it are in the same component. Let's connect not just every pair of vertices in it, but every pair of neighbouring ones in each group. It's easy to see that they are still in the same component. This graph will have $O(\sum \limits_{i = 1}^{m} k_i)$ edges which is a much smaller number. You can use dfs or dsu to find the components and their sizes. Overall complexity: $O(n + \sum \limits_{i = 1}^{m} k_i)$.
|
[
"dfs and similar",
"dsu",
"graphs"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int N = 500 * 1000 + 13;
int n, m;
int rk[N], p[N];
int getP(int a){
return (a == p[a] ? a : p[a] = getP(p[a]));
}
void unite(int a, int b){
a = getP(a), b = getP(b);
if (a == b) return;
if (rk[a] < rk[b]) swap(a, b);
p[b] = a;
rk[a] += rk[b];
}
int main(){
scanf("%d%d", &n, &m);
forn(i, n) p[i] = i, rk[i] = 1;
forn(i, m){
int k;
scanf("%d", &k);
int lst = -1;
forn(j, k){
int x;
scanf("%d", &x);
--x;
if (lst != -1)
unite(x, lst);
lst = x;
}
}
forn(i, n)
printf("%d ", rk[getP(i)]);
puts("");
}
|
1167
|
D
|
Bicolored RBS
|
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.
We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define \textbf{nesting depth} of the RBS as maximum number of bracket pairs, such that the $2$-nd pair lies inside the $1$-st one, the $3$-rd one — inside the $2$-nd one and so on. For example, nesting depth of "" is $0$, "()()()" is $1$ and "()((())())" is $3$.
Now, you are given RBS $s$ of even length $n$. You should color each bracket of $s$ into one of two colors: red or blue. Bracket sequence $r$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $b$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $s$, $r$ or $b$. No brackets can be left uncolored.
Among all possible variants you should choose one that \textbf{minimizes maximum} of $r$'s and $b$'s nesting depth. If there are multiple solutions you can print any of them.
|
Let $d(s)$ be nested depth of RBS $s$. There is an interesting fact that $\max(d(r), d(b)) \ge \left\lceil \frac{d(s)}{2} \right\rceil$. From the other side we can always reach equation $\max(d(r), d(b)) = \left\lceil \frac{d(s)}{2} \right\rceil$ using some approaches. Let's look at prefix of length $i$ of string $s$. Let $o_s(i)$ be number of opening bracket in the prefix, $c_s(i)$ - number of closing brackets. Then we can define balance of the $i$-th prefix of $s$ as $bal_s(i) = o_s(i) - c_s(i)$. The author's approach is next: Let's define level of pair of brackets (matched in natural way) as $bal_s(i - 1)$, where $i$ is position of opening bracket of this pair. Then we will color in red all pairs with even level and in blue - with odd level. -- Proof of $\max(d(r), d(b)) \ge \left\lceil \frac{d(s)}{2} \right\rceil$: It can be shown that $d(s) = \max\limits_{1 \le i \le n}(bal_s(i))$ and exists such $pos$ that $d(s) = bal_s(pos)$. After any coloring of $s$ we can define number of opening/closing red (blue) brackets of $pos$-th prefix of $s$ as $o_r(pos)$ ($o_b(pos)$) and $c_r(pos)$ ($c_b(pos)$) respectively. Since $o_s(pos) = o_r(pos) + o_b(pos)$ and $c_s(pos) = c_r(pos) + c_b(pos)$, then $\max(bal_r(pos), bal_b(pos)) = \max(o_r(pos) - c_r(pos), bal_b(pos)) \\ = \max((o_s(pos) - o_b(pos)) - (c_s(pos) - c_b(pos)), bal_b(pos)) = \max((o_s(pos) - c_s(pos)) - (o_b(pos) - c_b(pos)), bal_b(pos)) \\ = \max(bal_s(pos) - bal_b(pos), bal_b(pos)) \ge \left\lceil \frac{bal_s(pos)}{2} \right\rceil = \left\lceil \frac{d(s)}{2} \right\rceil.$ Finally, $\max(d(a), d(b)) = \max(\max\limits_{1 \le i \le n}(bal_r(i)), \max\limits_{1 \le i \le n}(bal_b(i))) \\ = \max\limits_{1 \le i, j \le n}(\max(bal_r(i), bal_b(j))) \ge \max(bal_r(pos), bal_b(pos)) \ge \left\lceil \frac{d(s)}{2} \right\rceil$
|
[
"constructive algorithms",
"greedy"
] | 1,500
|
#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())
int n;
string s;
inline bool read() {
if(!(cin >> n))
return false;
cin >> s;
return true;
}
inline void solve() {
string t(n, '0');
int bal = 0;
fore(i, 0, n) {
if(s[i] == ')')
bal--;
t[i] = char('0' + (bal & 1));
if(s[i] == '(')
bal++;
}
cout << t << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1167
|
E
|
Range Deleting
|
You are given an array consisting of $n$ integers $a_1, a_2, \dots , a_n$ and an integer $x$. It is guaranteed that for every $i$, $1 \le a_i \le x$.
Let's denote a function $f(l, r)$ which erases all values such that $l \le a_i \le r$ from the array $a$ and returns the resulting array. For example, if $a = [4, 1, 1, 4, 5, 2, 4, 3]$, then $f(2, 4) = [1, 1, 5]$.
Your task is to calculate the number of pairs $(l, r)$ such that $1 \le l \le r \le x$ and $f(l, r)$ is sorted in non-descending order. Note that the empty array is also considered sorted.
|
Lets find the maximum number $pref$ such that all values $1, 2, \dots, pref$ form the non-descending order array. It can be done the following way. Let values $1, 2, \dots, x$ form the non-descending order array. Then values $1, 2, \dots, x, x+1$ will form the non-descending order array if the first occurrence of $x+1$ in array $a$ is after the last occurrence of $x$. In similar manner we can find the minimum number $suf$ such that all values $suf, suf+1, \dots, x$ form the non-descending order array. Now let's find out how to get the minimum number $s$ such that all values $1, 2, \dots, p, s, s + 1, \dots, x$ form the non-descending order array if we fixed the value $p$. We denote this value $s$ for some fixed value $p$ as $f(p)$. Firstly, conditions $s > p$, $suf \le s$ and $p \le pre$ should hold. Secondly, there should be no such a pair $(m, r)$ that conditions $1 \le m < r \le n$, $1 \le a_r, \le p$ and $s \le a_m \le x$ hold. Since the condition $p \le pre$ is satisfied, it means that $s$ must be greater than $\max\limits_{1 \le i \le lst} a_i$, where $lst$ is the last occurrence of $p$ in array $a$. In this way the answer is $\sum\limits_{i=1}^{pref} (x - f(i) + 1)$.
|
[
"binary search",
"combinatorics",
"data structures",
"two pointers"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int N = int(1e6) + 99;
int n, x;
int a[N];
vector <int> pos[N];
int prefMax[N];
int main() {
scanf("%d %d", &n, &x);
for(int i = 0; i < n; ++i){
scanf("%d", a + i);
pos[a[i]].push_back(i);
prefMax[i] = max(a[i], (i > 0 ? prefMax[i - 1] : a[i]));
}
int p = 1;
int lst = n + 5;
for(int i = x; i >= 1; --i){
if(pos[i].empty()){
p = i;
continue;
}
if(pos[i].back() > lst) break;
p = i;
lst = pos[i][0];
}
long long res = 0;
lst = -1;
for(int l = 1; l <= x; ++l){
int r = max(l, p - 1);
if(lst != -1) r = max(r, prefMax[lst]);
res += x - r + 1;
if(!pos[l].empty()){
if(pos[l][0] < lst) break;
lst = pos[l].back();
}
}
cout << res << endl;
return 0;
}
|
1167
|
F
|
Scalar Queries
|
You are given an array $a_1, a_2, \dots, a_n$. All $a_i$ are pairwise distinct.
Let's define function $f(l, r)$ as follows:
- let's define array $b_1, b_2, \dots, b_{r - l + 1}$, where $b_i = a_{l - 1 + i}$;
- sort array $b$ in increasing order;
- result of the function $f(l, r)$ is $\sum\limits_{i = 1}^{r - l + 1}{b_i \cdot i}$.
Calculate $\left(\sum\limits_{1 \le l \le r \le n}{f(l, r)}\right) \mod (10^9+7)$, i.e. total sum of $f$ for all subsegments of $a$ modulo $10^9+7$.
|
Let's define some functions at first: indicator function $I(x) = 1$ if $x$ is true and $0$ otherwise. $lower(l, r, x)$ is a number of $a_j$ that $l \le j \le r$ and $a_j < x$. Good observation: $lower(l, r, x) = \sum_{j = l}^{j = r}{I(a_j < x)}$. Another observation: $f(l, r) = \sum\limits_{i = l}^{i = r}{a_i \cdot (lower(l, r, a_i) + 1})$. Now, it's time to transform what we'd like to calculate: $\sum_{1 \le l \le r \le n}{f(l, r)} = \sum_{1 \le l \le r \le n}{\sum_{i = l}^{i = r}{a_i \cdot (lower(l, r, a_i) + 1})} = \sum_{1 \le l \le r \le n}{(\sum_{i = l}^{i = r}{a_i \cdot lower(l, r, a_i)} + \sum_{i = l}^{i = r}{a_i})} = \\ = \sum_{1 \le l \le r \le n}{\sum_{i = l}^{i = r}{a_i \cdot lower(l, r, a_i)}} + \sum_{i = 1}^{i = n}{a_i \cdot i \cdot (n - i + 1)}$ Since transformation of the second sum was standard, we'll look at the first sum: $\sum_{1 \le l \le r \le n}{\sum_{i = l}^{i = r}{a_i \cdot lower(l, r, a_i)}} = \sum_{i = 1}^{i = n}{\sum_{1 \le l \le i \le r \le n}{a_i \cdot lower(l, r, a_i)}} = \sum_{i = 1}^{i = n}{a_i \sum_{1 \le l \le i \le r \le n}{lower(l, i, a_i) + lower(i, r, a_i)}} = \\ = \sum_{i = 1}^{i = n}{a_i \sum_{1 \le l \le i}{ \sum_{i \le r \le n}{lower(l, i, a_i) + lower(i, r, a_i)}}} = \sum_{i = 1}^{i = n}{a_i \left( (n - i + 1) \sum_{1 \le l \le i}{lower(l, i, a_i)} + i \sum_{i \le r \le n}{lower(i, r, a_i)} \right) }$ So, we can iterate over $i$ and we'd like to calculate this two sums fast enough. So, more transformations: $\sum_{1 \le l \le i}{lower(l, i, a_i)} = \sum_{1 \le l \le i}{\sum_{j = l}^{j = i}{I(a_j < a_i)}} = \sum_{j = 1}^{j = i}{\sum_{l = 1}^{l = j}{I(a_j < a_i)}} = \sum_{j = 1}^{j = i}{I(a_j < a_i) \cdot j}$ So, while iterating over $i$ we need to make queries of two types: set value $i$ in position $a_i$ and calculate $\sum_{a_j < a_i}{j}$. It can be done by BIT with coordinate compression. $\sum_{i \le r \le n}{lower(i, r, a_i)}$ can be calculated in the same way iterating over $i$ in reverse order. Result complexity is $O(n \log{n})$.
|
[
"combinatorics",
"data structures",
"math",
"sortings"
] | 2,300
|
#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())
typedef long long li;
const int MOD = int(1e9) + 7;
int add(int a, int b) {
a += b;
while(a >= MOD)
a -= MOD;
while(a < 0)
a += MOD;
return a;
}
int mul(int a, int b) {
return int(a * 1ll * b % MOD);
}
int n;
vector<int> a;
inline bool read() {
if(!(cin >> n))
return false;
a.resize(n);
fore(i, 0, n)
cin >> a[i];
return true;
}
vector<li> f;
void inc(int pos, int val) {
for(; pos < sz(f); pos |= pos + 1)
f[pos] += val;
}
li sum(int pos) {
li ans = 0;
for(; pos >= 0; pos = (pos & (pos + 1)) - 1)
ans += f[pos];
return ans;
}
vector<int> S[2];
inline void solve() {
fore(k, 0, 2) {
S[k].assign(n, 0);
f.assign(n, 0);
vector<int> dx(a.begin(), a.end());
sort(dx.begin(), dx.end());
fore(i, 0, n) {
int pos = int(lower_bound(dx.begin(), dx.end(), a[i]) - dx.begin());
S[k][i] = int(sum(pos) % MOD);
inc(pos, i + 1);
}
reverse(a.begin(), a.end());
}
reverse(S[1].begin(), S[1].end());
int ans = 0;
fore(i, 0, n)
ans = add(ans, mul(a[i], add(mul(i + 1, n - i), add(mul(S[0][i], n - i), mul(S[1][i], i + 1)))));
cout << ans << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1167
|
G
|
Low Budget Inception
|
So we got bored and decided to take our own guess at how would "Inception" production go if the budget for the film had been terribly low.
The first scene we remembered was the one that features the whole city bending onto itself:
It feels like it will require high CGI expenses, doesn't it? Luckily, we came up with a similar-looking scene which was a tiny bit cheaper to make.
Firstly, forget about 3D, that's hard and expensive! The city is now represented as a number line (infinite to make it easier, of course).
Secondly, the city doesn't have to look natural at all. There are $n$ buildings on the line. Each building is a square $1 \times 1$. \textbf{Buildings are numbered from $1$ to $n$ in ascending order of their positions.} Lower corners of building $i$ are at integer points $a_i$ and $a_i + 1$ of the number line. Also the distance between any two neighbouring buildings $i$ and $i + 1$ doesn't exceed $d$ (really, this condition is here just to make the city look not that sparse). Distance between some neighbouring buildings $i$ and $i + 1$ is calculated from the lower right corner of building $i$ to the lower left corner of building $i + 1$.
Finally, curvature of the bend is also really hard to simulate! Let the bend at some integer coordinate $x$ be performed with the following algorithm. Take the ray from $x$ to $+\infty$ and all the buildings which are on this ray and start turning the ray and the buildings counter-clockwise around point $x$. At some angle some building will touch either another building or a part of the line. You have to stop bending there (implementing buildings crushing is also not worth its money).
\textbf{Let's call the angle between two rays in the final state the terminal angle $\alpha_x$.}
The only thing left is to decide what integer point $x$ is the best to start bending around. Fortunately, we've already chosen $m$ candidates to perform the bending.
So, can you please help us to calculate terminal angle $\alpha_x$ for each bend $x$ from our list of candidates?
|
Let's solve the problem for a single query at first. There are two possible types of collisions: between two buildings and between a building and a ray. Obviously, if the collision of the second type happens, then it's the building which is the closest to the bend point (from either left or right). The less obvious claim is that among all buildings collisions, the closest is the biggest angle one. Let's boil down some possibilities of colliding buildings. Let two buildings be the same distance $D$ from the bend point $x$. Then they will collide and the collision point will $(x - D, 1)$. Two buildings also collide if the left one is $D + 1$ from $x$ and the right one is $D$. Then the point of collision is $(x - D + 1, 1)$. And for the opposite case the point of collision is also $(x - D + 1, 1)$. These points can be easily proven by checking the distances to upper corners of each building. No other two buildings will collide. Now that we know this, we can transition to solving a problem of checking if there exists such a pair that the distances to $x$ from them differ by at most one. Finding such a pair with minimal $D$ is enough. Obviously, this can be done with some sort of two pointers. However, that's not the intended solution. Let's constuct bitset of 7000 positions to the left of the bend and to the right of the bend. AND of these bitsets will give you the pairs such that the distance $D$ is the same for them. However, you can put 1 in points $y - 1$ and $y$ for each building to the left and $y$ and $y + 1$ for each building to the right. This way AND will give you the exact pairs you need. Use _Find_first to find the closest one. Let collision happen on distance $D$. Then the collision of the first type will have angle $2 \cdot arctan D$ and the collision of the second type will have angle $arctan D$. The answer is the maximum of these two values. Be careful with cases where $D = 0$. How to process lots of queries. Let's just move the bitsets to the right while going through queries in ascending order. Bitsets can be updated in $(d / 32)$ for each query and only $n$ buildings will be added to them in total. Overall complexity: $O(md / 32 + n)$.
|
[
"brute force",
"geometry"
] | 3,100
|
#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;
const int INF = int(1e9);
const li INF64 = li(1e18);
const int N = 200 * 1000 + 555;
const int D = 7077;
int n, d, m;
int a[N], qs[N];
inline bool read() {
if(scanf("%d%d", &n, &d) != 2)
return false;
fore(i, 0, n)
scanf("%d", &a[i]);
assert(scanf("%d", &m) == 1);
fore(i, 0, m)
scanf("%d", &qs[i]);
return true;
}
bitset<D> L, R, cur;
int dist[N];
set<int> has;
void shiftL(int s, int t, int &uk) {
L <<= t - s;
for(; uk < n && a[uk] < t; uk++) {
if(t - a[uk] - 1 < D)
L[t - a[uk] - 1] = 1;
if(t - a[uk] < D)
L[t - a[uk]] = 1;
}
}
void shiftR(int s, int t, int &uk) {
R >>= t - s;
if(!has.count(t))
R[0] = 0;
for(; uk < n && a[uk] < t + D; uk++) {
if(a[uk] - t >= 0) {
R[a[uk] - t] = 1;
if(a[uk] - t + 1 >= 0)
R[a[uk] - t + 1] = 1;
}
}
}
inline void solve() {
fore(i, 0, m) {
dist[i] = INF;
int pos = int(lower_bound(a, a + n, qs[i]) - a);
if(pos > 0)
dist[i] = qs[i] - a[pos - 1] - 1;
if(pos < n)
dist[i] = min(dist[i], a[pos] - qs[i]);
}
has = set<int>(a, a + n);
int uL = 0, uR = 0;
L.reset();
R.reset();
fore(i, 0, m) {
shiftL(i > 0 ? qs[i - 1] : -D, qs[i], uL);
shiftR(i > 0 ? qs[i - 1] : -D, qs[i], uR);
double ans = atan2(1, dist[i]);
cur = L & R;
int pos = (int)cur._Find_first();
if(pos < D) {
int ds = pos;
ans = max(ans, 2 * atan2(1, ds));
}
printf("%.15f\n", ans);
}
}
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;
}
|
1168
|
A
|
Increasing by Modulo
|
Toad Zitz has an array of integers, each integer is between $0$ and $m-1$ inclusive. The integers are $a_1, a_2, \ldots, a_n$.
In one operation Zitz can choose an integer $k$ and $k$ indices $i_1, i_2, \ldots, i_k$ such that $1 \leq i_1 < i_2 < \ldots < i_k \leq n$. He should then change $a_{i_j}$ to $((a_{i_j}+1) \bmod m)$ for each chosen integer $i_j$. The integer $m$ is fixed for all operations and indices.
Here $x \bmod y$ denotes the remainder of the division of $x$ by $y$.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
|
Let's check that the answer to the problem is $\leq x$. Then, for each element, you have some interval (interval on the "circle" of remainders modulo $m$) of values, that it can be equal to. So you need to check that you can pick in each interval some point, to make all these values non-decrease. You can do it with greedy! Each time, let's take the smallest element from the interval, that is at least the previously chosen value. And after this, let's make the binary search on $x$. So we have the solution in $O(n \log m)$.
|
[
"binary search",
"greedy"
] | 1,700
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, m;\n cin >> n >> m;\n vector <int> a(n);\n for (int &x : a) {\n cin >> x;\n }\n int l = -1, r = m;\n while (l < r - 1) {\n int mid = (l + r) / 2;\n int prev = 0;\n bool bad = false;\n for (int i = 0; i < n; i++) {\n int lf = a[i], rf = a[i] + mid;\n if ((lf <= prev && prev <= rf) || (lf <= prev + m && prev + m <= rf)) {\n continue;\n }\n if (lf < prev) {\n bad = true;\n break;\n } else {\n prev = lf;\n }\n }\n if (bad) {\n l = mid;\n }\n else {\n r = mid;\n }\n }\n cout << r << '\\n';\n}"
|
1168
|
B
|
Good Triple
|
Toad Rash has a binary string $s$. A binary string consists only of zeros and ones.
Let $n$ be the length of $s$.
Rash needs to find the number of such pairs of integers $l$, $r$ that $1 \leq l \leq r \leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \leq x, k \leq n$, $l \leq x < x + 2k \leq r$, and $s_x = s_{x+k} = s_{x+2k}$.
Find this number of pairs for Rash.
|
Lemma: there are no strings without such $x,k$ of length at least 9. In fact, you just can write brute force to find all "good" strings and then realize that they all are small. Ok, so with this you can just write some sort of "naive" solution, for each $l$ find the largest $r$, such that $l \ldots r$ is a "good" string, and then add $n - r$ to the answer. You can do it in $9 \cdot 9 \cdot n$ or in $9 \cdot n$, as I do in my solution.
|
[
"brute force",
"two pointers"
] | 1,900
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n string s;\n cin >> s;\n int n = (int) s.size();\n vector <int> vl(n + 1, n);\n ll ans = 0;\n for (int i = n - 1; i >= 0; i--) {\n vl[i] = vl[i + 1];\n for (int k = 1; i + 2 * k < vl[i]; k++) {\n if (s[i] == s[i + k] && s[i + k] == s[i + 2 * k]) {\n vl[i] = i + 2 * k;\n }\n }\n ans += n - vl[i];\n }\n cout << ans << endl;\n}"
|
1168
|
C
|
And Reachability
|
Toad Pimple has an array of integers $a_1, a_2, \ldots, a_n$.
We say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \ldots < p_k=y$, and $a_{p_i}\, \&\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \leq i < k$.
Here $\&$ denotes the bitwise AND operation.
You are given $q$ pairs of indices, check reachability for each of them.
|
Let's calculate $go_{i, k}$ - the smallest $j$, such that $a_j$ contains bit $k$, which is reachable from $i$. How to recalculate it? Let $last_{i,k}$ is the smallest $j > i$, such that $a_j$ contains bit $k$. Then, I claim that $go_{i,k}$ is equal to the $i$ or to the $\min{(go_{last_{i,j},k})}$ for all bits $j$ that $a_i$ contains. Why? Because if you go from $i$ to some number, which has bit $j$ in the intersection, it is useless to go to the number which is not equal to $last_{i,j}$, because from $last_{i,j}$ you can go to all numbers that have bit $j$ and that positioned farther. So in $O(n \log )$ you can calculate all these values, and then to answer the query you can check that there exists some bit $j$ in $a_y$ such that $go_{x, j} \leq y$.
|
[
"bitmasks",
"dp"
] | 2,200
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nconst int N = 3e5 + 7;\nconst int LG = 19;\n\nint go[N][LG];\nint a[N];\nint last[LG];\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, q;\n cin >> n >> q;\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n for (int j = 0; j < LG; j++) {\n go[n][j] = n;\n last[j] = n;\n }\n for (int i = n - 1; i >= 0; i--) {\n for (int j = 0; j < LG; j++) {\n go[i][j] = n;\n }\n for (int j = 0; j < LG; j++) {\n if ((a[i] >> j) & 1) {\n for (int k = 0; k < LG; k++) {\n go[i][k] = min(go[i][k], go[last[j]][k]);\n }\n last[j] = i;\n go[i][j] = i;\n }\n }\n }\n for (int i = 0; i < q; i++) {\n int x, y;\n cin >> x >> y;\n x--, y--;\n bool good = false;\n for (int j = 0; j < LG; j++) {\n good |= (((a[y] >> j) & 1) && go[x][j] <= y);\n }\n cout << (good ? \"Shi\" : \"Fou\") << '\\n';\n }\n}"
|
1168
|
D
|
Anagram Paths
|
Toad Ilya has a rooted binary tree with vertex $1$ being the root. A tree is a connected graph without cycles. A tree is rooted if one vertex is selected and called the root. A vertex $u$ is a child of a vertex $v$ if $u$ and $v$ are connected by an edge and $v$ is closer to the root than $u$. A leaf is a non-root vertex that has no children.
In the tree Ilya has each vertex has \textbf{at most two} children, and each edge has some character written on it. The character can be a lowercase English letter or the question mark '?'.
Ilya will $q$ times update the tree a bit. Each update will replace exactly one character on some edge. After each update Ilya needs to find if the tree is anagrammable and if yes, find its anagramnity for each letter. Well, that's difficult to explain, but we'll try.
To start with, a string $a$ is an anagram of a string $b$ if it is possible to rearrange letters in $a$ (without changing the letters itself) so that it becomes $b$. For example, the string "fortyfive" is an anagram of the string "overfifty", but the string "aabb" is not an anagram of the string "bbba".
Consider a path from the root of the tree to a leaf. The characters on the edges on this path form a string, we say that this string is associated with this leaf. The tree is anagrammable if and only if it is possible to replace each question mark with a lowercase English letter so that for all pair of leaves the associated strings for these leaves are anagrams of each other.
If the tree is anagrammable, then its anagramnity for the letter $c$ is the maximum possible number of letters $c$ in a string associated with some leaf in a valid replacement of all question marks.
Please after each update find if the tree is anagrammable and if yes, find the $\sum{f(c) \cdot ind(c)}$ for all letters $c$, where $f(c)$ is the anagramnity for the letter $c$, and $ind(x)$ is the index of this letter in the alphabet ($ind($"a"$) = 1$, $ind($"b"$) = 2$, ..., $ind($"z"$) = 26$).
|
Ok, let's make some useless (ha-ha, in fact not) observation at first, obviously, all leaves must have the same depth. Now, I will define the criterion for the tree to be good. Let $f(v,x)$ be the largest number of characters $x$ that contained on edges of some path from vertex $v$ to the leaf, and $len_v$ be the length of a path from $v$ to the leaf. Lemma: tree is good iff for each vertex $\sum{f(v,x)} \leq len_v$. Obviously, if the tree is good $\sum{f(v,x)} \leq len_v$ for each vertex because else you just don't have enough "space" in the subtree of the vertex to contain all required characters. Why is it criterion? If for each vertex it is satisfied, from the root you can find some suitable characters on the edges from it, and then it is easy to see that you can restore the children by induction. Ok, with this knowledge how to solve the problem? Maybe some spooky tree data structures will help us?... Yup, you can do it with the "Dynamic tree DP technique" with HLD, and you will get the solution in $O(n \log^2 n)$ even for not a binary tree. But it is not very easy to realize it :) Let's remember that all leaves must have the same depth, so I will give you another Lemma! Lemma: if you will "compress" all vertices with one son in the tree, where all leaves have an equal depth, then the depth of this tree will be $O(\sqrt{n})$. Why? let $a_i$ be the number of vertices on the depth $i$, then $a_i \geq a_{i-1}$ for each $i \leq h$ as each vertex at the depth $i-1$ should have at least one son, and you have $\sum{a_i}=n$, so there are $O( \sqrt{n})$ distinct values among them, so almost all (without some $O(\sqrt{n})$ values) $i$ has $a_i = a_{i-1}$ (which means that all vertices at the depth $i-1$ has exactly one son). So with this knowledge, you can "compress" the tree as I described, and after each query just go up from the end of the changed edge and recalculate the DP. Of course, each edge now will have several characters on it, so you should maintain a counter in each edge, but it is more a realization aspect.
|
[
"dp",
"implementation",
"trees"
] | 3,000
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, q;\n cin >> n >> q;\n vector <int> par(n), dep(n), deg(n), up(n), up_ch(n), len(n), sum(n), ch(n);\n vector <vector <int> > g(n), dp(n, vector <int> (26)), cnt(n, vector <int> (26));\n for (int i = 1; i < n; i++) {\n int p;\n char c;\n cin >> p >> c;\n p--;\n dep[i] = dep[p] + 1;\n deg[p]++;\n par[i] = p;\n ch[i] = c;\n }\n for (int i = n - 1; i; i--) {\n if (len[par[i]] && len[par[i]] != len[i] + 1) {\n for (int j = 0; j < q; j++) {\n cout << \"Fou\\n\";\n }\n return 0;\n }\n len[par[i]] = len[i] + 1;\n }\n for (int i = 0; i < n; i++) {\n if (deg[par[i]] > 1 || !par[i]) {\n up[i] = par[i];\n up_ch[i] = i;\n }\n else {\n up[i] = up[par[i]];\n up_ch[i] = up_ch[par[i]];\n }\n if (i && ch[i] != '?') {\n cnt[up_ch[i]][ch[i] - 'a']++;\n }\n }\n int bad = 0;\n for (int i = n - 1; i; i--) {\n if (deg[i] != 1) {\n for (int j = 0; j < 26; j++) {\n dp[up[i]][j] = max(dp[up[i]][j], dp[i][j] + cnt[up_ch[i]][j]);\n }\n g[up[i]].push_back(i);\n }\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < 26; j++) {\n sum[i] += dp[i][j];\n }\n if (sum[i] > len[i]) {\n bad++;\n }\n }\n up[0] = -1;\n auto upd = [&] (int v, char c) {\n if (c == '?') {\n return;\n }\n c -= 'a';\n for (; ~v; v = up[v]) {\n if (sum[v] > len[v]) {\n bad--;\n }\n sum[v] -= dp[v][c];\n dp[v][c] = 0;\n for (int to : g[v]) {\n dp[v][c] = max(dp[v][c], dp[to][c] + cnt[up_ch[to]][c]);\n }\n sum[v] += dp[v][c];\n if (sum[v] > len[v]) {\n bad++;\n }\n }\n };\n for (int i = 0; i < q; i++) {\n int v;\n char c;\n cin >> v >> c;\n v--;\n if (ch[v] != '?') {\n cnt[up_ch[v]][ch[v] - 'a']--;\n upd(up[v], ch[v]);\n }\n ch[v] = c;\n if (ch[v] != '?') {\n cnt[up_ch[v]][ch[v] - 'a']++;\n upd(up[v], ch[v]);\n }\n if (bad) {\n cout << \"Fou\\n\";\n } else {\n cout << \"Shi \";\n int val = 0;\n for (int i = 0; i < 26; i++) {\n val += (dp[0][i] + len[0] - sum[0]) * (i + 1);\n }\n cout << val << '\\n';\n }\n }\n}"
|
1168
|
E
|
Xor Permutations
|
Toad Mikhail has an array of $2^k$ integers $a_1, a_2, \ldots, a_{2^k}$.
Find two permutations $p$ and $q$ of integers $0, 1, \ldots, 2^k-1$, such that $a_i$ is equal to $p_i \oplus q_i$ for all possible $i$, or determine there are no such permutations. Here $\oplus$ denotes the bitwise XOR operation.
|
If xor of all elements of the array is not zero, then the answer is "Fou". Now let's assume that you have two permutations $p,q$ and when xored they are producing an array $a$. I will show that it is possible to change any two elements $a_i, a_j$ to elements $a_i \oplus x, a_j \oplus x$ with some transformation of the given permutations. Let's change $a_i, a_j$ to $a_i \oplus x, a_j \oplus x$. Let's find such $t$, that $a_i \oplus q_i = p_t$. If $t$ is equal to $i$ or $i+1$, then you can make some swaps to "fix" the array, to make it satisfy $a_i = p_i \oplus q_i$ for all $i$. Now you have: $p_t, q_t, a_t$ at position $t$ $p_i, q_i, a_i$ at position $i$ $p_j, q_j, a_j$ at position $j$ Let's make some swaps at these positions to transform it to: $p_i, q_j, a_t$ at position $t$ $p_t, q_i, a_i$ at position $i$ $p_j, q_t, a_j$ at position $j$ Now, after you make these transition, you will have $p_i \oplus q_i = a_i$, and now you need to "fix" positions $t$ and $j$, and just process recursively. Lemma: this thing will end in $O(n)$ operations. ______________________________________________________________________________________ Proof: Let's assume that at some two moments you have $p_t$ coincided with some $p_t$ earlier, let's check the first that moment. For simplicity of the proof, let's assume that numbers are moving like that: $p_t, q_i, a_i$ at position $t$ $p_i, q_j, a_t$ at position $i$ $p_j, q_t, a_j$ at position $j$ (So $p_i$'s are constant, and $a_i$'s are changing now. Obviously, it is equivalent to the previous transformation) Now, assume, that you had numbers: $p_t, q_t, a_t$ at position $t$ $p_i, q_x, a_y$ at position $i$ (1) $p_j, q_y, a_j$ at position $j$ (2) and then, you will make one transformation, and everything will go to: $p_t, q_x, a_y$ at position $t$ $p_i, q_y, a_t$ at position $i$ $p_j, q_t, a_j$ at position $j$ After that, before you will be stuck into described earlier equality: $p_t, q_x, a_y$ at position $t$ $p_i, q_v, a_u$ at position $i$ $p_j, q_u, a_j$ at position $j$ And after swapping with $t$ $p_i, q_u, a_y$ at position $i$ (3) $p_j, q_x, a_j$ at position $j$ (4) Let's look at (1), (2) and (3), (4) From (1), (2), we can see $q_y = p_i \oplus q_x \oplus a_y \oplus p_j \oplus a_j$ From (3), (4), we can see $q_u = p_i \oplus a_y \oplus p_j \oplus q_x \oplus a_j$ So $q_y = q_u$, but $u \neq y$, so it is a contradiction, because $q$ is a permutation.. _________________________________________________________________________________ Ok, using these operations it is pretty simple to get an arbitrary array. Just start with $0,0,\ldots,0$ (two equal permutations). And then make $a_i = b_i, a_{i+1} = a_{i+1} \oplus (a_i \oplus b_i)$, at the end you will have one element rest and it will be good because initially xor was zero.
|
[
"constructive algorithms",
"math"
] | 3,100
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int k;\n cin >> k;\n int n = (1 << k);\n int xr = 0;\n vector <int> b(n);\n for (int &x : b) {\n cin >> x;\n xr ^= x;\n }\n if (xr) {\n cout << \"Fou\\n\";\n return 0;\n } else {\n cout << \"Shi\\n\";\n vector <int> p(n), q(n), ind(n), a(n);\n for (int i = 0; i < n; i++) {\n p[i] = i;\n q[i] = i;\n ind[i] = i;\n }\n function<void(int, int)> fix = [&](int i, int j) { \n if (q[i] == (p[i] ^ a[i])) {\n return;\n } else if (q[i] == (p[i] ^ a[j])) {\n swap(q[i], q[j]);\n swap(p[i], p[j]);\n swap(ind[p[i]], ind[p[j]]);\n } else if (q[i] == (p[j] ^ a[i])) {\n swap(p[i], p[j]);\n swap(ind[p[i]], ind[p[j]]);\n } else if (q[i] == (p[j] ^ a[j])) {\n swap(q[i], q[j]);\n } else {\n int t = ind[a[i] ^ q[i]];\n swap(ind[p[t]], ind[p[i]]);\n swap(p[t], p[i]);\n swap(q[t], q[i]);\n swap(q[t], q[j]);\n swap(q[i], q[j]);\n fix(t, j);\n }\n };\n for (int i = 0; i + 1 < n; i++) {\n a[i + 1] ^= (a[i] ^ b[i]);\n a[i] = b[i];\n fix(i, i + 1);\n }\n for (int i = 0; i < n; i++) {\n cout << p[i] << ' ';\n }\n cout << '\\n';\n for (int i = 0; i < n; i++) {\n cout << q[i] << ' ';\n }\n cout << '\\n';\n }\n}"
|
1169
|
A
|
Circle Metro
|
The circle line of the Roflanpolis subway has $n$ stations.
There are two parallel routes in the subway. The first one visits stations in order $1 \to 2 \to \ldots \to n \to 1 \to 2 \to \ldots$ (so the next stop after station $x$ is equal to $(x+1)$ if $x < n$ and $1$ otherwise). The second route visits stations in order $n \to (n-1) \to \ldots \to 1 \to n \to (n-1) \to \ldots$ (so the next stop after station $x$ is equal to $(x-1)$ if $x>1$ and $n$ otherwise). All trains depart their stations simultaneously, and it takes exactly $1$ minute to arrive at the next station.
Two toads live in this city, their names are Daniel and Vlad.
Daniel is currently in a train of the \textbf{first} route at station $a$ and will exit the subway when his train reaches station $x$.
Coincidentally, Vlad is currently in a train of the \textbf{second} route at station $b$ and he will exit the subway when his train reaches station $y$.
Surprisingly, all numbers $a,x,b,y$ are distinct.
Toad Ilya asks you to check if Daniel and Vlad will ever be at the same station at the same time during their journey. In other words, check if there is a moment when their trains stop at the same station. Note that this includes the moments when Daniel or Vlad enter or leave the subway.
|
Straightforward simulation. Check the intended solutions: Simulation
|
[
"implementation",
"math"
] | 900
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, a, x, b, y;\n cin >> n >> a >> x >> b >> y;\n a--, x--, b--, y--;\n while (true) {\n if (a == b) {\n cout << \"YES\\n\";\n return 0;\n }\n if (a == x || b == y) {\n break;\n }\n a = (a + 1) % n;\n b = (b - 1 + n) % n;\n }\n cout << \"NO\\n\";\n}"
|
1169
|
B
|
Pairs
|
Toad Ivan has $m$ pairs of integers, each integer is between $1$ and $n$, inclusive. The pairs are $(a_1, b_1), (a_2, b_2), \ldots, (a_m, b_m)$.
He asks you to check if there exist two integers $x$ and $y$ ($1 \leq x < y \leq n$) such that in each given pair at least one integer is equal to $x$ or $y$.
|
One of $x,y$ is obviously one of $a_1, b_1$. For example, let's fix who is $x$ from the first pair. Then you need to check that there exists some $y$ such that all pairs that don't contain $x$, contain $y$. For this, you can remember in the array for each value how many pairs that don't contain $x$ contain this value, and then you need to check that in the array there exists some value that is equal to the number of pairs left.
|
[
"graphs",
"implementation"
] | 1,500
|
"#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#ifdef ONPC\n mt19937 rnd(228);\n#else\n mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\nint main() {\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, m;\n cin >> n >> m;\n vector <pair <int, int> > pairs;\n for (int i = 0; i < m; i++) {\n int a, b;\n cin >> a >> b;\n a--, b--;\n pairs.emplace_back(a, b);\n }\n vector <int> values = {pairs[0].first, pairs[0].second};\n for (int x : values) {\n vector <int> val(n);\n int all = 0;\n for (auto c : pairs) {\n if (c.first != x && c.second != x) {\n val[c.first]++, val[c.second]++, all++;\n }\n }\n if (*max_element(val.begin(), val.end()) == all) {\n cout << \"YES\\n\";\n return 0;\n }\n }\n cout << \"NO\\n\";\n}"
|
1172
|
A
|
Nauuo and Cards
|
Nauuo is a girl who loves playing cards.
One day she was playing cards but found that the cards were mixed with some empty ones.
There are $n$ cards numbered from $1$ to $n$, and they were mixed with another $n$ empty cards. She piled up the $2n$ cards and drew $n$ of them. The $n$ cards in Nauuo's hands are given. The remaining $n$ cards in the pile are also given in the order from top to bottom.
In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.
Nauuo wants to make the $n$ numbered cards piled up in increasing order (the $i$-th card in the pile from top to bottom is the card $i$) as quickly as possible. Can you tell her the minimum number of operations?
|
First, try to finish it without playing any empty cards. If that's not possible, the best choice is to play several empty cards in a row, then play from $1$ to $n$. For a card $i$, suppose that it is in the $p_i$-th position in the pile ($p_i=0$ if it is in the hand), you have to play at least $p_i - i + 1$ empty cards. So the answer will be $\max\{p_i-i+1+n\}$.
|
[
"greedy",
"implementation"
] | 1,800
|
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 200010;
int n, a[N], b[N], p[N], ans;
int main()
{
int i, j;
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
scanf("%d", a + i);
p[a[i]] = 0;
}
for (i = 1; i <= n; ++i)
{
scanf("%d", b + i);
p[b[i]] = i;
}
if (p[1])
{
for (i = 2; p[i] == p[1] + i - 1; ++i);
if (p[i - 1] == n)
{
for (j = i; j <= n && p[j] <= j - i; ++j);
if (j > n)
{
printf("%d", n - i + 1);
return 0;
}
}
}
for (i = 1; i <= n; ++i) ans = max(ans, p[i] - i + 1 + n);
printf("%d", ans);
return 0;
}
|
1172
|
B
|
Nauuo and Circle
|
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $n$ \textbf{distinct} points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of $n$ elements. A permutation of $n$ elements is a sequence of integers $p_1,p_2,\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once.
After a permutation is chosen Nauuo draws the $i$-th node in the $p_i$-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $998244353$, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which $n$ points on the circle are chosen.
|
First, if we choose a node as the root, then each subtree must be in a continuous arc on the circle. Then, we can use DP to solve this problem. Let $f_u$ be the number of plans to draw the subtree of $u$, then $f_u=(|son(u)|+[u\ne root])!\prod\limits_{v\in son(u)}f_v$ - choose a position for each subtree and then $u$ itself, then draw the subtrees. However, instead of choosing the position of the root, we suppose the root is on a certain point on the circle, then rotate the circle, thus get the answer: $nf_{root}$. In fact, we don't have to write a DP, the answer is $n$ times the product of the factorial of each node's degree ($n\prod\limits_{i = 1}^ndegree[i]!$).
|
[
"combinatorics",
"dfs and similar",
"dp",
"trees"
] | 1,900
|
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const int N = 200010;
const int mod = 998244353;
int n, ans, d[N];
int main()
{
int i, u, v;
scanf("%d", &n);
ans = n;
for (i = 1; i < n; ++i)
{
scanf("%d%d", &u, &v);
ans = (ll) ans * (++d[u]) % mod * (++d[v]) % mod;
}
cout << ans;
return 0;
}
|
1172
|
C2
|
Nauuo and Pictures (hard version)
|
\textbf{The only difference between easy and hard versions is constraints.}
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes $n$ pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $i$-th picture has a non-negative weight $w_i$, and the probability of the $i$-th picture being displayed is $\frac{w_i}{\sum_{j=1}^nw_j}$. That is to say, the probability of a picture to be displayed is proportional to its weight.
However, Nauuo discovered that some pictures she does not like were displayed too often.
To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $1$ to its weight; otherwise, she would subtract $1$ from its weight.
Nauuo will visit the website $m$ times. She wants to know the expected weight of each picture after all the $m$ visits modulo $998244353$. Can you help her?
The expected weight of the $i$-th picture can be denoted by $\frac {q_i} {p_i}$ where $\gcd(p_i,q_i)=1$, you need to print an integer $r_i$ satisfying $0\le r_i<998244353$ and $r_i\cdot p_i\equiv q_i\pmod{998244353}$. It can be proved that such $r_i$ exists and is unique.
|
First, let's focus on a single picture with weight $w$ which Nauuo likes, so we only have to know the sum of the weights of the pictures Nauuo likes ($SA=\sum\limits_{i=1}^nw_i[a_i=1]$) and the sum of the disliked ones ($SB=\sum\limits_{i=1}^nw_i[a_i=0]$) instead of all the $n$ weights. Then, we can use DP to solve this problem. Let $f_w[i][j][k]$ be the expected weight of a picture Nauuo likes with weight $w$ after another $i$ visits since $SA=j$ and $SB=k$. Obviously, $f_w[0][j][k]=w$. The state transition: The next visit displays the picture we focus on. Probaility: $\frac w{j+k}$. Lead to: $f_{w+1}[i-1][j+1][k]$. The next visit displays the picture we focus on. Probaility: $\frac w{j+k}$. Lead to: $f_{w+1}[i-1][j+1][k]$. The next visit displays a picture Nauuo likes but is not the one we focus on. Probaility: $\frac{j-w}{j+k}$. Lead to: $f_w[i-1][j+1][k]$. The next visit displays a picture Nauuo likes but is not the one we focus on. Probaility: $\frac{j-w}{j+k}$. Lead to: $f_w[i-1][j+1][k]$. The next visit displays a picture Nauuo doesn't like. Probaility: $\frac k{j+k}$. Lead to: $f_w[i-1][j][k-1]$. The next visit displays a picture Nauuo doesn't like. Probaility: $\frac k{j+k}$. Lead to: $f_w[i-1][j][k-1]$. So, $f_w[i][j][k]=\frac w{j+k}f_{w+1}[i-1][j+1][k]+\frac{j-w}{j+k}f_w[i-1][j+1][k]+\frac k{j+k}f_w[i-1][j][k-1]$. Let $g_w[i][j][k]$ be the expected weight of a picture Nauuo doesn't like with weight $w$ after another $i$ visits since $SA=j$ and $SB=k$. The state transition is similar. Note that $i,\,j,\,k,\,m$ have some relation. In fact we can let $f'_w[i][j]$ be $f_w[m-i-j][SA+i][SB-j]$ ($SA$ and $SB$ are the initial ones here). But up to now, we can only solve the easy version. To solve the hard version, let's introduce a lemma: $f_w[i][j][k]=wf_1[i][j][k]$ Proof: Obviously, this is true when $i=0$. Then, suppose we have already proved $f_w[i-1][j][k]=wf_1[i-1][j][k]$. $\begin{aligned}f_1[i][j][k]&=\frac 1{j+k}f_2[i-1][j+1][k]+\frac{j-1}{j+k}f_1[i-1][j+1][k]+\frac k{j+k}f_1[i-1][j][k-1]\\&=\frac2{j+k}f_1[i-1][j+1][k]+\frac{j-1}{j+k}f_1[i-1][j+1][k]+\frac k{j+k}f_1[i-1][j][k-1]\\&=\frac{j+1}{j+k}f_1[i-1][j+1][k]+\frac k{j+k}f_1[i-1][j][k-1]\end{aligned}$ $\begin{aligned}f_w[i][j][k]&=\frac w{j+k}f_{w+1}[i-1][j+1][k]+\frac{j-w}{j+k}f_w[i-1][j+1][k]+\frac k{j+k}f_w[i-1][j][k-1]\\&=\frac{w(w+1)}{j+k}f_1[i-1][j+1][k]+\frac{w(j-w)}{j+k}f_1[i-1][j+1][k]+\frac {wk}{j+k}f_1[i-1][j][k-1]\\&=\frac{w(j+1)}{j+k}f_1[i-1][j+1][k]+\frac {wk}{j+k}f_1[i-1][j][k-1]\\&=wf_1[i][j][k]\end{aligned}$ Also, a brief but not so strict proof: the increment in each step is proportional to the expectation. So, we only have to calculate $f_1[i][j][k]$ ($f'_1[i][j]$). In conclusion: $f'_1[i][j]=1\ (i+j=m)$ $f'_1[i][j]=\frac{SA+i+1}{SA+SB+i-j}f'_1[i+1][j]+\frac{SB-j}{SA+SB+i-j}f'_1[i][j+1]\ (i+j<m)$ $g'_1[i][j]=1\ (i+j=m)$ $g'_1[i][j]=\frac{SA+i}{SA+SB+i-j}g'_1[i+1][j]+\frac{SB-j-1}{SA+SB+i-j}g'_1[i][j+1]\ (i+j<m)$ If $a_i=1$, the expected weight of the $i$-th picture is $w_if'_1[0][0]$, otherwise, the expected weight is $w_ig'_1[0][0]$. Last question: how to calculate the result modulo $998244353$? If you don't know how, please read the wiki to learn it. You can calculate and store all the $\mathcal O(m)$ inverses at first, then you can get an $\mathcal O(n+m^2+m\log p)$ solution instead of $\mathcal O(n+m^2\log p)$ ($p=998244353$ here).
|
[
"dp",
"probabilities"
] | 2,600
|
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 200010;
const int M = 3010;
const int mod = 998244353;
int qpow(int x, int y) //calculate the modular multiplicative inverse
{
int out = 1;
while (y)
{
if (y & 1) out = (ll) out * x % mod;
x = (ll) x * x % mod;
y >>= 1;
}
return out;
}
int n, m, a[N], w[N], f[M][M], g[M][M], inv[M << 1], sum[3];
int main()
{
int i,j;
scanf("%d%d", &n, &m);
for (i = 1; i <= n; ++i) scanf("%d", a + i);
for (i = 1; i <= n; ++i)
{
scanf("%d", w + i);
sum[a[i]] += w[i];
sum[2] += w[i];
}
for (i = max(0, m - sum[0]); i <= 2 * m; ++i) inv[i] = qpow(sum[2] + i - m, mod - 2);
for (i = m; i >= 0; --i)
{
f[i][m - i] = g[i][m - i] = 1;
for (j = min(m - i - 1, sum[0]); j >= 0; --j)
{
f[i][j] = ((ll) (sum[1] + i + 1) * f[i + 1][j] + (ll) (sum[0] - j) * f[i][j + 1]) % mod * inv[i - j + m] % mod;
g[i][j] = ((ll) (sum[1] + i) * g[i + 1][j] + (ll) (sum[0] - j - 1) * g[i][j + 1]) % mod * inv[i - j + m] % mod;
}
}
for (i = 1; i <= n; ++i) printf("%d\n", int((ll) w[i] * (a[i] ? f[0][0] : g[0][0]) % mod));
return 0;
}
|
1172
|
D
|
Nauuo and Portals
|
Nauuo is a girl who loves playing games related to portals.
One day she was playing a game as follows.
In an $n\times n$ grid, the rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.
A portal is \textbf{a pair of} doors. You can travel from one of them to another without changing your direction. More formally, if you walk into a cell with a door, you will teleport to the cell with the other door of the same portal and then walk into the next cell facing the original direction. There \textbf{can not} be more than one doors in a single cell.
The "next cell" is the nearest cell in the direction you are facing. For example, if you are facing bottom, the next cell of $(2,5)$ is $(3,5)$.
If you walk into a cell without a door, you must walk into the next cell after that without changing the direction. If the next cell does not exist, you must exit the grid.
You have to set some (possibly zero) portals in the grid, so that if you walk into $(i,1)$ facing right, you will eventually exit the grid from $(r_i,n)$, if you walk into $(1, i)$ facing bottom, you will exit the grid from $(n,c_i)$.
It is guaranteed that both $r_{1..n}$ and $c_{1..n}$ are \textbf{permutations} of $n$ elements. A permutation of $n$ elements is a sequence of numbers $p_1,p_2,\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once.
She got confused while playing the game, can you help her to find a solution?
|
Consider this problem: the person in $(i,1)$ facing right is numbered $a_i$, the person in $(1,i)$ facing bottom is numbered $b_i$. The person numbered $p_i$ has to exit the grid from $(i,n)$, the person numbered $q_i$ has to exit the grid from $(n,i)$. The original problem can be easily transferred to this problem. And now let's transfer it into an $(n-1)\times (n-1)$ subproblem by satisfying the requirement of the first row and the first column. If $a_1=p_1$ and $b_1=q_1$, you can simply do nothing and get an $(n-1)\times (n-1)$ subproblem. Otherwise, you can set a portal consisting of two doors in $(x,1)$ and $(1,y)$ where $a_x=p_1$ and $b_y=q_1$. Swap $a_1$ and $a_x$, $b_1$ and $b_y$, then you will get an $(n-1)\times(n-1)$ subproblem. Then, you can solve the problem until it changes into a $1\times1$ one. This problem can be solved in $\mathcal O(n)$, but the checker needs $\mathcal O(n^2)$.
|
[
"constructive algorithms"
] | 2,900
|
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1010;
struct Portal
{
int x, y, p, q;
Portal(int _x, int _y, int _p, int _q): x(_x), y(_y), p(_p), q(_q) {}
};
vector<Portal> ans;
int n, a[N], b[N], c[N], d[N], ra[N], rb[N], rc[N], rd[N];
int main()
{
int i;
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
scanf("%d", b + i);
rb[b[i]] = i;
}
for (i = 1; i <= n; ++i)
{
scanf("%d", a + i);
ra[a[i]] = i;
}
for (i = 1; i <= n; ++i) c[i] = d[i] = rc[i] = rd[i] = i;
for (i = 1; i < n; ++i)
{
if (c[i] == ra[i] && d[i] == rb[i]) continue;
ans.push_back(Portal(i, rc[ra[i]], rd[rb[i]], i));
int t1 = c[i];
int t2 = d[i];
swap(c[i], c[rc[ra[i]]]);
swap(d[i], d[rd[rb[i]]]);
swap(rc[ra[i]], rc[t1]);
swap(rd[rb[i]], rd[t2]);
}
printf("%d\n", ans.size());
for (auto k : ans) printf("%d %d %d %d\n", k.x, k.y, k.p, k.q);
return 0;
}
|
1172
|
E
|
Nauuo and ODT
|
Nauuo is a girl who loves traveling.
One day she went to a tree, Old Driver Tree, literally, a tree with an old driver on it.
The tree is a connected graph consisting of $n$ nodes and $n-1$ edges. Each node has a color, and Nauuo will visit the ODT through a simple path on the tree in the old driver's car.
Nauuo wants to visit see more different colors in her journey, but she doesn't know which simple path she will be traveling on. So, she wants to calculate the sum of the numbers of different colors on all different paths. Can you help her?
What's more, the ODT is being redecorated, so there will be $m$ modifications, each modification will change a single node's color. Nauuo wants to know the answer after each modification too.
Note that in this problem, we consider the simple path from $u$ to $v$ and the simple path from $v$ to $u$ as two different simple paths if and only if $u\ne v$.
|
For each color, we can try to maintain the number of simple paths that do not contain such color. If we can maintain such information, we can easily calculate the number of simple paths that contain a certain color, thus get the answer. For each color, we delete all nodes that belong to such color, thus splitting the tree into some clusters (here we define a "cluster" as a connected subgraph of the original tree). By maintaining $\sum\text{cluster size}^2$, we can get the number of simple paths that do not contain such color. For each color we try to maintain the same information, add them together, and get the answer. So now the problem is: a white tree reverse the color of a node ( white <-> black ) reverse the color of a node ( white <-> black ) output $\sum\text{cluster size}^2$ output $\sum\text{cluster size}^2$ This problem can be solved by many data structures like top tree, link/cut tree or heavy path decomposition. Let's use the link/cut tree for example. You can maintain the size of each subtree and the sum of $\text{size}^2$ of each node's sons. Link/cut one node with its father (choose a node as the root and make the tree a rooted-tree first) when its color changes. In this way, the real clusters are the ones that are still connected after deleting the top node of a cluster in the link/cut tree. Update $\sum\text{cluster size}^2$ while linking/cutting. link: cut:
|
[
"data structures"
] | 3,300
|
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
const int N = 400010;
struct Node
{
int fa, ch[2], siz, sizi;
ll siz2i;
ll siz2() { return (ll) siz * siz; }
} t[N];
bool nroot(int x);
void rotate(int x);
void Splay(int x);
void access(int x);
int findroot(int x);
void link(int x);
void cut(int x);
void pushup(int x);
void add(int u, int v);
void dfs(int u);
int head[N], nxt[N << 1], to[N << 1], cnt;
int n, m, c[N], f[N];
ll ans, delta[N];
bool bw[N];
vector<int> mod[N][2];
int main()
{
int i, j, u, v;
ll last;
scanf("%d%d", &n, &m);
for (i = 1; i <= n; ++i)
{
scanf("%d", c + i);
mod[c[i]][0].push_back(i);
mod[c[i]][1].push_back(0);
}
for (i = 1; i <= n + 1; ++i) t[i].siz = 1;
for (i = 1; i < n; ++i)
{
scanf("%d%d", &u, &v);
add(u, v);
add(v, u);
}
for (i = 1; i <= m; ++i)
{
scanf("%d%d", &u, &v);
mod[c[u]][0].push_back(u);
mod[c[u]][1].push_back(i);
c[u] = v;
mod[v][0].push_back(u);
mod[v][1].push_back(i);
}
f[1] = n + 1;
dfs(1);
for (i = 1; i <= n; ++i) link(i);
for (i = 1; i <= n; ++i)
{
if (!mod[i][0].size())
{
delta[0] += (ll)n * n;
continue;
}
if (mod[i][1][0])
{
delta[0] += (ll)n * n;
last = (ll)n * n;
} else
last = 0;
for (j = 0; j < mod[i][0].size(); ++j)
{
u = mod[i][0][j];
if (bw[u] ^= 1)
cut(u);
else
link(u);
if (j == mod[i][0].size() - 1 || mod[i][1][j + 1] != mod[i][1][j])
{
delta[mod[i][1][j]] += ans - last;
last = ans;
}
}
for (j = mod[i][0].size() - 1; ~j; --j)
{
u = mod[i][0][j];
if (bw[u] ^= 1)
cut(u);
else
link(u);
}
}
ans = (ll) n * n * n;
for (i = 0; i <= m; ++i)
{
ans -= delta[i];
printf("%I64d ", ans);
}
return 0;
}
bool nroot(int x) { return x == t[t[x].fa].ch[0] || x == t[t[x].fa].ch[1]; }
void rotate(int x)
{
int y = t[x].fa;
int z = t[y].fa;
int k = x == t[y].ch[1];
if (nroot(y)) t[z].ch[y == t[z].ch[1]] = x;
t[x].fa = z;
t[y].ch[k] = t[x].ch[k ^ 1];
t[t[x].ch[k ^ 1]].fa = y;
t[x].ch[k ^ 1] = y;
t[y].fa = x;
pushup(y);
pushup(x);
}
void Splay(int x)
{
while (nroot(x))
{
int y = t[x].fa;
int z = t[y].fa;
if (nroot(y)) (x == t[y].ch[1]) ^ (y == t[z].ch[1]) ? rotate(x) : rotate(y);
rotate(x);
}
}
void access(int x)
{
for (int y = 0; x; x = t[y = x].fa)
{
Splay(x);
t[x].sizi += t[t[x].ch[1]].siz;
t[x].sizi -= t[y].siz;
t[x].siz2i += t[t[x].ch[1]].siz2();
t[x].siz2i -= t[y].siz2();
t[x].ch[1] = y;
pushup(x);
}
}
int findroot(int x)
{
access(x);
Splay(x);
while (t[x].ch[0]) x = t[x].ch[0];
Splay(x);
return x;
}
void link(int x)
{
int y = f[x];
Splay(x);
ans -= t[x].siz2i + t[t[x].ch[1]].siz2();
int z = findroot(y);
access(x);
Splay(z);
ans -= t[t[z].ch[1]].siz2();
t[x].fa = y;
Splay(y);
t[y].sizi += t[x].siz;
t[y].siz2i += t[x].siz2();
pushup(y);
access(x);
Splay(z);
ans += t[t[z].ch[1]].siz2();
}
void cut(int x)
{
int y = f[x];
access(x);
ans += t[x].siz2i;
int z = findroot(y);
access(x);
Splay(z);
ans -= t[t[z].ch[1]].siz2();
Splay(x);
t[x].ch[0] = t[t[x].ch[0]].fa = 0;
pushup(x);
Splay(z);
ans += t[t[z].ch[1]].siz2();
}
void pushup(int x)
{
t[x].siz = t[t[x].ch[0]].siz + t[t[x].ch[1]].siz + t[x].sizi + 1;
}
void add(int u, int v)
{
nxt[++cnt] = head[u];
head[u] = cnt;
to[cnt] = v;
}
void dfs(int u)
{
int i, v;
for (i = head[u]; i; i = nxt[i])
{
v = to[i];
if (v != f[u])
{
f[v] = u;
dfs(v);
}
}
}
|
1172
|
F
|
Nauuo and Bug
|
Nauuo is a girl who loves coding.
One day she was solving a problem which requires to calculate a sum of some numbers modulo $p$.
She wrote the following code and got the verdict "Wrong answer".
She soon discovered the bug — the ModAdd function only worked for numbers in the range $[0,p)$, but the numbers in the problem may be out of the range. She was curious about the wrong function, so she wanted to know the result of it.
However, the original code worked too slow, so she asked you to help her.
You are given an array $a_1,a_2,\ldots,a_n$ and a number $p$. Nauuo will make $m$ queries, in each query, you are given $l$ and $r$, and you have to calculate the results of Sum(a,l,r,p). You can see the definition of the Sum function in the pseudocode above.
Note that the integers won't overflow in the code above.
|
At first, let's solve this problem in $\mathcal{O}(n\sqrt{n \log n})$. Let's split our array into blocks by $B$ integers, and let's find a function, $f(x) =$ which value you will get at the end of the current block if you will start with $x$. With simple induction, you can prove that this function is a piece-wise linear, and it has $\mathcal{O}(B)$ segments, so you can build it iteratively in $\mathcal{O}(B^2)$ time for each block, so the preprocessing took $\mathcal{O}(nB)$. And to answer the query, you can keep the current value of $x$ and then find with binary search by that piece-wise linear function the $f(x)$ for the current block. With a good choice of $B$, this solution will work in $\mathcal{O}(n\sqrt{n \log n})$. Ok, but then how to solve it in $\mathcal{O}(n \log + q \log^2)$? Lemma: each segment of this piece-wise linear function has length at least $p$. You can prove it with simple induction. And then, with this lemma, it is possible by two functions $f(x)$ of size $n$ and $g(x)$ of size $m$ find the new function $h(x) = g(f(x))$, in the $\mathcal{O}(n + m)$, you can do it with two pointers, similar to the previous iterative method, but adding a several points to the function each time, best way to understand it is to check the indendent solution :) We had prepared a problem similar to 1174F - Ehab and the Big Finale before that round, so we needed to prepare new problems in four days. It was in such a hurry that there are some imperfections in our round. Please accept our sincere apology.
|
[
"data structures"
] | 3,300
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
const ll inf = (ll)1e16;
int n, m, P, a[N];
ll sum[N];
vector<ll> func[N << 2];
vector<ll> merge(int l, int r, int mid, const vector<ll> &f, const vector<ll> &g) {
ll suml = sum[mid] - sum[l - 1], sumr = sum[r] - sum[mid];
vector<ll> ret(f.size() + g.size() - 1, inf);
for (int i = 0, j = 0; i < (int)f.size(); ++i) {
ll xl = f[i], xr = (i + 1 == (int)f.size() ? inf : f[i + 1] - 1), yl = xl + suml - (ll)i * P, yr = xr + suml - (ll)i * P;
while (j > 0 && g[j] > yl) --j;
while (j < (int)g.size() && (j == 0 || g[j] <= yl)) ++j;
--j;
for (; j < (int)g.size() && g[j] <= yr; ++j)
ret[i + j] = min(ret[i + j], max(xl, g[j] - suml + (ll)i * P));
}
ret[0] = -inf;
return ret;
}
void build(int u, int l, int r) {
if (l == r) {
func[u].push_back(-inf);
func[u].push_back(P - a[l]);
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
func[u] = merge(l, r, mid, func[u << 1], func[u << 1 | 1]);
}
ll query(int u, int l, int r, int ql, int qr, ll now) {
if (l >= ql && r <= qr)
return now + sum[r] - sum[l - 1] - (ll)P * (upper_bound(func[u].begin(), func[u].end(), now) - func[u].begin() - 1);
int mid = l + r >> 1;
if (qr <= mid)
return query(u << 1, l, mid, ql, qr, now);
if (ql > mid)
return query(u << 1 | 1, mid + 1, r, ql, qr, now);
return query(u << 1 | 1, mid + 1, r, ql, qr, query(u << 1, l, mid, ql, qr, now));
}
int main() {
scanf("%d%d%d", &n, &m, &P);
for (int i = 1; i <= n; ++i)
scanf("%d", a + i), sum[i] = sum[i - 1] + a[i];
build(1, 1, n);
for (int l, r; m--;) {
scanf("%d%d", &l, &r);
printf("%I64d\n", query(1, 1, n, l, r, 0));
}
return 0;
}
|
1173
|
A
|
Nauuo and Votes
|
Nauuo is a girl who loves writing comments.
One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.
It's known that there were $x$ persons who would upvote, $y$ persons who would downvote, and there were also another $z$ persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the $x+y+z$ people would vote exactly one time.
There are three different results: if there are more people upvote than downvote, the result will be "+"; if there are more people downvote than upvote, the result will be "-"; otherwise the result will be "0".
Because of the $z$ unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the $z$ persons vote, that the results are different in the two situations.
Tell Nauuo the result or report that the result is uncertain.
|
Consider the two edge cases: all the $z$ persons upvote / all the $z$ persons downvote. If the results are the same in these two cases, it is the answer. Otherwise, the result is uncertain.
|
[
"greedy"
] | 800
|
#include <iostream>
using namespace std;
const char result[4] = {'+', '-', '0', '?'};
int solve(int x, int y)
{
return x == y ? 2 : x < y;
}
int main()
{
int x, y, z;
cin >> x >> y >> z;
cout << result[solve(x + z, y) == solve(x, y + z) ? solve(x, y) : 3];
return 0;
}
|
1173
|
B
|
Nauuo and Chess
|
Nauuo is a girl who loves playing chess.
One day she invented a game by herself which needs $n$ chess pieces to play on a $m\times m$ chessboard. The rows and columns are numbered from $1$ to $m$. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.
The game's goal is to place $n$ chess pieces numbered from $1$ to $n$ on the chessboard, the $i$-th piece lies on $(r_i,\,c_i)$, while the following rule is satisfied: for all pairs of pieces $i$ and $j$, $|r_i-r_j|+|c_i-c_j|\ge|i-j|$. Here $|x|$ means the absolute value of $x$.
However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.
She wants to find the \textbf{smallest} chessboard on which she can put $n$ pieces according to the rules.
She also wonders how to place the pieces on such a chessboard. Can you help her?
|
$m\ge\left\lfloor\frac n 2\right\rfloor+1$ Consider the chess pieces $1$ and $n$. $\because\begin{cases}|r_1-r_n|+|c_1-c_n|\ge n-1\\|r_1-r_n|\le m-1\\|c_1-c_n|\le m-1\end{cases}$ $\therefore m-1+m-1\ge n-1$ $\therefore m\ge\frac{n+1}2$ $\because m\text{ is an integer}$ $\therefore m\ge\left\lfloor\frac n 2\right\rfloor+1$ $m$ can be $\left\lfloor\frac n 2\right\rfloor+1$ If we put the $i$-th piece on $(r_i,c_i)$ satisfying $r_i+c_i=i+1$, it is a feasible plan, because $|r_i-r_j|+|c_i-c_j|\ge|r_i+c_i-r_j-c_j|$.
|
[
"constructive algorithms",
"greedy"
] | 1,100
|
#include <cstdio>
using namespace std;
int main()
{
int n, i, ans;
scanf("%d", &n);
ans = n / 2 + 1;
printf("%d", ans);
for (i = 1; i <= ans; ++i) printf("\n%d 1", i);
for (i = 2; i <= n - ans + 1; ++i) printf("\n%d %d", ans, i);
return 0;
}
|
1174
|
A
|
Ehab Fails to Be Thanos
|
You're given an array $a$ of length $2n$. Is it possible to reorder it in such way so that the sum of the first $n$ elements \textbf{isn't} equal to the sum of the last $n$ elements?
|
If all elements in the array are equal, there's no solution. Otherwise, sort the array. The sum of the second half will indeed be greater than that of the first half. Another solution is to see if they already have different sums. If they do, print the array as it is. Otherwise, find any pair of different elements from different halves and swap them.
|
[
"constructive algorithms",
"greedy",
"sortings"
] | 1,000
|
"#include <iostream>\n#include <algorithm>\nusing namespace std;\nint arr[2005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<2*n;i++)\n\tscanf(\"%d\",&arr[i]);\n\tsort(arr,arr+2*n);\n\tif (arr[0]==arr[2*n-1])\n\t{\n\t\tprintf(\"-1\");\n\t\treturn 0;\n\t}\n\tfor (int i=0;i<2*n;i++)\n\tprintf(\"%d \",arr[i]);\n}"
|
1174
|
B
|
Ehab Is an Odd Person
|
You're given an array $a$ of length $n$. You can perform the following operation on it as many times as you want:
- Pick two integers $i$ and $j$ $(1 \le i,j \le n)$ such that \textbf{$a_i+a_j$ is odd}, then swap $a_i$ and $a_j$.
What is lexicographically the smallest array you can obtain?
An array $x$ is lexicographically smaller than an array $y$ if there exists an index $i$ such that $x_i<y_i$, and $x_j=y_j$ for all $1 \le j < i$. Less formally, at the first index $i$ in which they differ, $x_i<y_i$
|
Notice that you can only swap 2 elements if they have different parities. If all elements in the array have the same parity, you can't do any swaps, and the answer will just be like the input. Otherwise, let's prove you can actually swap any pair of elements. Assume you want to swap 2 elements, $a$ and $b$, and they have the same parity. There must be a third element $c$ that has a different parity. Without loss of generality, assume the array is $[a,b,c]$. You'll do the following swaps: Swap $a$ and $c$: $[c,b,a]$. Swap $b$ and $c$: $[b,c,a]$. Swap $a$ and $c$: $[b,a,c]$. In other words, you'll use $c$ as an intermediate element to swap $a$ and $b$, and it'll return to its original position afterwards! Since you can swap any pair of elements, you can always sort the array, which is the lexicographically smallest permutation. Time complexity: $O(nlog(n))$.
|
[
"sortings"
] | 1,200
|
"#include <iostream>\n#include <algorithm>\nusing namespace std;\nbool ex[2];\nint arr[100005];\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tscanf(\"%d\",&arr[i]);\n\t\tex[arr[i]%2]=1;\n\t}\n\tif (ex[0] && ex[1])\n\tsort(arr,arr+n);\n\tfor (int i=0;i<n;i++)\n\tprintf(\"%d \",arr[i]);\n}"
|
1174
|
C
|
Ehab and a Special Coloring Problem
|
You're given an integer $n$. For every integer $i$ from $2$ to $n$, assign a positive integer $a_i$ such that the following conditions hold:
- For any pair of integers $(i,j)$, if $i$ and $j$ are coprime, $a_i \neq a_j$.
- The maximal value of all $a_i$ should be minimized (that is, as small as possible).
A pair of integers is called coprime if their greatest common divisor is $1$.
|
Let's call the maximum value in the array $max$. Let the number of primes less than or equal to $n$ be called $p$. Then, $max \ge p$. That's true because a distinct number must be assigned to each prime, since all primes are coprime to each other. Now if we can construct an answer wherein $max=p$, it'll be optimal. Let's first assign a distinct number to each prime. Then, assign to every composite number the same number as any of its prime divisors. This works because for any pair of numbers $(i,j)$, $i$ is given the same number of a divisor and so is $j$, so if they're coprime (don't share a divisor), they can't be given the same number! Time complexity: $O(nlog(n))$.
|
[
"constructive algorithms",
"number theory"
] | 1,300
|
"#include <iostream>\nusing namespace std;\nint ans[100005];\nint main()\n{\n\tint n,c=0;\n\tscanf(\"%d\",&n);\n\tfor (int i=2;i<=n;i++)\n\t{\n\t\tif (!ans[i])\n\t\t{\n\t\t\tans[i]=++c;\n\t\t\tfor (int j=i;j<=n;j+=i)\n\t\t\tans[j]=ans[i];\n\t\t}\n\t\tprintf(\"%d \",ans[i]);\n\t}\n}"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.