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
⌀ |
|---|---|---|---|---|---|---|---|
1840
|
G2
|
In Search of Truth (Hard Version)
|
\textbf{The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $1000$ queries.}
This is an interactive problem.
You are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in the adjacent room and do not know either the number of sectors or their numbers. There is also an arrow that initially points to some sector. Initially, the host tells you the number of the sector to which the arrow points. After that, you can ask the host to move the arrow $k$ sectors counterclockwise or clockwise at most $1000$ times. And each time you are told the number of the sector to which the arrow points.
Your task is to determine the integer $n$ — the number of sectors in at most $1000$ queries.
It is guaranteed that $1 \le n \le 10^6$.
|
Let's sample $n$ by making $k$ random queries "+ x" where we pick $x$ each time randomly between $1$ and $10^6$ and get $k$ random integers $n_1, n_2, \dots, n_k$ in the range $[1, n]$ as the answers to the queries. Then, we can sample $n$ with $n_0 = max(n_1, n_2, \dots, n_k)$. Now, we can assume that $n_0 \le n \le n_0 + d$ for some integer $d$. Let's talk about picking the right $d$ a bit later. Now we can perform an algorithm similar to G1 solution and determine $n$ within $2 \cdot \sqrt{d}$ queries. So, we have $1000$ queries in total, meaning that $2 \cdot \sqrt{d} + k$ is approximately equals to $1000$. Thus, for each $k$ we can find optimal $d = \frac{1000 - k}{2}$, the probability that $n$ is not in the range $[n_0, n_0 + d]$ does not exceed $(\frac{n - d}{n}) ^ k$ which is less than $8.5 \cdot 10 ^{-18}$ for $k = 320$ and for each $1 \le n \le 10^6$. Therefore, by picking $k$ somewhere between $300$ and $400$, we can get a solution which passes a testcase with probability of $p \ge 1 - 10 ^{-16}$.
|
[
"constructive algorithms",
"interactive",
"math",
"meet-in-the-middle",
"probabilities"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int MAXN = 1e6 + 7;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int pos[MAXN];
const int K = 400;
const int T = 300;
int get() {
return rng() % MAXN;
}
int32_t main() {
int num;
cin >> num;
int start = num;
int cur_delta = 0;
int N0 = num;
for (int i = 0; i < K; ++i) {
int delta = get();
cout << '+' << " " << delta << endl;
cur_delta += delta;
cin >> num;
N0 = max(N0, num);
}
cout << '-' << " " << cur_delta << endl;
cin >> num;
cout << '+' << " " << N0 - 1 << endl;
cur_delta = N0 - 1;
cin >> num;
pos[num] = N0;
for (int i = 0; i < T; ++i) {
++cur_delta;
cout << '+' << " " << 1 << endl;
cin >> num;
pos[num] = N0 + i + 1;
if (num == start) {
cout << '!' << " " << N0 + i << endl;
return 0;
}
}
cout << '-' << " " << cur_delta << endl;
cin >> num;
int ans = 0;
while (true) {
cout << '-' << " " << T << endl;
ans += T;
cin >> num;
if (pos[num]) {
cout << '!' << " " << ans + pos[num] - 1 << endl;
return 0;
}
}
return 0;
}
|
1841
|
A
|
Game with Board
|
Alice and Bob play a game. They have a blackboard; initially, there are $n$ integers written on it, and each integer is equal to $1$.
Alice and Bob take turns; Alice goes first. On their turn, the player has to choose several (\textbf{at least two}) \textbf{equal} integers on the board, wipe them and write a new integer which is equal to their sum.
For example, if the board currently contains integers $\{1, 1, 2, 2, 2, 3\}$, then the following moves are possible:
- choose two integers equal to $1$, wipe them and write an integer $2$, then the board becomes $\{2, 2, 2, 2, 3\}$;
- choose two integers equal to $2$, wipe them and write an integer $4$, then the board becomes $\{1, 1, 2, 3, 4\}$;
- choose three integers equal to $2$, wipe them and write an integer $6$, then the board becomes $\{1, 1, 3, 6\}$.
If a player cannot make a move (all integers on the board are different), that player \textbf{wins the game}.
Determine who wins if both players play optimally.
|
Let's try to find a winning strategy for Alice. We can force Bob into a situation where his only action will be to make a move that leaves Alice without any legal moves, so she will win. For example, Alice can start by merging $n-2$ ones, so the board will be $\{1, 1, n-2\}$ after her move. The only possible move for Bob is to merge the remaining $1$'s, and the board becomes $\{2, n-2\}$, and Alice wins. Unfortunately, this works only for $n \ge 5$. Cases $n=2$, $n=3$, $n=4$ should be analyzed separately: if $n=2$, the only possible first move for Alice is to merge two $1$'s, and the board becomes $\{2\}$, so Bob wins; if $n=3$, Alice can transform the board either to $\{3\}$ or to $\{1,2\}$; in both cases, Bob instantly wins; if $n=4$, Alice can transform the board to $\{4\}$, $\{1,3\}$, or $\{1,1,2\}$. In the first two cases, Bob instantly wins. In the third case, the only possible response for Bob is to merge two $1$'s; the board becomes $\{2,2\}$. It's easy to see that after the only possible move for Alice, the board becomes $\{4\}$, and Bob wins. So, when $n \ge 5$, Alice wins, and when $n \le 4$, Bob wins.
|
[
"constructive algorithms",
"games"
] | 800
|
t = int(input())
for i in range(t):
n = int(input())
print('Alice' if n >= 5 else 'Bob')
|
1841
|
B
|
Keep it Beautiful
|
The array $[a_1, a_2, \dots, a_k]$ is called beautiful if it is possible to remove several (maybe zero) elements from the beginning of the array and insert all these elements to the back of the array in the same order in such a way that the resulting array is sorted in non-descending order.
In other words, the array $[a_1, a_2, \dots, a_k]$ is beautiful if there exists an integer $i \in [0, k-1]$ such that the array $[a_{i+1}, a_{i+2}, \dots, a_{k-1}, a_k, a_1, a_2, \dots, a_i]$ is sorted in non-descending order.
For example:
- $[3, 7, 7, 9, 2, 3]$ is beautiful: we can remove four first elements and insert them to the back in the same order, and we get the array $[2, 3, 3, 7, 7, 9]$, which is sorted in non-descending order;
- $[1, 2, 3, 4, 5]$ is beautiful: we can remove zero first elements and insert them to the back, and we get the array $[1, 2, 3, 4, 5]$, which is sorted in non-descending order;
- $[5, 2, 2, 1]$ is not beautiful.
\textbf{Note that any array consisting of zero elements or one element is beautiful}.
You are given an array $a$, which is initially \textbf{empty}. You have to process $q$ queries to it. During the $i$-th query, you will be given one integer $x_i$, and you have to do the following:
- if you can append the integer $x_i$ to the \textbf{back} of the array $a$ so that the array $a$ stays beautiful, you have to append it;
- otherwise, do nothing.
After each query, report whether you appended the given integer $x_i$, or not.
|
First, notice that the given operation is a cyclic shift of the array. So we can treat the array as cyclic, meaning element $n$ is a neighbor of element $1$. Let's try to rephrase the condition for the beautiful array. What does it mean for the array to be sorted? For all $j$ from $1$ to $n-1$, $a_j \le a_{j+1}$ should hold. If they do, then you can choose $i=0$ (leave the array as is). What if there are such $j$ that $a_j > a_{j+1}$? If there is only one such $j$, then we might still be able to fix the array: choose $i = j$. However, that will make a pair $a_n$ and $a_1$ cyclically shift into the array. So $a_n \le a_1$ should hold. If there are at least two such $j$ or just one but $a_n > a_1$, then we can show that it's impossible to make the array sorted. Since there are at least two pairs of neighboring elements that are not sorted, at least one of them will still be in the array after any cyclic shift. Thus, we can maintain the number of such $j$ that $a_j > a_{j+1}$ and check if $a_n > a_1$ every time if the count is exactly $1$. Overall complexity: $O(q)$ per testcase.
|
[
"implementation"
] | 1,000
|
for _ in range(int(input())):
q = int(input())
a = []
cnt = 0
for x in map(int, input().split()):
nw_cnt = cnt + (len(a) > 0 and a[-1] > x)
if nw_cnt == 0 or (nw_cnt == 1 and x <= a[0]):
a.append(x)
cnt = nw_cnt
print('1', end="")
else:
print('0', end="")
print()
|
1841
|
C
|
Ranom Numbers
|
No, not "random" numbers.
Ranom digits are denoted by uppercase Latin letters from A to E. Moreover, the value of the letter A is $1$, B is $10$, C is $100$, D is $1000$, E is $10000$.
A Ranom number is a sequence of Ranom digits. The value of the Ranom number is calculated as follows: the values of all digits are summed up, but some digits are taken with negative signs: a digit is taken with negative sign if there is a digit with a \textbf{strictly greater} value to the right of it (not necessarily immediately after it); otherwise, that digit is taken with a positive sign.
For example, the value of the Ranom number DAAABDCA is $1000 - 1 - 1 - 1 - 10 + 1000 + 100 + 1 = 2088$.
You are given a Ranom number. You can change no more than one digit in it. Calculate the maximum possible value of the resulting number.
|
There are two main solutions to this problem: dynamic programming and greedy. DP approach Reverse the string we were given, so that the sign of each digit depends on the maximum digit to the left of it (not to the right). Then, run the following dynamic programming: $dp_{i,j,k}$ is the maximum value of the number if we considered $i$ first characters, applied $k$ changes to them ($k$ is either $0$ or $1$), and the maximum character we encountered so far was $j$ ($j$ can have $5$ possible values). The transitions are fairly simple: when we consider the state $dp_{i,j,k}$, we can either leave the current character as it is, or, if $k = 0$, iterate on the replacement for the current character and use the replacement instead (then we go to the state with $k=1$). Note that this solution can also work if we can make more than one operation. This dynamic programming has $O(n \cdot A \cdot m)$ states (where $A$ is the number of different characters, and $m$ is the maximum number of changes we can make), and each state has no more than $A+1$ outgoing transitions. In this problem, $A = 5$ and $m = 1$, so this solution easily passes. Greedy approach Of course, we can try to iterate on every character and check all possible replacements for it, but quickly calculating the answer after replacement can be a bit difficult. Instead, we claim the following: it is optimal to consider at most $10$ positions to replace - the first and the last position of A, the first and the last position of B, and so on. That way, we have only $50$ different candidates for the answer, and we can check each of them in $O(n)$. How to prove that this is enough? When we replace a character, we either increase or decrease it. If we increase a character, it's easy to see why it's optimal to try only the first occurrence of each character - increasing a character may affect some characters to the left of it (turn them from positive to negative), and by picking the first occurrence of a character, we make sure that the number of characters transformed from positive to negative is as small as possible. Note that if the string has at least one character different from E, we can replace the first such character with E and increase the answer by at least $9000$ (this will be useful in the second part of the proof). Now suppose it's optimal to decrease a character, let's show that it's always optimal to choose the last occurrence of a character to decrease. Suppose we decreased a character, and it was not the last occurrence. This means that this character will be negative after replacement, so it should be negative before the replacement. The maximum value we can add to the answer by replacing a negative character with another negative character is $999$ (changing negative D to negative A), and we have already shown that we can add at least $9000$ by replacing the first non-E character in the string with E. So, if we decrease a character and it was not the last occurrence of that character, it's suboptimal.
|
[
"brute force",
"dp",
"greedy",
"math",
"strings"
] | 1,800
|
def replace_char(s, i, c):
return s[:i] + c + s[i + 1:]
def id(c):
return ord(c) - ord('A')
def evaluate(s):
t = s[::-1]
ans = 0
max_id = -1
for x in t:
i = id(x)
if max_id > i:
ans -= 10 ** i
else:
ans += 10 ** i
max_id = max(max_id, i)
return ans
t = int(input())
for i in range(t):
s = input()
candidates = []
for x in ['A', 'B', 'C', 'D', 'E']:
for y in ['A', 'B', 'C', 'D', 'E']:
if not (x in s):
continue
candidates.append(replace_char(s, s.find(x), y))
candidates.append(replace_char(s, s.rfind(x), y))
print(max(map(evaluate, candidates)))
|
1841
|
D
|
Pairs of Segments
|
Two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if there exists at least one $x$ such that $l_1 \le x \le r_1$ and $l_2 \le x \le r_2$.
An array of segments $[[l_1, r_1], [l_2, r_2], \dots, [l_k, r_k]]$ is called \textbf{beautiful} if $k$ is even, and is possible to split the elements of this array into $\frac{k}{2}$ pairs in such a way that:
- every element of the array belongs to exactly one of the pairs;
- segments in each pair intersect with each other;
- segments in different pairs do not intersect.
For example, the array $[[2, 4], [9, 12], [2, 4], [7, 7], [10, 13], [6, 8]]$ is beautiful, since it is possible to form $3$ pairs as follows:
- the first element of the array (segment $[2, 4]$) and the third element of the array (segment $[2, 4]$);
- the second element of the array (segment $[9, 12]$) and the fifth element of the array (segment $[10, 13]$);
- the fourth element of the array (segment $[7, 7]$) and the sixth element of the array (segment $[6, 8]$).
As you can see, the segments in each pair intersect, and no segments from different pairs intersect.
You are given an array of $n$ segments $[[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]]$. You have to remove the minimum possible number of elements from this array so that the resulting array is beautiful.
|
The resulting array should consist of pairs of intersecting segments, and no segments from different pairs should intersect. Let's suppose that segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect, and segments $[l_3, r_3]$ and $[l_4, r_4]$ intersect. How to check that no other pair of these four segments intersects? Instead of pairs of segments, let's work with the union of segments in each pair; no point should belong to more than one of these unions. Since segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect, their union is also a segment, and its endpoints are $[\min(l_1, l_2), \max(r_1, r_2)]$. So, if we transform each pair into a union, then the union-segments we got should not intersect. Thus, we can solve the problem as follows: for each pair of intersecting segments in the input, generate their union segment, and pick the maximum number of unions we can (these unions represent the pairs in the answer). It's quite easy to see that we won't pick a segment in two pairs simultaneously (the corresponding unions will intersect). Okay, now we have $O(n^2)$ union segments, how to pick the maximum number of them without having an intersection? This is a somewhat classical problem, there are many methods to solve it. The one used in the model solution is a greedy algorithm: sort the union segments according to their right border (in non-descending order), and pick segments greedily in sorted order, maintaining the right border of the last segment we picked. If the union segment we consider is fully after the right border of the last union we picked, then we add it to the answer; otherwise, we skip it. This approach works in $O(n^2 \log n)$.
|
[
"data structures",
"greedy",
"sortings",
"two pointers"
] | 2,000
|
#include<bits/stdc++.h>
using namespace std;
bool comp(const pair<int, int>& a, const pair<int, int>& b)
{
return a.second < b.second;
}
void solve()
{
int n;
scanf("%d", &n);
vector<pair<int, int>> s(n);
for(int i = 0; i < n; i++)
scanf("%d %d", &s[i].first, &s[i].second);
vector<pair<int, int>> pairs;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if(max(s[i].first, s[j].first) <= min(s[i].second, s[j].second))
pairs.push_back(make_pair(min(s[i].first, s[j].first), max(s[i].second, s[j].second)));
int cnt_pairs = 0;
sort(pairs.begin(), pairs.end(), comp);
int last_pos = -1;
for(auto x : pairs)
if(x.first > last_pos)
{
cnt_pairs++;
last_pos = x.second;
}
printf("%d\n", n - cnt_pairs * 2);
}
int main()
{
int t;
scanf("%d", &t);
for(int i = 0; i < t; i++) solve();
}
|
1841
|
E
|
Fill the Matrix
|
There is a square matrix, consisting of $n$ rows and $n$ columns of cells, both numbered from $1$ to $n$. The cells are colored white or black. Cells from $1$ to $a_i$ are black, and cells from $a_i+1$ to $n$ are white, in the $i$-th column.
You want to place $m$ integers in the matrix, from $1$ to $m$. There are two rules:
- each cell should contain at most one integer;
- black cells should not contain integers.
The beauty of the matrix is the number of such $j$ that $j+1$ is written in the same row, in the next column as $j$ (in the neighbouring cell to the right).
What's the maximum possible beauty of the matrix?
|
Notice that the rows of the matrix are basically independent. When we fill the matrix with integers, the values from the rows are just added together. Moreover, in a single row, the segments of white cells separated by black cells are also independent in the same way. And how to solve the problem for one segment of white cells? Obviously, put the numbers one after another. Placing a non-zero amount of integers $k$ will yield the result of $k-1$. Thus, the answer is $\sum_\limits{i=1}^s k_i - 1$, where $s$ is the number of used segments. We know that the sum of $k_i$ is just $m$. So it becomes $m + \sum_\limits{i=1}^s -1 = m - s$. So, the problem asks us to minimize the number of used segments. In order to use the smallest number of segments, we should pick the longest ones. We only have to find them. In the worst case, there are $O(n^2)$ segments of white cells in the matrix. However, we can store them in a compressed form. Since their lengths are from $1$ to $n$, we can calculate how many segments of each length there are. Look at the matrix from the bottom to the top. First, there are some fully white rows. Then some black cell appears and splits the segment of length $n$ into two segments. Maybe more if there are more black cells in that row. After that the split segments behave independently of each other. Let's record these intervals of rows each segment exists at. So, let some segment exist from row $l$ to row $r$. What does that mean? This segment appeared because of some split at row $r$. At row $l$, some black cell appeared that split the segment in parts. If we knew the $r$ for the segment, we could've saved the information about it during the event at row $l$. So, we need a data structure that can support the following operations: find a segment that covers cell $x$; erase a segment; insert a segment. Additionally, that data structure should store a value associated with a segment. Thus, let's use a map. For a segment, which is a pair of integers, store another integer - the bottommost row this segment exists. Make events $(a_i, i)$ for each column $i$. Sort them and process in a non-increasing order. During the processing of the event, find the segment this black cell splits. Save the information about this segment. Then remove it and add two new segments (or less if some are empty): the one to the left and the one to the right. At the end, for each length from $1$ to $n$, we will have the number of segments of such length. In order to fill them with $m$ integers, start with the longest segments and use as many of each length as possible. So, while having $m$ more integers to place and $\mathit{cnt}$ segments of length $\mathit{len}$, you can use $\min(\lfloor \frac{m}{\mathit{len}} \rfloor, cnt)$ of segments. Overall complexity: $O(n \log n)$ per testcase.
|
[
"data structures",
"greedy",
"math"
] | 2,200
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
struct seg{
int l, r;
};
bool operator <(const seg &a, const seg &b){
return a.l < b.l;
}
int main() {
int t;
scanf("%d", &t);
while (t--){
int n;
scanf("%d", &n);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
long long m;
scanf("%lld", &m);
map<seg, int> used;
used[{0, n}] = n;
vector<int> ord(n);
iota(ord.begin(), ord.end(), 0);
sort(ord.begin(), ord.end(), [&a](int x, int y){
return a[x] > a[y];
});
long long ans = 0;
int j = 0;
vector<long long> cnt(n + 1);
for (int i = n; i >= 0; --i){
while (j < n && a[ord[j]] >= i){
auto it = used.upper_bound({ord[j], -1});
--it;
auto tmp = it->first;
cnt[tmp.r - tmp.l] += it->second - i;
used.erase(it);
if (tmp.l != ord[j])
used[{tmp.l, ord[j]}] = i;
if (tmp.r != ord[j] + 1)
used[{ord[j] + 1, tmp.r}] = i;
++j;
}
}
for (int i = n; i > 0; --i){
long long t = min(cnt[i], m / i);
ans += t * 1ll * (i - 1);
m -= t * 1ll * i;
if (t != cnt[i] && m > 0){
ans += m - 1;
m = 0;
}
}
printf("%lld\n", ans);
}
return 0;
}
|
1841
|
F
|
Monocarp and a Strategic Game
|
Monocarp plays a strategic computer game in which he develops a city. The city is inhabited by creatures of four different races — humans, elves, orcs, and dwarves.
Each inhabitant of the city has a happiness value, which is an integer. It depends on how many creatures of different races inhabit the city. Specifically, the happiness of each inhabitant is $0$ by default; it increases by $1$ for each \textbf{other} creature of the same race and decreases by $1$ for each creature of a hostile race. Humans are hostile to orcs (and vice versa), and elves are hostile to dwarves (and vice versa).
At the beginning of the game, Monocarp's city is not inhabited by anyone. During the game, $n$ groups of creatures will come to his city, wishing to settle there. The $i$-th group consists of $a_i$ humans, $b_i$ orcs, $c_i$ elves, and $d_i$ dwarves. Each time, Monocarp can either accept the \textbf{entire} group of creatures into the city, or reject the \textbf{entire} group.
The game calculates Monocarp's score according to the following formula: $m + k$, where $m$ is the number of inhabitants in the city, and $k$ is the sum of the happiness values of all creatures in the city.
Help Monocarp earn the maximum possible number of points by the end of the game!
|
Let's denote $a, b, c, d$ as the total number of humans, orcs, elves, and dwarves taken respectively. We calculate the contribution of humans and orcs to the final score. It will be $a(a-1) + b(b-1) - 2ab + a + b$, where $a(a-1) + b(b-1)$ is the contribution to the total happiness (and thus to the final score) for an increase of $1$ happiness point per inhabitant of the same race, $-2ab$ is the contribution to the total happiness decrease by $1$ point for each inhabitant of the hostile race, and the last two terms $a + b$ is the total number of humans and orcs, which contributes to the total score. Notice that $a(a-1) + b(b-1) - 2ab + a + b = (a-b)^2$. Similarly for the contribution of elves and dwarves. So we need to maximize the expression $(a-b)^2+(c-d)^2$. Let's say we have $n$ vectors, the $i$-th of which is equal to $(x_i; y_i) = (a_i - b_i; c_i - d_i)$. Then note that we want to select some subset of vectors among the $n$ vectors $(x_i; y_i)$, a subset $A$ such that the value of the function $x^2+y^2$ is maximum for the vector $(x, y)$ equal to the sum of the vectors of subset $A$. For each subset of vectors, we get a vector equal to the sum of the elements of the subset (vectors), let's denote the set of all such vectors as $S$. Then consider the $n$ line segments at the vertices $(0; 0)$ and $(x_i; y_i)$ and calculate their Minkowski sum. We get a convex polygon. Notice that all elements of $S$ are in it by the definition of the Minkowski sum. Also, each vertex of the resulting convex polygon is in $S$, which is also known from the properties of the sum. Note that due to the upward convexity of the function we want to maximize, it is enough for us to only consider the vertices of the resulting polygon, not all vectors from $S$. Thus, using a standard algorithm for calculating the Minkowski sum, we obtain the polygon of interest and calculate the values of the function at its vertices. We take the maximum from them. The total asymptotic time complexity is $O(n\ln{n})$.
|
[
"geometry",
"sortings",
"two pointers"
] | 2,700
|
#include <iostream>
#include <algorithm>
using namespace std;
#define int long long
#define x first
#define y second
const int MAXN = 2e6 + 16;
int a[MAXN], b[MAXN];
pair<int, int> v[MAXN];
int section(pair<int, int> a) {
if (a.x > 0 && a.y >= 0)
return 0;
else if (a.x <= 0 && a.y > 0)
return 1;
else if (a.x < 0 && a.y <= 0)
return 2;
else
return 3;
}
bool cmp(pair<int, int> a, pair<int, int> b) {
if (section(a) != section(b))
return section(a) < section(b);
else
return (__int128)a.x * (__int128)b.y - (__int128)a.y * (__int128)b.x > 0;
}
void print(__int128 x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) print(x / 10);
putchar(x % 10 + '0');
}
signed main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
vector<int> t(4);
for(int j = 0; j < 4; j++)
cin >> t[j];
a[i] = t[0] - t[1];
b[i] = t[2] - t[3];
}
int it = 0;
__int128 sx = 0, sy = 0;
for (int i = 0; i < n; ++i) {
v[i << 1].x = a[it];
v[i << 1].y = b[it];
++it;
v[i << 1 ^ 1].x = -v[i << 1].x;
v[i << 1 ^ 1].y = -v[i << 1].y;
if (!v[i << 1].x && !v[i << 1].y) {
--i, --n;
continue;
}
if (v[i << 1].y < 0 || (!v[i << 1].y && v[i << 1].x < 0))
sx += v[i << 1].x, sy += v[i << 1].y;
}
sort(v, v + 2 * n, cmp);
__int128 ans = sx * sx + sy * sy;
for (int i = 0; i < 2 * n; ++i) {
sx += v[i].x;
sy += v[i].y;
ans = std::max(ans, sx * sx + sy * sy);
}
print(ans);
return 0;
}
|
1842
|
A
|
Tenzing and Tsondu
|
\begin{quote}
Tsondu always runs first! ! !
\end{quote}
Tsondu and Tenzing are playing a card game. Tsondu has $n$ monsters with ability values $a_1, a_2, \ldots, a_n$ while Tenzing has $m$ monsters with ability values $b_1, b_2, \ldots, b_m$.
Tsondu and Tenzing take turns making moves, with Tsondu going first. In each move, the current player chooses two monsters: one on their side and one on the other side. Then, these monsters will fight each other. Suppose the ability values for the chosen monsters are $x$ and $y$ respectively, then the ability values of the monsters will become $x-y$ and $y-x$ respectively. If the ability value of any monster is smaller than or equal to $0$, the monster dies.
The game ends when at least one player has no monsters left alive. The winner is the player with at least one monster left alive. If both players have no monsters left alive, the game ends in a draw.
Find the result of the game when both players play optimally.
|
Let's view it as when monsters $x$ and $y$ fight, their health changes into $\max(x-y,0)$ and $\max(y-x,0)$ respectively. So any monster with $0$ health is considered dead. Therefore, a player loses when the health of his monsters are all $0$. Notice that $\max(x-y,0)=x-\min(x,y)$ and $\max(y-x,0)=y-\min(x,y)$. Therefore, after each step, the sum of the health of monsters decrease by the same amount for both players. Therefore, we only need to know $\sum a_i$ and $\sum b_i$ to determine who wins. If $\sum a_i > \sum b_i$, Tsondu wins. Else if $\sum a_i < \sum b_i$, Tenzing wins. Else, it is a draw.
|
[
"games",
"math"
] | 800
|
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
int n, m, a[50], b[50];
long long sumA = 0, sumB = 0;
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> a[i], sumA += a[i];
for (int i = 0; i < m; i++)
cin >> b[i], sumB += b[i];
if (sumA > sumB) cout << "Tsondu\n";
if (sumA < sumB) cout << "Tenzing\n";
if (sumA == sumB) cout << "Draw\n";
}
}
|
1842
|
B
|
Tenzing and Books
|
Tenzing received $3n$ books from his fans. The books are arranged in $3$ stacks with $n$ books in each stack. Each book has a non-negative integer difficulty rating.
Tenzing wants to read some (possibly zero) books. At first, his knowledge is $0$.
To read the books, Tenzing will choose a non-empty stack, read the book on the top of the stack, and then discard the book. If Tenzing's knowledge is currently $u$, then his knowledge will become $u|v$ after reading a book with difficulty rating $v$. Here $|$ denotes the bitwise OR operation. Note that Tenzing can stop reading books whenever he wants.
Tenzing's favourite number is $x$. Can you help Tenzing check if it is possible for his knowledge to become $x$?
|
Observe the bitwise OR: if a bit of the knowledge changes to $1$, it will never become $0$. It tells us, if a book has difficulty rating $y$, and $x|y \neq x$, Tenzing will never read this book because it will change a $0$ bit in $x$ to $1$. We called a number $y$ valid if $x|y=x$. For each sequence, we can find a longest prefix of it such that all numbers in this prefix are valid. Find the bitwise OR of the three prefix and check whether it equals to $x$. Time complexity: $O(n)$ per test case. A naive approach is to enumerate the prefixes of the three stacks, which is an enumeration of $n^3$. For each stack, the bitwise OR of the prefix has at most $31$ different values (including empty prefix), because the bitwise OR of the prefix is non-decreasing, and each change will increase the number of 1s in binary. Since the number of 1s in binary cannot exceed $30$, it can be changed at most 30 times. Therefore, the enumeration is reduced to $\min(n,31)^3$. In the worst case, the time complexity is $O(\sum n * 31^2)$.
|
[
"bitmasks",
"greedy",
"math"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
int n, x, ai;
cin >> n >> x;
vector<int> pre[3];
for (int i = 0; i < 3; i++) {
int s = 0;
pre[i].push_back(s);
for (int j = 0; j < n; j++) {
cin >> ai;
if ((s | ai) != s)
s |= ai, pre[i].push_back(s);
}
}
bool ans = 0;
for (int A : pre[0]) for (int B : pre[1]) for (int C : pre[2])
ans |= (A | B | C) == x;
cout << (ans ? "YES\n" : "NO\n");
}
}
|
1842
|
C
|
Tenzing and Balls
|
\begin{quote}
Enjoy erasing Tenzing, identified as Accepted!
\end{quote}
Tenzing has $n$ balls arranged in a line. The color of the $i$-th ball from the left is $a_i$.
Tenzing can do the following operation any number of times:
- select $i$ and $j$ such that $1\leq i < j \leq |a|$ and $a_i=a_j$,
- remove $a_i,a_{i+1},\ldots,a_j$ from the array (and decrease the indices of all elements to the right of $a_j$ by $j-i+1$).
Tenzing wants to know the maximum number of balls he can remove.
|
Let us write down the original index of each range we delete. Firstly, it is impossible to delete ranges $(a,c)$ and $(b,d)$ where $a<b<c<d$. Secondly, if we delete ranges $(a,d)$ and $(b,c)$ where $a<b<c<d$, we must have deleted range $(b,c)$ before deleting range $(a,d)$. Yet, the effect of deleting range $(b,c)$ and then $(a,d)$ is the same as only deleting $(a,d)$. Therefore, we can assume that in an optimal solution, the ranges we delete are all disjoint. Therefore, we want to find some disjoint range $[l_1,r_1],[l_2,r_2],...,[l_m,r_m]$ such that $a_{l_i}=a_{r_i}$ and $\sum (r_i-l_i+1)$ is maximized. We can write a DP. $dp_i$ denotes the minimum number of points we do not delete when considering the subarray $a[1\ldots i]$. We have $dp_i=\min(dp_{i-1}+1,\min\{dp_j|a_{j+1}=a_i,j+1<i\})$. This dp can be calculated in $O(n)$ since we can store for each $x$ what the minimum $dp_j$ which satisfy $a_{j+1}=x$.
|
[
"dp"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
const int N = 200000 + 5;
int n, a[N], dp[N], buc[N];
cin >> n;
dp[0] = 0;
for (int i = 1; i <= n; i++) buc[i] = 0x3f3f3f3f;
for (int i = 1; i <= n; i++) {
cin >> a[i];
dp[i] = min(dp[i - 1] + 1, buc[a[i]]);
buc[a[i]] = min(buc[a[i]], dp[i - 1]);
}
cout << n - dp[n] << '\n';
}
}
|
1842
|
D
|
Tenzing and His Animal Friends
|
\begin{quote}
Tell a story about me and my animal friends.
\end{quote}
Tenzing has $n$ animal friends. He numbers them from $1$ to $n$.
One day Tenzing wants to play with his animal friends. To do so, Tenzing will host several games.
In one game, he will choose a set $S$ which is a subset of $\{1,2,3,...,n\}$ and choose an integer $t$. Then, he will play the game with the animals in $S$ for $t$ minutes.
But there are some restrictions:
- Tenzing loves friend $1$ very much, so $1$ must be an element of $S$.
- Tenzing doesn't like friend $n$, so $n$ must not be an element of $S$.
- There are m additional restrictions. The $i$-th special restriction is described by integers $u_i$, $v_i$ and $y_i$, suppose $x$ is the \textbf{total} time that \textbf{exactly} one of $u_i$ and $v_i$ is playing with Tenzing. Tenzing must ensure that $x$ is less or equal to $y_i$. Otherwise, there will be unhappiness.
Tenzing wants to know the maximum total time that he can play with his animal friends. Please find out the maximum total time that Tenzing can play with his animal friends and a way to organize the games that achieves this maximum total time, or report that he can play with his animal friends for an infinite amount of time. Also, Tenzing does not want to host so many games, so he will host at most $n^2$ games.
|
Consider the restrictions on $u$, $v$, and $y$ as a weighted edge between $u$ and $v$ with weight $y$. Obviously, the final answer will not exceed the shortest path from $1$ to $n$. One possible approach to construct the solution is to start with the set ${1}$ and add vertices one by one. If $i$ is added to the set at time $T_i$, then we need to ensure that $|T_u-T_v|\leq y$ for any edge between $u$ and $v$ in the set. This can be modeled as a system of difference constraints problem and solved using shortest path algorithms. To be more specific, we can add vertices in increasing order of their distances from $1$. The time for each set can be calculated as the difference between the distances from $1$ to the two adjacent vertices in the sorted order.
|
[
"constructive algorithms",
"graphs",
"greedy"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
long long dis[100][100];
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
cin >> n >> m;
memset(dis, 0x3f, sizeof dis);
while (m--) {
int u, v, w;
cin >> u >> v >> w, u--, v--;
dis[u][v] = dis[v][u] = w;
}
for (int i = 0; i < n; i++) dis[i][i] = 0;
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
if (dis[0][n - 1] > 1e18)
cout << "inf", exit(0);
int ord[100];
iota(ord, ord + n, 0);
sort(ord + 1, ord + n, [](int a, int b) {
return dis[0][a] < dis[0][b];
});
string s(n, '0');
vector<pair<string, int>> ans;
for (int i = 0; i < n - 1; i++) {
int u = ord[i], v = ord[i + 1];
s[u] = '1';
ans.emplace_back(s, dis[0][v] - dis[0][u]);
if (v == n - 1) break;
}
cout << dis[0][n - 1] << ' ' << ans.size() << '\n';
for (auto [s, t] : ans)
cout << s << ' ' << t << '\n';
}
|
1842
|
E
|
Tenzing and Triangle
|
There are $n$ \textbf{pairwise-distinct} points and a line $x+y=k$ on a two-dimensional plane. The $i$-th point is at $(x_i,y_i)$. All points have non-negative coordinates and are strictly below the line. Alternatively, $0 \leq x_i,y_i, x_i+y_i < k$.
Tenzing wants to erase all the points. He can perform the following two operations:
- Draw triangle: Tenzing will choose two non-negative integers $a$, $b$ that satisfy $a+b<k$, then all points inside the triangle formed by lines $x=a$, $y=b$ and $x+y=k$ will be erased. It can be shown that this triangle is an isosceles right triangle. Let the side lengths of the triangle be $l$, $l$ and $\sqrt 2 l$ respectively. Then, the cost of this operation is $l \cdot A$.The blue area of the following picture describes the triangle with $a=1,b=1$ with cost $=1\cdot A$.
- Erase a specific point: Tenzing will choose an integer $i$ that satisfies $1 \leq i \leq n$ and erase the point $i$. The cost of this operation is $c_i$.
Help Tenzing find the minimum cost to erase all of the points.
|
Observe that all triangles will be disjoint, if two triangle were not disjoint, we can merge them together to such that the cost used is less. Therefore, we can consider doing DP. The oblique side of the triangle is a segment on the line $y=k-x$. Therefore, we use the interval $[L,R]$ to represent the triangle with the upper left corner at $(L,k-L)$ and the lower right corner at $(R,k-R)$. First, suppose that all points will generate costs. After covering points with a triangle, the costs can be reduced. Let $f(L,R)$ represent the sum of costs of points covered by triangle $[L,R]$ minus $A\times (R-L)$. We need to find several intervals $[l_1,r_1],[l_2,r_2],\cdots,[l_m,r_m]$ without common parts and maximize $\sum f(l_i,r_i)$. Let $dp_i$ represent the maximum value of $\sum f(l_i,r_i)$ when considering the prefix $[1,i]$. There are two transitions: If $i$ is not covered by any interval, then $dp_i\leftarrow dp_{i-1}$. If $i$ is covered by interval $[j+1,i]$, then $dp_i\leftarrow dp_j+f(j+1,i)$. Enumerate from small to large for $i$, maintain $g_j=dp_j+f(j+1,i)$. When $i-1\rightarrow i$, $g$ will change as follows: Subtract $A$ from $g_{0\dots i-1}$. For each point $(x,k-i)$, add the cost of the point to $g_{0\dots x}$. $g$ needs to support interval addition and global maximum value (assuming that illegal positions are 0), which can be achieved using a segment tree. Time complexity is $O((n+k)\log k)$. Please first understand the approach in the tutorial. A triangle $[L, R]$ can cover a point $(x, y)$ iff $L\le x$ and $k-y\le R$. Therefore, point $(x,y)$ can be regarded as interval $[x,k-y]$. Now the problem is transformed into one where some intervals $[l,r]$ have a cost of $w$, and you can place some non-overlapping intervals. If $[l,r]$ is not included in any placed interval, then you need to pay a cost of $w$. Further transformation: you can pay a cost of $A$ to cover $[i,i+1]$, and for an interval $[l,r]$ with a cost of $w$, if interval $[l,r]$ is not completely covered, then you need to pay a cost of $w$. Try to use minimum cut to solve this problem: First establish a bipartite graph with $n$ left nodes representing the points in the original problem and $k$ right nodes representing intervals $[i,i+1]$. The source node is connected to each left node with an edge capacity equal to the node's cost. Each right node is connected to the sink node with an edge capacity of $A$. For each left node representing interval $[l,r]$, it is connected to right nodes $l,l+1,l+2,...,r-1$ with an edge capacity of infinity. According to the maximum flow minimum cut theorem, let's consider how to find the maximum flow of this graph. This is basically a maximum matching problem of a bipartite graph. Each left node can match an interval on the right side, and each node has matching frequency restriction. A greedy algorithm: First sort all intervals in increasing order of the right endpoint, then consider each interval in turn and match it with positions within the interval from left to right. Specifically, let $cnt_i$ represent how many times the $i$-th point on the right side can still be matched. Initially, $cnt_{0\dots k-1}=A$. For each interval $[l,r]$ that can be matched at most $w$ times, each time find the smallest $i$ in $[l,r-1]$ such that $cnt_i\ne 0$, and match $\min(cnt_i,w)$ times with $i$. Use a Disjoint Set Union to query the smallest $i\ge l$ such that $cnt_i\ne 0$. The time complexity is $O(n\alpha(n))$. The Method of Four Russians can also be used to achieve $O(n)$ time complexity. Divide the sequence into blocks of $64$, use bit operations and __builtin_ctzll for searching within the block, and use Disjoint Set Union to skip blocks where $cnt_i$ is all $0$. In this way, the union operation only needs $O(\frac n{\log n})$ times and the find operation only needs $O(n)$ times. It can be proved that in this case, the time complexity of Disjoint Set Union is $O(n)$ instead of $O(n\alpha(n))$.
|
[
"data structures",
"dp",
"geometry",
"greedy",
"math"
] | 2,300
|
#include <bits/stdc++.h>
struct IO {
static const int inSZ = 1 << 17;
char inBuf[inSZ], *in1, *in2;
inline __attribute((always_inline))
int read() {
if(__builtin_expect(in1 > inBuf + inSZ - 32, 0)) {
auto len = in2 - in1;
memcpy(inBuf, in1, len);
in1 = inBuf, in2 = inBuf + len;
in2 += fread(in2, 1, inSZ - len, stdin);
if(in2 != inBuf + inSZ) *in2 = 0;
}
int res = 0;
unsigned char c = *in1++;
while(res = res * 10 + (c - 48), (c = *in1++) >= 48);
return res;
}
IO() {
in1 = inBuf;
in2 = in1 + fread(in1, 1, inSZ, stdin);
}
} IO;
inline int read() { return IO.read(); }
using namespace std;
const int N = 2e5 + 8, N2 = N / 64 + 8;
int n, k, A, pts[N][3], buc[N], LW[N][2];
int cnt[N], pa[N2], Rp[N];
uint64_t mask[N2];
int find(int x) {
return pa[x] < 0 ? x : pa[x] = find(pa[x]);
}
int main() {
n = read(), k = read(), A = read();
for (int i = 0; i < n; i++) {
pts[i][1] = read();
pts[i][0] = k - read();
pts[i][2] = read();
buc[pts[i][0]]++;
}
for (int i = 1; i <= k; i++) buc[i + 1] += buc[i];
for (int i = 0; i < n; i++) {
int t = --buc[pts[i][0]];
memcpy(LW[t], pts[i] + 1, 8);
}
for (int i = 0; i < k; i++) cnt[i] = A;
memset(mask, 0xff, sizeof mask);
memset(pa, -1, sizeof pa);
iota(Rp, Rp + N2, 0);
int ans = 0;
for (int r = 1; r <= k; r++)
for (int i = buc[r]; i < buc[r + 1]; i++) {
int l = LW[i][0], w = LW[i][1];
ans += w;
int lb = Rp[find(l >> 6)], rb = r >> 6;
auto S0 = mask[lb];
if (lb == l >> 6) S0 &= ~0ULL << (l & 63);
while (lb < rb) {
auto S = S0;
for (; S; S &= S - 1) {
int p = lb * 64 + __builtin_ctzll(S);
int tmp = min(w, cnt[p]);
cnt[p] -= tmp, w -= tmp;
if (!w) break;
}
mask[lb] ^= S0 ^ S;
if (!w) break;
int nxt = find(lb + 1);
if (!mask[lb]) {
lb = find(lb);
if (pa[nxt] > pa[lb]) swap(nxt, lb), Rp[nxt] = Rp[lb];
pa[nxt] += pa[lb], pa[lb] = nxt;
}
lb = Rp[nxt], S0 = mask[lb];
}
if (w != 0 & lb == rb) {
S0 &= (1ULL << (r & 63)) - 1;
auto S = S0;
for (; S; S &= S - 1) {
int p = lb * 64 + __builtin_ctzll(S);
int tmp = min(w, cnt[p]);
cnt[p] -= tmp, w -= tmp;
if (!w) break;
}
mask[lb] ^= S0 ^ S;
}
ans -= w;
}
cout << ans << '\n';
}
|
1842
|
F
|
Tenzing and Tree
|
Tenzing has an undirected tree of $n$ vertices.
Define the value of a tree with black and white vertices in the following way. The value of an edge is the absolute difference between the number of black nodes in the two components of the tree after deleting the edge. The value of the tree is the sum of values over all edges.
For all $k$ such that $0 \leq k \leq n$, Tenzing wants to know the maximum value of the tree when $k$ vertices are painted black and $n-k$ vertices are painted white.
|
Let $root$ be the centroid of all black vertices and $size_i$ be the number of black vertices in the subtree of node $i$. Then the value is $\sum_{i\neq root} k-2\cdot size_i=(n-1)\cdot k-2\cdot\sum_{i\neq root} size_i$. Consider painting node $i$ black, the total contributio to all of its ancestors is $2\cdot depth_i$, where $depth_i$ is the distance from $root$ to $i$. Since we want to maximize the value, we can greedily select the node with the smallest $depth_i$. But how do we ensure that $root$ is the centroid after selecting other black vertices? We can simply take the maximum of all possible $root$ because if a node is not the centroid, some edges will have a negative weight, making it worse than the optimal answer. Enumerate all possible $root$ and use BFS to add vertices based on their distance to $root$. The complexity is $O(n^2)$.
|
[
"dfs and similar",
"greedy",
"shortest paths",
"sortings",
"trees"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
const int N = 5000 + 8;
int n, ans[N];
vector<int> G[N];
void bfs(int u) {
static int q[N], dis[N];
memset(dis, -1, sizeof dis);
q[1] = u, dis[u] = 0;
for (int l = 1, r = 2; l < r; l++) {
u = q[l];
for (int v : G[u]) if (dis[v] < 0)
dis[v] = dis[u] + 1, q[r++] = v;
}
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += dis[q[i]];
ans[i] = max(ans[i], (n - 1) * i - sum * 2);
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v, u--, v--;
G[u].push_back(v), G[v].push_back(u);
}
for (int i = 0; i < n; i++) bfs(i);
for (int i = 0; i <= n; i++)
cout << ans[i] << ' ';
}
|
1842
|
G
|
Tenzing and Random Operations
|
\begin{quote}
Yet another random problem.
\end{quote}
Tenzing has an array $a$ of length $n$ and an integer $v$.
Tenzing will perform the following operation $m$ times:
- Choose an integer $i$ such that $1 \leq i \leq n$ uniformly at random.
- For all $j$ such that $i \leq j \leq n$, set $a_j := a_j + v$.
Tenzing wants to know the expected value of $\prod_{i=1}^n a_i$ after performing the $m$ operations, modulo $10^9+7$.
Formally, let $M = 10^9+7$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output the integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
|
Before starting to solve this problem, let's establish two basic properties: For two completely independent random variables $x_1,x_2$, we have $E(x_1x_2) = E(x_1)E(x_2)$. For $(a+b)\times (c+d)$, we have $E((a+b)\times (c+d)) = E(ac) + E(ad) + E(bc) + E(bd)$. Returning to this problem, let $x_{i,j}$ be a random variable: its value is $v$ when the $i$-th operation sets $a_j$ to $a_j + v$, otherwise it is $0$. Then note that the answer is the expected value of $\prod_{i=1}^{n}(a_i+\sum_{j=1}^{m}x_{j,i})$. Applying the second property above to split the product, each term is a product of some $a_i$ and $x$. Specifically, each term has $n$ factors, and for each $i\in [1,n]$, either $a_i$ is one of its factors, or some $x_{j,i}$ is one of its factors. Let's investigate the expectation of a specific term. Note that if $i_1\lt i_2$, then $E(x_{j,i_1}\times x_{j,i_2}) = E(x_{j,i_1})\times v$, that is, if $x_{j,i_1}$ is $0$ then the whole product is $0$, and if $x_{j,i_1}$ is $v$ then $x_{j,i_2}$ must be $v$. Therefore, for all the $x$ factors in a term, we categorize them by the first index, i.e. we group all $x_{j,...}$ into category $j$. For each category, we only need to focus on the first variable. If it's $v$, then the remaining variables take value $v$, otherwise the result is $0$. Note that the variables in different categories are completely independent (because their values are determined by operations in two different rounds), so the expected product of the variables in two categories can be split into the product of the expected products of the variables within each category. Our goal is to compute the expected sum of all the terms, which can be nicely combined with DP: Let $dp(i,j)$ be the value that we have determined the first $i$ factors of each term and there are $j$ categories that have appeared at least once (if adding the variable at position $i+1$ brings contribution $v$, otherwise the contribution is $\frac{i+1}{n}\times v$). The transition can be easily calculated with $O(1)$, depending on whether to append $a_{i+1}$ or $x_{...,i+1}$ to each term, and if it's the latter, we discuss whether the variable belongs to one of the $j$ categories that have appeared or the other $m-j$ categories. The time complexity is $O(n\times \min(n,m))$.
|
[
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
const int N = 5000 + 8, P = 1e9 + 7;
int n, m, v, a[N], coef[N], dp[N][N];
long long Pow(long long a, int n) {
long long r = 1;
while (n) {
if (n & 1) r = r * a % P;
a = a * a % P, n >>= 1;
}
return r;
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
cin >> n >> m >> v;
for (int i = 1; i <= n; i++) cin >> a[i];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
auto coef = i * Pow(n, P - 2) % P * v % P;
for (int j = 0; j < i; j++) {
dp[i][j + 1] = dp[i - 1][j] * coef % P * (m - j) % P;
dp[i][j] = (dp[i][j] + dp[i - 1][j] * (a[i] + 1LL * j * v % P)) % P;
}
}
int ans = 0;
for (int i = 0; i <= n; i++)
(ans += dp[n][i]) %= P;
cout << ans << '\n';
}
|
1842
|
H
|
Tenzing and Random Real Numbers
|
There are $n$ uniform random real variables between 0 and 1, inclusive, which are denoted as $x_1, x_2, \ldots, x_n$.
Tenzing has $m$ conditions. Each condition has the form of $x_i+x_j\le 1$ or $x_i+x_j\ge 1$.
Tenzing wants to know the probability that all the conditions are satisfied, modulo $998~244~353$.
Formally, let $M = 998~244~353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output the integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
|
Ignoring time complexity for now, how do we calculate the answer? The first step is to enumerate which variables are $<0.5$ and which variables are $>0.5$. Sort all variables $x_i$ by $\min(x_i,1-x_i)$ and enumerate the sorted result (referring to the permutation). Suppose no variable equals $0.5$, because the probability of being equal to $0.5$ is $0$, variables less than $0.5$ are called white vertices, and those greater than $0.5$ are called black vertices. Each black and white coloring is equiprobable, so we can calculate the probability that satisfies all conditions for each black and white coloring, and then take the average. For two variables less than $0.5$, the condition of $\le 1$ is always satisfied, and the condition of $\ge 1$ is never satisfied. Therefore, we do not need to consider the conditions between same-colored points. The condition between white vertex $u$ and black vertex $v$, $x_u+x_v\le 1$, is satisfied only when $x_u\le 1-x_v$. Let $y_u=\min(x_u,1-x_u)=\begin{cases}x_u&(u\text{ is white})\\1-x_u&(u\text{ is black})\end{cases}$, then $y_u$ can be regarded as a random variable in $[0,0.5)$, for $\le 1$ condition, the white vertex's $y$ must be less than or equal to the black vertex's $y$, so we add an edge from the white vertex to the black vertex; for $\ge 1$ condition, we add an edge from the black vertex to the white vertex. We get a directed graph that restricts the size relationship of $y_{1\cdots n}$. Suppose that sorting $y_{1\cdots n}$ from small to large is $y_{p_1},y_{p_2},\cdots,y_{p_n}$, then each permutation $p$ is equiprobable, and this $p$ contributes if and only if it is a topological sort, so the probability that satisfies all conditions is the number of topological sorts divided by $n!$. Now the problem has been transformed into a counting problem. For each coloring, count the total number of topological sorts. Now we do not enumerate coloring directly but enumerate topological sorts directly by enumerating a permutation $p$ such that $y_{p_1}<y_{p_2}<\cdots<y_{p_n}$ and count the number of colorings that satisfy the conditions. It can be found that $\le 1$ condition limits variablesin in the front position of $p$ to be less than $0.5$, and $\ge 1$ condition limits variables in the front position of $p$ to be greater than $0.5$. Then we can use bit-mask DP. Let $dp_{mask}$ represent that we have added all vertices in mask into topological sort. We enumerate new added vertex u for transition. If all variables with $\le 1$ conditions between it are included in mask, it can be colored black; if all variables with $\ge 1$ conditions between it are included in mask, it can be colored white. Time complexit is $O(2^nn)$.
|
[
"bitmasks",
"dp",
"graphs",
"math",
"probabilities"
] | 3,000
|
#include <iostream>
const int P = 998244353;
long long Pow(long long a, int n) {
long long r = 1;
while (n) {
if (n & 1) r = r * a % P;
a = a * a % P, n >>= 1;
}
return r;
}
inline void inc(int& a, int b) {
if((a += b) >= P) a -= P;
}
int n, m, G[20][2], f[1 << 20];
int main() {
std::cin >> n >> m;
while (m--) {
int t, i, j;
std::cin >> t >> i >> j;
i--, j--;
G[i][t] |= 1 << j;
G[j][t] |= 1 << i;
}
f[0] = 1;
for (int S = 0; S < 1 << n; S++)
for (int i = 0; i < n; i++) if (~S >> i & 1) {
if ((G[i][0] | S) == S) inc(f[S | 1 << i], f[S]);
if ((G[i][1] | S) == S) inc(f[S | 1 << i], f[S]);
}
long long t = 1;
for (int i = 1; i <= n; i++) t = t * i * 2 % P;
std::cout << f[(1 << n) - 1] * Pow(t, P - 2) % P << '\n';
}
|
1842
|
I
|
Tenzing and Necklace
|
\begin{quote}
bright, sunny and innocent......
\end{quote}
Tenzing has a beautiful necklace. The necklace consists of $n$ pearls numbered from $1$ to $n$ with a string connecting pearls $i$ and $(i \text{ mod } n)+1$ for all $1 \leq i \leq n$.
One day Tenzing wants to cut the necklace into several parts by cutting some strings. But for each connected part of the necklace, there should not be more than $k$ pearls. The time needed to cut each string may not be the same. Tenzing needs to spend $a_i$ minutes cutting the string between pearls $i$ and $(i \text{ mod } n)+1$.
Tenzing wants to know the minimum time in minutes to cut the necklace such that each connected part will not have more than $k$ pearls.
|
How to solve it if you want to cut exactly $m$ edges ? DP+divide and conquer Add a constraint: "you must cut off $m$ edges". Consider enumerating the minimum cut edges from small to large. Suppose the minimum cut edge chosen is $a_1$, and the subsequent optimal solution is $a_2, a_3, ..., a_m$. If another minimum cut edge is selected: $b_1$, and the subsequent optimal solution is $b_2, b_3, ..., b_m$. Assume that $a_i<a_{i+1}, b_i<b_{i+1}, b_1>a_1$. The adjustment method is as follows: Find the smallest $i$ such that $b_i<a_i$, and find the first $j$ such that $b_j\geq a_j$ after $i$, if it does not exist, let $j=m+1$. It can be observed that $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ can be replaced with $(a_i,a_{i+1},a_{i+2},...,a_{j-1})$, which is still a valid solution. Moreover, the solution $(a_i,a_{i+1},a_{i+2},...,a_{j-1})$ can also be replaced with $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$, because $b_{i-1}\geq a_{i-1}$ and $b_j\geq a_j$. Since $a$ and $b$ are both optimal solutions with fixed $a_1$ and $b_1$, $w_{b_i}+w_{b_{i+1}}+...+w_{b_{j-1}}=w_{a_i}+w_{a_{i+1}}+...+w_{a_{j-1}}$. Therefore, replacing $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ with $(a_i,a_{i+1},a_{i+2},...,a_{j-1})$ does not increase the total cost. Repeat the above adjustment until there is no $b_i<a_i$. Similarly, it can be proven that only adjusting $a_2,a_3,...,a_m$ is feasible, so that $\forall_{1\leq i\leq m} b_i\geq a_i$, and the total cost after adjustment remains unchanged. The adjustment method is as follows: Find the smallest $i$ such that $b_i> a_{i+1}$, and find the first $j$ such that $b_j\leq a_{j+1}$ after $i$ (let $a_{m+1}=+\infty$). $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ can be replaced with $(a_{i+1},a_{i+2},a_{i+3},...,a_{j})$, which is still a valid solution. Moreover, the solution $(a_{i+1},a_{i+2},a_{i+3},...,a_{j})$ can also be replaced with $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$, because $b_{i-1}\leq a_{i}$ and $b_j\leq a_{j+1}$. Since $a$ and $b$ are both optimal solutions with fixed $a_1$ and $b_1$, $w_{b_i}+w_{b_{i+1}}+...+w_{b_{j-1}}=w_{a_{i+1}}+w_{a_{i+2}}+...+w_{a_j}$. Therefore, replacing $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ with $(a_{i+1},a_{i+2},a_{i+3},...,a_{j})$ does not increase the total cost. Similarly, it can be proven that only adjusting $a_2,a_3,...,a_m$ is feasible, so that $\forall_{1\leq i<m}a_i\leq b_i\leq a_{i+1}$, and the total cost after adjustment remains unchanged. The adjustment method is as follows: Find the smallest $j$ such that $b_j\leq a_{j+1}$ (let $a_{m+1}=+\infty$). It can be observed that $(a_{2},a_{3},a_{4},...,a_{j})$ can be replaced with $(b_1,b_{2},b_{3},...,b_{j-1})$, which is still a valid solution. Moreover, the solution $(b_1,b_{2},b_{3},...,b_{j-1})$ can also be replaced with $(a_{2},a_{3},a_{4},...,a_{j})$, because $b_j\leq a_{j+1}$. Since $a$ is the optimal solution with fixed $a_1$ and $b_1$, $w_{b_1}+w_{b_{2}}+...+w_{b_{j-1}}\geq w_{a_{2}}+w_{a_{3}}+...+w_{a_j}$. Therefore, replacing $(b_1,b_{2},b_{3},...,b_{j-1})$ with $(a_{2},a_{3},a_{4},...,a_{j})$ does not increase the total cost. Combining the above conclusions, we can obtain a solution that must cut off $m$ edges: Let $a_1=1$, find the optimal solution $a_1,a_2,a_3,...,a_m$. Then, it can be assumed that all $b_i$ satisfy $a_i\leq b_i\leq a_{i+1}$. A divide-and-conquer algorithm can be used. Let $solve((l_1,r_1),(l_2,r_2),(l_3,r_3),...,(l_m,r_m))$ represent the optimal solution for all $l_i\leq b_i\leq r_i$. If $l_1>r_1$, then we are done. Otherwise, let $x=\lfloor\frac{l_1+r_1}{2}\rfloor$, we can use DP to calculate the cost and solution for $b_1=x$ in $O(\sum r_i-l_i+1)$ time complexity. Then, recursively calculate $solve((l_1,b_1-1),(l_2,b_2),(l_3,b_3),...,(l_m,b_m))$ and $solve((b_1+1,r_1),(b_2,r_2),(b_3,r_3),...,(b_m,r_m))$. Time complexity analysis: $\sum r_i-l_i+1=(\sum r_i-l_i)+m$. If the sum of adjacent parts is $\leq k$, it can be merged, but it is definitely not the optimal solution. Therefore, $m\leq 2\lceil\frac{n}{k}\rceil$. Assuming that the length of the first segment is $r_1-l_1+1=O(k)$, the time complexity is $O(n\log k+mk)=O(n\log k)$. Finally, we need to calculate the solution for all possible $m$ and take the $\min$ as the final answer. After pruning the first edge, if the optimal solution requires cutting off $m'$ edges, similar to the previous proof, other solutions can be adjusted to satisfy $|m-m'|\leq 1$ and the total cost does not increase.
|
[
"divide and conquer",
"dp",
"greedy"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 8;
int n, K, a[N], pre[N * 2];
long long dp[N * 2], ans;
vector<int> trim(vector<int> a, int L, int R) {
return vector(a.begin() + L, a.end() - R);
}
vector<int> init() {
static int q[N];
q[1] = 0;
for (int i = 1, l = 1, r = 1; i <= n; i++) {
if (q[l] < i - K) l++;
dp[i] = dp[q[l]] + a[i], pre[i] = q[l];
while (l <= r && dp[i] < dp[q[r]]) r--;
q[++r] = i;
}
ans = dp[n];
vector<int> res;
for (int i = n; i; i = pre[i]) res.push_back(i);
res.push_back(0), reverse(res.begin(), res.end());
return res;
}
vector<int> solve(int first, vector<int> L, vector<int> R) {
dp[first] = a[first];
int l = first, r = first;
long long val; int p;
auto checkMin = [&](int i) {
if (dp[i] < val) val = dp[i], p = i;
};
for (int i = 0; i < L.size(); i++) {
val = 1e18, p = 0;
for (int j = R[i]; j >= L[i]; j--) {
for (; r >= max(l, j - K); r--) checkMin(r + i);
dp[j + i + 1] = val + a[j];
pre[j + i + 1] = p;
}
l = L[i], r = R[i];
}
val = 1e18, p = 0;
for (int i = max(L.back(), n - K + first); i <= R.back(); i++)
checkMin(i + L.size());
ans = min(ans, val);
vector<int> res;
for (int i = L.size(); i; i--) res.push_back(p - i), p = pre[p];
reverse(res.begin(), res.end());
return res;
}
void divide(int l, int r, vector<int> L, vector<int> R) {
if (l > r) return;
int mid = (l + r) >> 1;
auto M = solve(mid, L, R);
divide(l, mid - 1, L, M), divide(mid + 1, r, M, R);
}
void divide(vector<int> p) {
p.push_back(n), divide(1, p[0], trim(p, 0, 1), trim(p, 1, 0));
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
cin >> n >> K;
for (int i = 1; i <= n; i++) cin >> a[i];
a[0] = a[n];
auto p = init();
divide(trim(p, 1, 1));
divide(solve(0, trim(p, 0, 1), trim(p, 1, 0)));
if ((p.size() - 2) * K >= n)
divide(solve(0, trim(p, 1, 2), trim(p, 2, 1)));
cout << ans << '\n';
}
}
|
1843
|
A
|
Sasha and Array Coloring
|
Sasha found an array $a$ consisting of $n$ integers and asked you to paint elements.
You have to paint each element of the array. You can use as many colors as you want, but each element should be painted into exactly one color, and for each color, there should be at least one element of that color.
The cost of one color is the value of $\max(S) - \min(S)$, where $S$ is the sequence of elements of that color. The cost of the whole coloring is the \textbf{sum} of costs over all colors.
For example, suppose you have an array $a = [\textcolor{red}{1}, \textcolor{red}{5}, \textcolor{blue}{6}, \textcolor{blue}{3}, \textcolor{red}{4}]$, and you painted its elements into two colors as follows: elements on positions $1$, $2$ and $5$ have color $1$; elements on positions $3$ and $4$ have color $2$. Then:
- the cost of the color $1$ is $\max([1, 5, 4]) - \min([1, 5, 4]) = 5 - 1 = 4$;
- the cost of the color $2$ is $\max([6, 3]) - \min([6, 3]) = 6 - 3 = 3$;
- the total cost of the coloring is $7$.
For the given array $a$, you have to calculate the \textbf{maximum} possible cost of the coloring.
|
First, there exists an optimal answer, in which there are no more than two elements of each color. Proof: let there exist an optimal answer, in which there are more elements of some color than 2. Then, take the median among the elements of this color and paint in another new color in which no other elements are painted. Then the maximum and minimum among the original color will not change, and in the new color the answer is 0, so the answer remains the same. Also, if there are two colors with one element each, they can be combined into one, and the answer will not decrease. It turns out that the numbers are paired (probably except for one; we'll assume it's paired with itself). Sort the array, and then the answer is $\sum_{pair_i < i} a_i - \sum_{i < pair_i} a_i$ ($pair_i$ is the number that is paired with $i$-th). Therefore, in the first summand you should take $\lfloor \frac{n}{2} \rfloor$ the largest, and in the second $\lfloor \frac{n}{2} \rfloor$ of the smallest elements of the array. Total complexity: $O(n \log n)$ for sorting.
|
[
"greedy",
"sortings",
"two pointers"
] | 800
|
def solve():
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
ans = 0
for i in range(n // 2):
ans += a[-i-1] - a[i]
print(ans)
t = int(input())
for _ in range(t):
solve()
|
1843
|
B
|
Long Long
|
Today Alex was brought array $a_1, a_2, \dots, a_n$ of length $n$. He can apply as many operations as he wants (including zero operations) to change the array elements.
In $1$ operation Alex can choose any $l$ and $r$ such that $1 \leq l \leq r \leq n$, and multiply all elements of the array from $l$ to $r$ inclusive by $-1$. In other words, Alex can replace the subarray $[a_l, a_{l + 1}, \dots, a_r]$ by $[-a_l, -a_{l + 1}, \dots, -a_r]$ in $1$ operation.
For example, let $n = 5$, the array is $[1, -2, 0, 3, -1]$, $l = 2$ and $r = 4$, then after the operation the array will be $[1, 2, 0, -3, -1]$.
Alex is late for school, so you should help him find the maximum possible sum of numbers in the array, which can be obtained by making any number of operations, as well as the minimum number of operations that must be done for this.
|
We can delete all zeros from the array, and it won't affect on answer. Maximum sum is $\sum_{i=1}^n |a_i|$. Minimum number of operations we should do - number of continuous subsequences with negative values of elements. Total complexity: $O(n)$
|
[
"greedy",
"math",
"two pointers"
] | 800
|
T = int(input())
for _ in range(T):
n = int(input())
a = list(map(int, input().split()))
sum = 0
cnt = 0
open = False
for x in a:
sum += abs(x)
if x < 0 and not open:
open = True
cnt += 1
if x > 0:
open = False
print(sum, cnt)
|
1843
|
C
|
Sum in Binary Tree
|
Vanya really likes math. One day when he was solving another math problem, he came up with an interesting tree. This tree is built as follows.
Initially, the tree has only one vertex with the number $1$ — the root of the tree. Then, Vanya adds two children to it, assigning them consecutive numbers — $2$ and $3$, respectively. After that, he will add children to the vertices in increasing order of their numbers, starting from $2$, assigning their children the minimum unused indices. As a result, Vanya will have an infinite tree with the root in the vertex $1$, where each vertex will have exactly two children, and the vertex numbers will be arranged sequentially by layers.
\begin{center}
{\small Part of Vanya's tree.}
\end{center}
Vanya wondered what the sum of the vertex numbers on the path from the vertex with number $1$ to the vertex with number $n$ in such a tree is equal to. Since Vanya doesn't like counting, he asked you to help him find this sum.
|
It is easy to notice that the children of the vertex with number $u$ have numbers $2 \cdot u$ and $2 \cdot u + 1$. So, the ancestor of the vertex $u$ has the number $\lfloor \frac{u}{2} \rfloor$. Note that based on this formula, the size of the path from the root to the vertex with number $n$ equals $\lfloor \log_2 n \rfloor$. Therefore with given constraints we can write out the path to the root explicitly and calculate the sum of vertex numbers on it in $O(\log n)$. Total complexity: $O(\log n)$ for the test case.
|
[
"bitmasks",
"combinatorics",
"math",
"trees"
] | 800
|
t = int(input())
for _ in range(t):
n = int(input())
s = 0
while n >= 1:
s += n
n //= 2
print(s)
|
1843
|
D
|
Apple Tree
|
Timofey has an apple tree growing in his garden; it is a rooted tree of $n$ vertices with the root in vertex $1$ (the vertices are numbered from $1$ to $n$). A tree is a connected graph without loops and multiple edges.
This tree is very unusual — it grows with its root upwards. However, it's quite normal for programmer's trees.
The apple tree is quite young, so only two apples will grow on it. Apples will grow in certain vertices (these vertices may be the same). After the apples grow, Timofey starts shaking the apple tree until the apples fall. Each time Timofey shakes the apple tree, the following happens to each of the apples:
Let the apple now be at vertex $u$.
- If a vertex $u$ has a child, the apple moves to it (if there are several such vertices, the apple can move to any of them).
- Otherwise, the apple falls from the tree.
It can be shown that after a finite time, both apples will fall from the tree.
Timofey has $q$ assumptions in which vertices apples can grow. He assumes that apples can grow in vertices $x$ and $y$, and wants to know the number of pairs of vertices ($a$, $b$) from which apples can fall from the tree, where $a$ — the vertex from which an apple from vertex $x$ will fall, $b$ — the vertex from which an apple from vertex $y$ will fall. Help him do this.
|
Let $cnt_v$ be the number of vertices from which an apple can fall if it is in the vertex $v$. Then the answer to the query is $cnt_v \cdot cnt_u$. Note that the value of $cnt_v$ is equal to the number of leaves in the subtree of vertex $v$. Then, these values can be computed using the DFS or BFS. The value $cnt$ for a vertex will be equal to $1$ if this vertex is a leaf, otherwise it will be equal to the sum of these values for all children of the vertex. Total complexity: $O(n + q)$.
|
[
"combinatorics",
"dfs and similar",
"dp",
"math",
"trees"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<vector<int>> g;
vector<ll> cnt;
void dfs(int v, int p) {
if (g[v].size() == 1 && g[v][0] == p) {
cnt[v] = 1;
} else {
for (auto u : g[v]) {
if (u != p) {
dfs(u, v);
cnt[v] += cnt[u];
}
}
}
}
void solve() {
int n, q;
cin >> n;
g.assign(n, vector<int>());
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
u--; v--;
g[u].push_back(v);
g[v].push_back(u);
}
cnt.assign(n, 0);
dfs(0, -1);
cin >> q;
for (int i = 0; i < q; i++) {
int c, k;
cin >> c >> k;
c--; k--;
ll res = cnt[c] * cnt[k];
cout << res << '\n';
}
}
signed main() {
int tests;
cin >> tests;
while (tests--) {
solve();
}
return 0;
}
|
1843
|
E
|
Tracking Segments
|
You are given an array $a$ consisting of $n$ zeros. You are also given a set of $m$ not necessarily different segments. Each segment is defined by two numbers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$) and represents a subarray $a_{l_i}, a_{l_i+1}, \dots, a_{r_i}$ of the array $a$.
Let's call the segment $l_i, r_i$ beautiful if the number of ones on this segment \textbf{is strictly greater} than the number of zeros. For example, if $a = [1, 0, 1, 0, 1]$, then the segment $[1, 5]$ is beautiful (the number of ones is $3$, the number of zeros is $2$), but the segment $[3, 4]$ is not is beautiful (the number of ones is $1$, the number of zeros is $1$).
You also have $q$ changes. For each change you are given the number $1 \le x \le n$, which means that you must assign an element $a_x$ the value $1$.
You have to find the first change after which \textbf{at least one} of $m$ given segments becomes beautiful, or report that none of them is beautiful after processing all $q$ changes.
|
Let's use a binary search for an answer. It will work, because if some segment was good, then after one more change it will not be no longer good, and if all segments were bad, then if you remove the last change, they will remain bad. To check if there is a good segment for the prefix of changes, you can build the array obtained after these changes, and then count the prefix sums in $O(n)$. After that, you can go through all the segments and check for $O(1)$ for a segment whether it is a good or not. Total complexity: $O((n + m) \cdot \log q)$.
|
[
"binary search",
"brute force",
"data structures",
"two pointers"
] | 1,600
|
def solve():
n, m = map(int, input().split())
segs = []
for i in range(m):
l, r = map(int, input().split())
l -= 1
segs.append([l, r])
q = int(input())
ord = [0] * q
for i in range(q):
ord[i] = int(input())
ord[i] -= 1
l = 0
r = q + 1
while r - l > 1:
M = (l + r) // 2
cur = [0] * n
for i in range(M):
cur[ord[i]] = 1
pr = [0] * (n + 1)
for i in range(n):
pr[i+1] = pr[i] + cur[i]
ok = False
for i in segs:
if(pr[i[1]] - pr[i[0]] > (i[1] - i[0]) // 2):
ok = True
break
if ok:
r = M
else:
l = M
if r == q + 1:
r = -1
print(r)
tc = int(input())
for T in range(tc):
solve()
|
1843
|
F1
|
Omsk Metro (simple version)
|
\textbf{This is the simple version of the problem. The only difference between the simple and hard versions is that in this version $u = 1$.}
As is known, Omsk is the capital of Berland. Like any capital, Omsk has a well-developed metro system. The Omsk metro consists of a certain number of stations connected by tunnels, and between any two stations there is exactly one path that passes through each of the tunnels no more than once. In other words, the metro is a tree.
To develop the metro and attract residents, the following system is used in Omsk. Each station has its own weight $x \in \{-1, 1\}$. If the station has a weight of $-1$, then when the station is visited by an Omsk resident, a fee of $1$ burle is charged. If the weight of the station is $1$, then the Omsk resident is rewarded with $1$ burle.
Omsk Metro currently has only one station with number $1$ and weight $x = 1$. Every day, one of the following events occurs:
- A new station with weight $x$ is added to the station with number $v_i$, and it is assigned a number that is one greater than the number of existing stations.
- Alex, who lives in Omsk, wonders: is there a subsegment$\dagger$ (possibly empty) of the path between vertices $u$ and $v$ such that, by traveling along it, exactly $k$ burles can be earned (if $k < 0$, this means that $k$ burles will have to be spent on travel). In other words, Alex is interested in whether there is such a subsegment of the path that the sum of the weights of the vertices in it is equal to $k$. Note that the subsegment can be empty, and then the sum is equal to $0$.
You are a friend of Alex, so your task is to answer Alex's questions.
$\dagger$Subsegment — continuous sequence of elements.
|
Let $\mathrm{mx}$ be the maximal sum on the path subsegment, $\mathrm{mn}$ - the minimal sum on the path subsegment. Then it is said that a subsegment with sum $x$ exists if and only if $\mathrm{mn} \leq x \leq \mathrm{mx}$. Proof: Let us fix the subsegment with the minimum sum and the subsegment with the maximum sum. Now, we want to go from the first segment to the second one by consecutively removing or adding elements from the ends of the segment. Note that, due to the fact that $x \in \{-1, 1\}$, for each such action, the sum on the segment will change by exactly $1$. In other words, no matter how we go from one segment to another, the sum will remain a discretely continuous value. Then, since this function takes values of the minimum and maximum sum, it also takes all values from the segment between them (by the intermediate value theorem). Thus, the set of all possible sums on the subsegments is the interval of integers between the minimum and maximum sum, from which the original assumption follows. Now, we have turned the problem down to finding the subsegment with the minimum and maximum sum on the path in the tree. Let $\mathrm{mx}_u$ be the maximum sum on the subsegment on the path from $1$ to $u$, $\mathrm{suf}_u$ - the maximum sum on the suffix of the path from $1$ to $u$, $p_u$ - the ancestor of vertex $u$, $x_u$ - its weight. Then $\mathrm{suf}_u = \max({0, \mathrm{suf}_{p_u} + x_u})$, $\mathrm{mx}_u = \max({\mathrm{mx}_{p_u}, \mathrm{suf}_u})$. Thus, we have learned to calculate the necessary values for a vertex immediately at the moment of its addition, which allows us to solve the problem online (but it is not required in the problem itself). The values for the minimum are counted in the same way. Total complexity: $O(n)$.
|
[
"data structures",
"dfs and similar",
"dp",
"graphs",
"greedy",
"math",
"trees"
] | 1,800
|
class info:
mn_suf = 0
mx_suf = 0
mn_ans = 0
mx_ans = 0
def solve():
n = int(input())
start = info()
start.mx_suf = start.mx_ans = 1
st = [start]
for i in range(n):
com = input().split()
if (com[0] == '+'):
v = int(com[1]) - 1
x = int(com[2])
pref = st[v]
cur = info()
cur.mn_suf = min(0, pref.mn_suf + x)
cur.mx_suf = max(0, pref.mx_suf + x)
cur.mn_ans = min(pref.mn_ans, cur.mn_suf)
cur.mx_ans = max(pref.mx_ans, cur.mx_suf)
st.append(cur)
else:
v = int(com[2]) - 1
x = int(com[3])
if st[v].mn_ans <= x <= st[v].mx_ans:
print("Yes")
else:
print("No")
t = int(input())
for testCase in range(t):
solve()
|
1843
|
F2
|
Omsk Metro (hard version)
|
\textbf{This is the hard version of the problem. The only difference between the simple and hard versions is that in this version $u$ can take any possible value.}
As is known, Omsk is the capital of Berland. Like any capital, Omsk has a well-developed metro system. The Omsk metro consists of a certain number of stations connected by tunnels, and between any two stations there is exactly one path that passes through each of the tunnels no more than once. In other words, the metro is a tree.
To develop the metro and attract residents, the following system is used in Omsk. Each station has its own weight $x \in \{-1, 1\}$. If the station has a weight of $-1$, then when the station is visited by an Omsk resident, a fee of $1$ burle is charged. If the weight of the station is $1$, then the Omsk resident is rewarded with $1$ burle.
Omsk Metro currently has only one station with number $1$ and weight $x = 1$. Every day, one of the following events occurs:
- A new station with weight $x$ is added to the station with number $v_i$, and it is assigned a number that is one greater than the number of existing stations.
- Alex, who lives in Omsk, wonders: is there a subsegment$\dagger$ (possibly empty) of the path between vertices $u$ and $v$ such that, by traveling along it, exactly $k$ burles can be earned (if $k < 0$, this means that $k$ burles will have to be spent on travel). In other words, Alex is interested in whether there is such a subsegment of the path that the sum of the weights of the vertices in it is equal to $k$. Note that the subsegment can be empty, and then the sum is equal to $0$.
You are a friend of Alex, so your task is to answer Alex's questions.
$\dagger$Subsegment — continuous sequence of elements.
|
Similarly to the problem F1, we need to be able to find a subsegment with maximum and minimum sum, but on an arbitrary path in the tree. To do this, we will use the technique of binary lifts. For each lift, we will store the maximum/minimum sum on the prefix and suffix, the sum of the subsegment and the maximum sum on the subsegment, as in the problem about the maximum sum on a subsegment of an array. Then, such values are easily can be recalculated by analogy with the recalculation from the problem F1. It is also worth noting that such binary lifts can also be constructed online, but this was not required in the problem. Then, all that remains is to go up from the ends of the path to their LCA, and then combine the answers of the vertical paths into the answer for the whole path. Total complexity: $O(n \log n)$.
|
[
"data structures",
"dfs and similar",
"divide and conquer",
"dp",
"math",
"trees"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct info {
int sum, minPrefL, maxPrefL, minPrefR, maxPrefR, minSeg, maxSeg;
info(int el = 0) {
sum = el;
minSeg = minPrefL = minPrefR = min(el, 0);
maxSeg = maxPrefL = maxPrefR = max(el, 0);
}
};
struct question {
int u, v, x;
};
info merge(info& a, info& b) {
info res;
res.sum = a.sum + b.sum;
res.minPrefL = min(a.minPrefL, a.sum + b.minPrefL);
res.maxPrefL = max(a.maxPrefL, a.sum + b.maxPrefL);
res.minPrefR = min(a.minPrefR + b.sum, b.minPrefR);
res.maxPrefR = max(a.maxPrefR + b.sum, b.maxPrefR);
res.minSeg = min({a.minSeg, b.minSeg, a.minPrefR + b.minPrefL});
res.maxSeg = max({a.maxSeg, b.maxSeg, a.maxPrefR + b.maxPrefL});
return res;
}
const int MAXN = 200100;
const int lg = 17;
int up[lg + 1][MAXN];
info ans[lg + 1][MAXN];
int d[MAXN];
void solve() {
int n;
cin >> n;
for (int i = 0; i <= lg; i++) up[i][0] = 0;
ans[0][0] = info(1);
d[0] = 0;
int cur = 0;
for (int q = 0; q < n; q++) {
char c;
cin >> c;
if (c == '+') {
int v, x;
cin >> v >> x;
v--;
cur++;
d[cur] = d[v] + 1;
up[0][cur] = v;
for (int j = 0; j <= lg - 1; j++) up[j + 1][cur] = up[j][up[j][cur]];
ans[0][cur] = info(x);
for (int j = 0; j <= lg - 1; j++) ans[j + 1][cur] = merge(ans[j][cur], ans[j][up[j][cur]]);
} else {
int u, v, x;
cin >> u >> v >> x;
u--; v--;
if (d[u] < d[v]) swap(u, v);
int dif = d[u] - d[v];
info a, b;
for (int i = lg; i >= 0; i--) {
if ((dif >> i) & 1) {
a = merge(a, ans[i][u]);
u = up[i][u];
}
}
if (u == v) {
a = merge(a, ans[0][u]);
} else {
for (int i = lg; i >= 0; i--) {
if (up[i][u] != up[i][v]) {
a = merge(a, ans[i][u]);
u = up[i][u];
b = merge(b, ans[i][v]);
v = up[i][v];
}
}
a = merge(a, ans[1][u]);
b = merge(b, ans[0][v]);
}
swap(b.minPrefL, b.minPrefR);
swap(b.maxPrefL, b.maxPrefR);
info res = merge(a, b);
if (res.minSeg <= x && x <= res.maxSeg) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
}
}
int main() {
int tests;
cin >> tests;
while (tests--) {
solve();
}
}
|
1844
|
A
|
Subtraction Game
|
You are given two positive integers, $a$ and $b$ ($a < b$).
For some positive integer $n$, two players will play a game starting with a pile of $n$ stones. They take turns removing exactly $a$ or exactly $b$ stones from the pile. The player who is unable to make a move loses.
Find a positive integer $n$ such that the second player to move in this game has a winning strategy. This means that no matter what moves the first player makes, the second player can carefully choose their moves (possibly depending on the first player's moves) to ensure they win.
|
We present two approaches. Approach 1 If $a \ge 2$, then $n = 1$ works. Else if $a = 1$ and $b \ge 3$, $n = 2$ works. Otherwise, $a = 1$ and $b = 2$, so $n = 3$ works. Approach 2 Printing $a+b$ works because no matter what move the first player makes, the second player can respond with the opposite move. The time complexity is $\mathcal{O}(1)$ per test case.
|
[
"constructive algorithms",
"games"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t,a,b;
scanf("%d",&t);
while (t--) {
scanf("%d %d",&a,&b);
printf("%d\n",a+b);
}
return 0;
}
|
1844
|
B
|
Permutations & Primes
|
You are given a positive integer $n$.
In this problem, the $\operatorname{MEX}$ of a collection of integers $c_1,c_2,\dots,c_k$ is defined as the smallest \textbf{positive} integer $x$ which does not occur in the collection $c$.
The primality of an array $a_1,\dots,a_n$ is defined as the number of pairs $(l,r)$ such that $1 \le l \le r \le n$ and $\operatorname{MEX}(a_l,\dots,a_r)$ is a prime number.
Find any permutation of $1,2,\dots,n$ with the maximum possible primality among all permutations of $1,2,\dots,n$.
Note:
- A prime number is a number greater than or equal to $2$ that is not divisible by any positive integer except $1$ and itself. For example, $2,5,13$ are prime numbers, but $1$ and $6$ are not prime numbers.
- A permutation of $1,2,\dots,n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
|
The cases $n \le 2$ can be handled separately. For $n \ge 3$, any construction with $a_1 = 2, a_{\lfloor (n+1)/2 \rfloor} = 1, a_n = 3$ is optimal. We can prove this as follows: Note that since $2$ and $3$ are both prime, any $(l,r)$ with $l \le \left\lfloor \frac{n+1}{2} \right\rfloor \le r$ has a prime $\operatorname{MEX}(a_l,\dots,a_r)$ except for possibly $(l,r) = (1,n)$, where $\operatorname{MEX}(a_1,\dots,a_n) = n+1$. Therefore the primality of this array is $\left\lfloor \frac{n+1}{2} \right\rfloor \cdot \left\lceil \frac{n+1}{2} \right\rceil - [n+1\text{ is not prime}]$, where $[P] = 1$ if proposition $P$ is true and $0$ if $P$ is false. On the other hand, for any permutation of $1,\dots,n$, let $k$ be the index with $a_k = 1$. The primality of this array cannot exceed $k(n+1-k)-[n+1\text{ is not prime}]$, since any pair $(l,r)$ with prime $\operatorname{MEX}(a_l,\dots,a_r) \ge 2$ must satisfy $l \le k \le r$, and additionally $\operatorname{MEX}(a_1,\dots,a_n) = n+1$ no matter what the permutation is. The function $f(k) = k(n+1-k)$ is a quadratic which is maximized at $k = \left\lfloor \frac{n+1}{2} \right\rfloor$, so $k(n+1-k)-[n+1\text{ is not prime}] \le \left\lfloor \frac{n+1}{2} \right\rfloor \cdot \left\lceil \frac{n+1}{2} \right\rceil - [n+1\text{ is not prime}]$ as required. The time complexity is $\mathcal{O}(n)$ (note that we don't even need to sieve for primes!).
|
[
"constructive algorithms",
"math"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int a[200000];
int main() {
int i;
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
if (n == 1) printf("1\n");
else if (n == 2) printf("1 2\n");
else {
int c = 4;
fill(a,a+n,0);
a[0] = 2,a[n/2] = 1,a[n-1] = 3;
for (i = 0; i < n; i++) {
if (a[i] == 0) a[i] = c++;
}
for (i = 0; i < n; i++) printf("%d%c",a[i],(i == n-1) ? '\n':' ');
}
}
return 0;
}
|
1844
|
C
|
Particles
|
You have discovered $n$ mysterious particles on a line with integer charges of $c_1,\dots,c_n$. You have a device that allows you to perform the following operation:
- Choose a particle and remove it from the line. The remaining particles will shift to fill in the gap that is created. If there were particles with charges $x$ and $y$ directly to the left and right of the removed particle, they combine into a single particle of charge $x+y$.
For example, if the line of particles had charges of $[-3,1,4,-1,5,-9]$, performing the operation on the $4$th particle will transform the line into $[-3,1,9,-9]$.
If we then use the device on the $1$st particle in this new line, the line will turn into $[1,9,-9]$.
You will perform operations until there is only one particle left. What is the maximum charge of this remaining particle that you can obtain?
|
Consider the set of even-indexed particles and the set of odd-indexed particles. Observe that particles can only ever combine with other particles from the same set. It follows that the answer is at most $\max\left(\sum_{\text{odd }i} \max(c_i,0),\sum_{\text{even }i} \max(c_i,0)\right).$ On the other hand, this bound is almost always obtainable. We can first perform the operation on all negatively charged particles in the same set as the desired final particle, then perform the operation on all the particles from the opposite set. There is a corner case where all particles are negative, where the answer is just $\max(c_1,\dots,c_n)$. The time complexity is $\mathcal{O}(n)$.
|
[
"dp",
"greedy",
"implementation",
"math"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
int c[200000];
int main() {
int i;
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
for (i = 0; i < n; i++) scanf("%d",&c[i]);
int allneg = 1;
for (i = 0; i < n; i++) allneg &= (c[i] < 0);
if (allneg) printf("%d\n",*max_element(c,c+n));
else {
LLI ans1 = 0,ans2 = 0;
for (i = 0; i < n; i++) {
if (i & 1) ans1 += max(c[i],0);
else ans2 += max(c[i],0);
}
printf("%lld\n",max(ans1,ans2));
}
}
return 0;
}
|
1844
|
D
|
Row Major
|
The row-major order of an $r \times c$ grid of characters $A$ is the string obtained by concatenating all the rows, i.e. $$ A_{11}A_{12} \dots A_{1c}A_{21}A_{22} \dots A_{2c} \dots A_{r1}A_{r2} \dots A_{rc}. $$
A grid of characters $A$ is bad if there are some two adjacent cells (cells sharing an edge) with the same character.
You are given a positive integer $n$. Consider all strings $s$ consisting of only lowercase Latin letters such that they are \textbf{not} the row-major order of \textbf{any} bad grid. Find any string with the minimum number of distinct characters among all such strings of length $n$.
It can be proven that at least one such string exists under the constraints of the problem.
|
The condition is equivalent to a graph of pairs of characters in $s$ that need to be different. In graph-theoretic language, we need to find the chromatic number of this graph. By considering the $1 \times n$ and $n \times 1$ grids, there is an edge between character $u$ and $u+1$ for all $1 \le u \le n-1$. By considering a $\frac{n}{d} \times d$ grid (where $d$ divides $n$), there is an edge between character $u$ and $u+d$ for all $1 \le u \le n-d$ whenever $d$ divides $n$. Let $c$ be the smallest positive integer that does not divide $n$. There is an edge between every pair of the characters $1,\dots,c$ (in graph-theoretic language, this is a clique), so the answer is at least $c$. On the other hand, consider the string obtained by letting $s_1,\dots,s_c$ be all distinct characters and repeating this pattern periodically ($s_i = s_{i+c}$ for all $1 \le i \le n-c$). Any pair of equal characters have an index difference that is a multiple of $c$, say $kc$. But since $c$ does not divide $n$, $kc$ also does not divide $n$, so these characters are not connected by an edge. Therefore this construction gives a suitable string with $c$ distinct characters. The time complexity is $\mathcal{O}(n)$.
|
[
"constructive algorithms",
"greedy",
"math",
"number theory",
"strings"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
char s[1000001];
int main() {
int i;
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
int c = 1;
while ((n % c) == 0) c++;
for (i = 0; i < n; i++) s[i] = 'a'+(i % c);
s[n] = '\0';
printf("%s\n",s);
}
return 0;
}
|
1844
|
E
|
Great Grids
|
An $n \times m$ grid of characters is called great if it satisfies these three conditions:
- Each character is either 'A', 'B', or 'C'.
- Every $2 \times 2$ contiguous subgrid contains all three different letters.
- Any two cells that share a common edge contain different letters.
Let $(x,y)$ denote the cell in the $x$-th row from the top and $y$-th column from the left.
You want to construct a great grid that satisfies $k$ constraints. Each constraint consists of two cells, $(x_{i,1},y_{i,1})$ and $(x_{i,2},y_{i,2})$, that share exactly one corner. You want your great grid to have the same letter in cells $(x_{i,1},y_{i,1})$ and $(x_{i,2},y_{i,2})$.
Determine whether there exists a great grid satisfying all the constraints.
|
We present two approaches. Approach 1 Let the letters 'A', 'B', and 'C' correspond to the numbers $0$, $1$, and $2$ modulo $3$ respectively. Consider drawing an arrow between any two adjacent cells in a great grid pointing to the right or down, and label this arrow with the difference of the two cells modulo $3$. The conditions imply that all labels are $1$ or $2$, and in each contiguous $2 \times 2$ subgrid, the top arrow has the same label as the bottom arrow, and the left arrow has the same label as the right arrow. Hence we can associate a type to each of $n-1$ rows and $m-1$ columns which is its label. A constraint for cells $(x,y)$ and $(x+1,y+1)$ means that row $x$ and column $y$ must have different labels, and a constraint for cells $(x,y+1)$ and $(x+1,y)$ means that row $x$ and $y$ must have the same label. These relations form a graph, and the problem reduces to a variant of $2$-colourability, which can be checked using DFS or a DSU. Approach 2 In a great grid, draw a '/' or '\' for each $2 \times 2$ subgrid connecting the equal letters. We can observe that these grids have a simple pattern: every two rows are either the same or opposite. Furthermore, any such pattern corresponds to a great grid (this can be proven with the idea in approach 1). We can associate a type to each row and column, a boolean variable $0$ or $1$, such that an entry is '/' or '\' depending on whether the labels are the same or different. The constraints correspond to entries needing to be '/' or '\', forming a graph of pairs of labels that must be the same or different. Thus the problem reduces to a variant of $2$-colourability, which can be checked using DFS or a DSU. The intended time complexity is $\mathcal{O}(n+m+k)$, although slower implementations with complexities like $\mathcal{O}(nm+k)$ or $\mathcal{O}(k(n+m))$ can also pass.
|
[
"2-sat",
"constructive algorithms",
"dfs and similar",
"dsu",
"graphs"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
typedef vector<pair<int,int> > vpii;
#define mp make_pair
#define pb push_back
vpii adjList[4000];
int colour[4000],bad = 0;
int doDFS(int u,int c) {
if (colour[u] != -1) {
if (colour[u] != c) bad = 1;
return 0;
}
colour[u] = c;
for (auto [v,e]: adjList[u]) doDFS(v,c^e);
return 0;
}
int main() {
int i;
int t,n,m,k;
int x1,y1,x2,y2;
scanf("%d",&t);
while (t--) {
scanf("%d %d %d",&n,&m,&k);
for (i = 0; i < k; i++) {
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
x1--,y1--,x2--,y2--;
adjList[min(x1,x2)].pb(mp(n+min(y1,y2),(x1+y1 != x2+y2)));
adjList[n+min(y1,y2)].pb(mp(min(x1,x2),(x1+y1 != x2+y2)));
}
fill(colour,colour+n+m,-1),bad = 0;
for (i = 0; i < n+m; i++) {
if (colour[i] == -1) doDFS(i,0);
}
printf(bad ? "NO\n":"YES\n");
for (i = 0; i < n+m; i++) adjList[i].clear();
}
return 0;
}
|
1844
|
F1
|
Min Cost Permutation (Easy Version)
|
\textbf{The only difference between this problem and the hard version is the constraints on $t$ and $n$.}
You are given an array of $n$ positive integers $a_1,\dots,a_n$, and a (possibly negative) integer $c$.
Across all permutations $b_1,\dots,b_n$ of the array $a_1,\dots,a_n$, consider the minimum possible value of $$\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|.$$ Find the lexicographically smallest permutation $b$ of the array $a$ that achieves this minimum.
A sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:
- $x$ is a prefix of $y$, but $x \ne y$;
- in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.
|
Let the cost of a permutation $b$ of $a$ be the value $\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$. When $c \ge 0$, it can be proven that the minimum cost can be obtained by sorting $a$ in nondecreasing order. As sorting $a$ in nondecreasing order is also the lexicographically smallest array, this is the answer. Similarly, when $c < 0$, it can be proven that the minimum cost can be obtained by sorting $a$ in nonincreasing order. Furthermore, if we have fixed the values of $b_1,\dots,b_k$ for some $1 \le k < n$, then intuitively, one optimal permutation $b_{k+1},\dots,b_n$ of the remaining elements is to sort them in nonincreasing order$^\dagger$. To find the lexicographically smallest permutation, we can greedily loop through $k = 1,\dots,n$, each time taking the smallest $b_k$ that does not increase the cost. If $a_k \ge \dots \ge a_n$ are the unused elements sorted in nonincreasing order, then the condition we need to check to determine if setting $b_k := a_i$ is good is whether $|a_{i-1}-a_i-c|+|a_i-a_{i+1}-c|+|b_{k-1}-a_k-c| \ge |a_{i-1}-a_{i+1}-c|+|b_{k-1}-a_i-c|+|a_i-a_k-c|\quad(*)$ (with some adjustments in the corner cases when $k = 1$ or $i = k,n$). This condition $(*)$ can be checked in constant time, and we try $\mathcal{O}(n)$ values of $i$ for each of the $\mathcal{O}(n)$ values of $k$, so the time complexity is $\mathcal{O}(n^2)$. The proofs of the claims used in this solution can be found at the end of the solution for the hard version. $^\dagger$This is actually not true as stated (e.g. when $c = -1$ and we fix $b_1 = 2$, $[2,1,9,8]$ is better than $[2,9,8,1]$), but it turns out it is true for all states that the greedy algorithm can reach (i.e. in this example, the greedy algorithm could not have chosen $b_1 = 2$).
|
[
"brute force",
"constructive algorithms",
"greedy",
"math"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
int a[200000];
int main() {
int i,j;
int t,n,c;
scanf("%d",&t);
while (t--) {
scanf("%d %d",&n,&c);
for (i = 0; i < n; i++) scanf("%d",&a[i]);
if (c >= 0) {
sort(a,a+n);
for (i = 0; i < n; i++) printf("%d%c",a[i],(i == n-1) ? '\n':' ');
continue;
}
sort(a,a+n,greater<int>());
for (i = 0; i < n; i++) {
for (j = n-1; j > i; j--) {
LLI diff = -abs(a[j]-a[j-1]-c);
if (j < n-1) {
diff -= abs(a[j+1]-a[j]-c);
diff += abs(a[j+1]-a[j-1]-c);
}
if (i == 0) diff += abs(a[i]-a[j]-c);
else {
diff -= abs(a[i]-a[i-1]-c);
diff += abs(a[i]-a[j]-c);
diff += abs(a[j]-a[i-1]-c);
}
if (diff == 0) {
for (; j > i; j--) swap(a[j],a[j-1]);
}
}
}
for (i = 0; i < n; i++) printf("%d%c",a[i],(i == n-1) ? '\n':' ');
}
return 0;
}
|
1844
|
F2
|
Min Cost Permutation (Hard Version)
|
\textbf{The only difference between this problem and the easy version is the constraints on $t$ and $n$.}
You are given an array of $n$ positive integers $a_1,\dots,a_n$, and a (possibly negative) integer $c$.
Across all permutations $b_1,\dots,b_n$ of the array $a_1,\dots,a_n$, consider the minimum possible value of $$\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|.$$ Find the lexicographically smallest permutation $b$ of the array $a$ that achieves this minimum.
A sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:
- $x$ is a prefix of $y$, but $x \ne y$;
- in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.
|
Let $c < 0$. We now simplify condition $(*)$, which involves considering a few cases depending on the sign of the terms. It turns out that the condition is equivalent to ($a_{i-1}-a_{i+1} \le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$) and ($b_{k-1}-a_i \le |c|$) (for full details, see the overall proof below). Sort $a$ in nonincreasing order so that $a_1 \ge a_2 \ge \dots \ge a_n$. We can simulate the greedy algorithm from the easy version with the help of a linked list of the unused elements of $a$ and a set of $a_i$ which satisfy the first part of the condition, ($a_{i-1}-a_{i+1} \le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$). Here, $a_{i-1}$ and $a_{i+1}$ actually refer to the closest unused elements of $a$, which are $a_i$'s left and right pointers in the linked list, respectively. Each time, we query the set for its smallest element $a_i$ that satisfies $a_i \ge b_{k-1}-|c|$. If this element does not exist, then we take $a_i$ to be the largest element in the linked list. Then, we set $b_k := a_i$, delete $a_i$ from the linked list, and update the set with the left and right elements of $a_i$ if they now satisfy the condition. One small observation is that in the answer $b$, $b_1 = a_1$ and $b_n = a_n$. This may simplify the implementation since it means that some edge cases of $(*)$ actually don't need to be checked. It is also actually not necessary to check the $a_{i-1} = a_i$ or $a_i = a_{i+1}$ condition. The time complexity is $\mathcal{O}(n \log n)$. The case $n \le 2$ is trivial. In the following, we only consider the case $c < 0$ and $n \ge 3$. The case $c \ge 0$ follows by symmetry (reverse the array). Let $c' := -c$ to reduce confusion with negative signs, and WLOG let $a_1 \ge a_2 \ge \dots \ge a_n$. Instead of considering $\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$, consider a permutation $b$ that minimizes the augmented cost $|b_1-b_n-c|+\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$. By circular symmetry, WLOG rotate $b$ so that $b_n = a_n$. We will perform a sequence of steps to sort $b$ in nonincreasing order without ever increasing the augmented cost. Consider looking at $b_{n-1},b_{n-2},\dots,b_1$ in order, such that when we look at $b_k$, we have the invariant that $b_{k+1} \ge b_{k+2} \ge \dots \ge b_n = a_n$. If $b_k \ge b_{k+1}$, do not do anything. Otherwise, since $b_k \ge a_n = b_n$, there exists an index $k+1 \le i < n$ such that $b_i \ge b_k \ge b_{i+1}$. Consider deleting $b_k$ from the array and reinserting it between index $i$ and $i+1$. We have the following results: Claim 1: Deleting $b_k$ decreases the augmented cost by at least $c'$. Proof: Let $x := b_{k-1}-b_k$ (or $b_n-b_1$ if $k = 1$) and $y := b_{k+1}-b_k \ge 0$. We need to check that $|x-y-c'|+c' \le |x-c'|+|-y-c'|$, which follows from $|x-c'|+|-y-c'| = |x-c'|+y+c' \ge |x-y-c'|+c'$ (we use the triangle inequality in the last step). Note that equality holds if and only if $x-c' \le 0$, i.e. $b_{k-1}-b_k \le c'$. Claim 2: Reinserting $b_k$ increases the augmented cost by at most $c'$. Proof: Let $x := b_i-b_k \ge 0$ and $y := b_k-b_{i+1} \ge 0$. We need to check that $|x-c'|+|y-c'| \le |x+y-c'|+c'$. Consider four cases: If $x,y \ge c'$, then $|x-c'|+|y-c'| = x+y-2c' < (x+y-c')+c' = |x+y-c'|+c'$. If $x \ge c', y \le c'$, then $|x-c'|+|y-c'| = x-y \le (x+y-c')+c' = |x+y-c'|+c'$. If $x \le c', y \ge c'$, then $|x-c'|+|y-c'| = y-x \le (x+y-c')+c' = |x+y-c'|+c'$. If $x,y \le c'$, then $|x-c'|+|y-c'| = 2c'-x-y = (c'-x-y)+c' \le |x+y-c'|+c'$. Note that equality holds if and only if $x = 0$ or $y = 0$ or $c'-x-y \ge 0$, i.e. $b_i-b_{i+1} \le c'$ or $b_i = b_k$ or $b_k = b_{i+1}$. Therefore, each step does not increase the augmented cost. After all the steps, $b$ will be sorted in nonincreasing order. Therefore, the smallest possible augmented cost is $|a_1-a_n-c|+\sum_{i=1}^{n-1} |a_{i+1}-a_i-c|$. Now note that $|a_1-a_n-c| = (a_1-a_n)+c'$ is the maximum possible value of $|b_1-b_n-c|$! This means that the minimum cost cannot be less than the minimum augmented cost minus $(a_1-a_n)+c'$. It follows that the minimum cost is obtained by sorting $a$ in nonincreasing order, and furthermore, any optimal permutation $b$ satisfies $b_1 = a_1$ and $b_n = a_n$. Furthermore, suppose we have fixed $b_1,\dots,b_k$ and also $b_n = a_n$. By a similar argument (looking at $b_{n-1},\dots,b_{k+1}$ and reinserting them to the right), one optimal permutation $b_{k+1},\dots,b_n$ of the remaining elements is to sort them in nonincreasing order. Our greedy algorithm can only reach states where the optimal remaining permutation satisfies $b_n = a_n$, so it is correct. Note that condition $(*)$ is similar to equality being achieved in both claim 1 and claim 2. It follows that $(*)$ is equivalent to ($a_{i-1}-a_{i+1} \le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$) and ($b_{k-1}-a_i \le |c|$) as claimed.
|
[
"binary search",
"constructive algorithms",
"data structures",
"greedy",
"math",
"sortings"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
#define mp make_pair
int a[200000],b[200000],l[200000],r[200000];
set<pii> S;
int main() {
int i;
int t,n,c;
scanf("%d",&t);
while (t--) {
scanf("%d %d",&n,&c);
for (i = 0; i < n; i++) scanf("%d",&a[i]);
if (c >= 0) {
sort(a,a+n);
for (i = 0; i < n; i++) printf("%d%c",a[i],(i == n-1) ? '\n':' ');
continue;
}
sort(a,a+n,greater<int>());
b[0] = a[0];
for (i = 0; i < n; i++) l[i] = (i+n-1) % n,r[i] = (i+1) % n;
for (i = 2; i < n-1; i++) {
if (a[l[i]]-a[r[i]] <= -c) S.insert(mp(a[i],i));
}
for (i = 1; i < n; i++) {
int u;
auto it = S.lower_bound(mp(b[i-1]+c,0));
if (it == S.end()) u = r[0];
else u = it->second,S.erase(it);
b[i] = a[u];
int x = l[u],y = r[u];
r[x] = y,l[y] = x;
S.erase(mp(a[x],x)),S.erase(mp(a[y],y));
if ((x != 0) && (l[x] != 0) && (r[x] != 0) && (a[l[x]]-a[r[x]] <= -c)) S.insert(mp(a[x],x));
if ((y != 0) && (l[y] != 0) && (r[y] != 0) && (a[l[y]]-a[r[y]] <= -c)) S.insert(mp(a[y],y));
}
for (i = 0; i < n; i++) printf("%d%c",b[i],(i == n-1) ? '\n':' ');
}
return 0;
}
|
1844
|
G
|
Tree Weights
|
You are given a tree with $n$ nodes labelled $1,2,\dots,n$. The $i$-th edge connects nodes $u_i$ and $v_i$ and has an unknown positive integer weight $w_i$. To help you figure out these weights, you are also given the distance $d_i$ between the nodes $i$ and $i+1$ for all $1 \le i \le n-1$ (the sum of the weights of the edges on the simple path between the nodes $i$ and $i+1$ in the tree).
Find the weight of each edge. If there are multiple solutions, print any of them. If there are no weights $w_i$ consistent with the information, print a single integer $-1$.
|
Let $x_u$ be the sum of the weights of the edges on the path from node $1$ to node $u$. We know that $x_1 = 0$ and $x_i + x_{i+1} - 2x_{\text{lca}(i,i+1)} = d_i$ for all $1 \le i \le n-1$. This is a system of $n$ linear equations in $n$ variables. As $x_u$ should be integers, let's first solve this system modulo $2$. The $2x_{\text{lca}(i,i+1)}$ term disappears, so we just have $x_{i+1} \equiv d_i - x_i \pmod 2$. Starting from $x_1 \equiv 0 \pmod 2$, this uniquely determines $x_2 \pmod 2$, then $x_3 \pmod 2$, and so on. Now that we know $x_1,\dots,x_n \pmod 2$, write $x_u = 2x_u' + b_u$ where $b_u$ is the first bit of $x_u$. We can rewrite our system of equations as $(2x_i'+b_i) + (2x_{i+1}'+b_{i+1}) - 2(2x_{\text{lca}(i,i+1)}'+b_{\text{lca}(i,i+1)}) = d_i$ $\iff x_i' + x_{i+1}' - 2x_{\text{lca}(i,i+1)}' = \frac{1}{2}\left(d_i-b_i-b_{i+1}+2b_{\text{lca}(i,i+1)}\right)$ which has the same form as the original system. Thus we can repeat this process to find $x_u' \pmod 2$ (giving $x_u \pmod 4$), then $x_u \pmod 8$, and so on. Note that each bit of $x_u$ is uniquely determined. If a solution exists, it satisfies $0 \le x_u \le n \cdot \max d_i \le 10^{17}$ for all $u$, so it suffices to repeat this process until we have found the first $57$ bits of $x_u$. Finally, we check that these $57$ bits correspond to a valid solution where all the original weights are positive. The time complexity is $\mathcal{O}(n(\log n + \log \max d_i))$, if the $\text{lca}(i,i+1)$ are precomputed. Remark: This idea is related to the method of Hensel Lifting.
|
[
"bitmasks",
"constructive algorithms",
"data structures",
"dfs and similar",
"implementation",
"math",
"matrices",
"number theory",
"trees"
] | 3,000
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
typedef vector<pair<int,int> > vpii;
#define mp make_pair
#define pb push_back
vpii adjList[100000];
LLI d[100000];
int parent[100000][17],parenti[100000],depth[100000];
int doDFS(int u,int p,int d) {
parent[u][0] = p,depth[u] = d;
for (auto [v,i]: adjList[u]) {
if (v != p) parenti[v] = i,doDFS(v,u,d+1);
}
return 0;
}
int logn;
int lca(int u,int v) {
int i;
if (depth[u] < depth[v]) swap(u,v);
for (i = logn-1; i >= 0; i--) {
if ((parent[u][i] != -1) && (depth[parent[u][i]] >= depth[v])) u = parent[u][i];
}
if (u == v) return u;
for (i = logn-1; i >= 0; i--) {
if (parent[u][i] != parent[v][i]) u = parent[u][i],v = parent[v][i];
}
return parent[u][0];
}
int lcas[100000],bit[100000];
LLI ans[100000],w[100000];
int main() {
int i;
int n,u,v;
scanf("%d",&n);
for (i = 0; i < n-1; i++) {
scanf("%d %d",&u,&v);
u--,v--;
adjList[u].pb(mp(v,i));
adjList[v].pb(mp(u,i));
}
for (i = 0; i < n-1; i++) scanf("%lld",&d[i]);
int j;
doDFS(0,-1,0);
for (i = 1; (1 << i) < n; i++) {
for (j = 0; j < n; j++) {
if (parent[j][i-1] != -1) parent[j][i] = parent[parent[j][i-1]][i-1];
else parent[j][i] = -1;
}
}
logn = i;
for (i = 0; i < n-1; i++) lcas[i] = lca(i,i+1);
for (i = 0; i < 57; i++) {
bit[0] = 0;
for (j = 0; j < n-1; j++) bit[j+1] = bit[j]^(d[j] & 1);
for (j = 0; j < n-1; j++) d[j] = (d[j]-bit[j]-bit[j+1]+2*bit[lcas[j]])/2;
for (j = 0; j < n; j++) ans[j] |= ((LLI) bit[j] << i);
}
for (i = 0; i < n-1; i++) {
if (d[i] != 0) {
printf("-1\n");
return 0;
}
}
for (i = 1; i < n; i++) {
w[parenti[i]] = ans[i]-ans[parent[i][0]];
if (w[parenti[i]] <= 0) {
printf("-1\n");
return 0;
}
}
for (i = 0; i < n-1; i++) printf("%lld\n",w[i]);
return 0;
}
|
1844
|
H
|
Multiple of Three Cycles
|
An array $a_1,\dots,a_n$ of length $n$ is initially all blank. There are $n$ updates where one entry of $a$ is updated to some number, such that $a$ becomes a permutation of $1,2,\dots,n$ after all the updates.
After each update, find the number of ways (modulo $998\,244\,353$) to fill in the remaining blank entries of $a$ so that $a$ becomes a permutation of $1,2,\dots,n$ and all cycle lengths in $a$ are multiples of $3$.
A permutation of $1,2,\dots,n$ is an array of length $n$ consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. A cycle in a permutation $a$ is a sequence of pairwise distinct integers $(i_1,\dots,i_k)$ such that $i_2 = a_{i_1},i_3 = a_{i_2},\dots,i_k = a_{i_{k-1}},i_1 = a_{i_k}$. The length of this cycle is the number $k$, which is a multiple of $3$ if and only if $k \equiv 0 \pmod 3$.
|
The partially formed permutation is composed of several paths and cycles, and only the length of each path/cycle modulo $3$ matters. We can use a DSU to track the number of paths/cycles of each length $\pmod 3$. If at any point a cycle whose length is not $\equiv 0 \pmod 3$ is formed, the answer is $0$. Thus, the problem reduces to the following: Given $a$ $1$s, $b$ $2$s, and $c$ $0$s, how many ways are there to build a permutation on these objects so that each cycle sums to a multiple of $3$? Let $f(a,b,c)$ be the answer to this problem. Note that $f(a,b,c) = (a+b+c)f(a,b,c-1)$ for $c > 0$, as there are $a+b+c$ ways to choose the next object of any $0$, and after merging this $0$ with its next object, there are $f(a,b,c-1)$ ways to build a permutation on the remaining objects. Repeatedly applying this recurrence gives $f(a,b,c) = \frac{(a+b+c)!}{(a+b)!}f(a,b,0)$, so we can eliminate the $c$ parameter and multiply the answer by a factorial and inverse factorial in the end. Now let $f(a,b) = f(a,b,0)$. We have not one, but two recurrence relations $f(a,b)$ satisfies: $f(a,b) = bf(a-1,b-1,1) + (a-1)f(a-2,b+1) = b(a+b-1)f(a-1,b-1) + (a-1)f(a-2,b+1)$ when $a > 0$ (consider the next object of any $1$) $f(a,b) = af(a-1,b-1,1) + (b-1)f(a+1,b-2) = a(a+b-1)f(a-1,b-1) + (b-1)f(a+1,b-2)$ when $b > 0$ (consider the next object of any $2$) The key idea now is that because we have two equations relating the four values $f(a,b),f(a-1,b-1),f(a+2,b-1),f(a-1,b+2)$, given any two of these values, we can solve for the other two. For example, if we know $f(a,b)$ and $f(a-1,b-1)$, we can calculate $f(a-2,b+1) = \frac{f(a,b)-b(a+b-1)f(a-1,b-1)}{a-1}$. Also note that the queried pairs $(a,b)$ can be visualized as a walk in the plane, where each pair does not differ from the previous pair by much. By using these recurrences carefully, it is possible to calculate $f(a,b)$ for all queries $(a,b)$ while calculating only $\mathcal{O}(n)$ values of $f$. The details can be tricky. The author's solution does the following: First, reverse the order of the updates, possibly adding dummy updates if a cycle whose length is not $\equiv 0 \pmod 3$ is created early. Then we need to find $f(a_i,b_i)$ for a sequence of pairs $(a_1,b_1),(a_2,b_2),\dots$ where $(a_1,b_1) = (0,0)$ and $(a_{i+1},b_{i+1})$ is one of $(a_i,b_i)$, $(a_i-1,b_i+2)$, $(a_i+2,b_i-1)$, or $(a_i+1,b_i+1)$ for all $i$. We loop through $i$ in order, maintaining two values $u := f(a_i,b_i)$ and $v := f(a_i+1,b_i+1)$ at all times. Whenever we need a transition of the form $(a_i,b_i) \to (a_i-1,b_i+2)$, we use the recurrence $f(a_i+1,b_i+1) = (b_i+1)(a_i+b_i+1)f(a_i,b_i) + a_if(a_i-1,b_i+2)$ to solve for $f(a_i-1,b_i+2)$ (the new value of $u$), then use the recurrence $f(a_i,b_i+3) = a_i(a_i+b_i+2)f(a_i-1,b_i+2) + (b_i+2)f(a_i+1,b_i+1)$ to find $f(a_i,b_i+3)$ (the new value of $v$). The $(a_i,b_i) \to (a_i+2,b_i-1)$ transition is similar. For $(a_i,b_i) \to (a_i+1,b_i+1)$ transitions, do both of the previous types of transitions once. The time complexity of the main part of the problem is $\mathcal{O}(N)$. The overall time complexity is $\mathcal{O}(N\alpha(N))$, dominated by the DSU operations. Remark 1: Since $1$s and $2$s behave symmetrically, $f(a,b,c) = f(b,a,c)$. Remark 2: The exponential generating function for $f(a,b)$ is $\sum_{a \ge 0}\sum_{b \ge 0} \frac{f(a,b)}{a!b!}x^ay^b = (1-(x^3+3xy+y^3))^{-1/3}$.
|
[
"combinatorics",
"data structures",
"dp",
"dsu",
"math"
] | 3,400
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int LLI;
#define MOD 998244353
int parent[300000],siz[300000];
int find(int n) {
if (parent[n] != n) parent[n] = find(parent[n]);
return parent[n];
}
int queries[600000][3],ans[600000];
int fact[300000],invfact[300000],invn[300000];
int inv(int n) {
int e = MOD-2,r = 1;
while (e > 0) {
if (e & 1) r = ((LLI) r*n) % MOD;
e >>= 1;
n = ((LLI) n*n) % MOD;
}
return r;
}
int main() {
int i;
int n,x,y,bad = 1e9;
int num[3];
scanf("%d",&n);
for (i = 0; i < n; i++) parent[i] = i,siz[i] = 1;
num[0] = 0,num[1] = n,num[2] = 0;
for (i = 0; i < n; i++) {
scanf("%d %d",&x,&y);
x--,y--;
if (find(x) != find(y)) {
num[siz[find(x)] % 3]--;
num[siz[find(y)] % 3]--;
siz[find(y)] += siz[find(x)];
parent[find(x)] = find(y);
num[siz[find(y)] % 3]++;
}
else if ((siz[find(x)] % 3) == 0) num[0]--;
else if (bad == 1e9) bad = i;
copy(num,num+3,queries[i]);
}
fact[0] = 1;
for (i = 1; i < n; i++) fact[i] = ((LLI) i*fact[i-1]) % MOD;
invfact[n-1] = inv(fact[n-1]);
for (i = n-2; i >= 0; i--) invfact[i] = ((LLI) (i+1)*invfact[i+1]) % MOD;
for (i = 1; i < n; i++) invn[i] = ((LLI) invfact[i]*fact[i-1]) % MOD;
int m = n;
while (num[1]+num[2] > 0) {
int a = (num[1] > 0) ? 1:2;
num[a]--;
int b = (num[1] > 0) ? 1:2;
num[b]--;
num[(a+b) % 3]++;
copy(num,num+3,queries[m++]);
}
x = 1,y = 1;
int u = 1,v = 8;
auto f = [&]() {
assert(x > 0);
int nu = (((v-(((LLI) (y+1)*(x+y+1)) % MOD)*u) % MOD)*invn[x]) % MOD;
int nv = ((((LLI) x*(x+y+2)) % MOD)*nu+(LLI) (y+2)*v) % MOD;
x--,y += 2,u = nu,v = nv;
if (u < 0) u += MOD;
if (v < 0) v += MOD;
};
auto g = [&]() {
assert(y > 0);
int nu = (((v-(((LLI) (x+1)*(x+y+1)) % MOD)*u) % MOD)*invn[y]) % MOD;
int nv = ((((LLI) y*(x+y+2)) % MOD)*nu+(LLI) (x+2)*v) % MOD;
x += 2,y--,u = nu,v = nv;
if (u < 0) u += MOD;
if (v < 0) v += MOD;
};
for (i = m-1; i >= 0; i--) {
int a = queries[i][1],b = queries[i][2],c = queries[i][0];
if ((a == 0) && (b == 0)) ans[i] = 1;
else if ((a == x) && (b == y)) ans[i] = u;
else if ((a == x-1) && (b == y+2)) f(),ans[i] = u;
else if ((a == x+2) && (b == y-1)) g(),ans[i] = u;
else if ((a == x+1) && (b == y+1)) {
if (x > 0) f(),g(),ans[i] = u;
else g(),f(),ans[i] = u;
}
else assert(0);
ans[i] = ((LLI) ans[i]*fact[a+b+c]) % MOD;
ans[i] = ((LLI) ans[i]*invfact[a+b]) % MOD;
}
for (i = 0; i < n; i++) printf("%d\n",(i >= bad) ? 0:ans[i]);
return 0;
}
|
1845
|
A
|
Forbidden Integer
|
You are given an integer $n$, which you want to obtain. You have an unlimited supply of every integer from $1$ to $k$, except integer $x$ (there are no integer $x$ at all).
You are allowed to take an arbitrary amount of each of these integers (possibly, zero). Can you make the sum of taken integers equal to $n$?
If there are multiple answers, print any of them.
|
The problem is about considering the least amount of cases possible. I propose the following options. If $x \neq 1$, then you can always print $n$ ones. So the answer is YES. If $k = 1$, then no integer is available, so the answer is NO. If $k = 2$, then only $2$ is available, so you can only collect even $n$. So if it's odd, the answer is NO. Otherwise, you can always collect $n$ with the following construction: if $n$ is even then take $2$, otherwise take $3$. Then take $\lfloor \frac{n}{2} \rfloor - 1$ twos. You can see that an even $n$ only uses twos, so it fits the previous check. If it's odd, then $k$ is at least $3$, so $3$ is allowed to take. Overall complexity: $O(n)$ per testcase.
|
[
"constructive algorithms",
"implementation",
"math",
"number theory"
] | 800
|
for _ in range(int(input())):
n, k, x = map(int, input().split())
if x != 1:
print("YES")
print(n)
print(*([1] * n))
elif k == 1 or (k == 2 and n % 2 == 1):
print("NO")
else:
print("YES")
print(n // 2)
print(*([3 if n % 2 == 1 else 2] + [2] * (n // 2 - 1)))
|
1845
|
B
|
Come Together
|
Bob and Carol hanged out with Alice the whole day, but now it's time to go home. Alice, Bob and Carol live on an infinite 2D grid in cells $A$, $B$, and $C$ respectively. Right now, all of them are in cell $A$.
If Bob (or Carol) is in some cell, he (she) can move to one of the neighboring cells. Two cells are called neighboring if they share a side. For example, the cell $(3, 5)$ has four neighboring cells: $(2, 5)$, $(4, 5)$, $(3, 6)$ and $(3, 4)$.
Bob wants to return to the cell $B$, Carol — to the cell $C$. Both of them want to go along the shortest path, i. e. along the path that consists of the minimum possible number of cells. But they would like to walk together as well.
What is the maximum possible number of cells that Bob and Carol can walk together if each of them walks home using one of the shortest paths?
|
Let $d(P_1, P_2)$ be the Manhattan distance between points $P_1 = (x_1, y_1)$ and $P_2 = (x_2, y_2)$. Then $d(P_1, P_2) = |x_1 - x_2| + |y_1 - y_2|$. Note that if you are going from $A$ to $B$ (or to $C$) along the shortest path, the Manhattan distance will be decreasing with each move. So Bob and Carol can walk together as along as they find the next cell that is closer to both $B$ and $C$. Now note that if they are in the bounding box of cells $B$ and $C$ then there are no such "next cell", since $d(X, B) + d(X, C)$ is constant and equal to $d(A, B)$ if $X$ is in the bounding box. In other words, Bob and Carol can walk together until they reach some cell $X$ inside the bounding box, where they split up. Finally, let's look at the total distance they will walk: from one side it's $d(A, B) + d(A, C)$. But from the other side it's $2 \cdot d(A, X) + d(X, B) + d(X, C)$. So, $d(A, X) = \frac{d(A, B) + d(A, C) - (d(X, B) + d(X, C))}{2}$ $\frac{d(A, B) + d(A, C) - d(B, C)}{2} + 1$
|
[
"geometry",
"implementation",
"math"
] | 900
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
pt A, B, C;
inline bool read() {
if(!(cin >> A.x >> A.y))
return false;
cin >> B.x >> B.y;
cin >> C.x >> C.y;
return true;
}
int dist(const pt &A, const pt &B) {
return abs(A.x - B.x) + abs(A.y - B.y);
}
inline void solve() {
cout << (dist(A, B) + dist(A, C) - dist(B, C)) / 2 + 1 << 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);
cout << fixed << setprecision(15);
int t; cin >> t;
while (t--) {
read();
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1845
|
C
|
Strong Password
|
Monocarp finally got the courage to register on ForceCoders. He came up with a handle but is still thinking about the password.
He wants his password to be as strong as possible, so he came up with the following criteria:
- the length of the password should be exactly $m$;
- the password should only consist of digits from $0$ to $9$;
- the password should not appear in the password database (given as a string $s$) as a \textbf{subsequence} (not necessarily contiguous).
Monocarp also came up with two strings of length $m$: $l$ and $r$, both consisting only of digits from $0$ to $9$. He wants the $i$-th digit of his password to be between $l_i$ and $r_i$, inclusive.
Does there exist a password that fits all criteria?
|
Consider the naive solution. You iterate over all password options that fit the criteria on $l$ and $r$ and check if they appear in $s$ as a subsequence. That check can be performed greedily: find the first occurrence of the first digit of the password, then find the first occurrence after it of the second digit of the password, and so on. If all digits are found, then it's present. Otherwise, it isn't. Notice how the checks from the $i$-th digit onwards only depend on the position of the $(i-1)$-st digit. Moreover, to have a lower probability to find these digits, we want the $(i-1)$-st digit to be as much to the right as possible. That leads us to the greedy solution to the full problem. Iterate over the first digit and choose the one that appears as much to the right as possible. Then the same for the second digit, and so on. If any digit is not found in the string after the starting position of the check, then the password that starts with the chosen digits is strong. So far, the solution sounds like $O(nmD)$, where $D$ is the number of digits (equal to $10$). Which is actually fine under these constraints, but we can do better. One option is to precalculate something to help us find the next occurrence of each digit. For example, that can be an array of positions of each digit. Then we can use lower_bound on it to find the next one. That would be $O(n + D + mD \log n)$. Alternatively, you can calculate an array $\mathit{next}[i][j]$ that stores the next occurrence of digit $j$ from position $i$. It's possible to calculate $\mathit{next}[i]$ from $\mathit{next}[i + 1]$. Notice that only $\mathit{next}[i][s[i]]$ changes. So you can copy $\mathit{next}[i + 1]$ into $\mathit{next}[i]$ and set $\mathit{next}[i][s[i]] = i$. Now you can just query the array by looking into the corresponding cells. That would be $O(nD + mD)$. Finally, let's analyze the complexity of the linear search better. So, for each digit, actually run a while loop that searches the string until it encounters that letter. We proposed that it is $O(nmD)$. Notice that if some iteration of the loop for the $i$-th digit passes a position $x$, then the digits from the $(i+1)$-st onwards won't look into it. So, such position can only be checked in $O(D)$ loops (all loops for the current digit). Thus, each of $n$ positions can only be accessed $O(D)$ times, making the solution $O(m + nD)$, which makes it the fastest of all our options. That is basically the same analysis as two pointers. $O(m)$ comes from the outer loop over digits that you can't really get rid of. However, you can say that $m \le n$ ($m > n$ can be solved in $O(1)$), and call the solution $O(nD)$. Overall complexity: $O(m + nD)$ for each testcase.
|
[
"binary search",
"dp",
"greedy",
"strings"
] | 1,400
|
import sys
for _ in range(int(sys.stdin.readline())):
s = [int(c) for c in sys.stdin.readline().strip()]
n = len(s)
m = int(sys.stdin.readline())
l = sys.stdin.readline()
r = sys.stdin.readline()
mx = 0
for i in range(m):
li = int(l[i])
ri = int(r[i])
nmx = mx
for c in range(li, ri + 1):
cur = mx
while cur < n and s[cur] != c:
cur += 1
nmx = max(nmx, cur)
mx = nmx + 1
print("YES" if mx > n else "NO")
|
1845
|
D
|
Rating System
|
You are developing a rating system for an online game. Every time a player participates in a match, the player's rating changes depending on the results.
Initially, the player's rating is $0$. There are $n$ matches; after the $i$-th match, the rating change is equal to $a_i$ (the rating increases by $a_i$ if $a_i$ is positive, or decreases by $|a_i|$ if it's negative. There are no zeros in the sequence $a$).
The system has an additional rule: for a fixed integer $k$, if a player's rating has reached the value $k$, it will never fall below it. Formally, if a player's rating at least $k$, and a rating change would make it less than $k$, then the rating will decrease \textbf{to exactly $k$}.
Your task is to determine the value $k$ in such a way that the player's rating after all $n$ matches is the maximum possible (among all integer values of $k$). If there are multiple possible answers, you can print any of them.
|
Let's fix some $k$ and look at the first and the last moment when the rating should fall below $k$, but doesn't. After such moments, the rating is equal to $k$. So we can "delete" all changes (array elements) between those moments. And the remaining changes (to the left from the first moment and to the right from the last moment) can be considered without any additional constraints (the value of $k$ doesn't affect those changes). Using this fact, we can see that the total rating is not greater than the sum of the whole array minus some continuous segment. So the maximum possible final rating doesn't exceed the sum of the array minus the minimum sum segment (this segment can be empty, if all elements are positive). In fact, there is always such $k$ that provides such rating. Let the minimum sum segment be $[l; r]$, then $k$ is equal to the prefix sum from $1$-st to $(l-1)$-th positions of the array. The only remaining question is: why the rating after $r$-th match is equal to $k$? It can't fall below $k$ (since the rating is at least $k$ already); and if it is greater than $k$, then there is a positive suffix of the segment $[l; r]$, so we can remove it, and the sum of the segment would decrease. Which means the segment $[l; r]$ is not minimum sum segment, which contradicts the previous statement. So the rating after $r$-th match is equal to $k$.
|
[
"binary search",
"brute force",
"data structures",
"dp",
"dsu",
"greedy",
"math",
"two pointers"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
using li = long long;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
li delta = 0, ans = 0;
li sum = 0, mx = 0;
for (int i = 0; i < n; ++i) {
li x; cin >> x;
sum += x;
mx = max(mx, sum);
if (sum - mx < delta) {
delta = sum - mx;
ans = mx;
}
}
cout << ans << '\n';
}
}
|
1845
|
E
|
Boxes and Balls
|
There are $n$ boxes placed in a line. The boxes are numbered from $1$ to $n$. Some boxes contain one ball inside of them, the rest are empty. At least one box contains a ball and at least one box is empty.
In one move, you \textbf{have to} choose a box with a ball inside and an adjacent empty box and move the ball from one box into another. Boxes $i$ and $i+1$ for all $i$ from $1$ to $n-1$ are considered adjacent to each other. Boxes $1$ and $n$ are \textbf{not adjacent}.
How many different arrangements of balls exist after \textbf{exactly} $k$ moves are performed? Two arrangements are considered different if there is at least one such box that it contains a ball in one of them and doesn't contain a ball in the other one.
Since the answer might be pretty large, print its remainder modulo $10^9+7$.
|
Consider a harder problem. For each $k'$ from $0$ to $k$, what's the number of arrangements that have $k'$ as the smallest number of operations needed that obtain them? That would help us solve the full problem. You just have to sum up the answer for $k'$ such that they have the same parity as $k$ (since, once the arrangement is obtained, you can perform two moves on it and change nothing). Turns out, calculating the smallest number of operations for a fixed arrangement is not that hard. Let the initial arrangement have balls in boxes $c_1, c_2, \dots, c_t$ for some $t$; the fixed arrangement have balls in boxes $d_1, d_2, \dots, d_t$. Then the first ball in the fixed arrangement has to come from the box of the first ball in the initial one. And so on. So the answer is at least $\sum\limits_{i=1}^t |c_t - d_t|$. That estimate can be achieved. Just move the balls one by one from left to right. So that amount is actually the smallest possible. That can lead to a dynamic programming solution. Following this construction, let $\mathit{dp}[i][j][k]$ be the number of ways to fill the first $i$ boxes with $j$ balls such that the smallest number of operations to move the first $j$ balls of the initial arrangement into their new boxes is $k$. The transitions are trivial. Either leave the $i$-th (all $0$-indexed) box empty and go to $\mathit{dp}[i+1][j][k]$ or put a ball into it and go to $\mathit{dp}[i+1][j+1][k + |i - c_j|]$. The answer will be in $\mathit{dp}[n][t][k']$ for all $k'$ of the same parity as $k$. That solution is $O(n^2k)$ that is supposedly too much (although unfortunately can be squeezed if you try hard enough). That solution has surprisingly little to do with the full one but gives us some insight into the problem. For a faster solution, let's change the way we calculate the smallest number of operations. What is exactly $|c_t - d_t|$? Let $c_t > d_t$. Then on its path the ball crosses the spaces between boxes $c_t$ and $c_t-1$, $c_t-1$ and $c_t-2$, so on until $d_t+1$ and $d_t$. The amount is exactly $(c_t - d_t)$. Thus, we could instead calculate the number of balls that move across each space between the boxes along their paths and add up the values. Now it's some sort of balance. We could also denote balls going to the right as positive values and going to the left as negative values. Notice how if some ball moves from a box $i$ to a box $i-1$ in the optimal construction, then there is no ball that moves from $i-1$ to $i$. Just because the balls never cross each other paths. So the absolute value of the balance is still what we have to add up. Intuitively, the value for space between boxes $i$ and $i+1$ is equal to the signed difference between the initial number of balls to the left of it and the one in the current arrangement. If the numbers are different, then we move exactly this amount of ball from one side to another. Now we can pack it into another dynamic programming. Let $\mathit{dp}[i][j][k]$ be the number of ways to fill the first $i$ boxes, such that the current balance is $j$ and the smallest number of operations to achieve that is $k$. The transitions are the following. If we place a ball into box $i$, the balance changes to $j + 1 - a_i$ ($a_i$ is whether there was a ball in box $i$ initially) and $|j + 1 - a_i|$ gets added to $k$. If we don't place a ball, the balance changes to $j - a_i$ and $|j - a_i|$ gets added to $k$. Notice that at the end the balance will be $0$ if and only if we placed as many boxes as there were initially. So, the answer will be in $\mathit{dp}[n][0][k']$ for all $k'$ of the same parity as $k$. That solution is still $O(n^2k)$ and even worse in the way that $j$ can range from $-n$ to $n$, doubling the runtime. However, notice how $j$ can't change by more than $1$ on each step. At the same time, $|j|$ always gets added to $k$. Thus, to make $j$ equal to $0$ at the end, we would have to add $|j| + (|j| - 1) + (|j| - 2) + \dots + 1$ to $k$. And since $k$ can't exceed $1500$, $|j|$ actually can't exceed $55$ (more or less $O(\sqrt{k})$). So, that solution can be optimized to $O(nk^{1.5})$ by reducing the second dimension of the dynamic programming. In order to store values from $-x$ to $x$ in an array, shift them up by $x$. So the values become from $0$ to $2x$. In order to avoid $O(nk^{1.5})$ memory, instead of storing all $n$ layers of the dp, only store the current and the next one. That will make it $O(k^{1.5})$ memory. Overall complexity: $O(nk^{1.5})$.
|
[
"dp",
"implementation",
"math"
] | 2,500
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int MOD = int(1e9) + 7;
int add(int a, int b){
a += b;
if (a >= MOD)
a -= MOD;
return a;
}
int main() {
int n, k;
scanf("%d%d", &n, &k);
vector<int> a(n);
forn(i, n) scanf("%d", &a[i]);
int lim = 1;
while (lim * (lim + 1) < k * 2) ++lim;
vector<vector<vector<int>>> dp(2, vector<vector<int>>(2 * lim + 1, vector<int>(k + 1)));
dp[0][lim][0] = 1;
forn(ii, n){
int i = ii & 1;
int ni = i ^ 1;
dp[ni] = vector<vector<int>>(2 * lim + 1, vector<int>(k + 1));
forn(j, 2 * lim + 1) forn(t, k + 1) if (dp[i][j][t]){
forn(z, 2){
int nj = j + z - a[ii];
int nt = t + abs(nj - lim);
if (nt <= k) dp[ni][nj][nt] = add(dp[ni][nj][nt], dp[i][j][t]);
}
}
}
int ans = 0;
for (int t = k & 1; t <= k; t += 2)
ans = add(ans, dp[n & 1][lim][t]);
printf("%d\n", ans);
return 0;
}
|
1845
|
F
|
Swimmers in the Pool
|
There is a pool of length $l$ where $n$ swimmers plan to swim. People start swimming at the same time (at the time moment $0$), but you can assume that they take different lanes, so they don't interfere with each other.
Each person swims along the following route: they start at point $0$ and swim to point $l$ with constant speed (which is equal to $v_i$ units per second for the $i$-th swimmer). After reaching the point $l$, the swimmer instantly (in negligible time) turns back and starts swimming to the point $0$ with the same constant speed. After returning to the point $0$, the swimmer starts swimming to the point $l$, and so on.
Let's say that some \textbf{real} moment of time is a meeting moment if there are \textbf{at least two} swimmers that are in the same point of the pool at that moment of time (that point may be $0$ or $l$ as well as any other real point inside the pool).
The pool will be open for $t$ seconds. You have to calculate the number of meeting moments while the pool is open. Since the answer may be very large, print it modulo $10^9 + 7$.
|
Firstly, note that there are two different situations when some two swimmers meet: they either move in the same direction, or in opposite directions. Suppose, swimmers $i$ and $j$ meet while moving in the same direction. We can write some easy system of equation and get that they will meet each $\frac{2l}{|v_i - v_j|}$ seconds. Analogically, if they meet while moving in the opposite directions, they will meet each $\frac{2l}{v_i + v_j}$ seconds. Let's create array $w$ that will contain all possible values $|v_i \pm v_j|$ exactly once. If $V = \max{v_i}$ then values $w_i \le 2V$ and we can calculate all of them using FFT fast multiplication two times: for sums $v_i + v_j$ and for differences $v_i - v_j$. Okay, we got all possible $w_i$, how to calculate the answer. For a fixed value $w_i$ meeting moments are $\frac{2l \cdot k}{w_i}$ for all $k$ in segment $[1, k_i]$. $k_i$ is the upper bound and can be calculated as $k_i = \left\lfloor \frac{t \cdot w_i}{2l} \right\rfloor$. We found that for each $w_i$ there are exactly $k_i$ meeting points, but since in one meeting moment more than two swimmers may meet we need to calculate each value $\frac{2l \cdot k}{w_i}$ exactly once. Note that $\frac{2l \cdot k_1}{w_i} = \frac{2l \cdot k_2}{w_j}$ iff $\frac{k_1}{w_i} = \frac{k_2}{w_j}$. And we can rephrase our task as following: calculate the number of unique fractions $\frac{k}{w_i}$ where $1 \le k \le k_i$. The key idea here is to calculate only irreducible fractions. Suppose we have fractions $\frac{1}{w_i}, \frac{2}{w_i}, \dots, \frac{k_i}{w_i}$. Let's add to the answer only irreducible fractions among them (we will discuss how to do it later). For any other fraction $\frac{k'}{w_i}$ $(k', w_i) = d > 1$ and $d$ is a divisor of $w_i$. If we fix some divisor $d$ of $w_i$ there will be exactly $\left\lfloor \frac{k_i}{d} \right\rfloor$ fractions $\frac{k'}{w_i}$ with $d | (k', w_i)$. Moreover, numerators will also form a segment $[1, \frac{k_i}{d}]$. So, instead of calculating them now, we will just "pass" that task to $w_j = \frac{w_i}{d}$. In total, we iterate $w_i$ in decreasing order, add only the number of irreducible fractions $\frac{k}{w_i}$ to the answer. Then iterate over all divisors $d$ of $w_i$ and "update" value $k_j$ for $w_j = \frac{w_i}{d}$ with value $\frac{k_i}{d}$. How to calculate the number of irreducible fractions $\frac{k}{w_i}$ with $1 \le k \le k_i$? With Möbius function, of course: $ir_i = \sum_{d | w_i}{\mu(d) \left\lfloor \frac{k_i}{d} \right\rfloor}$ Both passing calculations and Möbius inversion works in $O(\text{number of divisors}(w_i))$. And since we iterate over all $w_i \le 2 V$, the total complexity is $O(V \log V)$. Both FFT and next part works in $O(V \log V)$, so the total complexity is $O(n + V \log V)$. P.S.: If you note that if $w_j = \frac{w_i}{d}$ then $k_j$ is always equal to $\frac{k_i}{d}$ then you can not only simplify the part with "passing down calculations" but get rid of Möbius inversion at all, replacing it with Sieve-like two for-s iterations.
|
[
"dp",
"fft",
"math",
"number theory"
] | 2,800
|
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define forn(i, n) for(int i = 0; i < int(n); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
return out << "(" << p.x << ", " << p.y << ")";
}
template<class A> ostream& operator <<(ostream& out, const vector<A> &v) {
fore(i, 0, sz(v)) {
if(i) out << " ";
out << v[i];
}
return out;
}
const int INF = int(1e9);
const li INF64 = li(1e18);
const int LOGN = 19;
const int N = (1 << LOGN) + 555;
struct comp {
double x, y;
comp(double x = .0, double y = .0) : x(x), y(y) {}
inline comp conj() { return comp(x, -y); }
};
inline comp operator +(const comp &a, const comp &b) {
return comp(a.x + b.x, a.y + b.y);
}
inline comp operator -(const comp &a, const comp &b) {
return comp(a.x - b.x, a.y - b.y);
}
inline comp operator *(const comp &a, const comp &b) {
return comp(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
inline comp operator /(const comp &a, const double &b) {
return comp(a.x / b, a.y / b);
}
namespace FFT {
const double PI = acosl(-1.0);
vector<comp> w[LOGN];
vector<int> rv;
void precalc() {
forn(st, LOGN) {
w[st].resize(1 << st);
forn(i, 1 << st) {
double ang = PI / (1 << st) * i;
w[st][i] = comp(cos(ang), sin(ang));
}
}
rv.assign(1 << LOGN, 0);
fore(i, 1, sz(rv))
rv[i] = (rv[i >> 1] >> 1) | ((i & 1) << (LOGN - 1));
}
inline void fft(comp a[N], int n, bool inv) {
int ln = __builtin_ctz(n);
forn(i, n) {
int ni = rv[i] >> (LOGN - ln);
if(i < ni) swap(a[i], a[ni]);
}
for(int st = 0; st < ln; st++) {
int len = 1 << st;
for(int k = 0; k < n; k += (len << 1))
fore(pos, k, k + len) {
comp l = a[pos];
comp r = a[pos + len] * w[st][pos - k];
a[pos] = l + r;
a[pos + len] = l - r;
}
}
if(inv) {
forn(i, n)
a[i] = a[i] / n;
reverse(a + 1, a + n);
}
}
comp aa[N], bb[N], cc[N];
inline void multiply(int a[N], int sza, int b[N], int szb, int c[N], int &szc) {
int ln = 1;
while(ln < (sza + szb)) // sometimes works max(sza, szb)
ln <<= 1;
forn(i, ln)
aa[i] = (i < sza ? a[i] : comp());
forn(i, ln)
bb[i] = (i < szb ? b[i] : comp());
fft(aa, ln, false);
fft(bb, ln, false);
forn(i, ln)
cc[i] = aa[i] * bb[i];
fft(cc, ln, true);
szc = ln;
forn(i, szc)
c[i] = int(cc[i].x + 0.5);
}
}
const int MOD = int(1e9) + 7;
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);
}
li l, t;
int n;
vector<int> v;
inline bool read() {
if(!(cin >> l >> t >> n))
return false;
v.resize(n);
fore (i, 0, n)
cin >> v[i];
return true;
}
int mu[N], minD[N];
vector<int> divs[N];
void precalcDivs(int N) {
fore (d, 1, N) {
for (int v = d; v < N; v += d)
divs[v].push_back(d);
}
mu[1] = 1;
fore (d, 2, N) {
if (minD[d] == 0)
minD[d] = d;
if (minD[d] != minD[d / minD[d]])
mu[d] = -mu[d / minD[d]];
for (int v = 2 * d; v < N; v += d) {
if (minD[v] == 0)
minD[v] = d;
}
}
}
int vs[2][N], res[N], ps[N];
li mxk[N];
inline void solve() {
FFT::precalc();
fore (i, 0, n) {
vs[0][v[i]] = 1;
vs[1][v[i]] = 1;
}
int sz = 1 + *max_element(v.begin(), v.end());
int szRes = 0;
FFT::multiply(vs[0], sz, vs[1], sz, res, szRes);
fore (i, 0, szRes) {
if (!(i & 1) && vs[0][i >> 1] > 0)
res[i]--;
if (res[i] > 0) {
ps[i] = 1;
}
}
memset(vs[1], 0, sizeof vs[1]);
fore (i, 0, n)
vs[1][sz - 1 - v[i]] = 1;
FFT::multiply(vs[0], sz, vs[1], sz, res, szRes);
fore (i, sz, szRes) {
if (res[i] > 0) {
ps[i - sz + 1] = 1;
}
}
precalcDivs(2 * sz);
int ans = 0;
for (int i = N - 1; i > 0; i--) {
if (ps[i] > 0)
mxk[i] = max(mxk[i], t * 1ll * i / (2ll * l));
for (int d : divs[i]) {
// ans += mu[d] * (mxk[i] / d);
ans = norm(ans + mu[d] * int((mxk[i] / d) % MOD));
mxk[i / d] = max(mxk[i / d], mxk[i] / d);
}
}
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);
cout << fixed << setprecision(15);
if(read()) {
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
|
1846
|
A
|
Rudolph and Cut the Rope
|
There are $n$ nails driven into the wall, the $i$-th nail is driven $a_i$ meters above the ground, one end of the $b_i$ meters long rope is tied to it. All nails hang at different heights one above the other. One candy is tied to all ropes at once. Candy is tied to end of a rope that is not tied to a nail.
To take the candy, you need to lower it to the ground. To do this, Rudolph can cut some ropes, one at a time. Help Rudolph find the minimum number of ropes that must be cut to get the candy.
The figure shows an example of the first test:
|
In order for the candy to be on the ground, it is necessary that all the ropes touch the ground. This means that the length of all ropes must be greater than or equal to the height of the nails to which they are attached. That is, you need to cut all the ropes, the length of which is less than the height of their nail. Then the answer is equal to the number of elements that have $a_i>b_i$.
|
[
"implementation",
"math"
] | 800
|
#include <iostream>
using namespace std;
int main() {
int test_cases;
cin >> test_cases;
for (int test_case = 0; test_case < test_cases; test_case++) {
int n;
cin >> n;
int ans = 0;
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
if (a > b)
ans++;
}
cout << ans << endl;
}
return 0;
}
|
1846
|
B
|
Rudolph and Tic-Tac-Toe
|
Rudolph invented the game of tic-tac-toe for three players. It has classic rules, except for the third player who plays with pluses. Rudolf has a $3 \times 3$ field — the result of the completed game. Each field cell contains either a cross, or a nought, or a plus sign, or nothing. The game is won by the player who makes a horizontal, vertical or diagonal row of $3$'s of their symbols.
Rudolph wants to find the result of the game. Either exactly one of the three players won or it ended in a draw. It is guaranteed that multiple players cannot win at the same time.
|
To solve this problem, it is enough to check the equality of elements on each row, column and diagonal of three elements. If all three elements are equal and are not ".", then the value of these elements is the answer. Note that a row of "." does not give you answer ".". Statement does not say that the players have equal amount of moves, which means that one player can have several winning rows.
|
[
"brute force",
"implementation",
"strings"
] | 800
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int test_cases;
cin >> test_cases;
for (int test_case = 0; test_case < test_cases; test_case++) {
vector<string> v(3);
for (int i = 0; i < 3; i++)
cin >> v[i];
string ans = "DRAW";
for(int i = 0; i < 3; i++) {
if (v[i][0] == v[i][1] && v[i][1] == v[i][2] && v[i][0] != '.')
ans=v[i][0];
}
for (int i = 0; i < 3; i++) {
if (v[0][i] == v[1][i] && v[1][i] == v[2][i] && v[0][i] != '.')
ans=v[0][i];
}
if (v[0][0] == v[1][1] && v[1][1] == v[2][2] && v[0][0] != '.')
ans=v[0][0];
if (v[0][2] == v[1][1] && v[1][1] == v[2][0] && v[0][2] != '.')
ans=v[0][2];
cout << ans << endl;
}
return 0;
}
|
1846
|
C
|
Rudolf and the Another Competition
|
Rudolf has registered for a programming competition that will follow the rules of ICPC. The rules imply that for each solved problem, a participant gets $1$ point, and also incurs a penalty equal to the number of minutes passed from the beginning of the competition to the moment of solving the problem. In the final table, the participant with the most points is ranked higher, and in case of a tie in points, the participant with the lower penalty is ranked higher.
In total, $n$ participants have registered for the competition. Rudolf is a participant with index $1$. It is known that $m$ problems will be proposed. And the competition will last $h$ minutes.
A powerful artificial intelligence has predicted the values $t_{i, j}$, which represent the number of minutes it will take for the $i$-th participant to solve the $j$-th problem.
Rudolf realized that the order of solving problems will affect the final result. For example, if $h = 120$, and the times to solve problems are [$20, 15, 110$], then if Rudolf solves the problems in the order:
- ${3, 1, 2}$, then he will only solve the third problem and get $1$ point and $110$ penalty.
- ${1, 2, 3}$, then he will solve the first problem after $20$ minutes from the start, the second one after $20+15=35$ minutes, and he will not have time to solve the third one. Thus, he will get $2$ points and $20+35=55$ penalty.
- ${2, 1, 3}$, then he will solve the second problem after $15$ minutes from the start, the first one after $15+20=35$ minutes, and he will not have time to solve the third one. Thus, he will get $2$ points and $15+35=50$ penalty.
Rudolf became interested in what place he will take in the competition if each participant solves problems in the optimal order based on the predictions of the artificial intelligence. It will be assumed that in case of a tie in points and penalty, Rudolf will take the best place.
|
First of all, it is necessary to determine the optimal order of solving problems for each participant. It is claimed that it is most optimal to solve problems in ascending order of their solution time. Let's prove this: Firstly, it is obvious that this strategy will allow solving the maximum number of problems. Secondly, this strategy will also result in the minimum total penalty time. Let's assume that the participant solves a total of $m$ problems. The solution time of the first problem will be added to the penalty time for all $m$ problems, the solution time of the second problem will be added to the penalty time for $m-1$ problems, and so on. Therefore, it is advantageous for the longest time to be added to the fewest number of problems. In other words, the problem with the longest solution time should be solved last. Then, the same reasoning is repeated for the remaining $m-1$ problems. Next, it is necessary to calculate the number of solved problems and the penalty time for each participant, based on the described strategy. To do this, sort the solution times of the problems for each participant and simulate the solving process. Finally, count the number of participants who outperform Rudolph in the results table. The overall time complexity is $O(n \cdot m \cdot \log m)$.
|
[
"constructive algorithms",
"data structures",
"dp",
"greedy",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int ttt;
cin >> ttt;
while(ttt--){
int n, m, h;
cin >> n >> m >> h;
pair<int, long long> rud;
int ans = 1;
for(int i = 0; i < n; i++){
vector<int> cur(m);
for(int j = 0; j < m; j++){
cin >> cur[j];
}
std::sort(cur.begin(), cur.end());
int task_cnt = 0;
long long penalty = 0, sum = 0;
for(int j = 0; j < m; j++){
if (sum + cur[j] > h) break;
sum += cur[j];
penalty += sum;
task_cnt++;
}
if (i){
if (make_pair(-task_cnt, penalty) < rud) ans++;
} else rud = {-task_cnt, penalty};
}
cout << ans << '\n';
}
return 0;
}
|
1846
|
D
|
Rudolph and Christmas Tree
|
Rudolph drew a beautiful Christmas tree and decided to print the picture. However, the ink in the cartridge often runs out at the most inconvenient moment. Therefore, Rudolph wants to calculate in advance how much green ink he will need.
The tree is a vertical trunk with \textbf{identical} triangular branches at different heights. The thickness of the trunk is negligible.
Each branch is an isosceles triangle with base $d$ and height $h$, whose base is perpendicular to the trunk. The triangles are arranged upward at an angle, and the trunk passes exactly in the middle. The base of the $i$-th triangle is located at a height of $y_i$.
The figure below shows an example of a tree with $d = 4, h = 2$ and three branches with bases at heights $[1, 4, 5]$.
Help Rudolph calculate the total area of the tree branches.
|
Let's consider the triangles in ascending order of $y_i$. Let the current triangle have index $i$. There are two cases: The triangle does not intersect with the $(i+1)$-th triangle $(y_{i + 1} - y_i \ge h)$. In this case, we simply add the area of the triangle to the answer. The area will be $\frac{d \cdot h}{2}$. The triangle intersects with the $(i+1)$-th triangle $(y_{i + 1} - y_i < h)$. We can add to the answer the area of the figure that does not belong to the intersection and move on to the next triangle. Note that this figure is a trapezoid with a lower base $d$ and height $h' = y_{i + 1} - y_i$. The upper base can be found based on the similarity of triangles. The heights of the triangles are in the ratio $k = \frac{h - h'}{h}$. Then the upper base $d_{top} = d \cdot k$. The area of the trapezoid is $h' \cdot \frac{d + d_{top}}{2}$. Time complexity is $O(n)$.
|
[
"constructive algorithms",
"geometry",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout.precision(10); cout.setf(ios::fixed);
int ttt;
cin >> ttt;
while (ttt--) {
int n, d, h;
cin >> n >> d >> h;
vector<int> y(n);
for(int i = 0; i < n; i++){
cin >> y[i];
}
long double ans = (long double)d * h / 2.0;
for (int i = 0; i + 1 < n; ++i) {
if (y[i + 1] >= y[i] + h) ans += (long double)d * h / 2.0;
else{
long double d2 = (long double)d * (y[i] + h - y[i + 1]) / h;
long double nh = y[i + 1] - y[i];
ans += (d + d2) / 2.0 * nh;
}
}
cout << ans << '\n';
}
return 0;
}
|
1846
|
E1
|
Rudolf and Snowflakes (simple version)
|
\textbf{This is a simple version of the problem. The only difference is that in this version $n \le 10^6$.}
One winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician, Rudolf came up with a mathematical model of a snowflake.
He defined a snowflake as an undirected graph constructed according to the following rules:
- Initially, the graph has only one vertex.
- Then, more vertices are added to the graph. The initial vertex is connected by edges to $k$ new vertices ($k > 1$).
- Each vertex that is connected to only one other vertex is connected by edges to $k$ more new vertices. This step should be done \textbf{at least once}.
The smallest possible snowflake for $k = 4$ is shown in the figure.
After some mathematical research, Rudolf realized that such snowflakes may not have any number of vertices. Help Rudolf check if a snowflake with $n$ vertices can exist.
|
For the current given constraint you can precalculate whether it is possible to obtain each $n$ for some $k$. To do this, we can iterate through all possible $2 \le k \le 10^6$ and for each of them calculate the values $1 + k + k^2$, $1 + k + k^2 + k^3$, ..., $1 + k + k^2 + k^3 + ... + k^p$, where $p$ is such that $1 \le 1 + k + k^2 + k^3 + ... + k^p \le 10^6$. For this version of problem it is enougth to calculete valuse for $p \le 20$. Note that the minimum number of snowflake layers is $3$. Therefore, the calculations start from the value $1 + k + k^2$. We can store all the obtained values, for example, in a set. Alternatively, we can use an array called "used" and set the value $1$ in the array element with the corresponding index for each obtained value. It is better to perform this precalculation before iterating through the test cases. Then, for each test, we only need to read the value of $n$ and check if we have obtained it in the precalculation described above. The time complexity of the solution using a set is $O(\sqrt n \cdot p \cdot \log n + tc \cdot \log n$. The time complexity of the solution using the "used" array is $O(\sqrt n \cdot p + tc)$. Here $tc$ - number of test cases.
|
[
"brute force",
"implementation",
"math"
] | 1,300
|
#include<bits/stdc++.h>
using namespace std;
using LL = long long;
set<long long> nums;
int main() {
for (long long k = 2; k <= 1000; ++k) {
long long val = 1 + k;
long long p = k*k;
for (int cnt = 2; cnt <= 20; ++cnt) {
val += p;
if (val > 1e6) break;
nums.insert(val);
p *= k;
}
}
int _ = 0, __ = 1;
cin >> __;
for (int _ = 0; _ < __; ++_) {
long long n;
cin >> n;
if (nums.count(n)) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
|
1846
|
E2
|
Rudolf and Snowflakes (hard version)
|
\textbf{This is the hard version of the problem. The only difference is that in this version $n \le 10^{18}$.}
One winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician, Rudolf came up with a mathematical model of a snowflake.
He defined a snowflake as an undirected graph constructed according to the following rules:
- Initially, the graph has only one vertex.
- Then, more vertices are added to the graph. The initial vertex is connected by edges to $k$ new vertices ($k > 1$).
- Each vertex that is connected to only one other vertex is connected by edges to $k$ more new vertices. This step should be done \textbf{at least once}.
The smallest possible snowflake for $k = 4$ is shown in the figure.
After some mathematical research, Rudolf realized that such snowflakes may not have any number of vertices. Help Rudolf check whether a snowflake with $n$ vertices can exist.
|
On these constraints, it is also possible to precalculate whether it is possible to obtain certain values of $n$ for some $k$. To do this, we can iterate through all possible $2 \le k \le 10^6$ and for each of them calculate the values $1 + k + k^2$, $1 + k + k^2 + k^3$, ..., $1 + k + k^2 + k^3 + ... + k^p$, where $p$ is such that $1 \le 1 + k + k^2 + k^3 + ... + k^p \le 10^{18}$. However, in order to obtain all possible values of $n$, we would have to iterate through $k \le 10^9$, which exceeds the time limits. Therefore, let's precalculate all possible values of $n$ that can be obtained for $3 \le p \le 63$. We will store all the obtained values, for example, in a set. We cannot use an array called "used" here due to the constraints on $n$. It is better to perform this precalculation before iterating through the test cases of the current test case. Next, for each test, we only need to read the value of $n$ and check if we obtained it in the aforementioned precalculation. If we obtained it, we output "YES" and move on to the next test. If we did not obtain it, we need to separately check if we could obtain this value for $p = 2$. To do this, we solve the quadratic equation $k^2 + k + 1 = n$. If it has integer roots that satisfy the problem's constraints ($k > 1$), then the answer is "YES". Otherwise, it is "NO". The time complexity of the solution is $O(\sqrt[3] n \cdot p \cdot \log n + tc \cdot \log n)$. Here, $tc$ is the number of tests in the test case.
|
[
"binary search",
"brute force",
"implementation",
"math"
] | 1,800
|
#include<bits/stdc++.h>
using namespace std;
using LL = long long;
set<long long> nums;
int main() {
for (long long k = 2; k <= 1000000; ++k) {
long long val = 1 + k;
long long p = k*k;
for (int cnt = 3; cnt <= 63; ++cnt) {
val += p;
if (val > 1e18) break;
nums.insert(val);
if (p > (long long)(1e18) / k) break;
p *= k;
}
}
int _ = 0, __ = 1;
cin >> __;
for (int _ = 0; _ < __; ++_) {
long long n;
cin >> n;
if (n < 3)
{
cout << "NO" << endl;
continue;
}
long long d = 4*n - 3;
long long sq = sqrt(d);
long long sqd = -1;
for (long long i = max(0ll, sq - 5); i <= sq + 5; ++i) {
if (i*i == d)
{
sqd = i;
break;
}
}
if (sqd != -1 && (sqd - 1) % 2 == 0 && (sqd - 1) / 2 > 1)
{
cout << "YES" << endl;
continue;
}
if (nums.count(n)) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
|
1846
|
F
|
Rudolph and Mimic
|
\textbf{This is an interactive task.}
Rudolph is a scientist who studies alien life forms. There is a room in front of Rudolph with $n$ different objects scattered around. Among the objects there is \textbf{exactly one} amazing creature — a mimic that can turn into any object. He has already disguised himself in this room and Rudolph needs to find him by experiment.
The experiment takes place in several stages. At each stage, the following happens:
- Rudolf looks at all the objects in the room and writes down their types. The type of each object is indicated by a number; there can be several objects of the same type.
- After inspecting, Rudolph can point to an object that he thinks is a mimic. After that, the experiment ends. Rudolph only has one try, so if he is unsure of the mimic's position, he does the next step instead.
- Rudolf can remove any number of objects from the room (possibly zero). Then Rudolf leaves the room and at this time all objects, including the mimic, \textbf{are mixed} with each other, their order is changed, and the \textbf{mimic can transform} into any other object (even one that is not in the room).
- After this, Rudolf returns to the room and repeats the stage. The \textbf{mimic may not change appearance}, but it can not remain a same object for more than two stages in a row.
Rudolf's task is to detect mimic in no more than \textbf{five} stages.
|
The strategy is to keep track of the number of objects of each type. When the number of objects of a certain type increases, that means the mimic has turned into an object of that type. Then you can delete all other objects. After the first such removal, all objects will become equal. Then, after maximum two stages, the mimic will be forced to turn into something else and it will be possible to unambiguously identify it. Let's consider the worst case, where the mimic does not change its appearance between the first and second stages. Then we do not remove any element with the first two requests. Between the second and third steps, the mimic will be forced to transform, and then we can remove all objects except for those that have the same type as the mimic. The mimic may not change between the third and fourth stages, but will be forced to transform between the fourth and fifth. Then we will be able to unambiguously determine the mimic, since before the transformation all objects were the same.
|
[
"constructive algorithms",
"implementation",
"interactive"
] | 1,800
|
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
int test_cases;
cin >> test_cases;
for (int test_case = 0; test_case < test_cases; test_case++) {
int n;
cin >> n;
vector<int> v(n);
map<int, int> m;
for (int i = 0; i < n; i++) {
cin >> v[i];
m[v[i]]++;
}
vector<int> elements_to_erase;
int ans;
for (int i = 0; i < 5; i++) {
if (v.size() - elements_to_erase.size() == 1) {
cout << "! " << ans << endl;
break;
}
cout << "- " << elements_to_erase.size() << " ";
for (int j = 0; j < elements_to_erase.size(); j++) {
cout << elements_to_erase[j] << " ";
}
cout << endl;
vector<int> new_v;
map<int, int> new_m;
for (int j = 0; j < v.size() - elements_to_erase.size(); j++) {
int x;
cin >> x;
new_v.push_back(x);
new_m[x]++;
}
elements_to_erase.clear();
int tm = -1;
for (auto& k : new_m) {
if (k.second > m[k.first]) {
tm = k.first;
}
}
if (tm != -1) {
for (int j = 0; j < new_v.size(); j++) {
if (new_v[j] != tm)
elements_to_erase.push_back(j + 1);
else
ans = j + 1;
}
m.clear();
m[tm] = new_m[tm];
}
v = new_v;
}
}
return 0;
}
|
1846
|
G
|
Rudolf and CodeVid-23
|
A new virus called "CodeVid-23" has spread among programmers. Rudolf, being a programmer, was not able to avoid it.
There are $n$ symptoms numbered from $1$ to $n$ that can appear when infected. Initially, Rudolf has some of them. He went to the pharmacy and bought $m$ medicines.
For each medicine, the number of days it needs to be taken is known, and the set of symptoms it removes. Unfortunately, medicines often have side effects. Therefore, for each medicine, the set of symptoms that appear when taking it is also known.
After reading the instructions, Rudolf realized that taking more than one medicine at a time is very unhealthy.
Rudolph wants to be healed as soon as possible. Therefore, he asks you to calculate the minimum number of days to remove all symptoms, or to say that it is impossible.
|
Let's denote Rudolf's state as a binary mask of length $n$ consisting of $0$ and $1$, similar to how it is given in the input data. Then each medicine transforms Rudolf from one state to another. Let's construct a weighted directed graph, where the vertices will represent all possible states of Rudolf. There will be $2^n$ such vertices. Two vertices will be connected by an edge if there exists a medicine that transforms Rudolf from the state corresponding to the first vertex to the state corresponding to the second vertex. The weight of the edge will be equal to the number of days that this medicine needs to be taken. Note that in this case, we simply need to find the shortest path in this graph from the vertex $s$, corresponding to the initial state of Rudolf, to the vertex $f$, corresponding to the state without symptoms. To find the shortest path in a weighted graph, we will use Dijkstra's algorithm. We will run it from the vertex $s$ and if, as a result, we visit the vertex $f$, output the distance to it, otherwise $-1$. The time complexity is $O(n \cdot m \cdot 2^n)$.
|
[
"bitmasks",
"dp",
"graphs",
"greedy",
"shortest paths"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int ttt;
cin >> ttt;
while (ttt--) {
int n, m;
cin >> n >> m;
bitset<10> tmp;
cin >> tmp;
int s = (int) tmp.to_ulong();
vector<pair<pair<int, int>, int>> edges(m);
for (int i = 0; i < m; i++) {
cin >> edges[i].second;
cin >> tmp;
edges[i].first.first = ((1 << n) - 1) ^ (int) tmp.to_ulong();
cin >> tmp;
edges[i].first.second = (int) tmp.to_ulong();
}
vector<int> dist(1 << n, INT_MAX);
dist[s] = 0;
set<pair<int, int>> q = {{0, s}};
while (!q.empty()) {
auto [d, v] = *q.begin();
q.erase(q.begin());
for (int i = 0; i < m; i++) {
int to = v & edges[i].first.first;
to |= edges[i].first.second;
if (dist[to] > d + edges[i].second) {
q.erase({dist[to], to});
dist[to] = d + edges[i].second;
q.insert({dist[to], to});
}
}
}
if (dist[0] == INT_MAX) dist[0] = -1;
cout << dist[0] << '\n';
}
return 0;
}
|
1847
|
A
|
The Man who became a God
|
Kars is tired and resentful of the narrow mindset of his village since they are content with staying where they are and are not trying to become the perfect life form. Being a top-notch inventor, Kars wishes to enhance his body and become the perfect life form. Unfortunately, $n$ of the villagers have become suspicious of his ideas. The $i$-th villager has a suspicion of $a_i$ on him. Individually each villager is scared of Kars, so they form into groups to be more powerful.
The power of the group of villagers from $l$ to $r$ be defined as $f(l,r)$ where
$$f(l,r) = |a_l - a_{l+1}| + |a_{l + 1} - a_{l + 2}| + \ldots + |a_{r-1} - a_r|.$$
Here $|x-y|$ is the absolute value of $x-y$. A group with only one villager has a power of $0$.
Kars wants to break the villagers into exactly $k$ contiguous subgroups so that the sum of their power is minimized. Formally, he must find $k - 1$ positive integers $1 \le r_1 < r_2 < \ldots < r_{k - 1} < n$ such that $f(1, r_1) + f(r_1 + 1, r_2) + \ldots + f(r_{k-1} + 1, n)$ is minimised. Help Kars in finding the minimum value of $f(1, r_1) + f(r_1 + 1, r_2) + \ldots + f(r_{k-1} + 1, n)$.
|
Let us find $f(1,n)$. Now, you need to divide the array into more $K-1$ parts. When you split an array $b$ of size $m$ into two parts, the suspicion changes from $f(1,m)$ to $f(1,i)+f(i+1,m)$ ($1 \leq i < m$). Also, $f(1,m) = f(1,i) + |b_i - b_{i+1}| + f(i+1,m)$. Substituting this in previous change, we get $f(1,i) + |b_i - b_{i+1}| + f(i+1,m)$ changes to $f(1,i) + f(i+1,m)$. That is, $|b_i - b_{i+1}|$ gets subtracted. Now, to get minimum suspicion, we need to break the array $a$ at $i$ such that $|a_i-a_{i+1}|$ gets maximised. Now, we have array $dif$ of size $n-1$ where $dif_i = |a_{i+1} - a_i|$ ($1 \leq i < n$). We can solve the problem using any of the two approaches. - Find the least element in $dif$ and remove that from $dif$ and add that element to the answer. Do this exactly $k-1$ times. Time complexity - $O(n^2)$. - We can sort $dif$ and don't take $k-1$ maximum elements (or take first $(n-1)-(k-1)$ elements. Time Complexity - $O(n \log n)$.
|
[
"greedy",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define all(x) x.begin(),x.end()
void solve(){
int n , k;
cin >> n >> k;
ll arr[n];
for(int i = 0; i < n; i++)cin >> arr[i];
vector<ll> v;
ll sum = 0;
for(int i = 1; i < n; i++){
v.pb(abs(arr[i] - arr[i-1]));
sum += v.back();
}
sort(all(v));
for(int groups = 1; groups < k; groups++){
sum -= v.back();
v.pop_back();
}
cout << sum << '\n';
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin >> t;while(t--)
solve();
return 0;
}
|
1847
|
B
|
Hamon Odyssey
|
Jonathan is fighting against DIO's Vampire minions. There are $n$ of them with strengths $a_1, a_2, \dots, a_n$. $\def\and {{\,&\,}}$
Denote $(l, r)$ as the group consisting of the vampires with indices from $l$ to $r$. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group $(l, r)$ is defined as $$f(l,r) = a_l \and a_{l+1} \and a_{l+2} \and \ldots \and a_r.$$ Here, $\and$ denotes the bitwise AND operation.
Because Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in \textbf{exactly} one group, and the \textbf{sum} of strengths of the groups is \textbf{minimized}. Among all ways to divide the vampires, he would like to find the way with the \textbf{maximum} number of groups.
Given the strengths of each of the $n$ vampires, find the \textbf{maximum number} of groups among all possible ways to divide the vampires with the smallest sum of strengths.
|
There are two cases in this problem. First, if $f(1,n) > 0$, then maximum number of groups becomes $1$. This is because there are some bits set in all the elements. Now, if we divide the array in more than one group, then these bits are taken more than once which will not give smallest AND. Second case is when $f(1,n) = 0$. This means the smallest AND is $0$. Now, we need to greedily divide the array into subarrays such that the AND of each subarray should be $0$. We keep taking elements in the subarray until the AND becomes $0$. When AND becomes $0$, we take remaining elements in the next subarray. If the last subarray has AND more than $0$, then we need to merge that subarray with the previous subarray. Time complexity - $O(n)$.
|
[
"bitmasks",
"greedy",
"two pointers"
] | 1,000
|
#include <iostream>
#include <vector>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define all(x) x.begin(),x.end()
void solve(){
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++)cin >> arr[i];
int cur = arr[0];
int part = 1;
for(int i = 0; i < n; i++){
cur &= arr[i];
if(cur == 0){
if(i == n-1)break;
part++;
cur = arr[i + 1];
}
}
if(cur != 0)part--;
part = max(part,1);
cout << part << '\n';
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin >> t;while(t--)
solve();
return 0;
}
|
1847
|
C
|
Vampiric Powers, anyone?
|
DIO knows that the Stardust Crusaders have determined his location and will be coming to fight him. To foil their plans he decides to send out some Stand users to fight them. Initially, he summoned $n$ Stand users with him, the $i$-th one having a strength of $a_i$. Using his vampiric powers, he can do the following as many times as he wishes:
- Let the \textbf{current} number of Stand users be $m$.
- DIO chooses an index $i$ ($1 \le i \le m$).
- Then he summons a new Stand user, with index $m+1$ and strength given by: $$a_{m+1} = a_i \oplus a_{i+1} \oplus \ldots \oplus a_m,$$where the operator $\oplus$ denotes the bitwise XOR operation.
- Now, the number of Stand users becomes $m+1$.
Unfortunately for DIO, by using Hermit Purple's divination powers, the Crusaders know that he is plotting this, and they also know the strengths of the original Stand users. Help the Crusaders find the maximum possible strength of a Stand user among all possible ways that DIO can summon.
|
At the end of the array, you can only achieve xor of any subarray of the original array. Lets denote $f(u,v) =$ xor of all $a_i$ such that $min(u,v) \leq i < max(u,v)$. In the first operation you add $f(n,i)$. I.e. $[u_1,v_1)=[n,i)$. It can be proven that $f(u_k,v_k) = f(v_{k-1},v_k)$ in the $k$-th operation which is a range. Suppose we have taken $k$ ranges that already satisfy this property. Now, I add a new $k+1$-th range. So, first I need to take the $k$-th range $f(u_k,v_k)$. Now I'm xoring it with the range $f(u_{k - 1}, v_{k - 1})$. As [ $u_k, v_k$) and [ $u_{k - 1}, v_{k - 1}$) share an endpoint, the result for these ranges will be a range. For two ranges $f(x,y)$ and $f(y,z)$, if the two ranges do not intersect, the result will be the sum of the two ranges $f(x,z)$. If the two ranges intersect, then the intersections will be cancelled out, and the result will be the difference $f(x,z)$. Now, we maintain a boolean array $b$ where $b_i$ is $1$ if there is some $j$ such that $a_1 \oplus a_2 \oplus \cdots \oplus a_j = i$. Initially, $b$ is all $0$. We loop $j$ from $1$ to $n$ and check for each $k$ if $b_k=1$. If it is, then there is some position $p < j$ such that $a_1 \oplus a_2 \oplus \cdots \oplus a_p = k$. If we take xor of range from $(p,j]$, then it will be $k \oplus a_1 \oplus a_2 \oplus \cdots \oplus a_j$ (as $a_1 \oplus a_2 \oplus \cdots \oplus a_p$ gets cancelled). This $a_1 \oplus a_2 \oplus \cdots \oplus a_j$ can be stored as we loop ahead. We are looping all possible prefix xors and not all prefix positions because $n$ is large. Time Complexity - $O(n \cdot 2^8)$.
|
[
"bitmasks",
"brute force",
"dp",
"greedy"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0)->sync_with_stdio(0);
int ntest;
cin >> ntest;
while (ntest--) {
int n;
cin >> n;
vector<int> a(n);
for (auto &i : a)
cin >> i;
int const max_value = 1 << 8;
vector<char> has_pref(max_value);
has_pref[0] = true;
int cur_xor = 0;
int ans = 0;
for (auto i : a) {
cur_xor ^= i;
for (int pref = 0; pref < max_value; ++pref) {
if (has_pref[pref]) {
ans = max(ans, pref ^ cur_xor);
}
}
has_pref[cur_xor] = true;
}
cout << ans << '\n';
}
}
|
1847
|
D
|
Professor Higashikata
|
Josuke is tired of his peaceful life in Morioh. Following in his nephew Jotaro's footsteps, he decides to study hard and become a professor of computer science. While looking up competitive programming problems online, he comes across the following one:
Let $s$ be a binary string of length $n$. An operation on $s$ is defined as choosing two distinct integers $i$ and $j$ ($1 \leq i < j \leq n$), and swapping the characters $s_i, s_j$.
Consider the $m$ strings $t_1, t_2, \ldots, t_m$, where $t_i$ is the substring $^\dagger$ of $s$ from $l_i$ to $r_i$. Define $t(s) = t_1+t_2+\ldots+t_m$ as the concatenation of the strings $t_i$ in that order.
There are $q$ updates to the string. In the $i$-th update $s_{x_i}$ gets flipped. That is if $s_{x_i}=1$, then $s_{x_i}$ becomes $0$ and vice versa. After each update, find the minimum number of \textbf{operations one must perform on $s$} to make $t(s)$ lexicographically as large$^\ddagger$ as possible.
Note that no operation is actually performed. We are only interested in the number of operations.
Help Josuke in his dream by solving the problem for him.
\begin{center}
——————————————————————
\end{center}
$\dagger$ A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
$\ddagger$ A string $a$ is lexicographically larger than a string $b$ of the same length if and only if the following holds:
- in the first position where $a$ and $b$ differ, the string $a$ has a $1$, and the string $b$ has a $0$.
|
Lets assume you know string $t$. String $t$ is made by positions in $s$. Lets denote $f(i) =$ position in $s$ from which $t_i$ is made. For maximising $t$ you need to make the starting elements in $t$ as large as possible. Now, to make $t$ lexicographically as large as possible, we need to swap positions in $s$. We can swap positions greedily. We first try making $s_{f(1)} = 1$. Then we try making $s_{f(2)} = 1$ and so on. Now, suppose for two indices $i$,$j$ ($1 \leq i < j \leq |t|$) such that $f(i) = f(j)$, we know that index $j$ is waste. $t$ is basically the preference of indices in $s$ which should be equal to $1$. If $s_{f(j)}$ is to be set $1$, then it would already be set $1$ because before setting $s_{f(j)}$ equal to $1$ we would have already set $s_{f(i)}$ equal to $1$ because $f(i)$ is equal to $f(j)$. Hence, for each index $i$ in $s$, we only add its first occurrence in $t$. This makes the size of $t$ bound by size of $s$. Now, this $t$ can be found using various pbds like set,dsu,segment tree,etc. Now, before answering the queries, we find the answer for the current string $s$. We know that there are $x$ ones and $n-x$ zeros in $s$. So, for each $i$ ($1 \leq i \leq min(x,|t|)$), we make $s_{f(i)} = 1$. Hence, the number of swaps needed will become number of positions $i$ ($1\leq i \leq min(x,|t|)$) such that $s_i=0$. Now, in each query, there is exactly one positions that is either getting flipped from $0$ to $1$ or from $1$ to $0$. That is, $x$ is either getting changed to $x+1$ or $x-1$. You already know the answer for $x$. Now, if $x$ is getting reduced, then you need to decrease the answer by one if $x <= |t|$ and $s_{f(x)}=0$. If $x$ is increasing by one, then you need to add one to the answer if $x < |t|$ and $s_{f(x+1)} = 0$. Time complexity - $O(n \log n + q)$.
|
[
"data structures",
"dsu",
"greedy",
"implementation",
"strings"
] | 1,900
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define vf first
#define vs second
#define all(x) x.begin(),x.end()
void solve(){
int n , m , q;
cin >> n >> m >> q;
string st;
cin >> st;
vector<pair<int,int>> ranges;
for(int i = 0; i < m; i++){
int l , r;
cin >> l >> r;
l--;
r--;
ranges.pb(mp(l,r));
}
set<int> s;
for(int i = 0; i < n; i++)s.insert(i);
vector<int> v;
int pos_in_v[n];
memset(pos_in_v,-1,sizeof pos_in_v);
for(int i = 0; i < m; i++){
auto it = s.lower_bound(ranges[i].vf);
vector<int> toerase;
while(it != s.end() && (*it) <= ranges[i].vs){
toerase.pb((*it));
v.pb(toerase.back());
pos_in_v[toerase.back()] = v.size()-1;
it++;
}
while(toerase.size()){
s.erase(toerase.back());
toerase.pop_back();
}
}
int cnt = 0;
for(int i = 0; i < n; i++){
if(st[i] == '1')cnt++;
}
int ans = 0;
for(int i = 0; i < min(cnt , (int)v.size()); i++){
if(st[v[i]] == '0')ans++;
}
while(q--){
int pos;
cin >> pos;
pos--;
if(pos_in_v[pos] != -1 && pos_in_v[pos] < cnt){
if(st[pos] == '0'){
ans--;
}
else ans++;
}
if(st[pos] == '0'){
st[pos] = '1';
cnt++;
if(cnt <= v.size() && st[v[cnt-1]] == '0')ans++;
}
else {
st[pos] = '0';
if(cnt > 0 && cnt <= v.size() && st[v[cnt-1]] == '0')ans--;
cnt--;
}
cout << ans << '\n';
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//int t;cin >> t;while(t--)
solve();
return 0;
}
|
1847
|
E
|
Triangle Platinum?
|
This is an interactive problem.
Made in Heaven is a rather curious Stand. Of course, it is (arguably) the strongest Stand in existence, but it is also an ardent puzzle enjoyer. For example, it gave Qtaro the following problem recently:
Made in Heaven has $n$ hidden integers $a_1, a_2, \dots, a_n$ ($3 \le n \le 5000$, $1 \le a_i \le 4$). Qtaro must determine all the $a_i$ by asking Made in Heaven some queries of the following form:
- In one query Qtaro is allowed to give Made in Heaven three \textbf{distinct} indexes $i$, $j$ and $k$ ($1 \leq i, j, k \leq n$).
- If $a_i, a_j, a_k$ form the sides of a non-degenerate triangle$^\dagger$, Made in Heaven will respond with the area of this triangle.
- Otherwise, Made in Heaven will respond with $0$.
By asking at most $5500$ such questions, Qtaro must either tell Made in Heaven all the values of the $a_i$, or report that it is \textbf{not} possible to \textbf{uniquely} determine them.
Unfortunately due to the universe reboot, Qtaro is not as smart as Jotaro. Please help Qtaro solve Made In Heaven's problem.
\begin{center}
——————————————————————
\end{center}
$^\dagger$ Three positive integers $a, b, c$ are said to form the sides of a non-degenerate triangle if and only if all of the following three inequalities hold:
- $a+b > c$,
- $b+c > a$,
- $c+a > b$.
|
First, notice that we can uniquely determine the multiset of numbers any three $a_i, a_j, a_k$ except for the collision between triples $(1, 4, 4)$ and $(2, 2, 3)$. The issue is that even if we know the multiset we cannot always uniquely determine $a_i, a_j, a_k$. But what if all the elements of the multiset are equal? Then each element obviously has to be equal to the value of the multiset. So if for some three distinct $i, j, k$ the area of $a_i, a_j, a_k$ is one of $\sqrt{3}/4, \sqrt{3}, 9\sqrt{3}/4, 4\sqrt{3}$, then they are all equal to $1, 2, 3$ or $4$ respectively, depending on the area. Let us say we knew that $a_i = a_j = a_k = C$ for some $C \in [1, 4]$ after asking $q$ queries. By querying $(i, j, x)$ for every $x$ other than $i, j$ we can obtain the area of $C, C, a_x$ for each $x$. This will allow us to uniquely determine each $a_x$. But wait! There is an important edge case here. We also require $C, C, a_x$ to form a valid triangle. If $C \geq 2$, this is not an issue because $2, 2, 4$ can be just assigned an area of "$0$" and we can still uniquely retrieve the values. So using this procedure, it takes us $q+n-3$ queries to determine all the values. The only possibility remaining is when $C = 1$. In this case, the issue is that only $[1, 1, 1]$ let us know the value of $a_x$. When $a_x > 1$, it's impossible to distinguish between $a_x = 2, 3, 4$. So if we asked all questions, we would know which indices have value $> 1$ and which indices have a value of $1$. Now if we could find two equal elements among these indices with value $> 1$, we can repeat a similar linear scan as above and find all values. But how do we find two equal values? Notice that every value is among $2, 3, 4$. So if we had $\geq 4$ such indices with value $> 1$ some two of them would be equal, and we could find them by bruting queries of the form $(i, m_1, m_2)$ over all pairs of indices $m_1, m_2$ with value $> 1$. After this we can then again query all the other $> 1$ indices and find answer. This would take around $q+n'+2(n-n')-\mathcal O(1)$ queries, where $n'$ is the number of ones. Unfortunately this would QLE if $n'$ were around $n/2$. How do we fix this? The answer is surprisingly simple. When we were finding indices with value $> 1$ we simply stop the minute we have at least $4$ such indices (it's ok even if we don't). Now we brute over all pairs. If we find two equal, we are done within at most $q+n+16$ queries. On the other hand if we cannot find two equal it means that we can never distinguish between them. This is because any query of the form $(1, x, y)$ where $x \ne y$ are both $\geq 2$ is always a degenerate query hence will have answer $0$. So if we do not find two equal, we will print $-1$. After all this work, there are still a few details left. First, $q$ must be small. Otherwise all the above work is useless. Second there should be three equal elements in the first place. The first observation is that if $n \geq 9$ then by Piegonhole Principle, some $\lceil n/4 \rceil \geq 3$ must be equal. So if $n \geq 9$ then by bruting over all $1 \leq i < j < k \leq 9$ triples $(i, j, k)$ we can always find some three equal. Here we would have $q = {9 \choose 3} = 84$ and we are asking at most $n+84+16$ queries, which fits comfortably. But what if $n < 9$? In this case we can simply brute all possible ${9 \choose 3} = 84$ queries and then for each of the $4^n$ arrays possible check if the triples of that array match with the query answers obtained here. If there is exactly one such array, we have found it and we can print it, otherwise we print $-1$ because it is not possible to uniquely determine the values of the array. Notice that this takes at most $4^8 \cdot {8 \choose 3}$ operations, which is around $3.7 \cdot 10^6$ which fits in the TL. This solves the problem. You might wonder why $5500$ queries were allowed even though the above solution does not use more than around $5100$ queries. This is because we allowed randomisation as a valid way of finding three equal values $a_i, a_j, a_k$. Suppose there are $c_1, c_2, c_3, c_4$ counts of $1, 2, 3, 4$ respectively. If we randomly queried a triple $(i, j, k)$ each time, the probability all would be equal is precisely: $\frac{{c_1 \choose 3}+{c_2 \choose 3}+{c_3 \choose 3}+{c_4 \choose 3}}{{n \choose 3}}$
|
[
"brute force",
"combinatorics",
"implementation",
"interactive",
"math",
"probabilities"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18
#define f first
#define s second
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
const int N = 5005;
int ans[N];
int n;
int dp[5][5][5];
int holy[11][11][11];
int area(int a, int b, int c){
if (a >= b + c) return 0;
if (b >= a + c) return 0;
if (c >= a + b) return 0;
int s = (a + b + c);
return s * (s - 2 * a) * (s - 2 * b) * (s - 2 * c);
}
int query(int a, int b, int c){
cout << "? " << a << " " << b << " " << c << endl;
int ans; cin >> ans;
return ans;
}
void print(bool found = true){
if (!found){
cout << "! -1\n";
exit(0);
} else {
cout << "! ";
for (int i = 1; i <= n; i++) cout << ans[i] << " ";
cout << endl;
exit(0);
}
}
bool works(){
for (int i = 1; i <= n; i++){
for (int j = i + 1; j <= n; j++){
for (int k = j + 1; k <= n; k++){
if (area(ans[i], ans[j], ans[k]) != holy[i][j][k])
return false;
}
}
}
return true;
}
void brutesmall(){
for (int i = 1; i <= n; i++){
for (int j = i + 1; j <= n; j++){
for (int k = j + 1; k <= n; k++){
holy[i][j][k] = query(i, j, k);
}
}
}
int mask = 1 << (2 * n);
int lol = 0;
for (int i = 0; i < mask; i++){
int copy = i;
for (int i = 1; i <= n; i++){
ans[i] = 1 + copy % 4;
copy /= 4;
}
if (works()){
lol++;
}
}
if (lol > 1) print(false);
for (int i = 0; i < mask; i++){
int copy = i;
for (int i = 1; i <= n; i++){
ans[i] = 1 + copy % 4;
copy /= 4;
}
if (works()){
print();
}
}
}
void Solve()
{
cin >> n;
for (int i = 1; i <= 4; i++){
for (int j = 1; j <= 4; j++){
for (int k = 1; k <= 4; k++){
dp[i][j][k] = area(i, j, k);
}
}
}
if (n < 9){
brutesmall();
}
vector <int> tuple(4, -1);
while (true){
if (tuple[0] != -1) break;
int p1 = 1 + RNG() % n;
int p2 = 1 + RNG() % n;
int p3 = 1 + RNG() % n;
if (p1 == p2 || p2 == p3 || p3 == p1) continue;
int ar = query(p1, p2, p3);
for (int j = 1; j <= 4; j++){
if (ar == dp[j][j][j]){
tuple[0] = p1;
tuple[1] = p2;
tuple[2] = p3;
tuple[3] = j;
}
}
}
for (int i = 0; i < 3; i++) ans[tuple[i]] = tuple[3];
if (tuple[3] == 1){
vector <int> nv;
for (int i = 1; i <= n; i++){
if (ans[i] > 0) continue;
int fetch = query(tuple[0], tuple[1], i);
if (fetch == 0) {
nv.push_back(i);
if (nv.size() > 3) break;
} else {
ans[i] = 1;
}
}
if (nv.size() == 0) print();
vector <int> ntuple(3, -1);
for (int i1 = 0; i1 < nv.size(); i1++){
for (int i2 = i1 + 1; i2 < nv.size(); i2++){
int ok = query(tuple[0], nv[i1], nv[i2]);
for (int j = 2; j <= 4; j++){
if (ok == dp[1][j][j]){
ntuple[0] = nv[i1];
ntuple[1] = nv[i2];
ntuple[2] = j;
}
}
}
}
if (ntuple[0] == -1) print(false);
ans[ntuple[0]] = ntuple[2];
ans[ntuple[1]] = ntuple[2];
tuple[0] = ntuple[0];
tuple[1] = ntuple[1];
tuple[2] = -1;
tuple[3] = ntuple[2];
}
for (int i = 1; i <= n; i++){
if (ans[i] > 0) continue;
int fetch = query(tuple[0], tuple[1], i);
for (int j = 1; j <= 4; j++){
if (dp[tuple[3]][tuple[3]][j] == fetch)
ans[i] = j;
}
}
print();
}
int32_t main()
{
auto begin = std::chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
// cin >> t;
for(int i = 1; i <= t; i++)
{
Solve();
}
return 0;
}
|
1847
|
F
|
The Boss's Identity
|
While tracking Diavolo's origins, Giorno receives a secret code from Polnareff. The code can be represented as an infinite sequence of positive integers: $a_1, a_2, \dots $. Giorno immediately sees the pattern behind the code. The first $n$ numbers $a_1, a_2, \dots, a_n$ are \textbf{given}. For $i > n$ the value of $a_i$ is $(a_{i-n}\ |\ a_{i-n+1})$, where $|$ denotes the bitwise OR operator.
Pieces of information about Diavolo are hidden in $q$ questions. Each question has a positive integer $v$ associated with it and its answer is the smallest index $i$ such that $a_i > v$. If no such $i$ exists, the answer is $-1$. Help Giorno in answering the questions!
|
Lets start with an example of $n=5$. Let $a = [a,b,c,d,e]$ where $a$,$b$,$c$,$d$ and $e$ are variables. First $20$ elements of $a$ will be [$a$,$b$,$c$,$d$,$e$,$ab$,$bc$,$cd$,$de$,$abe$,$abc$,$bcd$,$cde$,$abde$,$abce$,$abcd$,$bcde$,$abcde$,$abcde$,$abcde$]. By removing and rearranging some elements we can get $b$$c$$d$$e$$\bf{ab}$$bc$$cd$$de$$\bf{eab}$$\bf{abc}$$bcd$$cde$$\bf{deab}$$\bf{eabc}$$\bf{abcd}$$bcde$ Here you can observe that each group will have a size of $n-1$. The next group will be the previous group, _or_ed with the element immediately before the first element (circularly). So we have the rule. Now let's solve the problem in binary (that is, every element is $0/1$). Let's take a look at the element $a$ in the rearranged version (the highlighted ones). If $a$ is $0$, it won't contribute anything to the subsequent groups, so we can ignore it. Otherwise, it will contribute by keeping moving to the right. This will end when it meets a cell in the group that is already $1$. And after that, we can drop the act of moving $a$. This algorithm can actually help us construct the whole array sparsely and incrementally. We can maintain the list of $1$ in the initial array, and then update the array by moving all of them to the right. That is, if we have one group, we can obtain the next group by moving the $1$. After that, we can drop moving some $1$ if it meets another $1$. The whole action is $O(n)$, as there are at most $n$ zeros to be updated. So for the original problem, first of all, we can repeat the above algorithm $bitlength=31$ times, that is, repeat the algorithm for each bit. Secondly, there are at most $O(\log n)$ unique numbers for each position, so we can just find all $O(n \log n)$ last positions of all numbers, and put them in a array. You can either find all $n \log n$ unique positions in ascending order and or in random order and sort the array. Then using binary search we can answer each query. Time complexity of the former version is $O(n \log n + q \log(n \log n))$ and the latter version is $O(n \log n \log(n \log n) + q \log(n \log n))$.
|
[
"binary search",
"bitmasks",
"data structures",
"dfs and similar",
"greedy",
"math",
"sortings"
] | 2,500
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define vf first
#define vs second
#define all(x) x.begin(),x.end()
const int B = 31;
struct item {
ll pos , bit, idx;
};
item make(ll pos , ll bit , ll idx){
item res;
res.pos = pos;
res.bit = bit;
res.idx = idx;
return res;
}
void solve(){
int n;
cin >> n;
int qu;
cin >> qu;
int arr[n];
for(int i = 0; i < n; i++)cin >> arr[i];
if(n == 1){
while(qu--){
int x;
cin >> x;
if(x < arr[0])cout << 1 << '\n';
else cout << -1 << '\n';
}
return;
}
vector<pair<ll,ll>> v;
queue<item> q;
bool vis[n][B];
memset(vis,0,sizeof vis);
for(int i = 0; i < n; i++){
for(int j = 0; j < B; j++){
if((arr[i] & (1 << j)) > 0){
vis[i][j] = 1;
}
}
v.pb(mp(i , arr[i]));
}
for(int i = 0; i < n - 1; i++){
v.pb(mp(n+i,arr[i]|arr[i+1]));
}
for(int j = 0; j < B; j++){
if(vis[n-1][j])q.push(make(n+n-1,j,0));
}
for(int i = 0; i < n - 1; i++){
for(int j = 0; j < B; j++){
if(vis[i][j])q.push(make(n+n+i,j,(i+1)%(n-1)));
}
}
int val[n-1];
for(int i = 0; i < n-1; i++)val[i] = arr[i]|arr[i+1];
while(q.size()){
item it = q.front();
q.pop();
if((val[it.idx] & (1 << it.bit)) > 0){
continue;
}
val[it.idx] += (1 << it.bit);
if(v.back().vf == it.pos){
v.pop_back();
}
v.pb(mp(it.pos , val[it.idx]));
q.push(make(it.pos + n , it.bit , (it.idx + 1)%(n-1)));
}
// first part gets over where v[i].first contains position in ascending order and v[i].second contains the value to what has become on that position.
for(int i = 1; i < v.size(); i++){
v[i].vs = max(v[i].vs , v[i-1].vs);
}
while(qu--){
int x;
cin >> x;
ll l = 0 , r = v.size()-1;
ll res = -1;
while(l <= r){
int mid = (l + r)/2;
if(v[mid].vs <= x){
l = mid + 1;
}
else {
r = mid - 1;
res = v[mid].vf+1;
}
}
cout << res << '\n';
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin >> t;while(t--)
solve();
return 0;
}
|
1848
|
A
|
Vika and Her Friends
|
Vika and her friends went shopping in a mall, which can be represented as a rectangular grid of rooms with sides of length $n$ and $m$. Each room has coordinates $(a, b)$, where $1 \le a \le n, 1 \le b \le m$. Thus we call a hall with coordinates $(c, d)$ a neighbouring for it if $|a - c| + |b - d| = 1$.
Tired of empty fashion talks, Vika decided to sneak away unnoticed. But since she hasn't had a chance to visit one of the shops yet, she doesn't want to leave the mall. After a while, her friends noticed Vika's disappearance and started looking for her.
Currently, Vika is in a room with coordinates $(x, y)$, and her $k$ friends are in rooms with coordinates $(x_1, y_1)$, $(x_2, y_2)$, ... $, (x_k, y_k)$, respectively. The coordinates can coincide. Note that all the girls \textbf{must} move to the neighbouring rooms.
Every minute, first Vika moves to one of the adjacent to the side rooms of her choice, and then each friend (\textbf{seeing Vika's choice}) also chooses one of the adjacent rooms to move to.
If \textbf{at the end of the minute} (that is, after all the girls have moved on to the neighbouring rooms) at least one friend is in the same room as Vika, she is caught and all the other friends are called.
Tell us, can Vika run away from her annoying friends forever, or will she have to continue listening to empty fashion talks after some time?
|
Let's color the halls of a rectangle in a chess coloring. Then Vika will be able to escape from her friends infinitely only if none of her friends is on a cell of the same color as Vika. This observation seems intuitively clear, but let's formalize it. $\Leftarrow)$ It is true, because if initially Vika and her friend were in halls of different colors, then after one move they will remain in halls of different colors. $\Rightarrow)$ Let's choose any of the friends who is in a hall of the same color as Vika. We will show how the friend will act to catch Vika in a finite time. First, let's define a quantity that we will call the area to Vika: If Vika and the friend are in the same column, then the area to Vika is equal to the sum of the areas of all rows in the direction of Vika and the row where the friend is located. If Vika and the friend are in the same row, then the area to Vika is equal to the sum of the areas of all columns in the direction of Vika and the column where the friend is located. Otherwise, the area to Vika is equal to the area of the quadrant in which Vika is located relative to the friend. If Vika is in the same column as the friend. If Vika goes towards the friend, then the friend goes towards her, reducing the distance. If Vika goes in the opposite direction, then the friend also goes towards her, reducing the area to Vika. If Vika goes along the row, then the friend goes towards Vika along the column, which also reduces the area to Vika. If Vika is in the same row as the friend. If Vika goes towards the friend, then the friend goes towards her, reducing the distance. If Vika goes in the opposite direction, then the friend also goes towards her, reducing the area to Vika. If Vika goes along the column, then the friend goes towards Vika along the row, which also reduces the area to Vika. If Vika and the friend are in different rows and columns. If Vika goes towards the friend along the row, then the friend goes towards her along the column, reducing the distance. If Vika goes towards the friend along the column, then the friend goes towards her along the row, reducing the distance. If Vika goes away from the friend, then the friend makes a move in the same direction, thereby reducing the area to Vika.
|
[
"games",
"math"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int t;
cin >> t;
while (t--) {
int n, m, k;
cin >> n >> m >> k;
int x, y;
cin >> x >> y;
string ans = "YES\n";
for (int i = 0; i < k; ++i) {
int xx, yy;
cin >> xx >> yy;
if ((x + y) % 2 == (xx + yy) % 2) {
ans = "NO\n";
}
}
cout << ans;
}
return 0;
}
|
1848
|
B
|
Vika and the Bridge
|
In the summer, Vika likes to visit her country house. There is everything for relaxation: comfortable swings, bicycles, and a river.
There is a wooden bridge over the river, consisting of $n$ planks. It is quite old and unattractive, so Vika decided to paint it. And in the shed, they just found cans of paint of $k$ colors.
After painting each plank in one of $k$ colors, Vika was about to go swinging to take a break from work. However, she realized that the house was on the other side of the river, and the paint had not yet completely dried, so she could not walk on the bridge yet.
In order not to spoil the appearance of the bridge, Vika decided that she would still walk on it, but only stepping on planks of the same color. Otherwise, a small layer of paint on her sole will spoil the plank of another color. Vika also has a little paint left, but it will only be enough to repaint \textbf{one} plank of the bridge.
Now Vika is standing on the ground in front of the first plank. To walk across the bridge, she will choose some planks of the same color (after repainting), which have numbers $1 \le i_1 < i_2 < \ldots < i_m \le n$ (planks are numbered from $1$ from left to right). Then Vika will have to cross $i_1 - 1, i_2 - i_1 - 1, i_3 - i_2 - 1, \ldots, i_m - i_{m-1} - 1, n - i_m$ planks as a result of each of $m + 1$ steps.
Since Vika is afraid of falling, she does not want to take too long steps. Help her and tell her the minimum possible maximum number of planks she will have to cross \textbf{in one step}, if she can repaint one (\textbf{or zero}) plank a different color while crossing the bridge.
|
In a single linear pass through the array, let's calculate, for each color, the lengths of the two maximum steps between planks of that color. To do this, we will maintain when we last encountered that color. Now we need to consider that we can repaint one of the planks. Let's say we repaint a plank in color $c$. It is easy to notice that we should repaint the plank in the middle of the longest step between planks of color $c$. After all, if we don't repaint such a plank, we will still have to make that longest step. Therefore, the answer for a fixed color will be the maximum of two values: half the length of the longest step between planks of that color, and the length of the second largest step between planks of that color. Knowing the answer for each individual color, we can determine the answer to the problem. To do this, we just need to take the minimum of the answers for all colors.
|
[
"binary search",
"data structures",
"greedy",
"implementation",
"math",
"sortings"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> c(n);
for (int i = 0; i < n; ++i) {
cin >> c[i];
}
vector<int> last(k, -1);
vector<int> max_step(k), max2_step(k);
for (int i = 0; i < n; ++i) {
int step = i - last[c[i] - 1];
if (step > max_step[c[i] - 1]) {
max2_step[c[i] - 1] = max_step[c[i] - 1];
max_step[c[i] - 1] = step;
} else if (step > max2_step[c[i] - 1]) {
max2_step[c[i] - 1] = step;
}
last[c[i] - 1] = i;
}
for (int i = 0; i < k; ++i) {
int step = n - last[i];
if (step > max_step[i]) {
max2_step[i] = max_step[i];
max_step[i] = step;
} else if (step > max2_step[i]) {
max2_step[i] = step;
}
}
int ans = 1e9;
for (int i = 0; i < k; ++i) {
ans = min(ans, max((max_step[i] + 1) / 2, max2_step[i]));
}
cout << ans - 1 << "\n";
}
return 0;
}
|
1848
|
C
|
Vika and Price Tags
|
Vika came to her favorite cosmetics store "Golden Pear". She noticed that the prices of $n$ items have changed since her last visit.
She decided to analyze how much the prices have changed and calculated the difference between the old and new prices for each of the $n$ items.
Vika enjoyed calculating the price differences and decided to continue this process.
Let the old prices be represented as an array of non-negative integers $a$, and the new prices as an array of non-negative integers $b$. Both arrays have the same length $n$.
In one operation, Vika constructs a new array $c$ according to the following principle: $c_i = |a_i - b_i|$. Then, array $c$ renamed into array $b$, and array $b$ renamed into array $a$ at the same time, after which Vika repeats the operation with them.
For example, if $a = [1, 2, 3, 4, 5, 6, 7]$; $b = [7, 6, 5, 4, 3, 2, 1]$, then $c = [6, 4, 2, 0, 2, 4, 6]$. Then, $a = [7, 6, 5, 4, 3, 2, 1]$; $b = [6, 4, 2, 0, 2, 4, 6]$.
Vika decided to call a pair of arrays $a$, $b$ dull if after some number of such operations all elements of array $a$ become zeros.
Output "YES" if the original pair of arrays is dull, and "NO" otherwise.
|
First of all, if $a_i$ and $b_i$ are both zero, then all numbers in the sequence will be zero. Otherwise, if one of the numbers $a_i, b_i$ is not zero, then if $a_i \ge b_i$, after one operation, the sum $a_i - b_i + b_i = a_i$ will decrease relative to the original value, or if $b_i > a_i$, after two operations, the sum $b_i - a_i + a_i = b_i$ will also decrease relative to the original value. Since the sum of non-negative integers cannot decrease infinitely, eventually one of the numbers $a_i, b_i$ will become zero. Let the first such moment occur after $cnt_i$ operations. Then, notice that now zeros will alternate with a period of $3$. Therefore, in the problem, we need to check that all $cnt_i$ have the same remainder when divided by $3$. Thus, the problem reduces to finding $cnt_i$ for each pair of non-zero $a_i, b_i$ modulo $3$. Solution 1: Without loss of generality, assume $a_i \ge b_i$, otherwise apply one operation. Then, the sequence of numbers will have the form: $(a_i, b_i, a_i - b_i, a_i - 2 \cdot b_i, b_i, a_i - 3 \cdot b_i, a_i - 4 \cdot b_i, b_i, \ldots)$. Let $a_i = k \cdot b_i + r$. Then, using simple formulas, we can find the first moment when the neighboring pair of numbers becomes $r$ and $b_i$ in some order, and then simply find the answer for them. Thus, the problem can be solved using the generalized Euclidean algorithm. Solution 2: We will build the sequence from the end. Let's find the first moment when we obtain $0$. Before this zero, there is some number $d$. It can be easily proven that $d$ is exactly equal to $gcd(a_i, b_i)$. Now, let's divide each number in the sequence by $d$, and obtain a new sequence of numbers, where the last number is zero and the penultimate number is $1$. Then, let's denote even numbers as $0$ and odd numbers as $1$. In this way, the sequence can be uniquely reconstructed from the end: $(0, 1, 1, 0, 1, 1, 0, 1, 1, \ldots)$. Thus, we can determine the remainder $cnt_i$ modulo $3$ by looking at the pair $(a_i / d, b_i / d)$ modulo $2$. The complexity of both solutions will be $O(n \cdot \log{a_i})$.
|
[
"math",
"number theory"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int gcd(int a, int b) {
if (a == 0) {
return 0;
}
if (b == 0) {
return 1;
}
if (a >= b) {
int r = a % b;
int k = a / b;
if (k % 2 == 1) {
return gcd(b, r) + k + k / 2;
} else {
return gcd(r, b) + k + k / 2;
}
}
return 1 + gcd(b, abs(a - b));
}
int calc(int a, int b) {
if (a == 0) {
return 0;
}
if (b == 0) {
return 1;
}
return 1 + calc(b, abs(a - b));
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
int n;
cin >> n;
vector<int> a(n);
vector<int> b(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
cin >> b[i];
}
set<int> cnt;
for (int i = 0; i < n; ++i) {
if (a[i] == 0 && b[i] == 0) {
continue;
}
cnt.insert(gcd(a[i], b[i]) % 3);
}
if (cnt.size() <= 1) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
|
1848
|
D
|
Vika and Bonuses
|
A new bonus system has been introduced at Vika's favorite cosmetics store, "Golden Pear"!
The system works as follows: suppose a customer has $b$ bonuses. Before paying for the purchase, the customer can choose one of two options:
- Get a discount equal to the current number of bonuses, while the bonuses are not deducted.
- Accumulate an additional $x$ bonuses, where $x$ is the last digit of the number $b$. As a result, the customer's account will have $b+x$ bonuses.
For example, if a customer had $24$ bonuses, he can either get a discount of $24$ or accumulate an additional $4$ bonuses, after which his account will have $28$ bonuses.
At the moment, Vika has already accumulated $s$ bonuses.
The girl knows that during the remaining time of the bonus system, she will make $k$ more purchases at the "Golden Pear" store network.
After familiarizing herself with the rules of the bonus system, Vika became interested in the maximum total discount she can get.
Help the girl answer this question.
|
First, let's note that the optimal strategy for Vika will be to accumulate bonuses first and then only get the discount. This simple observation is proved by greedy considerations. Next, let's note that the last digit of the bonus number will either become zero after a few actions (in which case it makes no sense for Vika to accumulate more bonuses), or it will cycle through the digits $2$, $4$, $8$, $6$. To begin with, let's consider two options: whether Vika will accumulate bonuses at all or always choose the option to get the discount. In the second case, the answer is trivially calculated, but in the first case, we can use the above statement. Now let's consider four options for the last digit. With a fixed last digit, we can simulate the first actions until we reach that last digit. Then we need to determine how many times we will "scroll" through the digits $2$, $4$, $8$, $6$ for the best result. Let's say that at the moment of obtaining the desired last digit, Vika has accumulated $b$ bonuses and she can perform $a$ more actions. Then, if the cycle is "scroll" $x$ times, the discount will be $(b + 20 \cdot x) \cdot (a - x)$. This is a parabola equation. Its maximum can be found using the formula for the vertex of a parabola or by ternary search.
|
[
"binary search",
"brute force",
"math",
"ternary search"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int f(int s, int k) {
// (s + 20x) * (k - 4x)
// (-80)x^2 + (20k - 4s)x + (sk)
// -b/2a = (5k-s)/40
int x = (5 * k - s) / 40;
x = min(x, k / 4);
int res = s * k;
if (x > 0) {
res = max(res, (s + 20 * x) * (k - 4 * x));
}
x = min(x + 1, k / 4);
if (x > 0) {
res = max(res, (s + 20 * x) * (k - 4 * x));
}
return res;
}
int32_t main() {
int t;
cin >> t;
while (t--) {
int s, k;
cin >> s >> k;
int ans = s * k;
if (s % 10 == 5) {
ans = max(ans, (s + 5) * (k - 1));
} else if (s % 10) {
if (s % 2 == 1) {
s += s % 10;
--k;
}
for (int i = 0; i < 4; ++i) {
if (k > 0) {
ans = max(ans, f(s, k));
}
s += s % 10;
--k;
}
}
cout << ans << "\n";
}
return 0;
}
|
1848
|
E
|
Vika and Stone Skipping
|
In Vika's hometown, Vladivostok, there is a beautiful sea.
Often you can see kids skimming stones. This is the process of throwing a stone into the sea at a small angle, causing it to fly far and bounce several times off the water surface.
Vika has skimmed stones many times and knows that if you throw a stone from the shore perpendicular to the coastline with a force of $f$, it will first touch the water at a distance of $f$ from the shore, then bounce off and touch the water again at a distance of $f - 1$ from the previous point of contact. The stone will continue to fly in a straight line, reducing the distances between the points where it touches the water, until it falls into the sea.
Formally, the points at which the stone touches the water surface will have the following coordinates: $f$, $f + (f - 1)$, $f + (f - 1) + (f - 2)$, ... , $f + (f - 1) + (f - 2) + \ldots + 1$ (assuming that $0$ is the coordinate of the shoreline).
Once, while walking along the embankment of Vladivostok in the evening, Vika saw a group of guys skipping stones across the sea, launching them from the same point with different forces.
She became interested in what is the maximum number of guys who can launch a stone with their force $f_i$, so that all $f_i$ are \textbf{different positive integers}, and all $n$ stones touched the water at the point with the coordinate $x$ (assuming that $0$ is the coordinate of the shoreline).
After thinking a little, Vika answered her question. After that, she began to analyze how the answer to her question would change if she multiplied the coordinate $x$ by some positive integers $x_1$, $x_2$, ... , $x_q$, which she picked for analysis.
Vika finds it difficult to cope with such analysis on her own, so she turned to you for help.
Formally, Vika is interested in the answer to her question for the coordinates $X_1 = x \cdot x_1$, $X_2 = X_1 \cdot x_2$, ... , $X_q = X_{q-1} \cdot x_q$. Since the answer for such coordinates can be quite large, find it modulo $M$. \textbf{It is guaranteed that $M$ is prime.}
|
The key observation is that the answer for coordinate $x$ is the number of odd divisors of $x$. Let's prove this. Let's see how far a pebble will fly with force $f$, which touches the water $cnt$ times: $f + (f - 1) + \ldots + (f - cnt + 1) = x$. If $cnt$ is even, then $x = (cnt / 2) \cdot (2 \cdot f - cnt + 1) = (p) \cdot (2 \cdot k + 1)$, where $p = cnt / 2, k = f - p$. In this case, the condition $f - cnt + 1 > 0$ is necessary, which is equivalent to $p \le k$. If $cnt$ is odd, then $x = cnt \cdot (f - (cnt - 1) / 2) = (2 \cdot k + 1) \cdot (p)$, where $p = (f - (cnt - 1) / 2), k = (cnt - 1) / 2$. Thus, the necessary condition $f - cnt + 1 > 0$ is equivalent to $p > k$. Therefore, for each odd divisor $2 \cdot k + 1$ of the number $x$, we can uniquely associate one of the decomposition options, and hence the number of possible answers is exactly equal to the number of different odd divisors in the factorization of the number $x$. Using this observation, it is easy to obtain the answer. We will maintain the power of each prime number in the current coordinate. The answer is the product of (powers $+ 1$). In order to quickly understand how these quantities change, we will pre-calculate the factorization of all numbers from $1$ to $10^6$. Then the query can be processed by quickly recalculating the powers using the pre-calculated factorizations.
|
[
"brute force",
"implementation",
"math",
"number theory"
] | 2,600
|
#include <bits/stdc++.h>
using namespace std;
const int K = 1e6;
#define int long long
int mod;
int dp[K + 1];
int cnt[K + 1];
const int MM = 3e6 + 7;
int inv[MM];
int cc = 0;
int mul(int a, int b) {
int bb = b;
while (bb % mod == 0) {
++cc;
bb /= mod;
}
return (a * (bb % mod)) % mod;
}
int dv(int a, int b) {
int bb = b;
while (bb % mod == 0) {
--cc;
bb /= mod;
}
return (a * inv[bb % mod]) % mod;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int x, q;
cin >> x >> q >> mod;
inv[1] = 1;
for (int i = 2; i < MM && i < mod; i++) {
inv[i] = mod - inv[mod % i] * (mod / i) % mod;
}
int y = x;
for (int i = 3; i <= K; i += 2) {
if (dp[i]) {
continue;
}
for (int j = i; j <= K; j += 2 * i) {
dp[j] = i;
}
}
int ans = 1;
while (x % 2 == 0) {
x /= 2;
}
for (int i = 3; i <= K; i += 2) {
while (x % i == 0) {
ans = dv(ans, cnt[i] + 1);
++cnt[i];
ans = mul(ans, cnt[i] + 1);
x /= i;
}
}
int f = 1;
if (x > 1) {
ans = mul(ans, 2);
}
x = y;
for (int i = 0; i < q; ++i) {
int d;
cin >> d;
while (d % 2 == 0) {
d /= 2;
}
int k = d;
while (dp[k]) {
ans = dv(ans, cnt[dp[k]] + 1);
++cnt[dp[k]];
ans = mul(ans, cnt[dp[k]] + 1);
k /= dp[k];
}
if (cc) {
cout << 0 << '\n';
} else {
cout << ans << '\n';
}
}
return 0;
}
|
1848
|
F
|
Vika and Wiki
|
Recently, Vika was studying her favorite internet resource - Wikipedia.
On the expanses of Wikipedia, she read about an interesting mathematical operation bitwise XOR, denoted by $\oplus$.
Vika began to study the properties of this mysterious operation. To do this, she took an array $a$ consisting of $n$ non-negative integers and applied the following operation to all its elements at the same time: $a_i = a_i \oplus a_{(i+1) \bmod n}$. Here $x \bmod y$ denotes the remainder of dividing $x$ by $y$. The elements of the array are numbered starting from $0$.
Since it is not enough to perform the above actions once for a complete study, Vika repeats them until the array $a$ becomes all zeros.
Determine how many of the above actions it will take to make all elements of the array $a$ zero. If this moment never comes, output $-1$.
|
Let's denote $next(i, delta) = (i + delta \bmod n) + 1$, and $a[cnt][i]$ represents the value of $a_i$ after $cnt$ operations. First, let's observe that if the array becomes all zeros, it will always remain all zeros. Therefore, we need to find the first moment in time when the array becomes all zeros. Furthermore, let's see how the array looks like after $2^t$ operations. We will prove by induction that $a[2^t][i] = a[0][i] \oplus a[0][next(i, 2^t)]$ for each $i$. Indeed, for $t = 0$, this is true by definition, and for $t \ge 1$: $a[2^t][i] = a[2^{t-1}][i] \oplus a[2^{t-1}][next(i, 2^{t-1})] = a[0][i] \oplus a[0][next(i, 2^{t-1})] \oplus a[0][next(i, 2^{t-1})] \oplus a[0][next(i, 2^t)] = a[0][i] \oplus a[0][next(i, 2^t)]$. Thus, $a[n][i] = a[2^k][i] = a[0][i] \oplus a[0][next(i, n)] = a[0][i] \oplus a[0][i] = 0$, which means that after $n$ steps, the array becomes all zeros. Now, we want to find the minimum number of operations $c$ after which the array $a$ becomes all zeros, knowing that $c \in [0, n]$. Let's check that $c \le n / 2$, by explicitly constructing the array $a[n/2][i] = a[0][i] \oplus a[0][next(i, n / 2)]$. The condition $c \le n / 2$ is equivalent to all elements of the array $a[n/2][i]$ being zeros. The algorithm can be summarized as follows: Check if $a_i = a_{next(i, n/2)}$ for each $i$. If this is true, find the answer for the prefix of the array $a$ of length $n/2$. Otherwise, perform $n/2$ operations on the array $a$, specifically $a_i = a_i \oplus a_{next(i, n / 2)}$. Now, the array satisfies the condition $a_i = a_{next(i, n/2)}$ for each $i$, so we only need to find the answer for its prefix of size $n/2$ and add $n/2$ to it. The overall complexity of the solution is $O(n)$.
|
[
"binary search",
"bitmasks",
"combinatorics",
"divide and conquer",
"dp",
"math"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = (1 << 20);
int a[MAXN];
int solve(int n) {
if (n == 1) {
if (a[0] == 0) {
return 0;
} else {
return 1;
}
}
int fl = true;
for (int i = 0; i < n / 2; ++i) {
if (a[i] != a[i + n / 2]) {
fl = false;
}
}
if (fl) {
return solve(n / 2);
}
for (int i = 0; i < n / 2; ++i) {
a[i] ^= a[i + n / 2];
}
return n / 2 + solve(n / 2);
}
int32_t main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
cout << solve(n) << endl;
return 0;
}
|
1849
|
A
|
Morning Sandwich
|
Monocarp always starts his morning with a good ol' sandwich. Sandwiches Monocarp makes always consist of bread, cheese and/or ham.
A sandwich always follows the formula:
- a piece of bread
- a slice of cheese or ham
- a piece of bread
- $\dots$
- a slice of cheese or ham
- a piece of bread
So it always has bread on top and at the bottom, and it alternates between bread and filling, where filling is a slice of either cheese or ham. Each piece of bread and each slice of cheese or ham is called a layer.
Today Monocarp woke up and discovered that he has $b$ pieces of bread, $c$ slices of cheese and $h$ slices of ham. What is the maximum number of layers his morning sandwich can have?
|
Notice that the type of filling doesn't matter. We can treat both cheese and ham together as one filling, with quantity $c + h$. Then let's start building a sandwich layer by layer. Put a piece of bread. Then put a layer of filling and a piece of bread. Then another layer of filling and a piece of bread. Observe that you can add one layer of filling and one piece of bread until one of them runs out. After you've done that $k$ times, you placed $k + 1$ layers of bread and $k$ layers of filling. Thus, there are two general cases. If bread runs out first, then $k = b - 1$. Otherwise, $k = c + h$. The one that runs out first is the smaller of these two values. So the answer is $min(b - 1, c + h)$. Overall complexity: $O(1)$ per testcase.
|
[
"implementation",
"math"
] | 800
|
fun main() = repeat(readLine()!!.toInt()) {
val (b, c, h) = readLine()!!.split(' ').map { it.toInt() }
println(minOf(b - 1, c + h) * 2 + 1)
}
|
1849
|
B
|
Monsters
|
Monocarp is playing yet another computer game. And yet again, his character is killing some monsters. There are $n$ monsters, numbered from $1$ to $n$, and the $i$-th of them has $a_i$ health points initially.
Monocarp's character has an ability that deals $k$ damage to the monster with the \textbf{highest current health}. If there are several of them, \textbf{the one with the smaller index is chosen}. If a monster's health becomes less than or equal to $0$ after Monocarp uses his ability, then it dies.
Monocarp uses his ability until all monsters die. Your task is to determine the order in which monsters will die.
|
Let's simulate the game process until the number of health points of each monster becomes $k$ or less. Then we can consider that the $i$-th monster has $a_i \bmod k$ health instead of $a_i$ (except for the case when $a_i$ is divisible by $k$, then the remaining health is $k$, not $0$). Now, the health points of all monsters are from $1$ to $k$, so each time we damage a monster, we kill it. Therefore, monsters with $k$ health points will die first, then the ones with $k-1$ health points, and so on. So, let's sort the monsters by their remaining health points in descending order (don't forget that, if two monsters have the same health, then they should be compared by index). And the order you get after sorting is the answer to the problem.
|
[
"greedy",
"math",
"sortings"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for (auto &x : a) {
cin >> x;
x %= k;
if (!x) x = k;
}
vector<int> ord(n);
iota(ord.begin(), ord.end(), 0);
stable_sort(ord.begin(), ord.end(), [&](int i, int j) {
return a[i] > a[j];
});
for (auto &x : ord) cout << x + 1 << ' ';
cout << endl;
}
}
|
1849
|
C
|
Binary String Copying
|
You are given a string $s$ consisting of $n$ characters 0 and/or 1.
You make $m$ copies of this string, let the $i$-th copy be the string $t_i$. Then you perform exactly one operation on each of the copies: for the $i$-th copy, you sort its substring $[l_i; r_i]$ (the substring from the $l_i$-th character to the $r_i$-th character, both endpoints inclusive). \textbf{Note that each operation affects only one copy, and each copy is affected by only one operation}.
Your task is to calculate the number of different strings among $t_1, t_2, \ldots, t_m$. Note that the initial string $s$ should be counted only if at least one of the copies stays the same after the operation.
|
We can see that each modified copy is determined by only two integers $lb$ and $rb$ - the first position at which the character has changed and the last such position. If we can find such numbers for each of the copies, the number of different pairs will be the answer to the problem. Let $lf_i$ be the position of the nearest character 0 at the position $i$ or to the left of it, and $rg_i$ be the position of the nearest character 1 at the position $i$ or to the right of it. If the first character of the string $s$ is 1 then $lf_0 = -1$, otherwise $lf_0 = 0$. And if the last character of the string $s$ is 0, then $rg_{n - 1} = n$, otherwise $rg_{n - 1} = n - 1$. The values $lf$ and $rg$ can be calculated using simple dynamic programming, $lf$ is calculated from left to right, and $rg$ - from right to left. Then the numbers $lb$ and $rb$ we need are equal to $rg_l$ and $lf_r$, respectively. If $rg_l > lf_r$, then the changed segment is degenerate (and this means that the string does not change at all). We can define some special segment for this type of strings, for example, $(-1, -1)$. Otherwise, the segment $(rg_l, lf_r)$ of the string will change. Time complexity: $O(n \log{n})$.
|
[
"binary search",
"brute force",
"data structures",
"hashing",
"strings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m;
string s;
cin >> n >> m >> s;
vector<int> lf(n), rg(n);
lf[0] = -1;
for (int i = 0; i < n; ++i) {
if (i > 0) lf[i] = lf[i - 1];
if (s[i] == '0') lf[i] = i;
}
rg[n - 1] = n;
for (int i = n - 1; i >= 0; --i) {
if (i + 1 < n) rg[i] = rg[i + 1];
if (s[i] == '1') rg[i] = i;
}
set<pair<int, int>> st;
for (int i = 0; i < m; ++i) {
int l, r;
cin >> l >> r;
int ll = rg[l - 1], rr = lf[r - 1];
if (ll > rr) {
st.insert({-1, -1});
} else {
st.insert({ll, rr});
}
}
cout << st.size() << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--) solve();
}
|
1849
|
D
|
Array Painting
|
You are given an array of $n$ integers, where each integer is either $0$, $1$, or $2$. Initially, each element of the array is blue.
Your goal is to paint each element of the array red. In order to do so, you can perform operations of two types:
- pay one coin to choose a blue element and paint it red;
- choose a red element which is not equal to $0$ and a blue element \textbf{adjacent} to it, decrease the chosen red element by $1$, and paint the chosen blue element red.
What is the minimum number of coins you have to spend to achieve your goal?
|
Suppose we used a second operation as follows: we decreased a red element $x$, and painted another element $y$ red. Let's then say that $x$ is the parent of $y$. Furthermore, let's say that the element $x$ controls the element $y$ if one of the two conditions applies: $x$ is the parent of $y$; $x$ controls the parent of $y$. Now, suppose we used coins to paint some elements red. For each of those elements, there exists a segment of red elements which it controls. So, the problem can actually be reformulated as follows: we want to split the given array into the minimum number of segments so that each segment can be painted using one coin. Let's call a segment of the array good if it can be painted using only one coin. To continue with our solution, we need the following property: if a segment is good, then its every subsegment is also good. This is kinda intuitive, but if you are interested in a formal proof, you can read the following paragraph. Formal proof: there are two main cases we need to consider: either the element that controls the main segment belongs to the subsegment we analyze, or it does not. In the first case, the proof is simple: we can paint all elements of the subsegment red using just one coin in the same way as we painted the whole segment, by starting from the element that controls it. In the second case, it is a bit more difficult, but instead of the element controlling the main segment, we can either start from the leftmost element of the subsegment, or from the rightmost element of the subsegment - depending on whether this subsegment is to the right or to the left of the element controlling the whole segment. This starting element will be painted red by spending a coin, and every other element of the subsegment can be painted red in the same way we painted the whole segment. Since if a segment is good, its every subsegment is also good, we can use the following greedy approach to solve the problem: start with the segment which contains only the first element of the array, and expand it to the right until it becomes bad. When the segment is no longer good, we need to start a new segment, which we will again expand to the right until it becomes bad, and so on. Then each element of the array will be considered only once. If we design a way to determine if the segment is still good when we add a new element to it in $O(1)$, our solution will work in $O(n)$. All that's left is to analyze how to check if the segment is good. There are multiple ways to do this. The way used in the model solution employs the following ideas: there cannot be any zeroes in the middle of the segment, since if we start painting red from the left of that zero, we cannot reach the elements to the right of that zero, and vice versa; if there are no zeroes in the middle, and at least one of the endpoints is not zero, the segment is good because we can just start from that endpoint and expand to the other endpoint; if there are no zeroes in the middle, and there is at least one element equal to $2$, we can start by painting that element red and expand to the left and to the right of it until we arrive at the borders of the segment; and if there are zeroes at both endpoints, but all other elements are $1$'s, it's easy to see that paining the whole segment using only one coin is impossible: the sum of elements on the segment is $k-2$, where $k$ is the length of the segment, but we need to paint at least $k-1$ elements red without spending coins. All of these ideas allow us to verify that the segment is good using just a couple if-statements. Solution complexity: $O(n)$.
|
[
"constructive algorithms",
"greedy",
"two pointers"
] | 1,700
|
n = int(input())
a = list(map(int, input().split()))
ans = 0
l = 0
while l < n:
r = l + 1
hasTwo = (a[l] == 2)
hasMiddleZero = False
while r < n:
if r - 1 > l and a[r - 1] == 0:
hasMiddleZero = True
if a[r] == 2:
hasTwo = True
good = (not hasMiddleZero) and (hasTwo or a[l] != 0 or a[r] != 0)
if not good:
break
r += 1
l = r
ans += 1
print(ans)
|
1849
|
E
|
Max to the Right of Min
|
You are given a permutation $p$ of length $n$ — an array, consisting of integers from $1$ to $n$, all distinct.
Let $p_{l,r}$ denote a subarray — an array formed by writing down elements from index $l$ to index $r$, inclusive.
Let $\mathit{maxpos}_{l,r}$ denote the \textbf{index} of the maximum element on $p_{l,r}$. Similarly, let $\mathit{minpos}_{l,r}$ denote the index of the minimum element on it.
Calculate the number of subarrays $p_{l,r}$ such that $\mathit{maxpos}_{l,r} > \mathit{minpos}_{l,r}$.
|
The problem was originally prepared as part of the lecture on a monotonic stack. Thus, I will omit its explanation. First, recall a common technique of counting all segments satisfying some property. You can count the segments that have the same right border at the same time. Consider all segments $[l, r]$ with a fixed $r$. How do the minimums and the maximums on them change from each other? If you look at the segments in the order of decreasing $l$, we can write down the sequence of the following events: the minimum becomes smaller or the maximum becomes larger. In fact, we can maintain both of these types with two monotonic stacks. Now, which $l$ correspond to good segments with regard to the events? Consider two adjacent events $(i_1, t_1)$ and $(i_2, t_2)$, where $i_j$ is the index of the event and $t_j$ is the type ($0$ for min, $1$ for max). It's easy to see that if $t_2 = 0$, then all segments that have $l$ from $i_1 + 1$ to $i_2$ are good. It means that, while going from right to left, the last event we encountered was the minimum getting smaller. Thus, the index of the minimum becomes to the left from the index of the maximum. As for the implementation, we will maintain these events in a set of pairs: (index of the event, type of the event). This way, it's not that hard to maintain the sum of distances from each event of type $0$ to the left to the previous event. When you erase an event, only a few distances can be affected: the distance from the next one to the current one, from the current one to the previous one and the newly created distance from the next one to the previous one. Just check for the types. When you add an event, you only add it to the very end of the set, so it's trivial to recalculate. That will be $O(n \log n)$ just from the set, the monotonic stacks by themselves are linear. You can optimize this solution to $O(n)$ by using a doubly-linked list, but it really was not necessary for the problem. There's also a different solution for which you can maintain the intervals of good values $l$ explicitly. First, compress them in such a way that the segments don't touch at borders. Now, you can notice that by going from $r$ to $r+1$ we can only affect the rightmost ones of them: possibly remove some, then change the last one and add a new one. So we can actually simulate this behavior with another stack. The details are left as an exercise to a reader. With the correct implementation, this solution will be $O(n)$.
|
[
"binary search",
"data structures",
"divide and conquer",
"dp",
"dsu",
"two pointers"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
bool comp(const pair<int, int> &a, const pair<int, int> &b){
return a.second < b.second;
}
int main(){
int n;
scanf("%d", &n);
vector<pair<int, int>> stmn, stmx;
stmn.push_back({-1, -1});
stmx.push_back({n, -1});
long long ans = 0;
int len = 0;
set<pair<int, int>> cur;
cur.insert({-1, 0});
cur.insert({-1, 1});
for (int i = 0; i < n; ++i){
int x;
scanf("%d", &x);
--x;
while (stmn.back().first > x){
auto it = cur.lower_bound({stmn.back().second, 0});
auto me = it;
auto prv = it; --prv;
++it;
len -= me->first - prv->first;
if (it != cur.end() && it->second == 0)
len += it->first - prv->first;
cur.erase(me);
stmn.pop_back();
}
len += i - cur.rbegin()->first;
cur.insert({i, 0});
stmn.push_back({x, i});
while (stmx.back().first < x){
auto it = cur.lower_bound({stmx.back().second, 1});
auto me = it;
auto prv = it; --prv;
++it;
if (it != cur.end() && it->second == 0)
len += me->first - prv->first;
cur.erase(me);
stmx.pop_back();
}
cur.insert({i, 1});
stmx.push_back({x, i});
ans += len;
}
printf("%lld\n", ans - n);
}
|
1849
|
F
|
XOR Partition
|
For a set of integers $S$, let's define its cost as the minimum value of $x \oplus y$ among all pairs of \textbf{different} integers from the set (here, $\oplus$ denotes bitwise XOR). If there are less than two elements in the set, its cost is equal to $2^{30}$.
You are given a set of integers $\{a_1, a_2, \dots, a_n\}$. You have to partition it into two sets $S_1$ and $S_2$ in such a way that every element of the given set belongs to exactly one of these two sets. The value of the partition is the \textbf{minimum} among the costs of $S_1$ and $S_2$.
Find the partition with the \textbf{maximum} possible value.
|
Disclaimer: the model solution to this problem is a bit more complicated than most of the solutions written by participants, but I will still use it for the editorial so that I can explain some of the classical techniques appearing in it. Suppose we have built a graph on $n$ vertices, where each pair of vertices is connected by an edge, and the weight of the edge connecting $i$ with $j$ is $a_i \oplus a_j$. If we treat the partition of the set as a coloring of this graph, then the cost of the partition is equal to the minimum weight of an edge connecting two vertices of the same color. So, suppose we want to check that the answer is at least $x$. It means that every edge with weight less than $x$ should connect two vertices of different colors; so, the graph where we erase all edges with weight greater than or equal to $x$ should be bipartite. This allows us to write a binary search solution if we somehow understand how to construct the graph and check that it is bipartite implicitly, but this is not the way the model solution goes. Instead, suppose we do the following greedy. Initially, let the graph be empty. Then, we add all edges with weight $1$, and check if it is bipartite. Then, we add all edges with weight $2$, and check if it is bipartite. And so on, until the graph is no longer bipartite. Of course, there are $O(n^2)$ edges, so this is too slow. But in fact, we don't need all the edges for this graph. Some of the edges we added didn't really affect the coloring of the graph: if, in this process, we add an edge which connects two vertices from the same component, one of the following two things happens: if it connects two vertices of the same color, then the graph is no longer bipartite; otherwise, this edge actually does not change anything in the coloring. Now, suppose we stop before making the graph non-bipartite. It means if an edge we added was connecting two vertices from the same component, that edge was actually redundant. Let's take a look again at what we're actually doing. Initially, the graph is empty. Then, we consider all possible edges in ascending order of their weights; if an edge connects two vertices in different components, it should be added to the graph (and it affects the coloring), otherwise, it does not matter (unless it makes us stop the algorithm, since the graph is no longer bipartite). Doesn't it sound familiar? Yup, it is almost like Kruskal's algorithm. And in fact, the problem can be solved as follows: build any MST of this graph, and use it to form the two-coloring (paint the vertices in such a way that every edge from MST connects two vertices of different colors). The paragraph below contains the formal proof that this coloring is optimal; feel free to skip it if you're not interested in the strict proof. Formal proof: suppose that, if we color the vertices using the MST, we get an answer equal to $x$. This means that there are two vertices $i$ and $j$ such that their colors are the same, and $a_i \oplus a_j = x$. Let us consider the cycle formed by the edge from $i$ to $j$ and the path from $j$ to $i$ in the MST. Since these two vertices have the same colors, this cycle contains an odd number of edges - so, at least one edge on this cycle will connect vertices of the same color no matter how we paint the graph. And there are no edges on this cycle with weight greater than $x$ - otherwise, that edge would be replaced by the edge $(i,j)$ in the MST. So, at least one edge with weight $\le x$ will be connecting two vertices of the same color, and thus the answer cannot be greater than $x$. Okay, now we have to actually build the MST in this graph. XOR-MST is a fairly classical problem (it was even used in one of the previous Educational Rounds several years ago). I know two different solutions to it: the one based on Boruvka's algorithm and the D&C + trie merging method. I will describe the former one. The classical Boruvka's algorithm is one of the algorithms of finding a minimum spanning tree. It begins with a graph containing no edges, and performs several iterations until it becomes connected. On each iteration, the algorithm considers each component of the graph and adds the minimum edge connecting any vertex from this component with any vertex outside this component (these edges are added at the same time for all components of the graph, so be careful about creating a cycle or adding the same edge twice; different methods can be used to prevent this - in the model solution, I memorize the edges I want to add on each iteration, then use a DSU to actually check which ones should be added without causing a cycle to appear). During each iteration of the algorithm, the number of components decreases to at least half of the original number, so the algorithm works in $O(I \log n)$, where $I$ is the complexity of one iteration. Usually, $I$ is $O(m)$ since we need to consider each edge of the graph twice; but in this problem, we can perform one iteration of Boruvka's algorithm much faster, in $O(n \log A)$, where $A$ is the constraint on the numbers in the input. It can be done as follows: maintain a trie data structure which stores all values of $a_i$ and allows processing a query "given an integer $x$, find the value $y$ in the data structure such that $x \oplus y$ is the minimum possible" (this can be done with a trie descent). When we consider a component and try to find the minimum edge leading outside of it, we first delete all vertices belonging to this component from the data structure; then, for each vertex from the component, find the best vertex in the data structure; and then, insert all vertices back. That way, a component of size $V$ will be processed in $O(V \log A)$, and the total time for one iteration is $O(n \log A)$. All of this results in a solution with complexity $O(n \log n \log A)$.
|
[
"binary search",
"bitmasks",
"data structures",
"divide and conquer",
"greedy",
"trees"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
typedef long long LL;
typedef pair<int, int> PII;
const int N = 200000;
const int NODES = 32 * N;
const int INF = int(2e9);
int n;
int a[N];
int nx[NODES][2], cnt[NODES], fn[NODES];
int nodeCount = 1;
void addInt(int x, int pos) {
int ind = 0;
for (int i = 29; i >= 0; --i) {
int bit = (x >> i) & 1;
if (nx[ind][bit] == 0) {
nx[ind][bit] = nodeCount++;
}
ind = nx[ind][bit];
++cnt[ind];
}
fn[ind] = pos;
}
void addInt(int x) {
int ind = 0;
for (int i = 29; i >= 0; --i) {
int bit = (x >> i) & 1;
ind = nx[ind][bit];
++cnt[ind];
}
}
void removeInt(int x) {
int ind = 0;
for (int i = 29; i >= 0; --i) {
int bit = (x >> i) & 1;
ind = nx[ind][bit];
--cnt[ind];
}
}
PII findXor(int x) {
int ind = 0, res = 0;
for (int i = 29; i >= 0; --i) {
int bit = (x >> i) & 1;
if (cnt[nx[ind][bit]]) {
ind = nx[ind][bit];
} else {
ind = nx[ind][bit ^ 1];
res |= 1 << i;
}
}
return mp(res, fn[ind]);
}
int par[200000], ra[200000];
void dsuInit() {
forn(i, n) par[i] = i, ra[i] = 1;
}
int dsuParent(int v) {
if (v == par[v]) return v;
return par[v] = dsuParent(par[v]);
}
int dsuMerge(int u, int v) {
u = dsuParent(u);
v = dsuParent(v);
if (u == v) return 0;
if (ra[u] < ra[v]) swap(u, v);
par[v] = u;
ra[u] += ra[v];
return 1;
}
vector<int> v[200000];
vector<pair<int, PII> > toMerge;
vector<int> g[200000];
int color[200000];
void coloring(int x, int c){
if(color[x] != -1) return;
color[x] = c;
for(auto y : g[x]) coloring(y, c ^ 1);
}
int main() {
scanf("%d", &n);
forn(i, n) scanf("%d", a + i);
forn(i, n) addInt(a[i], i);
dsuInit();
for (int merges = 0; merges < n - 1; ) {
forn(i, n) v[i].clear();
forn(i, n) v[dsuParent(i)].pb(i);
toMerge.clear();
forn(i, n) if (!v[i].empty()) {
for (int x : v[i]) {
removeInt(a[x]);
}
pair<pair<int, int>, int> res = mp(mp(INF, INF), INF);
for (int x : v[i]) {
res = min(res, mp(findXor(a[x]), x));
}
toMerge.pb(mp(res.first.first, mp(res.second, res.first.second)));
for (int x : v[i]) {
addInt(a[x]);
}
}
for (auto p : toMerge) {
if (dsuMerge(p.second.first, p.second.second)) {
++merges;
g[p.second.first].pb(p.second.second);
g[p.second.second].pb(p.second.first);
}
}
}
forn(i, n) color[i] = -1;
coloring(0, 1);
forn(i, n) printf("%d", color[i]);
puts("");
return 0;
}
|
1850
|
A
|
To My Critics
|
Suneet has three digits $a$, $b$, and $c$.
Since math isn't his strongest point, he asks you to determine if you can choose any two digits to make a sum greater or equal to $10$.
Output "YES" if there is such a pair, and "NO" otherwise.
|
One way to solve the problem is to check if $a + b + c - min(a, b, c) \geq 10$ using an if statement.
|
[
"implementation",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int a, b, c;
cin >> a >> b >> c;
cout << (a+b+c-min({a,b,c}) >= 10 ? "YES\n" : "NO\n");
}
int main()
{
int t;
cin >> t;
while(t--)
{
solve();
}
}
|
1850
|
B
|
Ten Words of Wisdom
|
In the game show "Ten Words of Wisdom", there are $n$ participants numbered from $1$ to $n$, each of whom submits one response. The $i$-th response is $a_i$ words long and has quality $b_i$. No two responses have the same quality, and at least one response has length at most $10$.
The winner of the show is the response which has the highest quality out of all responses that are not longer than $10$ words. Which response is the winner?
|
Let's iterate through all responses: if it has $> 10$ words, ignore it. Otherwise, keep track of the maximum quality and its index, and update it as we go along. Then output the index with maximum quality. The time complexity is $\mathcal{O}(n)$.
|
[
"implementation",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
int n;
cin >> n;
int winner = -1, best_score = 0;
for (int i = 1; i <= n; i++) {
int a, b;
cin >> a >> b;
if (b > best_score && a <= 10) {winner = i; best_score = b;}
}
cout << winner << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1850
|
C
|
Word on the Paper
|
On an $8 \times 8$ grid of dots, a word consisting of lowercase Latin letters is written vertically in one column, from top to bottom. What is it?
|
You can iterate through the grid and then once you find a letter, iterate downwards until you get the whole word. However there is an approach that is even faster to code: just input each character, and output it if it is not a dot. This works because we will input the characters in the same order from top to bottom. The complexity is $\mathcal{O}(1)$ regardless.
|
[
"implementation",
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 200007;
const int MOD = 1000000007;
void solve() {
for (int r = 0; r < 8; r++) {
for (int c = 0; c < 8; c++) {
char x;
cin >> x;
if (x != '.') {cout << x;}
}
}
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}
// solve();
}
|
1850
|
D
|
Balanced Round
|
You are the author of a Codeforces round and have prepared $n$ problems you are going to set, problem $i$ having difficulty $a_i$. You will do the following process:
- remove some (possibly zero) problems from the list;
- rearrange the remaining problems in any order you wish.
A round is considered balanced if and only if the absolute difference between the difficulty of any two consecutive problems is at most $k$ (less or equal than $k$).
What is the minimum number of problems you have to remove so that an arrangement of problems is balanced?
|
Let's calculate the maximum number of problems we can take, and the answer will be $n$ subtracted by that count. An arrangement that always minimizes the absolute difference between adjacent pairs is the array in sorted order. What we notice, is that if the array is sorted, we will always take a subarray (all taken elements will be consecutive). So, the problem converts to finding the largest subarray for which $a_i - a_{i-1} \leq k$. It's easy to see that all the subarrays are totally different (don't share any intersection of elements), thus, we can maintain a count variable of the current number of elements in the current subarray, and iterate through array elements from left to right. If we currently are at $i$ and $a_i - a_{i-1} > k$ then we just set the count to $1$ since we know a new subarray starts, otherwise, we just increase our count by $1$. The answer will be $n$ subtracted by the largest value that our count has achieved.
|
[
"brute force",
"greedy",
"implementation",
"sortings"
] | 900
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
void solve() {
int n, k; cin >> n >> k;
vector<int> a(n);
for(int i = 0; i < n; ++i) cin >> a[i];
sort(all(a));
int cnt = 1, ans = 1;
for(int i = 1; i < n; ++i) {
if(a[i] - a[i - 1] > k) {
cnt = 1;
} else {
++cnt;
}
ans = max(ans, cnt);
}
cout << n - ans << '\n';
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
solve();
}
}
|
1850
|
E
|
Cardboard for Pictures
|
Mircea has $n$ pictures. The $i$-th picture is a square with a side length of $s_i$ centimeters.
He mounted each picture on a square piece of cardboard so that each picture has a border of $w$ centimeters of cardboard on all sides. In total, he used $c$ square centimeters of cardboard. Given the picture sizes and the value $c$, can you find the value of $w$?
\begin{center}
{\small A picture of the first test case. Here $c = 50 = 5^2 + 4^2 + 3^2$, so $w=1$ is the answer.}
\end{center}
Please note that the piece of cardboard goes behind each picture, not just the border.
|
The key idea is to binary search on the answer. If you don't know what that is, you should read this Codeforces EDU article. Let's make a function $f(x)$, which tells us the total area of cardboard if we use a width of $x$. Then you can see that we can calculate $f(x)$ in $\mathcal{O}(n)$ time as $(a_1 + 2x)^2 + (a_2 + 2x)^2 + \dots + (a_n + 2x)^2$, because the side length of the $i$-th cardboard is $a_i + 2x$. So this means that now we can binary search on the answer: let's find the largest $w$ so that $f(w) \leq c$. The maximum theoretical value of $w$ can be seen not to exceed $10^9$, since $c$ is not more than $10^{18}$ (you can set an even lower bound). A quick note about implementation: the value of $f(x)$ can exceed 64-bit numbers, so you need to exit the function as soon as you get a value greater than $c$, or else you risk overflow. So the time complexity is $\mathcal{O}(n \log(10^9))$ per test case, which is equal to $\mathcal{O}(n)$ with some constant factor. It's not that big to make it fail. You can also use the quadratic formula, but be careful about implementation of square root and precision issues.
|
[
"binary search",
"geometry",
"implementation",
"math"
] | 1,100
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
#define int long long
void solve() {
int n, c; cin >> n >> c;
vector<int> a(n);
for(int i = 0; i < n; ++i) cin >> a[i];
int l = 1, r = 1e9;
while(l <= r) {
int mid = l + (r - l) / 2;
int sumall = 0;
for(int i = 0; i < n; ++i) {
sumall += (a[i] + 2 * mid) * (a[i] + 2 * mid);
if(sumall > c) break;
}
if(sumall == c) {
cout << mid << "\n";
return;
}
if(sumall > c) {
r = mid - 1;
} else {
l = mid + 1;
}
}
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
solve();
}
}
|
1850
|
F
|
We Were Both Children
|
Mihai and Slavic were looking at a group of $n$ frogs, numbered from $1$ to $n$, all initially located at point $0$. Frog $i$ has a hop length of $a_i$.
Each second, frog $i$ hops $a_i$ units forward. Before any frogs start hopping, Slavic and Mihai can place \textbf{exactly one} trap in a coordinate in order to catch all frogs that will ever pass through the corresponding coordinate.
However, the children can't go far away from their home so they can only place a trap in the first $n$ points (that is, in a point with a coordinate between $1$ and $n$) and the children can't place a trap in point $0$ since they are scared of frogs.
Can you help Slavic and Mihai find out what is the maximum number of frogs they can catch using a trap?
|
We disregard any $a_i$ larger than $n$ since we can't catch them anyway. We keep in $cnt_i$ how many frogs we have for each hop distance. We go through each $i$ from $1$ to $n$ and add $cnt_i$ to every multiple of $i$ smaller or equal to $n$. This action is a harmonic series and takes $O(nlogn)$ time. We go through all from $1$ to $n$ and take the maximum.
|
[
"brute force",
"implementation",
"math",
"number theory"
] | 1,300
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
void solve() {
int n; cin >> n;
vector<ll> cnt(n + 1, 0), mx(n + 1, 0);
for(int i = 0; i < n; ++i) {
int x; cin >> x;
if(x <= n) ++cnt[x];
}
for(int i = 1; i <= n; ++i) {
for(int j = i; j <= n; j += i) mx[j] += cnt[i];
}
cout << *max_element(all(mx)) << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
solve();
}
}
|
1850
|
G
|
The Morning Star
|
A compass points directly toward the morning star. It can only point in one of eight directions: the four cardinal directions (N, S, E, W) or some combination (NW, NE, SW, SE). Otherwise, it will break.
\begin{center}
{\small The directions the compass can point.}
\end{center}
There are $n$ distinct points with integer coordinates on a plane. How many ways can you put a compass at one point and the morning star at another so that the compass does not break?
|
Let's look at four directions of the line connecting the compass and morning star: vertical, horizontal, with slope $1$ (looks like /), and with slope $-1$ (looks like \). vertical: the two points need to have the same $y$-coordinate. If there are $k$ points with the same $y$-coordinate, then how many pairs are possible for the morning star and compass? Well, there are $k$ possibilities for the compass, and $k-1$ for the morning star, so there are a total of $k(k-1)$ valid pairs. In this case, we can use a data structure like a C++ map to count the number of points at each $y$-coordinate, and add $k(k-1)$ to the total for each $k$ in the map. horizontal: the two points need to have the same $x$-coordinate. Similarly, we count pairs with the same $x$-coordinate using a map. slope $1$: note that all lines of this form can be written as $x-y=c$ for a constant $c$. (Draw some examples out for $c=-1, 0, 1$.) So we can use a map to count values of $x-y$, and add to the total. slope $-1$: similarly, all such lines can be written as $x+y=c$ for a constant $c$.
|
[
"combinatorics",
"data structures",
"geometry",
"implementation",
"math",
"sortings"
] | 1,500
|
#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
using namespace std;
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define int long long
void solve()
{
int n;
cin >> n;
map<int, int> up, side, diag1, diag2;
int ans = 0;
for(int i = 0; i < n; i++)
{
int x, y;
cin >> x >> y;
up[x]++;
side[y]++;
diag1[x-y]++;
diag2[x+y]++;
}
for(auto x : up)
{
ans+=x.second*(x.second-1);
}
for(auto x : side)
{
ans+=x.second*(x.second-1);
}
for(auto x : diag1)
{
ans+=x.second*(x.second-1);
}for(auto x : diag2)
{
ans+=x.second*(x.second-1);
}
cout << ans << endl;
}
int32_t main(){
startt
int t = 1;
cin >> t;
while (t--) {
solve();
}
}
|
1850
|
H
|
The Third Letter
|
In order to win his toughest battle, Mircea came up with a great strategy for his army. He has $n$ soldiers and decided to arrange them in a certain way in camps. Each soldier has to belong to exactly one camp, and there is one camp at each integer point on the $x$-axis (at points $\cdots, -2, -1, 0, 1, 2, \cdots$).
The strategy consists of $m$ conditions. Condition $i$ tells that soldier $a_i$ should belong to a camp that is situated $d_i$ meters in front of the camp that person $b_i$ belongs to. (If $d_i < 0$, then $a_i$'s camp should be $-d_i$ meters behind $b_i$'s camp.)
Now, Mircea wonders if there exists a partition of soldiers that respects the condition and he asks for your help! Answer "YES" if there is a partition of the $n$ soldiers that satisfies \textbf{all} of the $m$ conditions and "NO" otherwise.
Note that two different soldiers \textbf{may} be placed in the same camp.
|
We can view the conditions and soldiers as a directed graph. The soldiers represent nodes and the conditions represent directed edges. Saying $a_i$ should be $d_i$ meters in front of $b_i$ is equivalent to adding two weighted directed edges: An edge from $a_i$ to $b_i$ with weight $d_i$. An edge from $b_i$ to $a_i$ with weight $-d_i$. Now, we iterate over all $n$ soldiers, and do a standard dfs whenever we encounter an unvisited soldier, assigning coordinates respecting the weights of the edges. That is, for the first soldier in the set we can just set his coordinate to $0$, then for every neighbor we visit we set it's coordinate to the coordinate of the current node added by the weight of the edge between it and its neighbor. Finally, we check at the end if all of the $m$ conditions are satisfied.
|
[
"dfs and similar",
"dsu",
"graphs",
"greedy",
"implementation"
] | 1,700
|
#include "bits/stdc++.h"
using namespace std;
#define ll long long
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(),v.rend()
#define pb push_back
#define sz(a) (int)a.size()
#define int long long
const int N = 2e5 + 5;
vector<pair<int, int>> adj[N];
int val[N], vis[N];
void dfs(int u) {
vis[u] = 1;
for(auto x: adj[u]) {
int v = x.first, w = x.second;
if(!vis[v]) {
val[v] = val[u] + w;
dfs(v);
}
}
}
void solve() {
int n, m; cin >> n >> m;
for(int i = 1; i <= n; ++i) {
adj[i].clear();
vis[i] = 0, val[i] = 0;
}
vector<array<int, 3>> c;
for(int i = 1; i <= m; ++i) {
int a, b, d; cin >> a >> b >> d;
adj[a].pb({b, d});
adj[b].pb({a, -d});
c.pb({a, b, d});
}
for(int i = 1; i <= n; ++i) {
if(!vis[i]) dfs(i);
}
for(int i = 1; i <= m; ++i) {
int a = c[i - 1][0], b = c[i - 1][1], d = c[i - 1][2];
if(val[a] + d != val[b]) {
cout << "NO\n";
return;
}
}
cout << "YES\n";
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
solve();
}
}
|
1851
|
A
|
Escalator Conversations
|
One day, Vlad became curious about who he can have a conversation with on the escalator in the subway. There are a total of $n$ passengers. The escalator has a total of $m$ steps, all steps indexed from $1$ to $m$ and $i$-th step has height $i \cdot k$.
Vlad's height is $H$ centimeters. Two people with heights $a$ and $b$ can have a conversation on the escalator if they are standing on \textbf{different} steps and the height difference between them is equal to the height difference between the steps.
For example, if two people have heights $170$ and $180$ centimeters, and $m = 10, k = 5$, then they can stand on steps numbered $7$ and $5$, where the height difference between the steps is equal to the height difference between the two people: $k \cdot 2 = 5 \cdot 2 = 10 = 180 - 170$. There are other possible ways.
Given an array $h$ of size $n$, where $h_i$ represents the height of the $i$-th person. Vlad is interested in how many people he can have a conversation with on the escalator \textbf{individually}.
For example, if $n = 5, m = 3, k = 3, H = 11$, and $h = [5, 4, 14, 18, 2]$, Vlad can have a conversation with the person with height $5$ (Vlad will stand on step $1$, and the other person will stand on step $3$) and with the person with height $14$ (for example, Vlad can stand on step $3$, and the other person will stand on step $2$). Vlad cannot have a conversation with the person with height $2$ because even if they stand on the extreme steps of the escalator, the height difference between them will be $6$, while their height difference is $9$. Vlad cannot have a conversation with the rest of the people on the escalator, so the answer for this example is $2$.
|
For each person in the array $h$, we will check the conditions. First, the height should not be the same as Vlad's height, then their difference should be divisible by $k$, and finally, the difference between the extreme steps should not exceed the difference in height. If these requirements are met, there will be steps where Vlad can talk to a person with that height.
|
[
"brute force",
"constructive algorithms",
"math"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define sz(v) (int)v.size()
#define all(v) v.begin(),v.end()
#define eb emplace_back
void solve() {
int n,m,k,H; cin >> n >> m >> k >> H;
int ans = 0;
forn(i, n) {
int x; cin >> x;
ans += (H != x) && abs(H - x) % k == 0 && abs(H-x) <= (m-1) * k;
}
cout << ans << endl;
}
int main() {
int t;
cin >> t;
forn(tt, t) {
solve();
}
}
|
1851
|
B
|
Parity Sort
|
You have an array of integers $a$ of length $n$. You can apply the following operation to the given array:
- Swap two elements $a_i$ and $a_j$ such that $i \neq j$, $a_i$ and $a_j$ are either \textbf{both} even or \textbf{both} odd.
Determine whether it is possible to sort the array in non-decreasing order by performing the operation any number of times (possibly zero).
For example, let $a$ = [$7, 10, 1, 3, 2$]. Then we can perform $3$ operations to sort the array:
- Swap $a_3 = 1$ and $a_1 = 7$, since $1$ and $7$ are odd. We get $a$ = [$1, 10, 7, 3, 2$];
- Swap $a_2 = 10$ and $a_5 = 2$, since $10$ and $2$ are even. We get $a$ = [$1, 2, 7, 3, 10$];
- Swap $a_4 = 3$ and $a_3 = 7$, since $3$ and $7$ are odd. We get $a$ = [$1, 2, 3, 7, 10$].
|
Let's copy array $a$ to array $b$. Then sort array $b$. Let's check that for each $1 \le i \le n$ it is satisfied that $(a_i \bmod 2) = (b_i \bmod 2)$, where $\bmod$ is the operation of taking the remainder from division. In other words, we need to check that in the sorted array $b$, the element at the $i$-th position has the same parity as the element at the $i$-th position in the unsorted array $a$. This is true because any array can be sorted using at most $n^2$ operations, in which any two elements are swapped. Consequently, if the parity of the elements in the sorted array is preserved, then the even and odd subsequences of the elements can be sorted separately, and the answer is YES. If the parity of the elements is not preserved after sorting, the answer is NO.
|
[
"greedy",
"sortings",
"two pointers"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
bool solve(){
int n;
cin >> n;
vector<int>a(n), b(n);
for(int i = 0; i < n; i++){
cin >> a[i];
b[i] = a[i];
}
sort(b.begin(), b.end());
for(int i = 0; i < n; i++){
if((a[i] % 2) != (b[i] % 2)) return false;
}
return true;
}
int main(){
int t;
cin >> t;
while(t--){
cout << (solve() ? "YES" : "NO") << "\n";
}
return 0;
}
|
1851
|
C
|
Tiles Comeback
|
Vlad remembered that he had a series of $n$ tiles and a number $k$. The tiles were numbered from left to right, and the $i$-th tile had colour $c_i$.
If you stand on the \textbf{first} tile and start jumping any number of tiles \textbf{right}, you can get a path of length $p$. The length of the path is the number of tiles you stood on.
Vlad wants to see if it is possible to get a path of length $p$ such that:
- it ends at tile with index $n$;
- $p$ is divisible by $k$
- the path is divided into blocks of length exactly $k$ each;
- tiles in each block have the same colour, the colors in adjacent blocks are not necessarily different.
For example, let $n = 14$, $k = 3$.
The colours of the tiles are contained in the array $c$ = [$\textcolor{red}{1}, \textcolor{violet}{2}, \textcolor{red}{1}, \textcolor{red}{1}, \textcolor{gray}{7}, \textcolor{orange}{5}, \textcolor{green}{3}, \textcolor{green}{3}, \textcolor{red}{1}, \textcolor{green}{3}, \textcolor{blue}{4}, \textcolor{blue}{4}, \textcolor{violet}{2}, \textcolor{blue}{4}$]. Then we can construct a path of length $6$ consisting of $2$ blocks:
$\textcolor{red}{c_1} \rightarrow \textcolor{red}{c_3} \rightarrow \textcolor{red}{c_4} \rightarrow \textcolor{blue}{c_{11}} \rightarrow \textcolor{blue}{c_{12}} \rightarrow \textcolor{blue}{c_{14}}$
All tiles from the $1$-st block will have colour $\textcolor{red}{\textbf{1}}$, from the $2$-nd block will have colour $\textcolor{blue}{\textbf{4}}$.
It is also possible to construct a path of length $9$ in this example, in which all tiles from the $1$-st block will have colour $\textcolor{red}{\textbf{1}}$, from the $2$-nd block will have colour $\textcolor{green}{\textbf{3}}$, and from the $3$-rd block will have colour $\textcolor{blue}{\textbf{4}}$.
|
Since the path must start in the first tile and end in the last tile, it is enough to construct a path consisting of $1$ or $2$ blocks of length $k$ to solve the problem. If $c_1 = c_n$, then we need to check that there are $k-2$ tiles of colour $c_0$ between the first and the last tile. If this condition is satisfied, then the tiles that are found together with the first and the last tile form the path $p$, and the answer is - YES. Otherwise - the answer is NO. If $c_1 \neq c_n$ we can solve the problem by the method of two pointers: let's move from the two ends of the array $c$ to the middle, counting the number of tiles of colour $c_1$ on the left and tiles of colour $c_n$ on the right. If the pointers meet no later than $k$ tiles of the desired colours are found on both sides, the answer is - YES, otherwise - NO.
|
[
"greedy"
] | 1,000
|
#include "bits/stdc++.h"
using namespace std;
bool solve(){
int n, k;
cin >> n >> k;
vector<int>c(n);
for(int i = 0; i < n; i++) cin >> c[i];
int left = 0, right = 0, i = 0, j = n - 1;
int k_left = k, k_right = k;
if (c[0] == c[n - 1]){
k_left = k / 2;
k_right = k - k_left;
}
for(; i < n && left < k_left; i++){
if(c[i] == c[0]) left++;
}
for(; j >= 0 && right < k_right; j--){
if(c[j] == c[n - 1]) right++;
}
return (i - 1) < (j + 1);
}
int main(){
int t;
cin >> t;
while(t--){
cout << (solve() ? "YES" : "NO") << "\n";
}
}
|
1851
|
D
|
Prefix Permutation Sums
|
Your friends have an array of $n$ elements, calculated its array of prefix sums and passed it to you, accidentally losing one element during the transfer. Your task is to find out if the given array can matches \textbf{permutation}.
A permutation of $n$ elements is an array of $n$ numbers from $1$ to $n$ such that each number occurs exactly \textbf{one} times in it.
The array of prefix sums of the array $a$ — is such an array $b$ that $b_i = \sum_{j=1}^i a_j, 1 \le i \le n$.
For example, the original permutation was $[1, 5, 2, 4, 3]$. Its array of prefix sums — $[1, 6, 8, 12, 15]$. Having lost one element, you can get, for example, arrays $[6, 8, 12, 15]$ or $[1, 6, 8, 15]$.
It can also be shown that the array $[1, 2, 100]$ does not correspond to any permutation.
|
To begin with, let's learn how to reconstruct an array from its prefix sum array. This can be done by calculating the differences between adjacent elements. If the element $\frac{n * (n + 1)}{2}$ is missing from the array, we will add it and check if the array corresponds to some permutation. Otherwise, there is a missing element in the middle or at the beginning of the array. Let's count the occurrences of each difference between adjacent elements. Obviously, we should have one extra number and $2$ missing numbers. If the count of differences occurring at least $2$ times is at least $2$, the answer is $NO$. The answer is also $NO$ if any difference occurs at least $3$ times. Otherwise, we check that exactly $2$ distinct numbers are missing, and their sum is equal to the only duplicate.
|
[
"implementation",
"math"
] | 1,300
|
#include <iostream>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
ll n;
bool isPermutation(vector<ll> a) {
for (int i = 0; i < n; ++i) {
if (a[i] <= 0 || a[i] > n) {
return false;
}
}
set<ll> s(a.begin(), a.end());
return s.size() == n;
}
vector<ll> prefSumToArray(vector<ll> p) {
vector<ll> res(n);
res[0] = p[0];
for (int i = 1; i < n; ++i) {
res[i] = p[i] - p[i - 1];
}
return res;
}
void solve() {
cin >> n;
vector<ll> a(n - 1);
for (int i = 0; i + 1 < n; ++i) {
cin >> a[i];
}
ll x = n * (n + 1) / 2;
if (a.back() != x) {
a.push_back(x);
vector<ll> b = prefSumToArray(a);
if (isPermutation(b)) {
cout << "YES\n";
} else {
cout << "NO\n";
}
return;
}
map<ll, int> cnt;
cnt[a[0]]++;
for (int i = 1; i < n - 1; ++i) {
cnt[a[i] - a[i - 1]]++;
}
vector<int> cntGt1;
for (auto p: cnt) {
if (p.second > 1) {
cntGt1.push_back(p.first);
}
}
if (cntGt1.size() > 1) {
cout << "NO\n";
return;
}
if (cntGt1.size() == 1) {
int x1 = cntGt1[0];
if (cnt[x1] > 2) {
cout << "NO\n";
return;
}
}
vector<int> cnt0;
for (int i = 1; i <= n; ++i) {
if (cnt[i] == 0) {
cnt0.push_back(i);
}
}
if (cnt0.size() != 2) {
cout << "NO\n";
return;
}
cout << "YES\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
solve();
}
return 0;
}
|
1851
|
E
|
Nastya and Potions
|
Alchemist Nastya loves mixing potions. There are a total of $n$ types of potions, and one potion of type $i$ can be bought for $c_i$ coins.
Any kind of potions can be obtained in no more than one way, by mixing from several others. The potions used in the mixing process will be \textbf{consumed}. Moreover, no potion can be obtained from itself through one or more mixing processes.
As an experienced alchemist, Nastya has an \textbf{unlimited} supply of $k$ types of potions $p_1, p_2, \dots, p_k$, but she doesn't know which one she wants to obtain next. To decide, she asks you to find, for each $1 \le i \le n$, the minimum number of coins she needs to spend to obtain a potion of type $i$ next.
|
To begin with, let's note that potions of types $p1, p2, \dots, p_k$ are essentially free, so we can replace their costs with $0$. Let $ans[i]$ be the answer for the $i$-th potion. Each potion can be obtained in one of two ways: by buying it or by mixing it from other potions. For mixing, we obtain all the required potions at the minimum cost. That is, if there is a way to mix a potion of type $i$, then the answer for it is either $c_i$ or the sum of answers for all $e_i$. Since the graph in the problem does not have cycles, this can be done by a simple depth-first search.
|
[
"dfs and similar",
"dp",
"graphs",
"sortings"
] | 1,500
|
#include <bits/stdc++.h>
#define int long long
using namespace std;
vector<int> dp;
vector<bool> used;
vector<vector<int>> sl;
int get(int v){
if(used[v]){
return dp[v];
}
used[v] = true;
int s = 0;
for(int u: sl[v]){
s += get(u);
}
if(!sl[v].empty()) dp[v] = min(dp[v], s);
return dp[v];
}
void solve(int tc) {
int n, k;
cin >> n >> k;
dp.resize(n);
used.assign(n, false);
sl.assign(n, vector<int>(0));
for(int &e: dp) cin >> e;
for(int i = 0; i < k; ++i){
int e;
cin >> e;
dp[--e] = 0;
}
for(int i = 0; i < n; ++i){
int m;
cin >> m;
sl[i].resize(m);
for(int &e: sl[i]){
cin >> e;
--e;
}
}
for(int i = 0; i < n; ++i){
get(i);
}
for(int e: dp) cout << e << " ";
}
bool multi = true;
signed main() {
int t = 1;
if(multi) cin >> t;
for (int i = 1; i <= t; ++i) {
solve(i);
cout << "\n";
}
return 0;
}
|
1851
|
F
|
Lisa and the Martians
|
Lisa was kidnapped by martians! It okay, because she has watched a lot of TV shows about aliens, so she knows what awaits her. Let's call integer martian if it is \textbf{a non-negative integer} and \textbf{strictly less than} $2^k$, for example, when $k = 12$, the numbers $51$, $1960$, $0$ are martian, and the numbers $\pi$, $-1$, $\frac{21}{8}$, $4096$ are not.
The aliens will give Lisa $n$ martian numbers $a_1, a_2, \ldots, a_n$. Then they will ask her to name any martian number $x$. After that, Lisa will select a pair of numbers $a_i, a_j$ ($i \neq j$) in the given sequence and count $(a_i \oplus x) \& (a_j \oplus x)$. The operation $\oplus$ means Bitwise exclusive OR, the operation $\&$ means Bitwise And. For example, $(5 \oplus 17) \& (23 \oplus 17) = (00101_2 \oplus 10001_2) \& (10111_2 \oplus 10001_2) = 10100_2 \& 00110_2 = 00100_2 = 4$.
Lisa is sure that the higher the calculated value, the higher her chances of returning home. Help the girl choose such $i, j, x$ that maximize the calculated value.
|
Solution 1. Let's use the data structure called a bitwise trie. Fix some $a_i$, where all $a_j$ for $j < i$ have already been added to the trie. We will iterate over the bits in $a_i$ from the $(k - 1)$-th bit to the $0$-th bit. Since $2^t > 2^{t - 1} + 2^{t - 2} + \ldots + 2 + 1$, if there exists $a_j$ with the same bit at the corresponding position in $a_i$, we will go into that branch of the trie and append $1 - b$ to the corresponding bit $x$. Otherwise, our path is uniquely determined. When we reach a leaf, the bits on the path will correspond to the optimal number $a_j$ for $a_i$. The complexity of this solution is $O(n k)$. Solution 2. Sort $a_1, a_2, \ldots, a_n$ in non-decreasing order. We will prove that the answer is some pair of adjacent numbers. Let the answer be numbers $a_i, a_j$ ($j - i > 1$). If $a_i = a_j$, then $a_i = a_{i + 1}$. Otherwise, they have a common prefix of bits, after which there is a differing bit. That is, at some position $t$, $a_i$ has a $0$ and $a_j$ has a $1$. Since $j - i > 1$, $a_{i + 1}$ can have either $0$ or $1$ at this position, but in the first case it is more advantageous to choose $a_i, a_{i + 1}$ as the answer, and in the second case it is more advantageous to choose $a_{i + 1}, a_j$ as the answer. The complexity of this solution is $O(n \log n)$. Solution 3 (secret). The problem can be easily reduced to finding a pair of numbers with the minimum $\oplus$. If you don't know about the bitwise trie and the sorting trick, such a problem can be solved using AVX instructions. The complexity of this solution is $O(\frac{n^2}{2 \cdot 8})$.
|
[
"bitmasks",
"greedy",
"math",
"strings",
"trees"
] | 1,800
|
#include <bits/stdc++.h>
#define all(arr) arr.begin(), arr.end()
using namespace std;
const int MAXN = 200200;
const int MAXK = 30;
const int MAXMEM = MAXN * MAXK;
mt19937 rng(07062006);
struct node {
node *chi[2] {nullptr};
int sz = 0, id = -1;
};
int n, k;
int arr[MAXN];
node *mem = new node[MAXMEM];
node *root, *mpos;
void add_num(node* &v, int val, int i, int id) {
if (v == nullptr) *(v = mpos++) = node();
v->sz++;
if (i == -1) {
v->id = id;
return;
}
add_num(v->chi[val >> i & 1], val, i - 1, id);
}
int down(node *v, int val, int i, int &x, int &jans) {
if (i == -1) {
jans = v->id;
return 0;
}
int b = val >> i & 1;
if (v->chi[b])
return down(v->chi[b], val, i - 1, x ^= ((1 ^ b) << i), jans) | (1 << i);
return down(v->chi[b ^ 1], val, i - 1, x ^= ((rng() & 1) << i), jans);
}
void build() {
root = nullptr;
mpos = mem;
add_num(root, *arr, k - 1, 0);
}
tuple<int, int, int> solve() {
int ians = 0, jans = 1, xans = 0;
for (int i = 1; i < n; ++i) {
int x = 0, j = -1;
int cur = down(root, arr[i], k - 1, x, j);
if (cur > ((arr[ians] ^ xans) & (arr[jans] ^ xans)))
ians = j, jans = i, xans = x;
add_num(root, arr[i], k - 1, i);
}
return {ians, jans, xans};
}
int main() {
int t; cin >> t;
while (t--) {
cin >> n >> k;
for (int i = 0; i < n; ++i)
cin >> arr[i];
build();
auto [ians, jans, xans] = solve();
cout << ++ians << ' ' << ++jans << ' ' << xans << endl;
}
}
|
1851
|
G
|
Vlad and the Mountains
|
Vlad decided to go on a trip to the mountains. He plans to move between $n$ mountains, some of which are connected by roads. The $i$-th mountain has a height of $h_i$.
If there is a road between mountains $i$ and $j$, Vlad can move from mountain $i$ to mountain $j$ by spending $h_j - h_i$ units of energy. If his energy drops below zero during the transition, he will not be able to move from mountain $i$ to mountain $j$. Note that $h_j - h_i$ can be negative and then the energy will be restored.
Vlad wants to consider different route options, so he asks you to answer the following queries: is it possible to construct some route starting at mountain $a$ and ending at mountain $b$, given that he initially has $e$ units of energy?
|
Let's consider the change in energy when traveling from $i \rightarrow j \rightarrow k$, $h_i - h_j + h_j - h_k = h_i - h_k$, it can be seen that this is the difference between the heights of the first and last mountains on the path. In other words, from vertex $a$, it is possible to reach any vertex for which there is a path that does not pass through vertices with a height greater than $h_a+e$. Therefore, for each query, it is necessary to construct a component from vertex $a$, in which all vertices with a height not greater than $h_a + e$ are included, and check if vertex $b$ lies within it. To do this efficiently, let's sort the queries by $h_a + e$, and the edges of the graph by $\max(h_u, h_v)$, and maintain a disjoint set data structure (DSU). Before each query, add all edges that have not been added yet and their $\max(h_u, h_v)$ is not greater than $h_a+e$ for that specific query. After this, it remains to only check if vertices $a$ and $b$ belong to the same connected component.
|
[
"binary search",
"data structures",
"dsu",
"graphs",
"implementation",
"sortings",
"trees",
"two pointers"
] | 2,000
|
#include <bits/stdc++.h>
#define x first
#define y second
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
typedef long double ld;
typedef long long ll;
using namespace std;
struct dsu{
vector<int> p, lvl;
dsu(int n){
p.resize(n);
lvl.assign(n, 0);
iota(all(p), 0);
}
int get(int i){
if(i == p[i]) return i;
return p[i] = get(p[i]);
}
bool unite(int a, int b){
a = get(a);
b = get(b);
if(a == b){
return false;
}
if(lvl[a] < lvl[b])swap(a, b);
p[b] = a;
if(lvl[a] == lvl[b]){
++lvl[a];
}
return true;
}
bool reachable(int a, int b){
return get(a) == get(b);
}
};
void solve(int tc) {
int n, m;
cin >> n >> m;
vector<pair<int, int>> h(n);
for(auto &e: h) cin >> e.x;
for(int i = 0; i < n; ++i){
h[i].y = i;
}
dsu graph(n);
vector<vector<int>> sl(n);
for(int i = 0; i < m; ++i){
int u, v;
cin >> u >> v;
--u, --v;
if(h[u].x > h[v].x) sl[u].emplace_back(v);
else sl[v].emplace_back(u);
}
int q;
cin >> q;
vector<pair<pair<int, int>, pair<int, int>>> req(q);
for(auto &e: req){
cin >> e.y.x >> e.y.y >> e.x.x;
--e.y.x, --e.y.y;
e.x.x += h[e.y.x].x;
}
for(int i = 0; i < q; ++i){
req[i].x.y = i;
}
sort(all(h));
sort(all(req));
vector<bool> ans(q);
int j = 0;
for(auto e: req){
while (j < n && h[j].x <= e.x.x) {
for(int u: sl[h[j].y]){
graph.unite(h[j].y, u);
}
++j;
}
ans[e.x.y] = graph.reachable(e.y.x, e.y.y);
}
for(bool e: ans) cout << (e? "YES": "NO") << "\n";
}
bool multi = true;
signed main() {
int t = 1;
if(multi) cin >> t;
for (int i = 1; i <= t; ++i) {
solve(i);
if(i < t) cout << "\n";
}
return 0;
}
|
1852
|
A
|
Ntarsis' Set
|
Ntarsis has been given a set $S$, initially containing integers $1, 2, 3, \ldots, 10^{1000}$ in sorted order. Every day, he will remove the $a_1$-th, $a_2$-th, $\ldots$, $a_n$-th smallest numbers in $S$ \textbf{simultaneously}.
What is the smallest element in $S$ after $k$ days?
|
Suppose that the numbers are arranged in a line in increasing order. Take a look at each number $x$ before some day. If it isn't deleted on that day, what new position does it occupy, and how is that impacted by its previous position? If $x$ is between $a_i$ and $a_{i+1}$, it will move to a new position of $x-i$, since $i$ positions before it are deleted. Take this observation, and apply it to simulate the process backwards. Suppose the numbers are arranged in a line in increasing order. Consider simulating backwards; instead of deleting the numbers at positions $a_1,a_2,\ldots,a_n$ in each operation, then checking the first number after $k$ operations, we start with the number $1$ at the front, try to insert zeroes right after positions $a_1-1, a_2-2, \ldots, a_{n}-n$ in each operation so that the zeroes will occupy positions $a_1, a_2, \ldots, a_n$ after the insertion, and after $k$ insertions, we will check the position that $1$ will end up at. If $a_1$ is not equal to $1$, the answer is $1$. Otherwise, each insertion can be processed in $O(1)$ if we keep track of how many of $a_1-1, a_{2}-2,\ldots,a_{n}-n$ are before the current position $x$ of $1$; if $a_1-1$ through $a_i-i$ are before $x$, then we will insert $i$ zeroes before $x$. The time complexity is $O(n+k)$ per test case. The editorial code additionally processes every insertion with the same $i$ value in $O(1)$, for $O(n)$ overall complexity. There are alternative solutions using binary search with complexity $O(k\log nk)$ or $O(k\log n\log nk)$, and we allowed them to pass. In fact, this problem was originally proposed with $k \leq 10^9$ but we lowered the constraints.
|
[
"binary search",
"math",
"number theory"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int inf = 1e9+10;
const ll inf_ll = 1e18+10;
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define cmax(x, y) (x = max(x, y))
#define cmin(x, y) (x = min(x, y))
#ifndef LOCAL
#define debug(...) 0
#else
#include "../../debug.cpp"
#endif
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int t; cin >> t;
while (t--) {
ll n, k; cin >> n >> k;
vector<ll> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
ll j = 0, x = 1;
while (k--) {
while (j < n && a[j] <= x+j)
j++;
x += j;
}
cout << x << "\n";
}
}
|
1852
|
B
|
Imbalanced Arrays
|
Ntarsis has come up with an array $a$ of $n$ non-negative integers.
Call an array $b$ of $n$ integers imbalanced if it satisfies the following:
- $-n\le b_i\le n$, $b_i \ne 0$,
- there are no two indices $(i, j)$ ($1 \le i, j \le n$) such that $b_i + b_j = 0$,
- for each $1 \leq i \leq n$, there are \textbf{exactly} $a_i$ indices $j$ ($1 \le j \le n$) such that $b_i+b_j>0$, where $i$ and $j$ are not necessarily distinct.
Given the array $a$, Ntarsis wants you to construct some imbalanced array. Help him solve this task, or determine it is impossible.
|
You can solve the problem by picking one number from each pair $(n, -n)$, $(n - 1, -n + 1) \dots$, $(1, -1)$. $b_i > b_j$ implies $a_i > a_j$. First, try to determine one index in $O(n)$, or determine if that's impossible. Sort the array $a$ to optimize the $O(n^2)$ solution. At the start, let $x$ be an index such that $b_x$ has the greatest absolute value. If $b_x$ is negative, we have $a_x=0$, and else $a_x=n$. Moreover, we can't have $a_y=0,a_z=n$ for any indices $y$ and $z$, because that implies $b_y+b_z$ is both positive and negative, contradiction. Hence, the necessary and sufficient condition to check if we can determine an element in array $b$ with maximum absolute value is (there exists an element of array $a$ equal to $0$) xor (there exists an element of array $a$ equal to $n$). Then, we can remove that element and re-calculate the $a$ array, leading to an $O(n^2)$ solution. If the check fails at any moment, there is no valid solution. To optimize it further, note that we can sort array $a$ at the start and keep track of them in a deque-like structure. We only need to check the front and end of the deque to see if our key condition holds. Finally, we can use a variable to record the number of positive elements deleted so far and subtract it from the front and end of the deque when checking our condition, so that each check is $O(1)$. The overall complexity becomes $O(n\log n)$ due to sorting.
|
[
"constructive algorithms",
"graphs",
"greedy",
"math",
"sortings",
"two pointers"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int n, ans[100010];
vector<pair<int,int>> arr;
void solve() {
cin >> n;
arr.resize(n);
for (int i = 0; i < n; i++) {
cin >> arr[i].first;
arr[i].second = i;
}
sort(arr.begin(), arr.end());
int l = 0, r = n - 1, sz = n;
while (l <= r) {
if ((arr[r].first == n - l) ^ (arr[l].first == n - 1 - r)) {
if (arr[r].first == n - l) {
ans[arr[r--].second] = sz--;
}
else {
ans[arr[l++].second] = -(sz--);
}
}
else {
cout << "NO" << "\n";
return;
}
}
cout << "YES" << "\n";
for (int i = 0; i < n; i++) cout << ans[i] << " ";
cout << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
int t; cin >> t;
while(t--) solve();
}
|
1852
|
C
|
Ina of the Mountain
|
To prepare her "Takodachi" dumbo octopuses for world domination, Ninomae Ina'nis, a.k.a. Ina of the Mountain, orders Hoshimachi Suisei to throw boulders at them. Ina asks you, Kiryu Coco, to help choose where the boulders are thrown.
There are $n$ octopuses on a single-file trail on Ina's mountain, numbered $1, 2, \ldots, n$. The $i$-th octopus has a certain initial health value $a_i$, where $1 \leq a_i \leq k$.
Each boulder crushes consecutive octopuses with indexes $l, l+1, \ldots, r$, where $1 \leq l \leq r \leq n$. You can choose the numbers $l$ and $r$ arbitrarily for each boulder.
For each boulder, the health value of each octopus the boulder crushes is reduced by $1$. However, as octopuses are immortal, once they reach a health value of $0$, they will immediately regenerate to a health value of $k$.
Given the octopuses' initial health values, find the \textbf{minimum} number of boulders that need to be thrown to make the health of all octopuses equal to $k$.
|
Suppose you knew in advance how many times each octopus will regenerate. Could you solve the problem then? To make things easier, replace health values of $k$ with health values of $0$, so the goal is to reach $0$ health. Regeneration is now from $0$, which was formerly $k$, to $k-1$, instead of $1$ to $k$, which is now $1$ to $0$. For clarity, create a new array $b$ such that $b[i] = a[i] \% k$. Now, instead of letting health values wrap around, we can just initially give each octopus a multiple of $k$ more health. For example, if $k=3$ and an octopus with initially $2$ health regenerates twice, we can pretend it initially had $2 + 2 \cdot 3 = 8$ health. Create a new array $c$ storing these new healths. Since all healths will reach $0$, it also represents the number of boulders that will hit each octopus. To find the minimum number of boulder throws, represent the health values with a histogram, where the heights of blocks are equal to the values of $c$: Then, erase all vertical borders between blocks. The resulting segments each represent a boulder throw: Intuitively, this should minimize the number of boulders, since any sequence of boulder throws should be rearrangeable into horizontal segments covering this histogram. We can easily calculate the number of boulders as the sum of all positive adjacent differences, treating the far left and far right as having health $0$. Formally, pad $c$ with an extra $0$ to the left and right (i.e. $c[0] = c[n+1] = 0$) and let the adjacent differences be $d[i] = c[i+1]-c[i]$. We claim the minimum number of boulder throws is $\mathrm{throws} = \sum_{i=0}^n{\max\{d[i],0\}}$. This many is necessary, since if $d[i]$ is positive, octopus $i+1$ gets crushed $d[i]$ more times than octopus $i$, so at least $d[i]$ boulders' ranges have left endpoint $l = i+1$. This many is necessary, since if $d[i]$ is positive, octopus $i+1$ gets crushed $d[i]$ more times than octopus $i$, so at least $d[i]$ boulders' ranges have left endpoint $l = i+1$. This many is achievable, as depicted above. Crush all octopuses with the highest health exactly once (crushing consecutive octopuses with the same boulder), then all octopuses with the new highest health, and so on. Each boulder's range's left endpoint corresponds with part of a positive adjacent difference. This many is achievable, as depicted above. Crush all octopuses with the highest health exactly once (crushing consecutive octopuses with the same boulder), then all octopuses with the new highest health, and so on. Each boulder's range's left endpoint corresponds with part of a positive adjacent difference. Can you figure out an $O(n^2)$ solution? And can you improve on it? Suppose you already had the optimal solution for the subarray $a[1 \ldots i]$. How could you extend it to $a[1 \ldots i+1]$? Read the solution in Hint One before continuing with this tutorial; it provides important definitions. To reduce the number of possibilities for each $c[i]$, we prove the following lemma: There exists an optimal choice of $c$ (minimizing $\mathrm{throws}$) where all differences between adjacent $c[i]$ have absolute value less than $k$. Intuitively, this is because we can decrease a $c[i]$ by $k$. Formally: We can prove this using a monovariant on the sum of all values in $c$. Start with an optimal choice of $c$. If there does not exist an $i$ with $\lvert d[i]\rvert \geq k$, we are done. Otherwise, choose one such $i$. Without loss of generality, we can assume $d[i]$ is positive, as the problem is symmetrical when flipped horizontally. Now, decrease $c[i+1]$ by $k$. This decreases $d[i]$ by $k$ to a still-positive value, which decreases $\mathrm{throws}$ by $k$. This also increases $d[i+1]$ by $k$, which increases $\mathrm{throws}$ by at most $k$. Thus, $\mathrm{throws}$ does not increase, so the new $c$ is still optimal. We can apply this operation repeatedly on any optimal solution until we do not have any more differences with absolute value $\geq k$. Since each operation decreases the sum of values in $c$ by $k$, this algorithm terminates since the sum of values in $c$ is finite. By the previous lemma, if we have determined $c[i]$, there are at most $2$ choices for $c[i+1]$. (There is $1$ choice when $b[i] = b[i+1]$, resulting in $d[i] = 0$, $c[i] = c[i+1]$, effectively merging the two octopuses.) We can visualize this as a DAG in the 2D plane over all points $(i,c[i])$ (over all possible choices of $c[i]$). Each point points to the points in the next column that are the closest above and below (if it exists), forming a grid-like shape. Our goal is to find a path of minimum cost from $(0,0)$ to $(n+1,0)$. This is the DAG for the second testcase in samples: Call each time we choose a $c[i+1] > c[i]$ (i.e. positive $d[i]$) an ascent. Note that the number of ascents is fixed because each nonzero $d[i]$ is either $x$ or $x+k$ for some fixed negative $x$, and there must be a fixed number of $+k$'s to make the total change from $c[0]$ to $c[n+1]$ zero. Each ascent brings the path up to the next "row" of descents. Since these rows slope downwards, the $j$th ascent must take place at or before some index $i_j$, because otherwise $c[i_j+1]$ would be negative. We can use the following strategy to find a path which we claim is optimal: If we can descend, then we descend. Otherwise, either we ascend, or alternatively, we change a previous descent into an ascent so we can descend here. (This can be further simplified by having a hypothetical "descent" here, so you do not need to compare two possibilities in the implementation.) Now, the best such location for an ascent is the one with minimum cost. We show how to improve (or preserve the optimality of) any other path into the one chosen by this strategy. Index the ascents by the order they are chosen by the strategy, not in left-to-right order. Let $j$ be the index of first ascent this strategy chooses that is not in the compared path. Besides the $j-1$ matching ascents, the compared path must contain at least $1$ more ascent at or before $i_j$, and because of how the strategy chooses ascents, said ascent(s) must have cost no less than the strategy's $j$th ascent. Any can be changed to match the strategy, since the matching ascents already guarantee that each of the first $j-1$ ascents in left-to-right order happens early enough. Repeating the above operation will obtain the strategy's path. We can implement the above strategy with a priority queue, where for each descent we push on the cost of the corresponding ascent, and when an ascent is required, we then pop off the minimum element. In particular, if $b[i] < b[i+1]$, then the corresponding ascent has cost $b[i+1]-b[i]$, while if $b[i] > b[i+1]$, it has cost $b[i+1]-b[i]+k$. Also, since the bottom of the DAG corresponds to $c[i] = b[i]$, an ascent is required exactly when $b[i] < b[i+1]$.
|
[
"data structures",
"dp",
"greedy",
"math"
] | 2,400
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
int n, k;
cin >> n >> k;
priority_queue<int, vector<int>, greater<int>> differences;
int previous = 0;
ll ans = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
x %= k;
if (x > previous) {
differences.push(x - previous);
ans += differences.top();
differences.pop();
} else {
differences.push(k + x - previous);
}
previous = x;
}
cout << ans << "\n";
}
int main() {
int t;
cin >> t;
while (t--)
solve();
}
|
1852
|
D
|
Miriany and Matchstick
|
Miriany's matchstick is a $2 \times n$ grid that needs to be filled with characters A or B.
He has already filled in the first row of the grid and would like you to fill in the second row. You must do so in a way such that the number of adjacent pairs of cells with different characters$^\dagger$ is equal to $k$. If it is impossible, report so.
$^\dagger$ An adjacent pair of cells with different characters is a pair of cells $(r_1, c_1)$ and $(r_2, c_2)$ ($1 \le r_1, r_2 \le 2$, $1 \le c_1, c_2 \le n$) such that $|r_1 - r_2| + |c_1 - c_2| = 1$ and the characters in $(r_1, c_1)$ and $(r_2, c_2)$ are different.
|
Solve the samples for all values of $k$. What does constructing a second row from left to right look like? How does knowing the possible $k$ for any first row help you construct a second row? Apply dynamic programming to calculate the possible $k$, and use the information in the DP to construct a solution. Call the number of adjacent pairs of cells with different characters the cost. If we construct the second row from left to right, the amount each character adds to the cost only depends on the previous character. Thus, we can represent the problem with a DAG whose vertices represent choices for each character and whose edges represent the cost of choosing two adjacent characters. Our goal is to find a path starting from the far left and ending at the far right of cost $k$. For example, below is the DAG for the third testcase in the sample. (For convenience, we include the cost of cells in the top row with the corresponding cells in the bottom row.) A general way to find such a path is as follows: For each vertex, store all possible costs of a path starting from the far left and ending at that vertex, which can be calculated with dynamic programming. Then we construct our path backwards from the right. For each candidate previous vertex, we check that the constructed path's cost plus the cost of the edge from this vertex plus some stored cost in this vertex equals $k$, in which case we know that some completion of the path from the far left to this vertex exists and we can choose this vertex. Naively calculating this DP would require $O(n)$ time per operation. However, intuitively, each set of possible costs should contain almost all values between its minimum and maximum, and experiments suggest it always consists of at most two intervals. We will first formalize the DP and then prove this observation. Let $\mathrm{dp}_A[i]$ store the set of possible values of $k$ when the grid is truncated to the first $i$ columns and the last character in the second row is $A$. Define $\mathrm{dp}_B[i]$ similarly. Using the notation $[\mathrm{true}] = 1$, $[\mathrm{false}] = 0$, $S+x = \{s+x \mid s \in S\}$, we have the recurrences $\begin{align*} \mathrm{dp}_A[i] &= \mathrm{dp}_A[i-1]\cup(\mathrm{dp}_B[i-1]+1)+[s_i \ne A]+[s_i \ne s_{i-1}] \\ \mathrm{dp}_B[i] &= \mathrm{dp}_B[i-1]\cup(\mathrm{dp}_A[i-1]+1)+[s_i \ne B]+[s_i \ne s_{i-1}] \end{align*}$ with initial values $\mathrm{dp}_A[1] = [s_1 \ne A]$ and $\mathrm{dp}_B[1] = [s_1 \ne B]$. Now either we hope that each set consists of $O(1)$ intervals, or we have to prove that each set indeed consists of at most two intervals: We will use induction to prove that the following stronger property holds for all $i \ge 2$: $\mathrm{dp}_A[i]$ and $\mathrm{dp}_B[i]$ are overlapping intervals, except that possibly one (non-endpoint) value $v$ is missing from one interval, but in that case either $v-1$ or $v+1$ is present in the other interval. ($i = 1$ must be treated separately, but it can easily be checked.) Base case. To prove this holds for $i = 2$, WLOG let $s_1 = A$ so $\mathrm{dp}_A[1] = \{0\}$ and $\mathrm{dp}_B[1] = \{1\}$. If $s_2 = A$, then $\begin{align*} \mathrm{dp}_A[2] &= \{0\}\cup(\{1\}+1)+0+0 = \{0,2\} \\ \mathrm{dp}_B[2] &= \{1\}\cup(\{0\}+1)+1+0 = \{2\} \end{align*}$ which satisfies the property with $v = 1$. If $s_2 = B$, then $\begin{align*} \mathrm{dp}_A[2] &= \{0\}\cup(\{1\}+1)+1+1 = \{2,4\} \\ \mathrm{dp}_B[2] &= \{1\}\cup(\{0\}+1)+0+1 = \{2\} \end{align*}$ which satisfies the property with $v = 3$. Induction step. Suppose the property holds for $i-1$. Since the conditions of the property only depend on relative positions, for convenience we shift the sets $\mathrm{dp}_A[i]$ and $\mathrm{dp}_B[i]$ left by $h = [s_i \ne A]+[s_i \ne s_{i-1}]$ to get $\begin{align*} \mathrm{dp}'_A[i] &= \mathrm{dp}_A[i]-h = \mathrm{dp}_A[i-1]\cup(\mathrm{dp}_B[i-1]+1) \\ \mathrm{dp}'_B[i] &= \mathrm{dp}_B[i]-h = \mathrm{dp}_B[i-1]\cup(\mathrm{dp}_A[i-1]+1)+(s_i = A\ ?\ 1 : -1). \end{align*}$ If the property holds for $\mathrm{dp}'$, then it holds for $\mathrm{dp}$. First, we show that a missing value in $\mathrm{dp}'_A[i]$ or $\mathrm{dp}'_B[i]$ can only come directly from a missing value in $\mathrm{dp}_A[i-1]$ or $\mathrm{dp}_B[i-1]$ and not from the union operation merging two non-adjacent intervals. This is true because $\mathrm{dp}_A[i-1]$ and $\mathrm{dp}_B[i-1]$ overlap, so even after $1$ is added to either, they are still at least adjacent. If a value $v$ is missing, WLOG let it be missing from $\mathrm{dp}_A[i-1]$. If $v+1 \in \mathrm{dp}_B[i-1]$, then $\mathrm{dp}'_A[i]$ may be missing $v$ while $\mathrm{dp}'_B[i]$ does not miss any value. Also, since $v-1$ is adjacent to the missing value (which isn't an endpoint), it is in $\mathrm{dp}_A[i-1]$, so either $v+1$ or $v-1$ is in $\mathrm{dp}'_B[i]$. This also guarantees the intervals overlap, satisfying the property for $i$. If $v+1 \in \mathrm{dp}_B[i-1]$, then $\mathrm{dp}'_A[i]$ may be missing $v$ while $\mathrm{dp}'_B[i]$ does not miss any value. Also, since $v-1$ is adjacent to the missing value (which isn't an endpoint), it is in $\mathrm{dp}_A[i-1]$, so either $v+1$ or $v-1$ is in $\mathrm{dp}'_B[i]$. This also guarantees the intervals overlap, satisfying the property for $i$. The case for $v-1 \in \mathrm{dp}_B[i-1]$ is very similar. $\mathrm{dp}'_B[i]$ may be missing either $v$ or $v+2$, and since $v+1 \in \mathrm{dp}_A[i-1]$, $v+1$ is in $\mathrm{dp}'_A[i]$. The case for $v-1 \in \mathrm{dp}_B[i-1]$ is very similar. $\mathrm{dp}'_B[i]$ may be missing either $v$ or $v+2$, and since $v+1 \in \mathrm{dp}_A[i-1]$, $v+1$ is in $\mathrm{dp}'_A[i]$. If no value is missing, let $x$ be a common value in both $\mathrm{dp}_A[i-1]$ and $\mathrm{dp}_B[i-1]$. Then, $\mathrm{dp}'_A[i] \supseteq \{x,x+1\}$ and $\mathrm{dp}'_B[i]$ is a superset of either $\{x-1,x\}$ or $\{x+1,x+2\}$, so the intervals overlap. To find the union of two sets of intervals, sort them by left endpoint and merge adjacent overlapping intervals. After computing the DP, apply the aforementioned backwards construction to obtain a valid second row. Below is a visualization of solving the third testcase in the sample. Generate your own here!
|
[
"constructive algorithms",
"dp",
"greedy"
] | 2,800
|
#include <bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
struct state {
// represents a set of integers compressed as a vector
// of non-overlapping intervals [l, r]
basic_string<array<int, 2>> a;
// add d to everything in the set
friend state add(state x, int d) {
for (auto& [l, r] : x.a)
l += d, r += d;
return x;
}
// union of two sets of integers
friend state unite(state x, state y) {
state z;
merge(all(x.a), all(y.a), back_inserter(z.a));
int j = 0;
for (int i = 1; i < z.a.size(); i++) {
if (z.a[i][0] <= z.a[j][1]+1)
z.a[j][1] = max(z.a[j][1], z.a[i][1]);
else
z.a[++j] = z.a[i];
}
z.a.erase(z.a.begin() + j + 1, z.a.end());
return z;
}
// whether integer k is in the set
friend bool contains(state x, int k) {
for (auto& [l, r] : x.a)
if (k >= l && k <= r)
return true;
return false;
}
};
// set containing only one integer d
state from_constant(int d) {
return state({{{d, d}}});
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int t; cin >> t;
while (t--) {
int n, k; cin >> n >> k;
string s; cin >> s;
vector<array<state, 2>> dp(n);
dp[0][0] = from_constant(s[0] != 'A');
dp[0][1] = from_constant(s[0] != 'B');
for (int i = 1; i < n; i++) {
dp[i][0] = add(unite(dp[i-1][0], add(dp[i-1][1], 1)), (s[i] != 'A') + (s[i] != s[i-1]));
dp[i][1] = add(unite(dp[i-1][1], add(dp[i-1][0], 1)), (s[i] != 'B') + (s[i] != s[i-1]));
}
if (!(contains(dp[n-1][0], k) || contains(dp[n-1][1], k))) {
cout << "NO\n";
continue;
}
string ans;
for (int i = n-1; i >= 0; i--) {
char c = contains(dp[i][0], k - (i == n-1 ? 0 : (ans.back() != 'A'))) ? 'A' : 'B';
k -= (c != s[i]);
if (i > 0)
k -= (s[i] != s[i-1]);
if (i < n-1)
k -= (c != ans.back());
ans += c;
}
reverse(all(ans));
cout << "YES\n" << ans << "\n";
}
}
|
1852
|
E
|
Rivalries
|
Ntarsis has an array $a$ of length $n$.
The power of a subarray $a_l \dots a_r$ ($1 \leq l \leq r \leq n$) is defined as:
- The largest value $x$ such that $a_l \dots a_r$ contains $x$ and neither $a_1 \dots a_{l-1}$ nor $a_{r+1} \dots a_n$ contains $x$.
- If no such $x$ exists, the power is $0$.
Call an array $b$ a rival to $a$ if the following holds:
- The length of both $a$ and $b$ are equal to some $n$.
- Over all $l, r$ where $1 \leq l \leq r \leq n$, the power of $a_l \dots a_r$ equals the power of $b_l \dots b_r$.
- The elements of $b$ are positive.
Ntarsis wants you to find a rival $b$ to $a$ such that the sum of $b_i$ over $1 \leq i \leq n$ is maximized. Help him with this task!
|
For each distinct value, only the leftmost and rightmost positions actually have an effect on the power. Think of each distinct value as an interval corresponding to its leftmost and rightmost positions, and let that distinct value be the value of its interval. If interval $x$ strictly contains an interval $y$ with greater value, then $x$ will not have an effect on the power and it can be discarded. In order to not change the power, we can only add intervals that strictly contain an interval with greater value. Afterwards, if $i$ is not the endpoint of an interval, $b_i$ equals the largest value of an interval containing $i$. There will only be at most one interval that we have to add. Assume that there are multiple intervals that we can add without changing the answer. In this case it is easy to see that its more optimal to combine the interval with smaller value into the interval with larger value. Thus, it is never optimal to add multiple intervals. Read the hints. We can remove all intervals that will not affect the power by iterating over them in decreasing order of value and maintain a segment tree that stores for each left endpoint of any processed intervals, the right endpoint that corresponds to it. Checking if an interval is strictly contained then becomes a range minimum query. Assume that we know the value $x$ of the interval that we want to add. We can immediately fill the value for the interior of all intervals that correspond to a value greater than $x$. However, we also have to guarantee that $x$ is strictly contained by an interval with greater value, so we can try each interval to contain $x$. If are no unfilled indices the left or right side of the interval, then we want to replace the smallest filled on either side value with $x$. Otherwise, we can just fill in all the unfilled indices with $x$. Note that it is also possible for $x$ to not be able to be contained by any interval. Thus, we can just try every possible $x$ in decreasing order and maintain the filled indices as we iterate. There are only at most $n$ values of $x$ to check, which is just the set of $a_i - 1$ that does not appear in $a$.
|
[
"constructive algorithms",
"data structures",
"greedy"
] | 3,400
|
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9 + 1;
void setIO() {
ios_base::sync_with_stdio(0); cin.tie(0);
}
pii seg[400005];
int n;
void build(int l = 0, int r = n - 1, int cur = 0){
seg[cur] = {INF, INF};
if(l == r) return;
int mid = (l + r)/2;
build(l, mid, cur*2 + 1);
build(mid + 1, r, cur*2 + 2);
}
void update(int x, int v, int l = 0, int r = n - 1, int cur = 0){
if(l == r){
seg[cur] = {v, l};
return;
}
int mid = (l + r)/2;
if(x <= mid) update(x, v, l, mid, cur*2 + 1);
else update(x, v, mid + 1, r, cur*2 + 2);
seg[cur] = min(seg[cur*2 + 1], seg[cur*2 + 2]);
}
pii query(int l, int r, int ul = 0, int ur = n - 1, int cur = 0){
if(l <= ul && ur <= r) return seg[cur];
if(l > r || ur < l || ul > r) return {INF, INF};
int mid = (ul + ur)/2;
return min(query(l, r, ul, mid, cur*2 + 1), query(l, r, mid + 1, ur, cur*2 + 2));
}
int main(){
setIO();
int t;
cin >> t;
for(int tt = 1; tt <= t; tt++){
cin >> n;
map<int, vector<int>> m;
int arr[n];
for(int i = 0; i < n; i++){
cin >> arr[i];
m[arr[i]].pb(i);
}
vector<int> rel; //relevant numbers
for(auto &i : m){
rel.pb(i.ff);
for(int j = 1; j < i.ss.size() - 1; j++){
arr[i.ss[j]] = 0;
}
}
reverse(rel.begin(), rel.end());
vector<int> nw;
build();
for(int i : rel){
int l = m[i].front(), r = m[i].back();
if(query(l, r).ff <= r){
arr[l] = arr[r] = 0;
} else {
update(l, r);
nw.pb(i);
}
}
swap(rel, nw);
set<int> s;
for(int i = 0; i < n; i++) if(!arr[i]) s.insert(i);
vector<int> vals; //possible target values
for(int i = rel.size() - 1; i >= 0; i--){
if(i == rel.size() - 1 || rel[i] - 1 != rel[i + 1]){
vals.pb(rel[i] - 1);
}
}
ll sum = 0, mx = 0, mxval = 0;
int lex = -1, rex = -1;
build();
for(int i = 0; i < n; i++) if(!arr[i]) update(i, -1);
reverse(vals.begin(), vals.end());
queue<pii> upd;
int ind = 0;
//try to add an interval with value i
for(int i : vals){
vector<int> nxt;
//try filling in all intervals > i
while(ind < rel.size() && rel[ind] > i){
int l = m[rel[ind]].front(), r = m[rel[ind]].back();
set<int>::iterator it = s.lower_bound(l);
while(it != s.end() && *it < r){
sum += rel[ind];
update(*it, rel[ind]);
upd.push({*it, rel[ind]});
it = s.erase(it);
}
nxt.pb(rel[ind++]);
}
//try each necessary interval to be strictly contained by i
for(int j : nxt){
int l = m[j].front(), r = m[j].back();
if(s.size() && 0 < l && r < n - 1){
//find which indeces on each side to replace with i
pii rnw = query(r + 1, n);
pii lnw = query(0, l - 1);
if(rnw.ff == INF || lnw.ff == INF) continue;
ll add = (ll)i*s.size() + (rnw.ff == -1 ? 0 : i - rnw.ff) + (lnw.ff == -1 ? 0 : i - lnw.ff);
if(i && sum + add > mx){
mx = sum + add;
mxval = i;
lex = (lnw.ff == -1 ? -1 : lnw.ss);
rex = (rnw.ff == -1 ? -1 : rnw.ss);
//it is optimal to fill in all intervals > i
while(!upd.empty()){
arr[upd.front().ff] = upd.front().ss;
upd.pop();
}
}
}
}
}
//don't want to add any intervals
if(s.size() == 0 && sum > mx){
mx = sum;
lex = rex = -1;
//it is optimal to fill in all remaining intervals
while(!upd.empty()){
arr[upd.front().ff] = upd.front().ss;
upd.pop();
}
}
if(lex != -1) arr[lex] = 0;
if(rex != -1) arr[rex] = 0;
for(int i = 0; i < n; i++) cout << (arr[i] ? arr[i] : mxval) << " ";
cout << endl;
}
}
|
1852
|
F
|
Panda Meetups
|
The red pandas are in town to meet their relatives, the blue pandas! The town is modeled by a number line.
The pandas have already planned their meetup, but the schedule keeps changing. You are given $q$ updates of the form x t c.
- If $c < 0$, it means $|c|$ more \textbf{red} pandas enter the number line at position $x$ and time $t$. Then, each unit of time, they can each independently move one unit in either direction across the number line, or \textbf{not move at all}.
- If $c > 0$, it means that $c$ more \textbf{blue} pandas check position $x$ for red pandas at time $t$. If a blue panda does not meet a red panda at that specific location and time, they dejectedly leave the number line right away. If there is a red panda at a position at the same time a blue panda checks it, they form a friendship and leave the number line. Each red panda can form a friendship with \textbf{at most one} blue panda and vice versa.
The updates will be given in order of \textbf{non-decreasing} $x$ values. After each update, please print the maximum number of friendships if the red pandas move in an optimal order based on all the updates given in the input above (and including) this update.
The order in which a red panda moves can change between updates.
|
If we want to answer one of the questions (say, the question involving all the events) in polynomial time, how do we do it? Construct a network with edges from the source to each of the red panda events with capacities equal to the number of red pandas, edges from red panda events to blue panda events with innite capacities if the red pandas can catch the corresponding blue pandas, and edges from each of the blue panda events to the sink with capacities equal to the number of blue pandas. The next step is to use the max-flow min-cut theorem: the maximum flow is equal to the minimum number of red pandas plus blue pandas we need to remove from the graph such that no remaining red panda can reach any remaining blue panda. How do we go from here? For any cut, consider the region of the $x$-$t$ plane reachable by the remaining red pandas. No remaining blue pandas can lie in this region, and its border is a polyline that intersects each vertical line in the $x$-$t$ plane exactly once. Furthermore, the slope of every segment in this polyline has slope plus or minus $1$. Conversely, we can associate every polyline satisfying this condition with a cut; we just need to remove every red panda lying below the polyline and every blue panda lying on or above the polyline. Now, figure out how to answer the queries online. Read the hints to understand the solution better. We can answer the queries online. For each $x$-coordinate $x$, maintain a treap that stores for every $x$-coordinate, the minimum cut $dp[x][t]$ associated with a polyline satisfying the condition above that starts at $x = -\infty$ and ends at $(x, t)$ when only considering events with $x$-coordinate at most $x$. When transitioning from to $x$ to $x+1$, we need to set for every $dp[x+1][t] = min(dp[x][t-1], dp[x][t], dp[x][t+1])$ for every $t$. To do this quickly, we maintain the values of $t$ where $dp[x][t+1] - dp[x][t] \neq 0$ in increasing order, of which there are at most $n$. When $x$ increases by one, each value of increases or decreases by one, depending on the sign of $dp[x][t+1]-dp[x][t]$, and some of the values of $t$ merge, decreasing the size of our treap. As long as we can process each merge in $\log n$ time, our solution will run in $O(n\log n)$ total time. When processing an event, we need to increase all $dp$ values in a suffix for red panda events, and all $dp$ values in a prefix for blue panda events. To answer a query, we just need to return the minimum prefix sum in our treap.
|
[
"data structures",
"dp",
"flows"
] | 3,500
|
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ff first
#define ss second
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9 + 1;
void setIO() {
ios_base::sync_with_stdio(0); cin.tie(0);
}
struct node {
//mnpos - leftmost negative
//mxpos - rightmost positive
int pos, tag, mnpos, mxpos;
//minimum distance
pair<int, pii> mndif;
ll sum, pre, val;
int weight;
node(){}
node(int pos_, ll val_){
pos = pos_;
val = val_;
sum = val;
pre = min((ll)0, val);
mxpos = -INF;
mnpos = INF;
mndif = {INF, {INF, INF}};
if(val > 0) mxpos = pos;
if(val < 0) mnpos = pos;
tag = 0;
weight = rand();
}
};
int sz = 1;
node treap[1000005];
int left0[1000005];
int right0[1000005];
int newnode(int pos, ll val){
treap[sz] = node(pos, val);
return sz++;
}
pair<int, pii> comb(int a, int b){
if(a == -INF || b == INF) return {INF, {INF, INF}};
return {b - a, {a, b}};
}
void pull(int x){
treap[x].sum = treap[x].val;
treap[x].pre = min((ll)0, treap[x].val);
treap[x].mxpos = -INF;
treap[x].mnpos = INF;
treap[x].mndif = {INF, {INF, INF}};
if(treap[x].val > 0) treap[x].mxpos = treap[x].pos;
if(treap[x].val < 0) treap[x].mnpos = treap[x].pos;
if(left0[x]){
treap[x].mndif = min(treap[x].mndif, treap[left0[x]].mndif);
treap[x].mndif = min(treap[x].mndif, comb(treap[left0[x]].mxpos, treap[x].mnpos));
treap[x].mnpos = min(treap[x].mnpos, treap[left0[x]].mnpos);
treap[x].mxpos = max(treap[x].mxpos, treap[left0[x]].mxpos);
treap[x].pre = min(treap[left0[x]].pre, treap[left0[x]].sum + treap[x].pre);
treap[x].sum += treap[left0[x]].sum;
}
if(right0[x]){
treap[x].mndif = min(treap[x].mndif, treap[right0[x]].mndif);
treap[x].mndif = min(treap[x].mndif, comb(treap[x].mxpos, treap[right0[x]].mnpos));
treap[x].mnpos = min(treap[x].mnpos, treap[right0[x]].mnpos);
treap[x].mxpos = max(treap[x].mxpos, treap[right0[x]].mxpos);
treap[x].pre = min(treap[x].pre, treap[x].sum + treap[right0[x]].pre);
treap[x].sum += treap[right0[x]].sum;
}
}
int move(node& x, int shift){
int ret = x.pos;
if(x.val < 0) ret -= shift;
if(x.val > 0) ret += shift;
return ret;
}
void apply(int x, int tag){
treap[x].pos = move(treap[x], tag);
treap[x].tag += tag;
if(treap[x].mnpos != INF) treap[x].mnpos -= tag;
if(treap[x].mxpos != -INF) treap[x].mxpos += tag;
if(treap[x].mndif.ff != INF){
treap[x].mndif.ff -= 2*tag;
treap[x].mndif.ss.ff += tag;
treap[x].mndif.ss.ss -= tag;
}
}
void push(int x){
if(!treap[x].tag) return;
if(left0[x]) apply(left0[x], treap[x].tag);
if(right0[x]) apply(right0[x], treap[x].tag);
treap[x].tag = 0;
}
int merge(int a, int b){
if(!a) return b;
if(!b) return a;
if(treap[a].weight < treap[b].weight){
push(a);
right0[a] = merge(right0[a], b);
pull(a);
return a;
} else {
push(b);
left0[b] = merge(a, left0[b]);
pull(b);
return b;
}
}
//splits rt's tree into [0, k) [k, INF)
pair<int, int> split(int x, int k){
if(!x) return pair<int, int>{0, 0};
push(x);
pair<int, int> ret;
if(treap[x].pos < k){
ret = split(right0[x], k);
right0[x] = ret.first;
ret.first = x;
} else {
ret = split(left0[x], k);
left0[x] = ret.second;
ret.second = x;
}
pull(x);
return ret;
}
int rt = 0;
void erase(int x){
pair<int, int> a = split(rt, x);
pair<int, int> b = split(a.second, x + 1);
rt = merge(a.first, b.second);
}
//position, value
void insert(int a, ll b){
if(!rt){
rt = newnode(a, b);
return;
}
pair<int, int> nw = split(rt, a);
rt = merge(nw.first, merge(newnode(a, b), nw.second));
}
//value
ll query(int x){
pair<int, int> a = split(rt, x);
pair<int, int> b = split(a.second, x + 1);
ll ret = (b.first ? treap[b.first].val : 0);
rt = merge(a.first, merge(b.first, b.second));
return ret;
}
int main(){
setIO();
int n;
cin >> n;
int prv = 0;
ll st = 0;
for(int i = 1; i <= n; i++){
int x, t, c;
cin >> x >> t >> c;
int dif = x - prv;
//remove overlap
while(rt && treap[rt].mndif.ff <= 2*dif){
pair<int, pii> x = treap[rt].mndif;
ll a = query(x.ss.ff), b = query(x.ss.ss);
ll sub = min(a, -b);
erase(x.ss.ff);
erase(x.ss.ss);
a -= sub, b += sub;
if(a != 0) insert(x.ss.ff, a);
if(b != 0) insert(x.ss.ss, b);
}
//shift everything
if(rt){
treap[rt].pos = move(treap[rt], dif);
treap[rt].tag += dif;
if(treap[rt].mnpos != INF) treap[rt].mnpos -= dif;
if(treap[rt].mxpos != -INF) treap[rt].mxpos += dif;
if(treap[rt].mndif.ff != INF){
treap[rt].mndif.ff -= 2*dif;
treap[rt].mndif.ss.ff += dif;
treap[rt].mndif.ss.ss -= dif;
}
}
ll cur = query(t + 1);
if(cur != 0) erase(t + 1);
if(cur - c != 0) insert(t + 1, cur - c);
if(c > 0) st += c;
cout << st + (!rt ? 0 : treap[rt].pre) << endl;
prv = x;
}
}
|
1853
|
A
|
Desorting
|
Call an array $a$ of length $n$ sorted if $a_1 \leq a_2 \leq \ldots \leq a_{n-1} \leq a_n$.
Ntarsis has an array $a$ of length $n$.
He is allowed to perform one type of operation on it (zero or more times):
- Choose an index $i$ ($1 \leq i \leq n-1$).
- Add $1$ to $a_1, a_2, \ldots, a_i$.
- Subtract $1$ from $a_{i+1}, a_{i+2}, \ldots, a_n$.
The values of $a$ can be negative after an operation.
Determine the minimum operations needed to make $a$ \textbf{not sorted}.
|
To make $a$ not sorted, we just need to pick one index $i$ so $a_i > a_{i + 1}$. How do we do this? To make $a$ not sorted, we just have to make $a_i > a_{i + 1}$ for one $i$. In one operation, we can reduce the gap between two adjacent elements $i, i + 1$ by $2$ by adding $1$ to $1 \dots i$ and subtracting $1$ from ${i + 1} \dots n$. It is clearly optimal to pick the smallest gap between a pair of adjacent elements to minimize the number of operations we have to do. If we have $a_i = x, a_{i + 1} = y$, we can make $x > y$ within $\lfloor \frac{(y - x)}{2} \rfloor + 1$ operations. Thus, we can just go through $a$, find the minimum difference gap, and calculate the minimum operations using the above formula. Note that if $a$ is not sorted, we can just output $0$. The time complexity is $O(n)$.
|
[
"brute force",
"greedy",
"math"
] | 800
|
#include <bits/stdc++.h>
#include <numeric>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int T; cin >> T;
while (T--) {
int n; cin >> n;
vector<int> nums(n);
int diff = 1e9;
bool sorted = true;
for (int i = 0; i < n; i++) {
cin >> nums[i];
if (i > 0) {
diff = min(nums[i] - nums[i - 1], diff);
sorted &= nums[i] >= nums[i - 1];
}
}
if (!sorted) {
cout << 0 << endl;
continue;
}
cout << diff/2 + 1 << endl;
}
}
|
1853
|
B
|
Fibonaccharsis
|
Ntarsis has received two integers $n$ and $k$ for his birthday. He wonders how many fibonacci-like sequences of length $k$ can be formed with \textbf{$n$ as the $k$-th element} of the sequence.
A sequence of \textbf{non-decreasing non-negative} integers is considered fibonacci-like if $f_i = f_{i-1} + f_{i-2}$ for all $i > 2$, where $f_i$ denotes the $i$-th element in the sequence. Note that $f_1$ and $f_2$ can be arbitrary.
For example, sequences such as $[4,5,9,14]$ and $[0,1,1]$ are considered fibonacci-like sequences, while $[0,0,0,1,1]$, $[1, 2, 1, 3]$, and $[-1,-1,-2]$ are not: the first two do not always satisfy $f_i = f_{i-1} + f_{i-2}$, the latter does not satisfy that the elements are non-negative.
Impress Ntarsis by helping him with this task.
|
Can a sequence involving $n$, which is up to $10^5$, really have up to $10^9$ terms? The terms of the fibonacci sequence will increase exponentially. This is quite intuitive, but mathematically, fibonnaci-like sequences will increase at a rate of phi to the power of $n$, where phi (the golden ratio) is about $1.618$. Thus, the maximum number of terms a sequence can have before it reaches $10^9$, or the maximum value of $n$, is pretty small (around $\log n$). Instead of trying to fix the first two elements of the sequence and counting how many sequences $s$ will have $s_k = n$, note that we already have $n$ fixed. If we loop over the $k-1$th element of the sequence, the sequence is still fixed. If we know the $x$th element and $x-1$th element of $s$, we can find that $s_{x - 2} = s_{x} - s_{x - 1}$. Thus, we can just go backwards and simulate for $k$ iterations in $O(\log n)$ since $k$ is small, breaking at any point if the current sequence is not fibonnaci-like (there are negative elements or it is not strictly increasing). Otherwise, we add $1$ to our answer. The time complexity is $O(n \cdot \log n)$. Bonus: Solve for $n, k \leq 10^9$ Analysis by awesomeguy856 $f[k] = F_{k-2}f[0]+F_{k-1}f[1]$ By the Extended Euclidean Algorithm, we can find one integral solution for this equation, since $\gcd (F_{k-2}, F_{k-1}) = 1 | f[k].$ Let this solution be $(f[0], f[1]) = (x, y).$ Then all other integral solutions are in the form $(x+cF_{k-1}, y-cF_{k-2}),$ for $c \in Z$ so we can find all valid solutions by binary search on $f[1],f[0] \geq 0$ and $f[1]>f[0]$, or just by some calculations.
|
[
"binary search",
"brute force",
"math"
] | 1,200
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int T; cin >> T;
while (T--) {
int n; int k;
cin >> n >> k;
int ans = 0;
for (int i = 1; i <= n; i++) {
int second = n; //xth element where x is k
int first = i; //fixing x-1th element where x is k-1
bool valid_seq = true;
for (int j = 0; j < k - 2; j++) {
//for s_x and s_x-1, s_x-2 = s_x - s_x-1
int fx = first;
first = second - fx;
second = fx;
valid_seq &= first <= second;
valid_seq &= min(first, second) >= 0;
if (!valid_seq) break; //break if the sequence is not fibonacci-like
}
if (valid_seq) ans++;
}
cout << ans << endl;
}
}
|
1854
|
A1
|
Dual (Easy Version)
|
\begin{quote}
Popskyy & tiasu - Dual
\hfill ⠀
\end{quote}
\textbf{The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.}
You are given an array $a_1, a_2,\dots, a_n$ of integers (positive, negative or $0$). You can perform multiple operations on the array (possibly $0$ operations).
In one operation, you choose $i, j$ ($1 \leq i, j \leq n$, they can be equal) and set $a_i := a_i + a_j$ (i.e., add $a_j$ to $a_i$).
Make the array non-decreasing (i.e., $a_i \leq a_{i+1}$ for $1 \leq i \leq n-1$) in at most $50$ operations. You do not need to minimize the number of operations.
|
There are several solutions to the easy version. In any case, how to get $a_i \leq a_{i+1}$? For example, you can try making $a_{i+1}$ bigger using a positive element. What to do if all the elements are negative? If all the elements are negative, you can win in $n-1$ moves. If there is a positive element, you can try to make $a_1 \leq a_2$, then $a_2 \leq a_3$, etc. Make a big positive element using moves $(i, i)$, then make $a_2$ bigger. If all the elements are negative, you can make suffix sums (they are nondecreasing) with moves $(n-1, n), (n-2, n-1), \dots$ If there is at least one positive element $a_x$, make $a_x > 20$ using $5$ moves $(x, x)$; make $a_2$ the biggest element using $2$ moves $(2, x)$; make $a_3$ the biggest element using $2$ moves $(3, 2)$; ... This strategy requires $5 + 2(n-1) \leq 43$ moves. Complexity: $O(n)$
|
[
"constructive algorithms",
"math"
] | 1,400
| null |
1854
|
A2
|
Dual (Hard Version)
|
\begin{quote}
Popskyy & tiasu - Dual
\hfill ⠀
\end{quote}
\textbf{The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.}
You are given an array $a_1, a_2,\dots, a_n$ of integers (positive, negative or $0$). You can perform multiple operations on the array (possibly $0$ operations).
In one operation, you choose $i, j$ ($1 \leq i, j \leq n$, they can be equal) and set $a_i := a_i + a_j$ (i.e., add $a_j$ to $a_i$).
Make the array non-decreasing (i.e., $a_i \leq a_{i+1}$ for $1 \leq i \leq n-1$) in at most $31$ operations. You do not need to minimize the number of operations.
|
The hints and the solution continue from the easy version. You can win in $n-1$ moves if all the elements are negative, but also if all the elements are positive. Again, make a big positive / negative element, then use it to make everything positive / negative. In how many moves can you either make everything positive or make everything negative? Assume the positive elements are at least as many as the negative elements. Can you win in $34$ moves? The bottleneck is making the big positive element. Is it always necessary? Can you find a better bound on the "best" number of moves? If you either make everything positive or make everything negative, you can win in $n-1 \leq 19$ moves by making prefix sums or suffix sums, respectively. So, you have to reach one of these configurations in $12$ moves. How to make everything positive? First, you create a big element with the maximum absolute value (this requires $x_1$ moves), then you add it to every negative element (this requires $x_2$ moves). $y_1$ and $y_2$ are defined similarly in the negative case. So, one of $x_1$ and $y_1$ is $0$ (because the element with the maximum absolute value at the beginning is either positive or negative), and the other one is $\leq 5$ (because you can make $|a_i| \geq 32$ in $5$ moves); $x_2$ is the number of negative elements, $y_2$ is the number of positive elements. So, $x_2 + y_2 \leq n \leq 20$. Therefore, you need additional $\min(x_1 + x_2, y_1 + y_2)$ moves. Since $x_1 + x_2 + y_1 + y_2 \leq 25$, $\min(x_1 + x_2, y_1 + y_2) \leq \lfloor \frac{25}{2} \rfloor = 12$, as we wanted. Now you can simulate the process in both cases (positive and negative), and choose one that requires $\leq 31$ moves in total. Complexity: $O(n)$
|
[
"constructive algorithms",
"math"
] | 1,900
| null |
1854
|
B
|
Earn or Unlock
|
Andrea is playing the game Tanto Cuore.
He has a deck of $n$ cards with values $a_1, \ldots, a_n$ from top to bottom. Each card can be either locked or unlocked. Initially, only the topmost card is unlocked.
The game proceeds in turns. In each turn, Andrea chooses an unlocked card in the deck — the value written on the card is $v$ — and performs exactly one of the following two operations:
- Unlock the first $v$ \textbf{locked} cards in the deck from the top. If there are less than $v$ locked cards in the deck, then unlock all the locked cards.
- Earn $v$ \underline{victory points}.
In both cases, after performing the operation, he removes the card from the deck.The game ends when all the cards remaining in the deck are locked, or there are no more cards in the deck.
What is the maximum number of victory points Andrea can earn?
|
The order of used cards doesn't matter. So, you can assume you always use the card on the top. Suppose that you unlock $x$ cards in total. How many points can you get? If you unlock $x$ cards, it means you end up making moves with the first $x$ cards. So, you know the total number of (cards + points) that you get. If you unlock $x$ cards, the number of points is uniquely determined. It's convenient to assume that $x \leq 2n$ and the cards $n+1, \dots, 2n$ have value $0$. Now you have to determine the unlockable prefixes of cards (i.e., the values of $x$ you can reach). It looks similar to knapsack. You can optimize the solution using a bitset. Be careful not to use locked cards. First, note that the order of used cards doesn't matter. If you use at least once a card that is not on the top on the deck, you can prove that using the cards in order (from the top) would give the same number of victory points. Let's add $n$ cards with value $0$ at the end of the deck. Then, it's optimal to unlock $x \leq 2n$ cards, and use cards $1, \dots, x$, getting $a_1 + \dots + a_x - x + 1$ points. Let's find the reachable $x$. Let $dp_i$ be a bitset that stores the reachable $x$ after using the first $i$ cards. Base case: $dp_{0,1} = 1$. Base case: $dp_{0,1} = 1$. Transitions: first, $dp_{i}$ |= $dp_{i-1}$ << $a_i$. If $dp_{i,i} = 1$, you can update the answer with $a_1 + \dots + a_i - i + 1$, but you can't unlock any other card, so you have to set $dp_{i,i} = 0$ before transitioning to $i+1$. Transitions: first, $dp_{i}$ |= $dp_{i-1}$ << $a_i$. If $dp_{i,i} = 1$, you can update the answer with $a_1 + \dots + a_i - i + 1$, but you can't unlock any other card, so you have to set $dp_{i,i} = 0$ before transitioning to $i+1$. Complexity: $O(n^2/w)$
|
[
"bitmasks",
"brute force",
"dp"
] | 2,200
| null |
1854
|
C
|
Expected Destruction
|
You have a set $S$ of $n$ distinct integers between $1$ and $m$.
Each second you do the following steps:
- Pick an element $x$ in $S$ uniformly at random.
- Remove $x$ from $S$.
- If $x+1 \leq m$ and $x+1$ is not in $S$, add $x+1$ to $S$.
What is the expected number of seconds until $S$ is empty?
Output the answer modulo $1\,000\,000\,007$.
Formally, let $P = 1\,000\,000\,007$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{a}{b}$, where $a$ and $b$ are integers and $b \not \equiv 0 \pmod{P}$. Output the integer equal to $a \cdot b^{-1} \bmod P$. In other words, output an integer $z$ such that $0 \le z < P$ and $z \cdot b \equiv a \pmod{P}$.
|
Consider $n$ blocks in positions $S_1, S_2, \dots, S_n$. After how much time does block $x$ disappear? It may be convenient to put a fake "static" block in position $m+1$. Block $x$ disappears when it reaches block $x+1$. But what if block $x+1$ disappears before block $x$? From the perspective of block $x$, it's convenient to assume that block $x+1$ never disappears: when it touches another block $y$, it's $y$ that disappears. When you consider the pair of blocks $x, x+1$, the other blocks don't really matter, and you can use linearity of expectation to calculate the contribution of each pair independently. A reasonable interpretation is given by considering an $(n+1) \times (m+1)$ grid, where the $i$-th row initially contains a block in column $S_i$. Then, you are calculating the expected time required for the blocks $1, \dots, m$ to have another block immediately below them (in the same column). Blocks $x, x+1$ both move with probability $1/2$, unless block $x+1$ has reached position $m+1$. $dp_{i,j} =$ expected number of moves of block $x$ before it disappears, if the block $x$ is in position $i$ and the block $x+1$ is in position $j$. Consider an $(n+1) \times (m+1)$ grid, where the $i$-th row initially contains a block in column $S_i$, and row $n+1$ contains a block in column $m+1$. The set is empty if all the blocks are in column $m+1$; i.e., if every block has reached the block in the following row. Every "connected component" of blocks (except the last one) represents an element in the set. These components move equiprobably. Let's calculate the expected time required for the block in row $x$ to "reach" the block in row $x+1$. If you consider a single pair of blocks, every block moves with probability $1/2$, unless block $x+1$ is in column $m+1$. So, you can calculate $dp_{i,j} =$ expected number of moves of the block $x$ before it reaches the block $x+1$, if the block $x$ is in position $i$ and the block $x+1$ is in position $j$. The base cases are $dp_{i,m+1} = (m+1)-i$ (because only the block $x$ can move) and $dp_{i,i} = 0$ (because block $x$ has already reached block $x+1$). In the other cases, $dp_{i,j} = ((dp_{i+1,j} + 1) + dp_{i,j+1})/2$. By linearity of expectation, the answer is the sum of $dp_{S_i, S_{i+1}}$. Complexity: $O(m^2)$
|
[
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,500
| null |
1854
|
D
|
Michael and Hotel
|
Michael and Brian are stuck in a hotel with $n$ rooms, numbered from $1$ to $n$, and need to find each other. But this hotel's doors are all locked and the only way of getting around is by using the teleporters in each room. Room $i$ has a teleporter that will take you to room $a_i$ (it might be that $a_i = i$). But they don't know the values of $a_1,a_2, \dots, a_n$.
Instead, they can call up the front desk to ask queries. In one query, they give a room $u$, a positive integer $k$, and a set of rooms $S$. The hotel concierge answers whether a person starting in room $u$, and using the teleporters $k$ times, ends up in a room in $S$.
Brian is in room $1$. Michael wants to know the set $A$ of rooms so that if he starts in one of those rooms they can use the teleporters to meet up. He can ask at most $2000$ queries.
The values $a_1, a_2, \dots, a_n$ are fixed before the start of the interaction and do not depend on your queries. In other words, the interactor is not adaptive.
|
You can find any $a_i$ in $9$ queries. Find the nodes in the cycle in the component with node $1$. What happens if you know the whole cycle? Suppose you already know some nodes in the cycle. Can you find other nodes faster? Can you "double" the number of nodes in the cycle? The component with node $1$ contains a cycle. If you know the whole cycle (of length $x$), you can win in $n-x$ queries by asking for each node if it ends up in the cycle after $n$ moves. You can get a node in the cycle in $9$ queries, doing a binary search on the $n$-th successor of node $1$. How to find the rest of the cycle? First, find $k$ nodes in the cycle, doing a binary search on the successor of the last node found. These nodes make a set $C$. Then, check for each node if it's "sufficiently close" to $C$, by asking $(i, k, C)$. Now, you know either $2k$ nodes in the cycle, or the whole cycle. Repeat until you get the whole cycle. If you choose $k = 63$, you spend at most $9 \cdot 63 + (500 - 63) + (500 - 126) + (500 - 252) + (500 - 252) = 1874$ queries.
|
[
"binary search",
"interactive",
"trees"
] | 3,000
| null |
1854
|
E
|
Game Bundles
|
Rishi is developing games in the 2D metaverse and wants to offer game bundles to his customers. Each game has an associated enjoyment value. A game bundle consists of a subset of games whose total enjoyment value adds up to $60$.
Your task is to choose $k$ games, where $1 \leq k \leq 60$, along with their respective enjoyment values $a_1, a_2, \dots, a_k$, in such a way that exactly $m$ distinct game bundles can be formed.
|
Go for a randomized approach. Many ones are useful. Either you go for a greedy or for a backpack. We describe a randomized solution that solves the problem for $m$ up to $10^{11}$ (and, with some additional care, may be able to solve also $m$ up to $10^{12}$). We decided to give the problem with the smaller constraint $m\le 10^{10}$ to make the problem more accessible and because there may be some rare cases below $10^{11}$ for which our solution is too slow (even though we could not find any). We don't know any provably correct solution, if you have one we would be curious to see it. We expect to see many different solutions for this problem. Main idea: Choose suitably the values $a_1, a_2, \dots, a_h$ that belong to $[1,29]$ and then find $a_{h+1}, a_{h+2},\dots,a_k$ in $[31,60]$ by solving a backpack-like problem. Let us describe more precisely the main idea. Assume that $a_1, a_2, \dots, a_h\le 30$ are fixed and they satisfy $a_1+a_2+\cdots+a_h<60$. For any $s=0,1,2,\dots,29$, let $f(s)$ be the number of subsets $I\subseteq{1,2,\dots,h}$ so that $\sum_{i\in I}a_i=s$. If we can find some values $0\le s_1,s_2,\dots,s_{k-h}\le 29$ so that $f(s_1)+f(s_2)+\cdots+f(s_{k-h})=s$, then by setting $a_{h+i} = 60-s_i$ for $i=1,2,\dots, k-h$ we have found a valid solution to the problem. There are two main difficulties: How can we find $s_1, s_2,\dots, s_{k-h}$? How should we choose $a_1, a_2,\dots, a_h$? Since it is important to get a good intuitive understanding of the computational complexity of the algorithm, let us say now that we will choose $h\le 44$ and (accordingly) $k-h=16$. These values are flexible (the solution would still work with $h\le 45$ and $k-h=45$ for example). We will say something more about the choice of these values when we will describe how $a_1,a_2,\dots, a_h$ shall be chosen. The backpack problem to find $s_1, s_2,\dots, s_{k-h}$. The naive way to find $s_1,\dots, s_{k-h}$ would be to try all of them. There are $\binom{k-h + 29}{29}$ possible ways (up to order, which does not matter). Since $k-h=16$ this number is $\approx 2\cdot 10^{11}$ which is too much to fit in the time limit. To speed up the process, we will do as follows. Partition randomly $A\cup B={0,1,\dots, 29}$ into two sets of size $15$. We iterate over all possible $s_1, s_2, \dots, s_{(k-h)/2}\in A$ and over all possible $s_{(k-h)/2+1},\dots, s_{k-h}\in B$ and check whether the sum of one choice from the first group and one choice from the second group yields the result. This is a standard optimization for the subset sum problem. What is its complexity? It can be implemented in linear time in the size of the two groups we have to iterate over, which have size $\binom{(k-h)/2+15}{15}\approx 5\cdot 10^5$. Notice that in this faster way we will not visit all the $\binom{k-h+29}{29}$ possible choices $s_1,s_2,\dots, s_{k-h}$ because we are assuming that exactly half of them belong to $A$ and exactly half of them belong to $B$. This is not a big deal because with sufficiently high probability we will find a solution in any case. The choice of $a_1, a_2,\dots, a_{h}$. It remains to decide how we should select $a_1, a_2, \dots, a_{h}$. The following choice works: Approximately the first $\log_2(m)$ values are set equal to $1$. Five additional values are chosen randomly from $[1, 6]$ so that the total sum stays below $60$. One should repeat the whole process until a solution is found. Some intuition on the construction. The choice of $a_1, \dots, a_{h}$ may seem arbitrary; let us try to justify it. The goal is to generate a set of values $f(0), f(1),\dots, f(29)$ that are simultaneously ``random enough'' and with size smaller but comparable to $m$. These two conditions are necessary to expect that the backpacking problem finds a solution with high enough probability. If $a_1=a_2=\cdots=a_{h}=1$, then $f(s) = \binom{k-h}{s}$ and these numbers have size comparable to $m$ if $2^{h}$ is comparable to $m$. This observation explains why we start with approximately $\log_2(m)$ ones. The issue is that we need some flexibility in the process as we may need to repeat it many times, this flexibility is provided by the addition of some additional random elements which don't change the magnitude of the values $f(0), f(1), \dots, f(29)$ but that modify them as much as possible (if we added a large number it would not affect many $f(s)$ and thus it would not be very useful).
|
[
"brute force",
"constructive algorithms",
"dp",
"greedy",
"math"
] | 3,000
| null |
1854
|
F
|
Mark and Spaceship
|
Mark loves to move fast. So he made a spaceship that works in $4$-dimensional space.
He wants to use the spaceship to complete missions as fast as possible. In each mission, the spaceship starts at $(0, 0, 0, 0)$ and needs to end up at $(a, b, c, d)$. To do this, he instructs the spaceship's computer to execute a series of moves, where each move is a unit step in one of the eight cardinal directions: $(\pm 1, 0, 0, 0)$, $(0, \pm 1, 0, 0)$, $(0, 0, \pm 1, 0)$, $(0, 0, 0, \pm 1)$.
Unfortunately, he also moved fast when building the spaceship, so there is a bug in the spaceship's code. The first move will be executed once, the second move will be executed twice, the third move will be executed thrice, and so on. In general, the $i$-th move will be executed $i$ times.
For any four integers $a, b, c, d$, let $f(a, b, c, d)$ be the minimum number of moves of a mission that ends up at $(a, b, c, d)$. Compute the sum of $f(a, b, c, d)$ over all points (with integer coordinates) such that $-A\le a\le A$, $-B\le b\le B$, $-C\le c\le C$, $-D\le d\le D$.
|
Solve the 2d version first. The 4d version is not too different from the 2d one. Find all the points such that the expected number of necessary moves is wrong. Let us begin by cpnsidering the $2$-dimensional version of the problem. The solution to this simpler version provides the idea of the approach for the $4$-dimensional version. We want to reach $(a, b)$. Can we do it with exactly $k$ moves? Two simple necessary conditions are: $|a|+|b|\le 1 + 2 + \cdots + k$, $a+b$ and $1 + 2 + \cdots + k$ shall have the same parity. It turns out that this two conditions are also sufficient! One can prove it by induction on $k$ as follows. If $k=0$ or $k=1$ or $k=2$ the statement is simple, thus we may assume $k\ge 3$. Without loss of generality we may assume $0\le a\le b$. If $|a|+|b-k| \le 1 + 2 + \cdots + k-1$, then the statement follows by inductive hypothesis. Assume by contradiction that such inequality is false. If $b\ge k$ then we have a contradiction because $|a|+|b-k| = |a|+|b|-k \le (1 + 2 + \cdots + k) - k$. Otherwise $b < k$ and the contradiction is $|a|+|b-k| = a + k-b \le k \le 1 + 2 + \cdots + k-1$. Hence, we have shown: Lemma 1: The point $(a, b)$ is reachable with exactly $k$ moves if and only if $|a|+|b| \le 1 + 2 + \cdots + k$ and $a+b$ has the same parity of $1+2+\cdots + k$. One may expect statement analogous to the one of Lemma 1 to hold also when there are $4$ coordinates. It does not, but it almost does and this is the crucial idea of the solution. More precisely, the number of counter examples to such statement is rather small and we can find all of them. This is the intuition behind the following definition. Definition: For $k\ge 0$, let $A_k$ be the set of points $(a, b, c, d)$ such that $|a|+|b|+|c|+|d|\le 1 + 2 + \cdots + k$ and $a+b+c+d$ has the same parity of $1 + 2 + \cdots + k$ but $(a, b, c, d)$ is not reachable with exactly $k$ moves. As an immediate consequence of the definition, we have Observation: The point $(a, b, c, d)$ is reachable with exactly $k$ moves if and only if $|a|+|b|+|c|+|d| \le 1 + 2 + \dots + k$ and $a+b+c+d$ has the same parity of $1+2+\cdots + k$ and $(a, b, c, d)\not\in A_k$. Thanks to this observation, if one is able to efficiently find $A_k$ for all interesting values of $k$, then solving the problem is (comparatively) easy. The following lemma is our main tool for this purpose. Lemma 2: Assume that $(a, b, c, d) \in A_k$ with $0\le a\le b\le c\le d$. Then, either $k\le 6$ or $(a, b, c, d - k) \in A_{k-1}$. Proof: The strategy is the same adopted to show Lemma 1. In some sense, we are saying that the inductive step works also in dimension $4$, but the base cases don't. If $|a|+|b|+|c|+|d-k|\le 1 + 2 + \cdots + k-1$, then it must be $(a, b, c, d-k)\in A_{k-1}$ because if $(a, b, c, d-k$ were reachable with $k-1$ moves then $(a, b, c, d)$ were reachable with $k$ and we know that this is not true. Assume by contradiction that $|a|+|b|+|c|+|d-k|> 1 + 2 + \cdots + k-1$. If $d\ge k$ then we reach the contradiction $|a|+|b|+|c|+|d-k| = a+b+c+d-k \le (1 + 2 + \dots + k) - k$. Otherwise, $d < k$ and thus we reach the contradiction $|a|+|b|+|c|+|d-k| = a+b+c+k-d\le a+b+k\le 3k-2\le 1 + 2 + \dots + k-1$ (for $k\ge 7$). We can now describe the solution. Assume that we know $A_{k-1}$. First of all, notice that it is then possible to determine in $O(1)$ whether a point belongs to $A_k$ or not. To generate a list of candidate elements for $A_k$ we proceed as follows: If $k\le 6$, we simply iterate over all points with $|a|+|b|+|c|+|d|\le 1 + 2 + \cdots + k$. Otherwise, we iterate over the points in $A_{k-1}$ and we consider as candidate elements for $A_k$ the points that can be obtained by changing the value of one coordinate by $k$. Thanks to Lemma 2, we know that this process finds all the elements in $A_k$. Once $A_0, A_1, A_2, A_3,\dots$ are known, the problem boils down to a (relatively) simple counting argument that we skip. One can verify that to handle correctly all points with coordinates up to $1000$ it is necessary to compute $A_k$ for $0\le k \le 62$. One additional cheap trick is required to make $A_k$ sufficiently small and get a sufficiently fast solution. Given $(a, b, c, d)$, the instance of the problem is equivalent if we change the signs of the coordinates or we change the order of the coordinates. Hence we shall always ``normalize'' the point so that $0\le a \le b\le c\le d$. If we do this consistently everywhere in the process, the solution becomes an order of magnitude faster. In particular, this trick guarantees $|A_k|\le 5000$ for all $0\le k\le 62$. Bonus question: Find an explicit closed form for the elements in $A_k$ for any $k$. (in this way one can solve the problem also with larger constraints on $A, B, C, D$; but it is tedious)
|
[
"brute force",
"dp"
] | 3,500
| null |
1855
|
A
|
Dalton the Teacher
|
Dalton is the teacher of a class with $n$ students, numbered from $1$ to $n$. The classroom contains $n$ chairs, also numbered from $1$ to $n$. Initially student $i$ is seated on chair $p_i$. It is guaranteed that $p_1,p_2,\dots, p_n$ is a permutation of length $n$.
A student is happy if his/her number is different from the number of his/her chair. In order to make all of his students happy, Dalton can repeatedly perform the following operation: choose two distinct students and swap their chairs. What is the minimum number of moves required to make all the students happy? One can show that, under the constraints of this problem, it is possible to make all the students happy with a finite number of moves.
A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
|
What's the most efficient way to make the sad students happy? In most cases, you can make $2$ sad students happy in $1$ move. Let $s$ be the number of sad students at the beginning. The answer is $\lceil \frac{s}{2} \rceil$. In one move, you can make at most $2$ sad students happy (because you can change the position of at most two students), so you need at least $\lceil \frac{s}{2} \rceil$ moves. In fact, you can make everyone happy in exactly $\lceil \frac{s}{2} \rceil$ moves: while there are at least $2$ sad students, you can swap them and both of them will be happy; if there is exactly $1$ sad student left, you can swap it with any other student. Complexity: $O(n)$
|
[
"greedy",
"math"
] | 800
| null |
1855
|
B
|
Longest Divisors Interval
|
Given a positive integer $n$, find the maximum size of an interval $[l, r]$ of positive integers such that, for every $i$ in the interval (i.e., $l \leq i \leq r$), $n$ is a multiple of $i$.
Given two integers $l\le r$, the size of the interval $[l, r]$ is $r-l+1$ (i.e., it coincides with the number of integers belonging to the interval).
|
What's the answer if $n$ is odd? Try to generalize Hint 1. What's the answer if $n$ is not a multiple of $3$? If the answer is not a multiple of $x$, the answer is $< x$. If the answer is a multiple of $1, \dots, x$, the answer is $\geq x$. Suppose you find a valid interval $[l, r]$. Note that the interval $[l, r]$ contains at least one multiple of $x$ for each $1 \leq x \leq r-l+1$ (you can find it out by looking at the values in $[l, r]$ modulo $x$). Then, the interval $[1, r-l+1]$ is also valid and has the same length. So, it's enough to check intervals with $l = 1$, i.e., find the smallest $x$ that does not divide $n$. The answer is $x-1$. Complexity: $O(\log(\max n))$
|
[
"brute force",
"combinatorics",
"greedy",
"math",
"number theory"
] | 900
| null |
1856
|
A
|
Tales of a Sort
|
Alphen has an array of positive integers $a$ of length $n$.
Alphen can perform the following operation:
- For \textbf{all} $i$ from $1$ to $n$, replace $a_i$ with $\max(0, a_i - 1)$.
Alphen will perform the above operation until $a$ is sorted, that is $a$ satisfies $a_1 \leq a_2 \leq \ldots \leq a_n$. How many operations will Alphen perform? Under the constraints of the problem, it can be proven that Alphen will perform a finite number of operations.
|
Suppose we have performed $k$ operations and have gotten the array $b$. Then $b_i := \max(0, a_i - k)$ for all $i$ from $1$ to $n$. If $b$ is sorted, then $b_i \le b_{i + 1}$ for all $i$ from $1$ to $n - 1$. In other words, $\max(0, a_i - k) \le \max(0, a_{i + 1} - k)$. Let's find for which $k$ this inequality holds. Suppose $a_i \le a_{i + 1}$. Then $\max(0, a_i - k) \le \max(0, a_{i + 1} - k)$ is true for any $k \ge 0$. Now suppose $a_i > a_{i + 1}$. Then $\max(0, a_i - k) \le \max(0, a_{i + 1} - k)$ is true only if $k \ge a_i$. For the array to be sorted after $k$ operations, $\max(0, a_i - k) \le \max(0, a_{i + 1} - k)$ must hold for all $1 \le i < n$. From the statements above, we can see that the smallest $k$ for which this is true is equal to the maximum value of $a_{i}$ over all $1 \le i < n$ such that $a_{i} > a_{i + 1}$. If no such $i$ exists, the answer is $0$, since the array is already sorted. Complexity: $\mathcal{O}(n)$ Note: there are at least two other solutions: The solution above is also equivalent to finding the maximum value of $a_{i}$ over all $1 \le i < j \le n$ such that $a_i > a_j$, which leads to a $\mathcal{O}(n^2)$ solution. Alternatively, you can do binary search on the answer to get a $\mathcal{O}(n \log A)$ solution, where $A$ is the maximum possible value of $a_i$.
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int ans = 0;
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
ans = max(ans, a[i]);
}
}
cout << ans << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
solve();
}
}
|
1856
|
B
|
Good Arrays
|
You are given an array of \textbf{positive} integers $a$ of length $n$.
Let's call an array of \textbf{positive} integers $b$ of length $n$ good if:
- $a_i \neq b_i$ for \textbf{all} $i$ from $1$ to $n$,
- $a_1 + a_2 +\ldots + a_n = b_1 + b_2 + \ldots + b_n$.
Does a good array exist?
|
Suppose $b$ didn't have to consist of only positive integers. Then, one simple strategy would be to to decrease each of $a_2, a_3, \ldots a_n$ by $1$ and increase $a_1$ by $n - 1$. Except for $n = 1$, when it is impossible to get a good array. When $b$ has to consist of only positive integers, we can't decrease elements that are equal to $1$. But to make $b_i \neq a_i$, we also have to increase them by at least $1$. Let $cnt_1$ be the number of elements in $a$ that are equal to $1$. To not change the sum of the array, we have to decrease the other $n - cnt_1$ elements by at least $cnt_1$. For this to be possible, their sum must be equal to at least $(n - cnt_1) + cnt_1 = n$, since each of the $n - cnt_1$ elements must remain positive. So, $a_1 + a_2 + \ldots + a_n$ has to be equal to at least $cnt_1 + (n - cnt_1) + cnt_1 = cnt_1 + n$. So, if $a_1 + \ldots + a_n < cnt_1 + n$, a good array doesn't exist. If $n = 1$, a good array also doesn't exist. Now suppose $a_1 + \ldots + a_n \ge cnt_1 + n$ and $n \neq 1$. We will prove that if this is the case, a good array must exist. If $cnt_1 \le \frac{n}{2}$, we increase all $a_i = 1$ by $1$ and decrease $cnt_1$ elements that are $\ge 2$ by $1$ and apply the simple strategy described above for the other $n - 2 \cdot cnt_1$ elements $\ge 2$, so in this case, a good array exists. If $cnt_1 > \frac{n}{2}$, we increase all $a_i = 1$ by $1$ and decrease each element $\ge 2$ by at least $1$, so $b_i \neq a_i$ holds for all $1 \le i \le n$, so in this case, a good array also exists. Complexity: $\mathcal{O}(n)$
|
[
"implementation",
"math"
] | 900
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
ll sum_a = 0, cnt_1 = 0;
for (int x: a) {
sum_a += x;
if (x == 1) cnt_1++;
}
if (sum_a >= cnt_1 + n && n > 1) {
cout << "YES" << nl;
} else {
cout << "NO" << nl;
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
solve();
}
}
|
1856
|
C
|
To Become Max
|
You are given an array of integers $a$ of length $n$.
In one operation you:
- Choose an index $i$ such that $1 \le i \le n - 1$ and $a_i \le a_{i + 1}$.
- Increase $a_i$ by $1$.
Find the maximum possible value of $\max(a_1, a_2, \ldots a_n)$ that you can get after performing this operation at most $k$ times.
|
We will do binary search on the answer. The lower bound can be set to $0$, while $\max(a_1, \ldots a_n) + k$ is clearly enough for the upper bound. Let $b$ be some resulting array after performing at most $k$ operations. Suppose for some $x$ we want to check if we can get $\max(b_1, \ldots b_n) \ge x$ in at most $k$ operations. That is, there must exist some index $i$ such that $b_i \ge x$. So, let's iterate $i$ from $1$ to $n$ and check if it possible to have $b_i \ge x$ in at most $k$ operations. Let $f(i, y)$ be the minimum number of operations needed to make $b_i \ge y$. Then: $f(i, y) = 0$ for all $y \le a_i$, $f(i, y) = y - a_i + f(i + 1, y - 1)$ for all $1 \le i < n$ and $y > a_i$, $f(i, y) = +\infty$ for $i = n$ and all $y > a_i$. It is easy to see that calculating $f(i, x)$ takes $\mathcal{O}(n)$ time for one call in the worst case. Thus, our check consists of comparing $f(i, x)$ and $k$ for all $i$ from $1$ to $n$. If at least one of the values is $\le k$, it is possible to have some $b_i \ge x$ in at most $k$ operations and we increase the lower bound in the binary search after updating the current answer. Otherwise, it is impossible and we decrease the upper bound. Complexity: $\mathcal{O}(n^2 \cdot \log A)$, where A is the maximum possible value of $a_i$ and $k$. Notes: You can get a $\mathcal{O}(n^2 \cdot \log n)$ solution by setting the lower bound in the binary search to $\max(a_1, \ldots, a_n)$ and the upper bound to $\max(a_1, \ldots, a_n) + n$. There exists a $\mathcal{O}(n^2)$ dp solution that relies on the fact that the answer lies in the range $[ \max(a_1, \ldots, a_n); \max(a_1, \ldots, a_n) + n ]$
|
[
"binary search",
"brute force",
"data structures",
"dp"
] | 1,600
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
void solve() {
ll n, k;
cin >> n >> k;
vector<ll> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
ll lb = 0, ub = *max_element(all(a)) + k, ans = 0;
while (lb <= ub) {
ll tm = (lb + ub) / 2;
bool good = false;
for (int i = 0; i < n; i++) {
vector<ll> min_needed(n);
min_needed[i] = tm;
ll c_used = 0;
for (int j = i; j < n; j++) {
if (min_needed[j] <= a[j]) break;
if (j + 1 >= n) {
c_used = k + 1;
break;
}
c_used += min_needed[j] - a[j];
min_needed[j + 1] = max(0LL, min_needed[j] - 1);
}
if (c_used <= k) good = true;
}
if (good) {
ans = tm;
lb = tm + 1;
} else {
ub = tm - 1;
}
}
cout << ans << nl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) solve();
}
|
1856
|
D
|
More Wrong
|
\textbf{This is an interactive problem.}
The jury has hidden a permutation$^\dagger$ $p$ of length $n$.
In one query, you can pick two integers $l$ and $r$ ($1 \le l < r \le n$) by paying $(r - l)^2$ coins. In return, you will be given the number of inversions$^\ddagger$ in the subarray $[p_l, p_{l + 1}, \ldots p_r]$.
Find the index of the maximum element in $p$ by spending at most $5 \cdot n^2$ coins.
\textbf{Note: the grader is not adaptive}: the permutation is fixed before any queries are made.
$^\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
$^\ddagger$ The number of inversions in an array is the number of pairs of indices $(i,j)$ such that $i < j$ and $a_i > a_j$. For example, the array $[10,2,6,3]$ contains $4$ inversions. The inversions are $(1,2),(1,3),(1,4)$, and $(3,4)$.
|
Let $q(l, r)$ be be the number of inversions in the subarray $[p_l, p_{l + 1}, \ldots p_r]$. If $l = r$, we have $q(l, r) = 0$, otherwise, $q(l, r) =$ is equal to the result of the query "? l r". Let $f(l, r)$ calculate the index of the maximum value in $p_l, p_{l+1}, \ldots, p_r$. If $l = r$, we have $f(l, r) = l$. Suppose $l < r$. Let $i := f(l, m)$ and $j := f(m + 1, r)$, where $m := \lfloor \frac{l + r}{2} \rfloor$. Let's compare $q(l, j - 1)$ and $q(l, j)$. If they are equal, $p_j$ is greater than all the elements in the subarray $[p_l, p_{l + 1}, \ldots, p_m]$, so $f(l, r) = j$. If $q(l, j - 1) < q(l, j)$, $p_j$ is not greater that all the elements in the subarray $[p_l, p_{l + 1}, \ldots, p_m]$, and thus, the maximum on the whole subarray is $p_i$, so $f(l, r) = i$. Note that the case $q(l, j - 1) > q(l, j)$ is impossible, since all inversions in the subarray $[p_l, p_{l + 1}, \ldots, p_{j - 1}]$ remain as inversions for the subarray $[p_l, p_{l + 1}, \ldots, p_j]$. To find the values of $q(l, j - 1)$ and $q(l, j)$, we will use $(j - 1 - l)^2 + (j - l)^2 \le (r - l)^2 + (r - l)^2 = 2 \cdot (r - l)^2$ coins. Let $g_n$ be the number of coins needed to find the maximum on a subarray of length $n$. We will prove by induction that $g_n \le 4 \cdot n^2$ for all natural $n$. Base case: $n = 1$, $g_1 := 0 \le 4 \cdot n^2 = 4$. Induction step: let $m := \lceil \frac{n}{2} \rceil$. From the statements above, we have: $g_n \le 2 \cdot (n - 1)^2 + g_{m} + g_{n - m} \le$ $2 \cdot (n - 1)^2 + 4 \cdot (m^2 + (n - m)^2) =$ $6n^2 + 8m^2 + 2 - 8nm - 4n =$ $4n^2 + 2 \cdot (n^2 - 4nm + 4m^2) + 2 - 4n =$ $4n^2 + 2 \cdot (n - 2m)^2 + 2 - 4n \le$ $4n^2 + 2 \cdot 1 + 2 - 4n =$ $4n^2 + 4 - 4n \le 4n^2$ Thus, to calculate $f(1, n)$, the answer to our problem, we will use $g_n \le 4 \cdot n^2$ coins, which comfortably fits into the problem's $5 \cdot n^2$ coin limit. Complexity: $\mathcal{O}(n)$
|
[
"divide and conquer",
"interactive"
] | 2,100
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
int query(int l, int r) {
if (l == r) return 0;
cout << "? " << l << ' ' << r << endl;
int res;
cin >> res;
return res;
}
// Finds max on p[l; r]
int solve(int l, int r) {
if (l == r) return l;
int m = (l + r) / 2;
int a = solve(l, m);
int b = solve(m + 1, r);
int r1, r2;
r1 = query(a, b - 1);
r2 = query(a, b);
if (r1 == r2) {
return b;
} else {
return a;
}
}
void solve() {
int n;
cin >> n;
int ans = solve(1, n);
cout << "! " << ans << endl;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int T;
cin >> T;
while (T--) {
solve();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.