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
1469
D
Ceil Divisions
You have an array $a_1, a_2, \dots, a_n$ where $a_i = i$. In one step, you can choose two indices $x$ and $y$ ($x \neq y$) and set $a_x = \left\lceil \frac{a_x}{a_y} \right\rceil$ (ceiling function). Your goal is to make array $a$ consist of $n - 1$ ones and $1$ two in no more than $n + 5$ steps. Note that you don't have to minimize the number of steps.
There are many different approaches. We will describe a pretty optimal one. Let's solve the problem recursively. Let's say we need to process segment $[1, x]$. If $x = 2$, we don't need to do anything. Otherwise, $x > 2$. Let's find the minimum $y$ such that $y \ge \left\lceil \frac{x}{y} \right\rceil$. The chosen $y$ is convenient because it allows making $x$ equal to $1$ in two divisions (and it's the minimum number of divisions to get rid of $x$). Now we can, firstly, make all $z \in [y + 1, x)$ equal to $1$ in one step (by division on $x$) and then make $x$ equal to $1$ with two divisions on $y$. As a result, we've spent $x - y + 1$ operations and can solve our task recursively for $[1, y]$. In total, we will spend $n - 2 + \mathit{\text{number_of_segments}}$ and since the segments are like $(\sqrt{x}, x]$, $(\sqrt{\sqrt{x}}, \sqrt{x}]$,... There will be at most $\log{(\log{n})}$ segments and $n + 3$ operations are enough for $n \le 2^{32}$.
[ "brute force", "constructive algorithms", "math", "number theory" ]
1,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; int n; inline bool read() { if(!(cin >> n)) return false; return true; } void calc(int n, vector<pt> &ans) { if (n == 2) return; int y = max(1, (int)sqrt(n) - 1); while (y < (n + y - 1) / y) y++; fore (pos, y + 1, n) ans.emplace_back(pos, n); ans.emplace_back(n, y); ans.emplace_back(n, y); calc(y, ans); } inline void solve() { vector<pt> ans; calc(n, ans); cout << sz(ans) << endl; for(auto p : ans) cout << p.first << " " << p.second << '\n'; } 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 tc; cin >> tc; while(tc--) { read(); solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1469
E
A Bit Similar
Let's call two strings $a$ and $b$ (both of length $k$) a bit similar if they have the same character in some position, i. e. there exists at least one $i \in [1, k]$ such that $a_i = b_i$. You are given a binary string $s$ of length $n$ (a string of $n$ characters 0 and/or 1) and an integer $k$. Let's denote the string $s[i..j]$ as the substring of $s$ starting from the $i$-th character and ending with the $j$-th character (that is, $s[i..j] = s_i s_{i + 1} s_{i + 2} \dots s_{j - 1} s_j$). Let's call a binary string $t$ of length $k$ beautiful if it is a bit similar to all substrings of $s$ having length exactly $k$; that is, it is a bit similar to $s[1..k], s[2..k+1], \dots, s[n-k+1..n]$. Your goal is to find the \textbf{lexicographically} smallest string $t$ that is beautiful, or report that no such string exists. String $x$ is lexicographically less than string $y$ if either $x$ is a prefix of $y$ (and $x \ne y$), or there exists such $i$ ($1 \le i \le \min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$.
Let's denote $z$ as the number of substrings of $s$ having length exactly $k$ (so, $z = n - k + 1$). The first and crucial observation is that if $2^k > z$, then the answer always exists. Each of $z$ substrings forbids one of the strings from being the answer (a string is forbidden if every each character differs from the corresponding character in one of the substrings); we can forbid at most $z$ strings from being the answer, and the number of possible candidates for the answer is $2^k$. This observation leads us to a more strong fact that actually allows us to find a solution: we can set the first $k - \lceil \log_2 (z+1) \rceil$ characters in the answer to 0; all the remaining characters are enough to find the answer. There are at most $2^{\lceil\log_2(z+1)\rceil}$ possible combinations of the last characters, and this number is not greater than $2n$. Let's iterate on each substring of $s$ of length $k$ and check which combination it forbids by inverting the last $\lceil \log_2 (z+1) \rceil$ characters of the substring. After that, find the minimum unforbidden combination. Note that there may be a case when a substring doesn't actually forbid any combination - if there are zeroes in the first $k - \lceil \log_2 (z+1) \rceil$ characters of the substring, it is a bit similar to the answer no matter which combination we choose. This can be checked by precalculating the closest position of zero to the left/right of each index. The whole solution works in $O(n \log n)$ per test case - the hardest part is inverting the suffix of each substring we are interested in.
[ "bitmasks", "brute force", "hashing", "string suffix structures", "strings", "two pointers" ]
2,400
#include<bits/stdc++.h> using namespace std; const int N = 1000043; int q; char buf[N]; int n, k; int ceilLog(int x) { int y = 0; while((1 << y) < x) y++; return y; } int main() { scanf("%d", &q); for(int i = 0; i < q; i++) { scanf("%d %d", &n, &k); scanf("%s", buf); string s = buf; int m = min(k, ceilLog(n - k + 2)); vector<int> used(1 << m, 0); vector<int> next0(n, int(1e9)); if(s[n - 1] == '0') next0[n - 1] = n - 1; for(int j = n - 2; j >= 0; j--) if(s[j] == '0') next0[j] = j; else next0[j] = next0[j + 1]; int d = k - m; for(int j = 0; j < n - k + 1; j++) { if(next0[j] - j < d) continue; int cur = 0; for(int x = j + d; x < j + k; x++) cur = cur * 2 + (s[x] - '0'); used[((1 << m) - 1) ^ cur] = 1; } int ans = -1; for(int j = 0; j < (1 << m); j++) if(used[j] == 0) { ans = j; break; } if(ans == -1) puts("NO"); else { puts("YES"); string res(d, '0'); string res2; for(int j = 0; j < m; j++) { res2.push_back('0' + (ans % 2)); ans /= 2; } reverse(res2.begin(), res2.end()); res += res2; puts(res.c_str()); } } }
1469
F
Power Sockets
// We decided to drop the legend about the power sockets but feel free to come up with your own :^) Define a chain: - a chain of length $1$ is a single vertex; - a chain of length $x$ is a chain of length $x-1$ with a new vertex connected to the end of it with a single edge. You are given $n$ chains of lengths $l_1, l_2, \dots, l_n$. You plan to build a tree using some of them. - Each vertex of the tree is either white or black. - The tree initially only has a white root vertex. - All chains initially consist only of white vertices. - You can take one of the chains and connect any of its vertices to any white vertex of the tree with an edge. The chain becomes part of the tree. Both endpoints of this edge become black. - Each chain can be used no more than once. - Some chains can be left unused. The distance between two vertices of the tree is the number of edges on the shortest path between them. If there is at least $k$ white vertices in the resulting tree, then the value of the tree is the distance between the root and the $k$-th closest white vertex. What's the minimum value of the tree you can obtain? If there is no way to build a tree with at least $k$ white vertices, then print -1.
At first, let's realize that the tree structure doesn't matter that much. What we actually need is the array $cnt_i$ such that it stores the number of white vertices on depth $i$. Initially, $cnt_0=1$ and all other are zero. If you take a chain and attach it to some vertex on depth $d$, then the number of vertices on depth $d$ decreases by $1$. Also, the added vertices update some other counts. So far, it's extremely unclear what to begin with. Let's start by introducing some greedy ideas. For each $t$ let's find the most optimal tree using exactly $t$ chains and update the answer with each of them. First, it's always optimal to attach a chain with its middle vertex. Just consider the changes in the white vertices counts. Second, for each $t$ it's always optimal to take the longest $t$ chains to use. If not the longest $t$ are used, then you can replace any of them and there will be more white vertices. It would be nice if we were able to just add another chain to the tree for $t-1$ to get the tree for $t$. However, that's not always the case. But we can still attempt it and show that the optimal answer was achieved somewhere in the process. Let's show that it's always optimal to attach a new chain to the closest white vertex. So there are basically two cases: there is not enough white vertices yet and there is enough. What happens if there is not enough vertices, and we pick the closest one to attach a chain to? If there are still not enough vertices, then we'll just continue. Otherwise, we'll have to show that the answer can't get any smaller by rearranging something. Consider what the answer actually is. Build a prefix sum array over $cnt$, then the answer is the shortest prefix such that its prefix sum is greater or equal to $k$. So we put the $t$-th chain to the closest white vertex at depth $d$. It decreases $cnt_d$ by $1$ and increases $cnt_{d+2}$ and further by $1$ or $2$. Every chain we have put to this point was attached to a vertex at depth less or equal to the answer (otherwise, we could've rearranged it and obtain the answer before). The optimal answer can be neither $d$, nor $d+1$ (also because we could've rearranged). Thus, the answer is at least $d+2$ and every single chain we have put was packed as tightly as possible below that depth. The second case works similarly. We could've obtained the optimal answer before $t$. So the answer is below $d+2$ and we can do nothing about that. Or the optimal answer is ahead of us, so putting the chain at $d$ can decrease it as much or stronger as any other choice. Thus, updating the answer on every iteration will give us the optimal result. Now we are done with the greedy, time to implement it. I chose the most straightforward way. We basically have to maintain a data structure that can add on range, get the value of a cell and find the shortest prefix with sum at least $k$. That can be easily done with segtree. Overall complexity: $O(n \log n)$.
[ "binary search", "data structures", "greedy" ]
2,600
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; int n, k, nn; vector<long long> t, ps; void push(int v, int l, int r){ if (l < r - 1){ ps[v * 2] += ps[v]; ps[v * 2 + 1] += ps[v]; } t[v] += ps[v] * (r - l); ps[v] = 0; } void upd(int v, int l, int r, int L, int R, int val){ push(v, l, r); if (L >= R) return; if (l == L && r == R){ ps[v] = val; push(v, l, r); return; } int m = (l + r) / 2; upd(v * 2, l, m, L, min(m, R), val); upd(v * 2 + 1, m, r, max(m, L), R, val); t[v] = t[v * 2] + t[v * 2 + 1]; } long long get(int v, int l, int r, int L, int R){ push(v, l, r); if (L >= R) return 0; if (l == L && r == R) return t[v]; int m = (l + r) / 2; long long res = get(v * 2, l, m, L, min(m, R)) + get(v * 2 + 1, m, r, max(m, L), R); t[v] = t[v * 2] + t[v * 2 + 1]; return res; } int trav(int v, int l, int r, int cnt){ push(v, l, r); if (l == r - 1) return l; int m = (l + r) / 2; push(v * 2, l, m); push(v * 2 + 1, m, r); int res = INF; if (t[v * 2] >= cnt) res = trav(v * 2, l, m, cnt); else if (t[v * 2 + 1] >= cnt - t[v * 2]) res = trav(v * 2 + 1, m, r, cnt - t[v * 2]); t[v] = t[v * 2] + t[v * 2 + 1]; return res; } int main() { scanf("%d%d", &n, &k); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); sort(a.begin(), a.end(), greater<int>()); nn = a[0] + 500; t.resize(4 * nn); ps.resize(4 * nn); upd(1, 0, nn, 0, 1, 1); int fst = 0; int ans = INF; forn(i, n){ while (get(1, 0, nn, 0, fst + 1) == 0) ++fst; upd(1, 0, nn, fst, fst + 1, -1); upd(1, 0, nn, fst + 2, fst + 2 + (a[i] - 1) / 2, 1); upd(1, 0, nn, fst + 2, fst + 2 + a[i] / 2, 1); ans = min(ans, trav(1, 0, nn, k)); } printf("%d\n", ans == INF ? -1 : ans); return 0; }
1470
A
Strange Birthday Party
Petya organized a strange birthday party. He invited $n$ friends and assigned an integer $k_i$ to the $i$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $m$ unique presents available, the $j$-th present costs $c_j$ dollars ($1 \le c_1 \le c_2 \le \ldots \le c_m$). It's \textbf{not} allowed to buy a single present more than once. For the $i$-th friend Petya can either buy them a present $j \le k_i$, which costs $c_j$ dollars, or just give them $c_{k_i}$ dollars directly. Help Petya determine the minimum total cost of hosting his party.
Let's note that it is beneficial to give cheaper gifts to people with a larger $k_i$ value. Suppose that in the optimal answer a pair of people $A$ and $B$, such that $k_A \ge k_B$ get gifts with values $a \ge b$. Then we can give a gift $b$ to a person $A$ and to a person $B$ give a gift $a$ or $min(a, c_{k_B})$ dollars. If $a \le c_{k_B}$, than we spend the same amount of money. Otherwise, it's a better answer. So the problem can be solved using greedy algorithm. Let's sort guest in order of descending value $k_i$. Than give each person a cheapest gift, or $c_{k_i}$ dollars, if it better. To determinate a cheapest gift, let's store the index of the last purchased gift. Thus, the final asymptotics is $O(m \log n)$.
[ "binary search", "dp", "greedy", "sortings", "two pointers" ]
1,300
null
1470
B
Strange Definition
Let us call two integers $x$ and $y$ adjacent if $\frac{lcm(x, y)}{gcd(x, y)}$ is a perfect square. For example, $3$ and $12$ are adjacent, but $6$ and $9$ are not. Here $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$, and $lcm(x, y)$ denotes the least common multiple (LCM) of integers $x$ and $y$. You are given an array $a$ of length $n$. Each second the following happens: each element $a_i$ of the array is \textbf{replaced} by the product of all elements of the array (including itself), that are adjacent to the current value. Let $d_i$ be the number of adjacent elements to $a_i$ (including $a_i$ itself). The beauty of the array is defined as $\max_{1 \le i \le n} d_i$. You are given $q$ queries: each query is described by an integer $w$, and you have to output the beauty of the array after $w$ seconds.
It is well known that $lcm(x, y)=\frac{x \cdot y}{gcd(x, y)}$, and it immediately follows that $\frac{lcm(x, y)}{gcd(x, y)}$ $=$ $\frac{x \cdot y}{gcd(x, y)^2}$, which means that numbers $x$ and $y$ are adjacent if and only if $x \cdot y$ is a perfect square. Let $alpha_x$ be the maximum possible integer such that $p^{alpha_x}$ divides $x$, and $alpha_y$ be the maximum possible integer such that $p^{alpha_y}$ divides $y$. Then $x \cdot y$ is perfect square if and only if $\alpha_x + \alpha_y$ is even, which means $\alpha_x \equiv \alpha_y$ (mod $2$). Let $x =p_1^{\alpha1} \cdot \ldots \cdot p_k^{\alpha_k}$. Let's replace it with $p_1^{\alpha1\bmod2} \cdot \ldots \cdot p_k^{\alpha_k\bmod2}$. After such a replacement two integers are adjacent if and only if they are equal. Let's replace each element of the array and split the numbers into classes of equal numbers. If the number of integers in a single class is even, after a single operation each element from this class will be transformed to $1$, and if the number of integers is odd, the class of the element will remain unchanged. Since the class of integer 1 always remains unchanged, all integers will keep their classes starting from after the first operation. Since $d_i$ denotes the size of the class, the beauty of the array is defined as the size of the maximal class. If $a$ if the size of the maximal class at the beginning of the process, and $b$ - the total number of elements with a class of even size or with the class equal to 1. Then for a query with $w = 0$ the answer is $a$, for a query with $w > 0$ the answer is $max(a, b)$. This solution can easily be implemented with $O(n\log{A})$ complexity, where $A$ denotes the maximum number in the array.
[ "bitmasks", "graphs", "hashing", "math", "number theory" ]
1,900
null
1470
C
Strange Shuffle
This is an interactive problem. $n$ people sitting in a circle are trying to shuffle a deck of cards. The players are numbered from $1$ to $n$, so that players $i$ and $i+1$ are neighbours (as well as players $1$ and $n$). Each of them has exactly $k$ cards, where $k$ is \textbf{even}. The left neighbour of a player $i$ is player $i - 1$, and their right neighbour is player $i + 1$ (except for players $1$ and $n$, who are respective neighbours of each other). Each turn the following happens: if a player has $x$ cards, they give $\lfloor x / 2 \rfloor$ to their neighbour on the left and $\lceil x / 2 \rceil$ cards to their neighbour on the right. This happens for all players simultaneously. However, one player $p$ is the impostor and they just give all their cards to their neighbour on the right. You know the number of players $n$ and the number of cards $k$ each player has initially, but $p$ is unknown to you. Your task is to determine the value of $p$, by asking questions like "how many cards does player $q$ have?" for an index $q$ of your choice. After each question all players will make exactly one move and give their cards to their neighbours. You need to find the impostor by asking no more than $1000$ questions.
Short version: note that, during the first $\frac{n}{2}$ iterations the number of people with more than $k$ cards, increases. Let's find at least one such person. To do this, let's wait for $\sqrt{n}$ iterations. After this there is always a continuous segment of length $\sqrt{n}$ with elements $>k$. To find it, we can split the array into blocks of size $\sqrt{n}$, ask one element from each block, and find the desired integer $>k$. Then we can use binary search to find the position $p$. In total we need $2 \sqrt{n} + \log{n}$ queries. More detailed version: let's use induction to prove that players that are located from the same distance from the player $p$ always have $2k$ cards in total. It is obviously true initially. After one operation, when the array $a$ is transformed to the array $b$, and let's consider a pair of elements located on the same distance from position $p$: $i$ and $j$. Note that, $b_{i} + b_{j} = (\lceil \frac{a_{i - 1}}{2} \rceil + \lfloor \frac{a_{i + 1}}{2} \rfloor) + (\lceil\frac{a_{j - 1}}{2} \rceil + \lfloor \frac{a_{j + 1}}{2} \rfloor) = (\lceil\frac{a_{i - 1}}{2} \rceil + \lfloor \frac{a_{j + 1}}{2} \rfloor) + (\lfloor \frac{a_{i + 1}}{2} \rfloor + \lceil\frac{a_{j - 1}}{2} \rceil) = k + k = 2k$ (excluding the neighbours of $p$). It proves that the player $p$ will always have $k$ cards. Now let's prove that the number of cards that players $p + 1, p + 2, \ldots, n, 1, \ldots p - 1$ have is not increasing. Again, if we consider a single step: $b_{i + 1} = \lceil \frac{a_i}{2} \rceil + \lfloor \frac {a_{i + 2}}{2} \rfloor \ge \lceil \frac{a_{i - 1}}{2} \rceil + \lfloor \frac{a_{i + 1}}{2} \rfloor = b_{i}$. During the first $\frac{n}{2}$ iterations, the number of elements that are greater than $k$, is increasing. Before $i$-th iteration we have $a_{p + i - 1} > k, a_{p + i} = k$. After $i$-th iteration $a_{p + i} = \lceil \frac{a_{p + i - 1}}{2} \rceil + \frac{k}{2} > k$, because $k$ is even. The rest of the solution is described in the <<short>> version of the solution above.
[ "binary search", "brute force", "constructive algorithms", "interactive" ]
2,500
null
1470
D
Strange Housing
Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold: - All passages between two houses will be closed, if there are no teachers in both of them. All other passages will stay open. - It should be possible to travel between any two houses using the underground passages that are \textbf{open}. - Teachers should not live in houses, directly connected by a passage. Please help the organizers to choose the houses where teachers will live to satisfy the safety requirements or determine that it is impossible.
One can prove that the answer always exists if the graph is connected, and the algorithm proves it. Let us paint all vertices with black and white colors. Let us pick any vertex and paint it black, and let us paint all its neighbours with white. Then let's pick any uncoloured vertex that is connected to a white one, paint it black, and paint all its neighbours white. We continue this process until there are no uncoloured vertices left. We claim that the set of black vertices is the answer. We are never painting two adjacent vertices black, since we colour all their neighbours with white. It is also true that the set of already coloured vertices is always connected if we keep only the edges adjacent to black vertices: it is true initially, and whenever we paint a vertex white, it is connected to a black one directly, and when we paint a vertex black, one of its edges goes to a white one coloured on the previous steps (that is how we pick the vertex to paint it white).
[ "constructive algorithms", "dfs and similar", "graph matchings", "graphs", "greedy" ]
2,200
null
1470
E
Strange Permutation
Alice had a permutation $p_1, p_2, \ldots, p_n$. Unfortunately, the permutation looked very boring, so she decided to change it and choose some \textbf{non-overlapping} subranges of this permutation and reverse them. The cost of reversing a single subrange $[l, r]$ (elements from position $l$ to position $r$, inclusive) is equal to $r - l$, and the cost of the operation is the sum of costs of reversing individual subranges. Alice had an integer $c$ in mind, so she only considered operations that cost no more than $c$. Then she got really bored, and decided to write down all the permutations that she could possibly obtain by performing exactly one operation on the initial permutation. Of course, Alice is very smart, so she wrote down each obtainable permutation exactly once (no matter in how many ways it can be obtained), and of course the list was sorted lexicographically. Now Bob would like to ask Alice some questions about her list. Each question is in the following form: what is the $i$-th number in the $j$-th permutation that Alice wrote down? Since Alice is too bored to answer these questions, she asked you to help her out.
Let call the cost of rotation of segment $[L, R]$ value $R - L$ coins. Let's calculate how many ways can we apply to the array of length $len$ with total cost less or equal to $c$. We can fix $len - 1$ bars between neighbouring elements of array. There is a bijection between ways to select $c$ of them and ways to apply some not overlapping rotations with total cost equals $c$. We can see, that the number of ways is equals ${{len-1}\choose{0}} + \dots + {{len-1}\choose{c}} = ways(len, c)$. Now we can check if the answer to the query is $-1$. It is easy to see, that the answer on query depends only on construction of $j$-th permutation from $p$. This construction can be represented as set of rotations of size not larger than $c$. And the number of possible rotations in this set doesn't exceed $m = nc$. If we can answer this query for each suffix of $p$, we can determine $j$-th permutation: $l$ $c$ $k$ What is the leftmost rotation on the suffix of length $len$, if we have $c$ coins and we want to get $k$-th permutation of this suffix. Let's fix any suffix $p_x, p_{x+1}, \dots, p_n$. We can build a long array consisting of the leftmost rotations in construction of each permutation of this suffix using not more than $c$ coins. It is easy to see that each rotation will appear on some segment of this array. We can determine the length of this segment: if it was the rotation $[l, r]$, than the length of this segment is $ways(n - r, c - r + l)$. Exactly once happends that there is no leftmost rotation. For $x-1$ (suffix $p_{x-1}, p_x, \dots, p_n$) relative order of this segments won't change because we will add $p_{x-1}$ to the beginning of each permutation. Only $c$ segments will appear (rotations $[x-1, x], [x-1, x+1], \dots, [x-1, x+c-1]$). We can show that new segment will appear only in the beginning and in the end (because only their first element isn't equal $p_{x-1}$). We can show that query $l$ $c$ $k$ is equivalent to query $n$ $c$ $k'$ because of the structure of this array. In $\mathcal{O}(m)$ we can build this array using deque. We should do this for each $c$. Let's answer the queries offline using the following algorithm: Iterate in order of decreasing $c$ (let's call a level set of queries with the same $c$). Sort queries in order of increasing $k$. Using two pointers approach we can move all queries to another level and change them to type $n$ $c$ $k'$. If we will remove queries from each level after answering them, memory will be reduced from $\mathcal{O}(qc + nc)$ to $\mathcal{O}(q + nc)$. Total work time: $\mathcal{O}(sort(q) \cdot c + nc^2)$. It can be optimized to $\mathcal{O}(sort(q) + q \cdot log{n} \cdot log{c} + nc^2)$ using another sort algorithms. Also there is a solution in $\mathcal{O}(nc^2 + q \cdot c \cdot log(nc))$ and $\mathcal{O}(nc)$ memory with binary search and slower solutions with different data structures.
[ "binary search", "combinatorics", "data structures", "dp", "graphs", "implementation", "two pointers" ]
3,200
null
1470
F
Strange Covering
You are given $n$ points on a plane. Please find the minimum sum of areas of two axis-aligned rectangles, such that each point is contained in at least one of these rectangles. Note that the chosen rectangles can be degenerate. Rectangle contains all the points that lie inside it or on its boundary.
It is clear that there are only 3 structurally different ways to pick two rectangles optimally: Two rectangles do not intersect: In this case one can iterate over all horizontal / vertical lines, separating those rectangles, find the extremal points in both halfplanes, and pick the rectangles with corners in the extremal points. In this case one can iterate over all horizontal / vertical lines, separating those rectangles, find the extremal points in both halfplanes, and pick the rectangles with corners in the extremal points. Rectangles do intersect, forming a <<cross>>: In this case note that for each of the rectangles at least two sides lie on the boundary of the bounding box of all points: To find such rectangles efficiently, one can iterate over the right boundary of the <<vertical>> rectangle. Let $L_d$ - be the lowest $y$ coordinate of a point to the left of left boundary of the <<vertical>> rectangle, $L_u$ - the highest $y$ coordinate of a point to the left of the boundary of the <<vertical>> rectangle, and similarly $R_d$ - the lowest $y$-coordinate of a point to the right of the <<vertical>> rectangle, $R_u$ - the highest $y$-coordinate of a point to the right. We can assume that $R_u \geq L_u$ (this can be guaranteed by picking a prefix in our data structure that we will find later). On such a prefix where $L_d \geq R_d$ we need to choose the rightmost bound. What remains is a subrange where $L_d \leq R_d$ and $L_u \leq R_u$. If we fix two bounds of a rectangle $L$ and $R$, their total area equals $(R_u - L_d) \cdot H + (R-L) \cdot W$, where $W$ is the height of the bounding box, and $H$ - its length. Rewriting $(R_u - L_d) \cdot H + (R-L) \cdot W = (R \cdot W + R_u \cdot H) - (L \cdot W + L_d \cdot H)$ one can see that the optimal $L$ can be chosen with a segment tree. In this case note that for each of the rectangles at least two sides lie on the boundary of the bounding box of all points: To find such rectangles efficiently, one can iterate over the right boundary of the <<vertical>> rectangle. Let $L_d$ - be the lowest $y$ coordinate of a point to the left of left boundary of the <<vertical>> rectangle, $L_u$ - the highest $y$ coordinate of a point to the left of the boundary of the <<vertical>> rectangle, and similarly $R_d$ - the lowest $y$-coordinate of a point to the right of the <<vertical>> rectangle, $R_u$ - the highest $y$-coordinate of a point to the right. We can assume that $R_u \geq L_u$ (this can be guaranteed by picking a prefix in our data structure that we will find later). On such a prefix where $L_d \geq R_d$ we need to choose the rightmost bound. What remains is a subrange where $L_d \leq R_d$ and $L_u \leq R_u$. If we fix two bounds of a rectangle $L$ and $R$, their total area equals $(R_u - L_d) \cdot H + (R-L) \cdot W$, where $W$ is the height of the bounding box, and $H$ - its length. Rewriting $(R_u - L_d) \cdot H + (R-L) \cdot W = (R \cdot W + R_u \cdot H) - (L \cdot W + L_d \cdot H)$ one can see that the optimal $L$ can be chosen with a segment tree. Two rectangles intersect in a such a way so that one of the vertices lies inside or on the boundary of the other one: In this case one of the corners of each rectangle coincides with a corner of the bounding box. Let's call such a corner interesting. If we fix the interesting vertex of one of the rectangles, the remaining rectangle can be uniquely determined. Looking at the formulas, it is clear that once we know the $x$-coordinate of an interesting corner of the rectangles, one can choose the $y$-coordinate of the interesting corner by answering a query in form <<minimize $a \cdot x+b \cdot y$>>, where $(a, b)$ - one of the pairs belonging to a fixed precomputed set, and $(x,y)$ is a query. Dividing the expression by $x$ one can get $a+b \cdot \frac{y}{x}$ - a standard query that can be solved using convex hull trick. The only piece remaining is to guarantee that the chosen rectangles intersect. To achieve this once we fixed $x$ we only need to consider a continuous segment of $y$s, so we need to find the maximal value of a subrange of linear functions, which can be implemented in offline manner in $O(n \log n)$ time with a segment tree of convex stacks The overall complexity of this solution is $O(n \log n)$. In this case one of the corners of each rectangle coincides with a corner of the bounding box. Let's call such a corner interesting. If we fix the interesting vertex of one of the rectangles, the remaining rectangle can be uniquely determined. Looking at the formulas, it is clear that once we know the $x$-coordinate of an interesting corner of the rectangles, one can choose the $y$-coordinate of the interesting corner by answering a query in form <<minimize $a \cdot x+b \cdot y$>>, where $(a, b)$ - one of the pairs belonging to a fixed precomputed set, and $(x,y)$ is a query. Dividing the expression by $x$ one can get $a+b \cdot \frac{y}{x}$ - a standard query that can be solved using convex hull trick. The only piece remaining is to guarantee that the chosen rectangles intersect. To achieve this once we fixed $x$ we only need to consider a continuous segment of $y$s, so we need to find the maximal value of a subrange of linear functions, which can be implemented in offline manner in $O(n \log n)$ time with a segment tree of convex stacks The overall complexity of this solution is $O(n \log n)$.
[ "divide and conquer" ]
3,500
null
1471
A
Strange Partition
You are given an array $a$ of length $n$, and an integer $x$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $[3, 6, 9]$, in a single operation one can replace the last two elements by their sum, yielding an array $[3, 15]$, or replace the first two elements to get an array $[9, 9]$. Note that the size of the array decreases after each operation. The beauty of an array $b=[b_1, \ldots, b_k]$ is defined as $\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil$, which means that we divide each element by $x$, round it up to the nearest integer, and sum up the resulting values. For example, if $x = 3$, and the array is $[4, 11, 6]$, the beauty of the array is equal to $\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8$. Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.
Note that, $\left\lceil \frac{a + b}{x} \right\rceil \leq \left\lceil \frac{a}{x} \right\rceil + \left\lceil \frac{b}{x} \right\rceil$. It means that the maximal sum is attained if we do not apply any operations, and the minimal one is attained if we replace all the element with a single one, equal to the sum of all elements.
[ "greedy", "math", "number theory" ]
900
null
1471
B
Strange List
You have given an array $a$ of length $n$ and an integer $x$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $q$. If $q$ is divisible by $x$, the robot adds $x$ copies of the integer $\frac{q}{x}$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $q$ is not divisible by $x$, the robot shuts down. Please determine the sum of all values of the array at the end of the process.
Solution 1. Let's represent each element $a_{i}$ as $x^{b_{i}} \cdot c_{i}$, where $b_{i}$ is the maximal possible. Let's take minimum over all values $b_{i}$, and let's assume it's attained at position $j$. The robot will add each element to the array $b_{j}$ times (element at position $j$ will be the first one, which will stop being divisible by $x$). However, we should not forget about the prefix before position $j$: each of those number is divisible by a higher power of $x$, and this prefix will count towards the total sum. The final answer is $(b_{j} + 1) \cdot \sum_{i=1}^{n}a_{i} + \sum_{i=1}^{j-1}a_{i}$ In this solution we divide each number $a_{i}$ by $x$ to generate the array $b_{1}, b_{2}, \ldots, b_{n}$, and then it takes $O(n)$ to compute both sums. The final complexity of the solution is $O(n \log A)$, where $A$ denotes the maximum possible element of the array. Solution 2. Let's maintain the list of pairs $\{ a_{i}, cnt_{i} \}$ - it indicates a range of $cnt_{i}$ elements equal to $a_{i}$. Then we can easily implement the operation performed by the robot: if we consider pair $\{ a, cnt \}$, we either append the array with a pair $\{ \frac{a}{x}, cnt \cdot x \}$, or terminate the process. The answer to the problem equals to sum of values $a_{i} \cdot cnt_{i}$. Each number $a_{i}$ will be copied to the end of the array at most $O(\log A)$ times, since each time $a_{i}$ is divided by $x$. Since there are $n$ elements in the array initially, the total complexity of this solution is $O(n \log A)$.
[ "brute force", "greedy", "implementation", "math" ]
1,100
null
1472
A
Cards for Friends
For the New Year, Polycarp decided to send postcards to all his $n$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $w \times h$, which can be cut into pieces. Polycarp can cut any sheet of paper $w \times h$ that he has in only two cases: - If $w$ is even, then he can cut the sheet in half and get two sheets of size $\frac{w}{2} \times h$; - If $h$ is even, then he can cut the sheet in half and get two sheets of size $w \times \frac{h}{2}$; If $w$ and $h$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above. After cutting a sheet of paper, the total number of sheets of paper is increased by $1$. Help Polycarp to find out if he can cut his sheet of size $w \times h$ at into $n$ or more pieces, using only the rules described above.
If we cut the sheet in width, we will reduce its width by half, without changing the height. Therefore, the width and height dimensions do not affect each other in any way. Let's calculate the maximum number of sheets that we can get by cutting. Let's say that initially this number is $1$. Let's cut the sheet in width. Then the sheets number will become $2$, but they will be the same. If we can cut the sheet again, it is more profitable to cut all the sheets we have, because this way we will get more new sheets and their size will still be the same. So we can maintain the current number of identical sheets and as long as either the width or height is divided by $2$, divide it, and multiply the number of sheets by two.
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int w, h, n; cin >> w >> h >> n; int res = 1; while (w % 2 == 0) { w /= 2; res *= 2; } while (h % 2 == 0) { h /= 2; res *= 2; } cout << (res >= n ? "YES\n" : "NO\n"); } int main() { int t; cin >> t; while (t--) { solve(); } }
1472
B
Fair Division
Alice and Bob received $n$ candies from their parents. \textbf{Each candy weighs either 1 gram or 2 grams}. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies. Check if they can do that. Note that candies \textbf{are not allowed to be cut in half}.
If the sum of all the weights is not divisible by two, then it is impossible to divide the candies between two people. If the sum is divisible, then let's count the number of candies with a weight of $1$ and $2$. Now, if we can find a way to collect half the sum with some candies, then these candies can be given to Alice, and all the rest can be given to Bob. Simple solution - let's iterate through how many candies of weight $2$ we will give to Alice, then the remaining weight should be filled by candies of weight $1$. If there are enough of them, then we have found a way of division. In fact, if the sum is even and there are at least two candies with weight $1$ (there can't be one candy), then the answer is always "YES" (we can collect the weight as close to half as possible with weight $2$ and then add weight $1$). If there are no candies with weight $1$, then you need to check whether $n$ is even (since all the candies have the same weight, you just need to divide them in half).
[ "dp", "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; cin >> n; int cnt1 = 0, cnt2 = 0; for (int i = 0; i < n; i++) { int c; cin >> c; if (c == 1) { cnt1++; } else { cnt2++; } } if ((cnt1 + 2 * cnt2) % 2 != 0) { cout << "NO\n"; } else { int sum = (cnt1 + 2 * cnt2) / 2; if (sum % 2 == 0 || (sum % 2 == 1 && cnt1 != 0)) { cout << "YES\n"; } else { cout << "NO\n"; } } } int main() { int t; cin >> t; while (t--) { solve(); } }
1472
C
Long Jumps
Polycarp found under the Christmas tree an array $a$ of $n$ elements and instructions for playing with it: - At first, choose index $i$ ($1 \leq i \leq n$) — starting position in the array. Put the chip at the index $i$ (on the value $a_i$). - While $i \leq n$, add $a_i$ to your score and move the chip $a_i$ positions to the right (i.e. replace $i$ with $i + a_i$). - If $i > n$, then Polycarp ends the game. For example, if $n = 5$ and $a = [7, 3, 1, 2, 3]$, then the following game options are possible: - Polycarp chooses $i = 1$. Game process: $i = 1 \overset{+7}{\longrightarrow} 8$. The score of the game is: $a_1 = 7$. - Polycarp chooses $i = 2$. Game process: $i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$. The score of the game is: $a_2 + a_5 = 6$. - Polycarp chooses $i = 3$. Game process: $i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$. The score of the game is: $a_3 + a_4 = 3$. - Polycarp chooses $i = 4$. Game process: $i = 4 \overset{+2}{\longrightarrow} 6$. The score of the game is: $a_4 = 2$. - Polycarp chooses $i = 5$. Game process: $i = 5 \overset{+3}{\longrightarrow} 8$. The score of the game is: $a_5 = 3$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.
Let $score(i)$ be the result of the game if we chose $i$ as the starting position. Let's look at some starting position $j$. After making a move from it, we will get $a[j]$ points and move to the position $j + a[j]$, continuing the same game. This means that by choosing the position $j$, we can assume that we will get a result $a[j]$ more than if we chose the position $j + a[j]$. Formally, $score(j) = score(j + a[j]) + a[j]$. Let's calculate all the results of $score$ and store them in an array. Let's start iterating through the positions from the end, then being in the position $i$ we will know $score(j)$ for all $j > i$. Using the formula above, we can calculate $score(i)$ in one operation. It remains only to choose the maximum of all such values.
[ "dp", "graphs" ]
1,100
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int &x : a) { cin >> x; } vector<int> dp(n); for (int i = n - 1; i >= 0; i--) { dp[i] = a[i]; int j = i + a[i]; if (j < n) { dp[i] += dp[j]; } } cout << *max_element(dp.begin(), dp.end()) << endl; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1472
D
Even-Odd Game
During their New Year holidays, Alice and Bob play the following game using an array $a$ of $n$ integers: - Players take turns, Alice moves first. - Each turn a player chooses any element and removes it from the array. - If Alice chooses \textbf{even value}, then she adds it to her score. If the chosen value is odd, Alice's score does not change. - Similarly, if Bob chooses \textbf{odd value}, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if $n = 4$ and $a = [5, 2, 7, 3]$, then the game could go as follows (there are other options): - On the first move, Alice chooses $2$ and get two points. Her score is now $2$. The array $a$ is now $[5, 7, 3]$. - On the second move, Bob chooses $5$ and get five points. His score is now $5$. The array $a$ is now $[7, 3]$. - On the third move, Alice chooses $7$ and get no points. Her score is now $2$. The array $a$ is now $[3]$. - On the last move, Bob chooses $3$ and get three points. His score is now $8$. The array $a$ is empty now. - Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. \textbf{Note that there may be duplicate numbers in the array}.
Let's look at an analogy for this game. If Alice takes an even number $x$, she adds $x$ points to the global result, otherwise $0$; If Bob takes an odd number $x$, he adds $-x$ points to the global result, otherwise $0$; Alice wants to maximize the global result and Bob wants to minimize it. Obviously, this game is completely equivalent to the conditional game. Suppose now it's Alice's move. Let's look at some number $x$ in the array. If this number is even, then taking it will add $x$ points, and giving it to Bob will add $0$ points. If this number is odd, then taking it will add $0$ points, and giving it to Bob will add $-x$ points. So taking the number $x$ by $x$ points is more profitable than not taking it (regardless of the parity). To maximize the result, Alice should always take the maximum number in the array. Similar reasoning can be done for Bob. In the task, it was necessary to sort the array and simulate the game.
[ "dp", "games", "greedy", "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; cin >> n; vector<int> v(n); for (int &e : v) { cin >> e; } sort(v.rbegin(), v.rend()); ll ans = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (v[i] % 2 == 0) { ans += v[i]; } } else { if (v[i] % 2 == 1) { ans -= v[i]; } } } if (ans == 0) { cout << "Tie\n"; } else if (ans > 0) { cout << "Alice\n"; } else { cout << "Bob\n"; } } int main() { int t; cin >> t; while (t--) { solve(); } return 0; }
1472
E
Correct Placement
Polycarp has invited $n$ friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side. Each friend is characterized by two values $h_i$ (their height) and $w_i$ (their width). On the photo the $i$-th friend will occupy a rectangle $h_i \times w_i$ (if they are standing) or $w_i \times h_i$ (if they are lying on the side). The $j$-th friend can be placed in front of the $i$-th friend on the photo if his rectangle is lower and narrower than the rectangle of the $i$-th friend. Formally, \textbf{at least one} of the following conditions must be fulfilled: - $h_j < h_i$ \textbf{and} $w_j < w_i$ (both friends are standing or both are lying); - $w_j < h_i$ \textbf{and} $h_j < w_i$ (one of the friends is standing and the other is lying). For example, if $n = 3$, $h=[3,5,3]$ and $w=[4,4,3]$, then: - the first friend can be placed in front of the second: $w_1 < h_2$ and $h_1 < w_2$ (one of the them is standing and the other one is lying); - the third friend can be placed in front of the second: $h_3 < h_2$ and $w_3 < w_2$ (both friends are standing or both are lying). In other cases, the person in the foreground will overlap the person in the background. Help Polycarp for each $i$ find any $j$, such that the $j$-th friend can be located in front of the $i$-th friend (i.e. at least one of the conditions above is fulfilled). Please note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend $i$ any other friend $j$ who can be located in front of him. Think about it as you need to solve $n$ separate independent subproblems.
Let's sort all people by their height in descending order. Now let's go through all the people and look for the position of the person in the sorted array, the height of which is strictly less than ours (for example, by binary search). Obviously, only those people who are in the sorted array later than the found person can stand in front of us (all of them have a height strictly less than ours). Among all these people, it is more profitable for us to take a person with minimum width. In order to find such a person quickly, we can find a person with the minimum width for each suffix of the sorted array. To handle a situation where a person is lying down, we need to swap the width and height and repeat the algorithm above.
[ "binary search", "data structures", "dp", "sortings", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; struct man { int h, w, id; }; bool operator<(const man &a, const man &b) { return tie(a.h, a.w, a.id) < tie(b.h, b.w, b.id); } struct my_min { pii mn1, mn2; }; vector<pair<int, my_min>> createPrefMins(const vector<man>& a) { vector<pair<int, my_min>> prefMin; my_min curMin{pii(INT_MAX, -1), pii(INT_MAX, -1)}; for (auto x : a) { if (x.w < curMin.mn1.first) { curMin.mn2 = curMin.mn1; curMin.mn1 = pii(x.w, x.id); } else { curMin.mn2 = min(curMin.mn2, pii(x.w, x.id)); } prefMin.emplace_back(x.h, curMin); } return prefMin; } int findAny(const vector<pair<int, my_min>> &mins, int h, int w, int id) { int l = -1, r = (int) mins.size(); while (r - l > 1) { int m = (l + r) / 2; if (mins[m].first < h) { l = m; } else { r = m; } } if (l == -1) { return -1; } auto mn1 = mins[l].second.mn1; auto mn2 = mins[l].second.mn2; if (mn1.second != id) { return mn1.first < w ? mn1.second + 1 : -1; } return mn2.first < w ? mn2.second + 1 : -1; } void solve() { int n; cin >> n; vector<man> hor, ver; vector<pii> a; for (int i = 0; i < n; i++) { int h, w; cin >> h >> w; hor.push_back({h, w, i}); ver.push_back({w, h, i}); a.emplace_back(h, w); } sort(hor.begin(), hor.end()); sort(ver.begin(), ver.end()); auto horMins = createPrefMins(hor); auto verMins = createPrefMins(ver); for (int i = 0; i < n; i++) { auto[h, w] = a[i]; int id = findAny(horMins, h, w, i); if (id == -1) { id = findAny(verMins, h, w, i); } cout << id << " "; } cout << endl; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1472
F
New Year's Puzzle
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle. Polycarp got the following problem: given a grid strip of size $2 \times n$, some cells of it are blocked. You need to check if it is possible to tile all free cells using the $2 \times 1$ and $1 \times 2$ tiles (dominoes). For example, if $n = 5$ and the strip looks like this (black cells are blocked): Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors). And if $n = 3$ and the strip looks like this: It is impossible to tile free cells. Polycarp easily solved this task and received his New Year's gift. Can you solve it?
If the first column is empty, we can always cover it with a vertical tile: if the next column is also empty, then we will have to put either two vertical or two horizontal tiles, but they are obtained from each other by rotating; if the next column contains at least one blocked cell, then we have no other options but to cover the column with a vertical board. If the first column is fully blocked, then we can just skip it. Remove such columns from the beginning, reducing the problem. Now the first column contains one empty and one blocked cell. Obviously, in place of an empty cell, we will have to place a horizontal tile. If this did not work, then the tiling does not exist. Otherwise there are two cases: if the next column is empty, it will turn into a column with one occupied cell. Then we continue to put horizontal tiles; if the next column contains one blocked cell, then it becomes fully blocked and we return to the first step. It turns out the following greedy algorithm, we sort all columns with at least one cell blocked (there are no more than $m$ such columns) by number. Now, if we see a column with one occupied cell, then the next one must also be with one occupied cell (we skipped the empty columns), but this cell must have a different color in the chess coloring (so that we can tile the space between them with horizontal boards. This check is easy to do after sorting the columns.
[ "brute force", "dp", "graph matchings", "greedy", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n, m; cin >> n >> m; map<int, int> v; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; v[y] |= (1 << (x - 1)); } const int FULL = 3; v[2e9] = FULL; int hasLast = 0, lastColor = 0; for (auto[x, mask] : v) { if (mask != FULL && hasLast) { int color = (x + mask) % 2; if (lastColor == color) { cout << "NO\n"; return; } else { hasLast = false; } } else if (mask == FULL && hasLast) { cout << "NO\n"; return; } else if (mask != FULL) { lastColor = (x + mask) % 2; hasLast = true; } } cout << "YES\n"; } int main() { int t; cin >> t; while (t--) { solve(); } return 0; }
1472
G
Moving to the Capital
There are $n$ cities in Berland. The city numbered $1$ is the capital. Some pairs of cities are connected by a \textbf{one-way} road of length 1. Before the trip, Polycarp for each city found out the value of $d_i$ — the shortest distance from the capital (the $1$-st city) to the $i$-th city. Polycarp begins his journey in the city with number $s$ and, being in the $i$-th city, chooses one of the following actions: - Travel from the $i$-th city to the $j$-th city if there is a road from the $i$-th city to the $j$-th and $d_i < d_j$; - Travel from the $i$-th city to the $j$-th city if there is a road from the $i$-th city to the $j$-th and $d_i \geq d_j$; - Stop traveling. Since the government of Berland does not want all people to come to the capital, so Polycarp \textbf{no more than once} can take the second action from the list. in other words, he can perform the second action $0$ or $1$ time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible. For example, if $n = 6$ and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options): - $2 \rightarrow 5 \rightarrow 1 \rightarrow 2 \rightarrow 5$; - $3 \rightarrow 6 \rightarrow 2$; - $1 \rightarrow 3 \rightarrow 6 \rightarrow 2 \rightarrow 5$. Polycarp wants for each starting city $i$ to find out how close he can get to the capital. More formally: he wants to find the minimal value of $d_j$ that Polycarp can get from the city $i$ to the city $j$ according to the rules described above.
Find the distances to all vertices and construct a new graph that has only edges that goes from a vertex with a smaller distance to a vertex with a larger distance. Such a graph cannot contain cycles. Next, you need to run a dynamic programming similar to finding bridges in an undirected graph. First, we write the minimum distance from each vertex to the capital using no more than one edge. This distance is either equal to the distance from the capital to the vertex itself, or the distance to the vertex connected to us by one of the remote edges. We can't go through more than one remote edge. The real answer for a vertex $v$ is the minimum of such values in all vertices reachable from $v$ in the new graph. Since the new graph is acyclic, we can calculate the answer using dynamic programming and a depth-first search started from the capital.
[ "dfs and similar", "dp", "graphs", "shortest paths" ]
2,100
#include <bits/stdc++.h> using namespace std; vector<int> calcDist(vector<vector<int>> const &g) { vector<int> dist(g.size(), -1); dist[1] = 0; queue<int> pq; pq.push(1); while (!pq.empty()) { int u = pq.front(); pq.pop(); for (int v : g[u]) { if (dist[v] == -1) { dist[v] = dist[u] + 1; pq.push(v); } } } return dist; } void dfs(int u, vector<vector<int>> const &g, vector<int> const &dist, vector<int> &dp, vector<bool> &used) { used[u] = true; dp[u] = dist[u]; for (int v : g[u]) { if (!used[v] && dist[u] < dist[v]) { dfs(v, g, dist, dp, used); } if (dist[u] < dist[v]) { dp[u] = min(dp[u], dp[v]); } else { dp[u] = min(dp[u], dist[v]); } } } void solve() { int n, m; cin >> n >> m; vector<vector<int>> g(n + 1); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; g[u].push_back(v); } vector<int> dist = calcDist(g); vector<int> dp(n + 1); vector<bool> used(n + 1); dfs(1, g, dist, dp, used); for (int i = 1; i <= n; i++) { cout << dp[i] << " "; } cout << endl; } int main() { int tests; cin >> tests; while (tests-- > 0) { solve(); } return 0; }
1473
A
Replacing Elements
You have an array $a_1, a_2, \dots, a_n$. All $a_i$ are positive integers. In one step you can choose three distinct indices $i$, $j$, and $k$ ($i \neq j$; $i \neq k$; $j \neq k$) and assign the sum of $a_j$ and $a_k$ to $a_i$, i. e. make $a_i = a_j + a_k$. Can you make all $a_i$ lower or equal to $d$ using the operation above any number of times (possibly, zero)?
Let's note that since all $a_i$ are positive, any $a_i + a_j > \max(a_i, a_j)$. It means that we can't make the first and second minimums lower than they already are: suppose the first and second minimums are $mn_1$ and $mn_2$, if we choose any other element to replace, we can't make it less than $mn_1 + mn_2$ and if we choose to replace $mn_1$ or $mn_2$ we will only make them bigger. As a result, it means that we can choose for each element either not to change it or make it equal to $mn_1 + mn_2$. So, to be able to make all elements $\le d$ we need just check that either $mn_1 + mn_2 \le d$ or maximum $a_i \le d$. We can do it, for example, by sorting our array $a$ in increasing order and checking that either $a_1 + a_2 \le d$ or $a_n \le d$.
[ "greedy", "implementation", "math", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while (tc--) { int n, d; cin >> n >> d; vector<int> a(n); for (int& x : a) cin >> x; sort(a.begin(), a.end()); cout << (a.back() <= d || a[0] + a[1] <= d ? "YES" : "NO") << endl; } }
1473
B
String LCM
Let's define a multiplication operation between a string $a$ and a positive integer $x$: $a \cdot x$ is the string that is a result of writing $x$ copies of $a$ one after another. For example, "abc" $\cdot~2~=$ "abcabc", "a" $\cdot~5~=$ "aaaaa". A string $a$ is divisible by another string $b$ if there exists an integer $x$ such that $b \cdot x = a$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa". LCM of two strings $s$ and $t$ (defined as $LCM(s, t)$) is the shortest non-empty string that is divisible by both $s$ and $t$. You are given two strings $s$ and $t$. Find $LCM(s, t)$ or report that it does not exist. It can be shown that if $LCM(s, t)$ exists, it is unique.
We should notice that if some string $x$ is a multiple of string $y$, then $|x|$ is a multiple of $|y|$. This fact leads us to the conclusion that $|LCM(s, t)|$ should be a common multiple of $|s|$ and $|t|$. Since we want to minimize the length of the string $LCM(s, t)$, then its length is $LCM(|s|, |t|)$. So we have to check that $\frac{LCM(|s|, |t|)}{|s|}$ copies of the string $s$ equal to $\frac{LCM(|s|, |t|)}{|t|}$ copies of the string $t$. If such strings are equal, print them, otherwise, there is no solution.
[ "brute force", "math", "number theory", "strings" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { auto mul = [](string s, int k) -> string { string res = ""; while (k--) res += s; return res; }; int tc; cin >> tc; while (tc--) { string s, t; cin >> s >> t; int n = s.length(), m = t.length(); int g = __gcd(n, m); if (mul(s, m / g) == mul(t, n / g)) cout << mul(s, m / g) << endl; else cout << "-1" << endl; } }
1473
C
No More Inversions
You have a sequence $a$ with $n$ elements $1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k)$ ($k \le n < 2k$). Let's call as inversion in $a$ a pair of indices $i < j$ such that $a[i] > a[j]$. Suppose, you have some permutation $p$ of size $k$ and you build a sequence $b$ of size $n$ in the following manner: $b[i] = p[a[i]]$. Your goal is to find such permutation $p$ that the total number of inversions in $b$ doesn't exceed the total number of inversions in $a$, and $b$ is lexicographically maximum. Small reminder: the sequence of $k$ integers is called a permutation if it contains all integers from $1$ to $k$ exactly once. Another small reminder: a sequence $s$ is lexicographically smaller than another sequence $t$, if either $s$ is a prefix of $t$, or for the first $i$ such that $s_i \ne t_i$, $s_i < t_i$ holds (in the first position that these sequences are different, $s$ has smaller number than $t$).
At first, let's look at sequence $s$: $s_1, s_2, \dots, s_{p - 1}, s_{p}, s_{p - 1}, \dots s_2, s_1$. Let's prove that the number of inversions in $s$ is the same regardless of what $s_i$ are (the only condition is that $s_i$ should be distinct). Let's group all elements $s_i$ by their value - there will be $1$ or $2$ elements in each group. Then we can take any two groups with values $x$ and $y$ and calculate the number of inversions between elements in these groups. It's easy to note that construction will always be like $\dots x, \dots, y, \dots, y, \dots, x \dots$ (or $\dots x, \dots, y, \dots, x \dots$) and regardless of $x > y$ or $x < y$ in both cases there will be exactly two inversions between groups equal to $x$ and to $y$ (or one inversion in the second case). So the total number of inversion will be equal to $2 \frac{(p - 1)(p - 2)}{2} + (p - 1) = (p - 1)^2$. Now we can split sequences $a$ and $b$ into two parts. Let $m = n - k$, then the first part is elements from segment $[1, k - m - 1]$ and the second is from $[k - m, k + m]$. Note that the second parts both in $a$ and $b$ are exactly the sequence $s$ described above. The total number of inversions is equal to the sum of inversions in the first part, in the second part, and the inversions with elements from both parts. Note that in $a$ the first and the third components are equal to $0$ and the second component is constant, so in $b$ we must also have $0$ inversions in the first part and $0$ inversion between parts. It means that $b$ must start from $1, 2, \dots, (k - m - 1)$. But since the number of inversions in the second part is constant we can set the remaining elements the way we want. And since we want to build lexicographically maximum $b$, we should make the second part as $k, k - 1, \dots, (k - m + 1), (k - m), (k - m + 1), \dots, k$. In the end, optimal $b$ is $1, 2, \dots, (k - m - 1), k, (k - 1), \dots, (k - m + 1), (k - m), (k - m + 1), \dots, k$. The permutation $p$ to make such $b$ is equal to $1, 2, \dots, (k - m - 1), k, (k - 1), \dots, (k - m)$.
[ "constructive algorithms", "math" ]
1,500
fun main() { repeat(readLine()!!.toInt()) { val (n, k) = readLine()!!.split(' ').map { it.toInt() } for (i in 1 until (k - (n - k))) print("$i ") for (i in k downTo (k - (n - k))) print("$i ") println("") } }
1473
D
Program
You are given a program that consists of $n$ instructions. Initially a single variable $x$ is assigned to $0$. Afterwards, the instructions are of two types: - increase $x$ by $1$; - decrease $x$ by $1$. You are given $m$ queries of the following format: - query $l$ $r$ — how many distinct values is $x$ assigned to if all the instructions between the $l$-th one and the $r$-th one inclusive are ignored and the rest are executed without changing the order?
The value of $x$ always changes by $1$, thus, the set of values of $x$ is always some contiguous segment. The length of such segment can be determined by just its minimum and maximum values. So we have to solve two separate tasks for each query: find the minimum and the maximum value $x$ gets assigned to. I'll describe only the minimum one. This task, however, can as well be split into two parts: minimum value on a prefix before $l$ and on a suffix after $r$. The prefix is easy - it doesn't get changed by a query, so it can be precalculated beforehand. Minimum value on a prefix of length $i$ is minimum of a minimum value on a prefix of length $i-1$ and the current value. The suffix minimum is not that trivial. First, in order to precalculate the minimum value on a suffix of length $i$, we have to learn to prepend an instruction to the suffix of length $i+1$. Consider the graph of values of $x$ over time. What happens to it if the initial value of $x$ is not $0$ but $1$, for example? It just gets shifted by $1$ upwards. That move is actually the same as prepending a '+' instruction. So the minimum value for a suffix of length $i$ is a minimum of a minimum value for a suffix of length $i-1$, increased by the current instruction, and $0$ (the start of the graph). So now we have a minimum value on a suffix after $r$. However, it can't be taken into the answer as it is, because it considers the graph for the suffix to be starting from $0$. And that's not the case. The graph for the suffix starts from the value the prefix ends on. So we can shift the answer for the suffix by the value of $x$ after the prefix. The overall minimum value is just the minimum on a prefix and on a suffix, then. Overall complexity: $O(n + m)$ per testcase.
[ "data structures", "dp", "implementation", "strings" ]
1,700
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int main() { cin.tie(0); ios_base::sync_with_stdio(0); int t; cin >> t; forn(_, t){ int n, m; string s; cin >> n >> m; cin >> s; vector<int> sul(1, 0), sur(1, 0); for (int i = n - 1; i >= 0; --i){ int d = s[i] == '+' ? 1 : -1; sul.push_back(min(0, sul.back() + d)); sur.push_back(max(0, sur.back() + d)); } reverse(sul.begin(), sul.end()); reverse(sur.begin(), sur.end()); vector<int> prl(1, 0), prr(1, 0), pr(1, 0); forn(i, n){ int d = s[i] == '+' ? 1 : -1; pr.push_back(pr.back() + d); prl.push_back(min(prl.back(), pr.back())); prr.push_back(max(prr.back(), pr.back())); } forn(i, m){ int l, r; cin >> l >> r; --l; int l1 = prl[l], r1 = prr[l]; int l2 = sul[r] + pr[l], r2 = sur[r] + pr[l]; printf("%d\n", max(r1, r2) - min(l1, l2) + 1); } } return 0; }
1473
E
Minimum Path
You are given a weighted undirected connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Let's define the weight of the path consisting of $k$ edges with indices $e_1, e_2, \dots, e_k$ as $\sum\limits_{i=1}^{k}{w_{e_i}} - \max\limits_{i=1}^{k}{w_{e_i}} + \min\limits_{i=1}^{k}{w_{e_i}}$, where $w_i$ — weight of the $i$-th edge in the graph. Your task is to find the minimum weight of the path from the $1$-st vertex to the $i$-th vertex for each $i$ ($2 \le i \le n$).
Let's consider a problem where you can subtract the weight of any edge (not only the maximum one) that belong to the current path and similarly add the weight of any edge (not only the minimum one) that belong to the current path. To solve that problem we can build a new graph where the node can be represented as the following triple (node from the initial graph, flag that some edge has been subtracted, flag that some edge has been added). Now we can run Dijkstra's algorithm to find the length of the shortest paths in such a graph. We can notice that on the shortest path, the maximum weight edge was subtracted and the minimum weight edge was added. Let's assume that this is not the case, and an edge of non-maximum weight was subtracted from the path, then we can reduce the length of the path by choosing an edge of maximum weight. But this is not possible, because we considered the shortest path. Similarly, it is proved that the added edge was of minimal weight. Using this fact, it is not difficult to notice that by solving the modified problem, we have solved the original one.
[ "graphs", "shortest paths" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 13; int n, m; vector<pair<int, int>> g[N]; long long d[N][2][2]; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int v, u, w; scanf("%d%d%d", &v, &u, &w); --v; --u; g[v].emplace_back(u, w); g[u].emplace_back(v, w); } for (int i = 0; i < n; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) d[i][j][k] = (long long)1e18; d[0][0][0] = 0; set<pair<long long, array<int, 3>>> q; q.insert({0, {0, 0, 0}}); while (!q.empty()) { auto [v, mx, mn] = q.begin()->second; q.erase(q.begin()); for (auto [u, w] : g[v]) { for (int i = 0; i <= 1 - mx; i++) { for (int j = 0; j <= 1 - mn; j++) { if (d[u][mx | i][mn | j] > d[v][mx][mn] + (1 - i + j) * w) { auto it = q.find({d[u][mx | i][mn | j], {u, mx | i, mn | j}}); if (it != q.end()) q.erase(it); d[u][mx | i][mn | j] = d[v][mx][mn] + (1 - i + j) * w; q.insert({d[u][mx | i][mn | j], {u, mx | i, mn | j}}); } } } } } for (int i = 1; i < n; i++) { printf("%lld ", d[i][1][1]); } puts(""); }
1473
F
Strange Set
\textbf{Note that the memory limit is unusual.} You are given an integer $n$ and two sequences $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$. Let's call a set of integers $S$ such that $S \subseteq \{1, 2, 3, \dots, n\}$ strange, if, for every element $i$ of $S$, the following condition is met: for every $j \in [1, i - 1]$, if $a_j$ divides $a_i$, then $j$ is also included in $S$. An empty set is always strange. The cost of the set $S$ is $\sum\limits_{i \in S} b_i$. You have to calculate the maximum possible cost of a strange set.
We will model the problem as the minimum cut in a flow network. Build a network as follows: create a source node $s$, a sink node $t$, and a vertex for every number from $1$ to $n$. Let's say that we are going to find the minimum $s$-$t$ cut in this network, and the vertices belonging to the same cut part with $s$ represent the numbers that are taken into the answer. Using the edges of the network, we should model these constraints: taking an element $i$ that depends on another element $j$ should force us to take $j$ as well; taking an element $i$ with $b_i > 0$ should add $b_i$ to our score; taking an element $i$ with $b_i < 0$ should subtract $|b_i|$ from our score. Constraint $1$ can be modeled in the following way: for every pair $(i, j)$ such that element $i$ depends on element $j$ ($i > j$ and $a_i \bmod a_j = 0$), add a directed edge with infinite capacity from $i$ to $j$. That way, if $i$ is taken and $j$ is not, the value of the cut will be infinite because of this edge, and this cut cannot be minimum. Constraint $2$ is modeled in the following way: for every $i$ such that $b_i > 0$, add a directed edge with capacity $b_i$ from $s$ to $i$. That way, if we don't take some element $i$ with $b_i > 0$ into the answer, $b_i$ is added to the value of the cut. And for constraint $3$, for every $i$ such that $b_i < 0$, add a directed edge with capacity $|b_i|$ from $i$ to $t$. That way, if we take some element $i$ with $b_i < 0$, $|b_i|$ is added to the value of the cut. It's now easy to see that the answer is $\sum\limits_{i = 1}^{n} \max(b_i, 0) - mincut$, since it is exactly the sum of elements that were taken (for positive elements, we add them all up and then subtract the ones that don't belong to the answer; for negative ones, we just subtract those which belong to the answer). To find a minimum cut, just run maximum flow in this network. There's one caveat though. If, for example, all $a_i$ are equal (or many $a_i$ are divisible by many other values in $a$), this network can contain $O(n^2)$ edges. To reduce the number of edges, let's see that if for some index $i$ there exist two equal divisors of $a_i$ to the left of it (let's say that these divisors are $j$ and $k$: $j < k < i$; $a_i \bmod a_j = 0$; $a_j = a_k$), then we only need to add an edge from $i$ to $k$, because taking $k$ also should force taking $j$ into the answer. So, for every divisor of $a_i$, we are interested in only one closest occurrence of this divisor to the left, and we need to add a directed edge only to this occurrence, and ignore all other occurrences. That way, for every vertex $i$, we add at most $D(a_i)$ edges to other vertices (where $D(a_i)$ is the number of divisors of $a_i$). It can be proven that any maximum flow algorithm that relies on augmenting paths will finish after $O(V)$ iterations in this network, so it won't work longer than $O(VE)$, and both $V$ and $E$ are proportional to $n$, so any maximum flow solution will run in $O(n^2)$.
[ "flows", "math" ]
2,700
#include<bits/stdc++.h> using namespace std; template<typename T> struct dinic { struct edge { int u, rev; T cap, flow; }; int n, s, t; T flow; vector<int> lst; vector<int> d; vector<vector<edge>> g; T scaling_lim; bool scaling; dinic() {} dinic(int n, int s, int t, bool scaling = false) : n(n), s(s), t(t), scaling(scaling) { g.resize(n); d.resize(n); lst.resize(n); flow = 0; } void add_edge(int v, int u, T cap, bool directed = true) { g[v].push_back({u, g[u].size(), cap, 0}); g[u].push_back({v, int(g[v].size()) - 1, directed ? 0 : cap, 0}); } T dfs(int v, T flow) { if (v == t) return flow; if (flow == 0) return 0; T result = 0; for (; lst[v] < g[v].size(); ++lst[v]) { edge& e = g[v][lst[v]]; if (d[e.u] != d[v] + 1) continue; T add = dfs(e.u, min(flow, e.cap - e.flow)); if (add > 0) { result += add; flow -= add; e.flow += add; g[e.u][e.rev].flow -= add; } if (flow == 0) break; } return result; } bool bfs() { fill(d.begin(), d.end(), -1); queue<int> q({s}); d[s] = 0; while (!q.empty() && d[t] == -1) { int v = q.front(); q.pop(); for (auto& e : g[v]) { if (d[e.u] == -1 && e.cap - e.flow >= scaling_lim) { q.push(e.u); d[e.u] = d[v] + 1; } } } return d[t] != -1; } T calc() { T max_lim = numeric_limits<T>::max() / 2 + 1; for (scaling_lim = scaling ? max_lim : 1; scaling_lim > 0; scaling_lim >>= 1) { while (bfs()) { fill(lst.begin(), lst.end(), 0); T add; while((add = dfs(s, numeric_limits<T>::max())) > 0) flow += add; } } return flow; } vector<bool> min_cut() { vector<bool> res(n); for(int i = 0; i < n; i++) res[i] = (d[i] != -1); return res; } }; int main() { int n; cin >> n; vector<int> a(n), b(n); for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) cin >> b[i]; int s = n; int t = n + 1; dinic<int> d(n + 2, s, t, true); vector<int> last(101, -1); for(int i = 0; i < n; i++){ if(b[i] > 0) d.add_edge(s, i, b[i]); if(b[i] < 0) d.add_edge(i, t, -b[i]); for(int k = 1; k <= 100; k++) if(last[k] != -1 && a[i] % k == 0) d.add_edge(i, last[k], int(1e9)); last[a[i]] = i; } int sum = 0; for(int i = 0; i < n; i++) sum += max(0, b[i]); cout << sum - d.calc() << endl; }
1473
G
Tiles
Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged. The road is constructed as follows: - the first row consists of $1$ tile; - then $a_1$ rows follow; each of these rows contains $1$ tile greater than the previous row; - then $b_1$ rows follow; each of these rows contains $1$ tile less than the previous row; - then $a_2$ rows follow; each of these rows contains $1$ tile greater than the previous row; - then $b_2$ rows follow; each of these rows contains $1$ tile less than the previous row; - ... - then $a_n$ rows follow; each of these rows contains $1$ tile greater than the previous row; - then $b_n$ rows follow; each of these rows contains $1$ tile less than the previous row. \begin{center} An example of the road with $n = 2$, $a_1 = 4$, $b_1 = 2$, $a_2 = 2$, $b_2 = 3$. Rows are arranged from left to right. \end{center} You start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile. Calculate the number of different paths from the first row to the last row. Since it can be large, print it modulo $998244353$.
The group of the rows where the number of rectangular tiles increases $a$ times and then decreases $b$ times can be represented as a rectangular table, with $a+b+1$ diagonals, where the size of the first diagonal is equal to the number of rectangular tiles before the operations are applied (let their number be $m$), and the size of the last diagonal is $m+a-b$. In such a rectangular table, one can move from the cell $(i, j)$ to the cells $(i+1, j)$ and $(i, j+1)$ (if they exist), which lie on the next diagonal (next row in terms of the original problem). It's a well-known fact that the number of different paths from one cell to another is some binomial coefficient. Let's define $ans_{i,j}$ as the number of paths from the $1$-st row to the $j$-th tile in the ($\sum\limits_{k=1}^{i} (a_i+b_i)$)-th row (i.e. row after the $i$-th group of operations). Now we want to find the values of $ans_{i}$ using the values of $ans_{i-1}$ (let its size be $m$). Using the fact described in the first paragraphs we know that $ans_{i, j}$ depends on $ans_{i-1, k}$ with some binomial coefficient. In fact $ans_{i, j} = \sum\limits_{k=1}^{m} \binom{a_i+b_i}{b_i-k+j} ans_{i-1,k}$ for $1 \le j \le m + a_i - b_i$. But this solution is too slow. To speed up this solution we have to notice that the given formula is a convolution of $ans_{i-1}$ and some binomial coefficients. So we can use NTT to multiply them in $O(n\log n)$ instead of $O(n^2)$ time.
[ "combinatorics", "dp", "fft", "math" ]
2,800
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define fore(i, l, r) for (int i = int(l); i < int(r); ++i) #define sz(a) int((a).size()) template<const int &MOD> struct _m_int { int val; _m_int(int64_t v = 0) { if (v < 0) v = v % MOD + MOD; if (v >= MOD) v %= MOD; val = int(v); } _m_int(uint64_t v) { if (v >= MOD) v %= MOD; val = int(v); } _m_int(int v) : _m_int(int64_t(v)) {} _m_int(unsigned v) : _m_int(uint64_t(v)) {} static int inv_mod(int a, int m = MOD) { int g = m, r = a, x = 0, y = 1; while (r != 0) { int q = g / r; g %= r; swap(g, r); x -= q * y; swap(x, y); } return x < 0 ? x + m : x; } explicit operator int() const { return val; } explicit operator unsigned() const { return val; } explicit operator int64_t() const { return val; } explicit operator uint64_t() const { return val; } explicit operator double() const { return val; } explicit operator long double() const { return val; } _m_int& operator+=(const _m_int &other) { val -= MOD - other.val; if (val < 0) val += MOD; return *this; } _m_int& operator-=(const _m_int &other) { val -= other.val; if (val < 0) val += MOD; return *this; } static unsigned fast_mod(uint64_t x, unsigned m = MOD) { #if !defined(_WIN32) || defined(_WIN64) return unsigned(x % m); #endif // Optimized mod for Codeforces 32-bit machines. // x must be less than 2^32 * m for this to work, so that x / m fits in an unsigned 32-bit int. unsigned x_high = unsigned(x >> 32), x_low = unsigned(x); unsigned quot, rem; asm("divl %4\n" : "=a" (quot), "=d" (rem) : "d" (x_high), "a" (x_low), "r" (m)); return rem; } _m_int& operator*=(const _m_int &other) { val = fast_mod(uint64_t(val) * other.val); return *this; } _m_int& operator/=(const _m_int &other) { return *this *= other.inv(); } friend _m_int operator+(const _m_int &a, const _m_int &b) { return _m_int(a) += b; } friend _m_int operator-(const _m_int &a, const _m_int &b) { return _m_int(a) -= b; } friend _m_int operator*(const _m_int &a, const _m_int &b) { return _m_int(a) *= b; } friend _m_int operator/(const _m_int &a, const _m_int &b) { return _m_int(a) /= b; } _m_int& operator++() { val = val == MOD - 1 ? 0 : val + 1; return *this; } _m_int& operator--() { val = val == 0 ? MOD - 1 : val - 1; return *this; } _m_int operator++(int) { _m_int before = *this; ++*this; return before; } _m_int operator--(int) { _m_int before = *this; --*this; return before; } _m_int operator-() const { return val == 0 ? 0 : MOD - val; } friend bool operator==(const _m_int &a, const _m_int &b) { return a.val == b.val; } friend bool operator!=(const _m_int &a, const _m_int &b) { return a.val != b.val; } friend bool operator<(const _m_int &a, const _m_int &b) { return a.val < b.val; } friend bool operator>(const _m_int &a, const _m_int &b) { return a.val > b.val; } friend bool operator<=(const _m_int &a, const _m_int &b) { return a.val <= b.val; } friend bool operator>=(const _m_int &a, const _m_int &b) { return a.val >= b.val; } _m_int inv() const { return inv_mod(val); } _m_int pow(int64_t p) const { if (p < 0) return inv().pow(-p); _m_int a = *this, result = 1; while (p > 0) { if (p & 1) result *= a; a *= a; p >>= 1; } return result; } friend string to_string(_m_int<MOD> x) { return to_string(x.val); } friend ostream& operator<<(ostream &os, const _m_int &m) { return os << m.val; } }; extern const int MOD = 998244353; using Mint = _m_int<MOD>; const int g = 3; const int LOGN = 15; vector<Mint> w[LOGN]; vector<int> rv[LOGN]; void prepare() { Mint wb = Mint(g).pow((MOD - 1) / (1 << LOGN)); forn(st, LOGN - 1) { w[st].assign(1 << st, 1); Mint bw = wb.pow(1 << (LOGN - st - 1)); Mint cw = 1; forn(k, 1 << st) { w[st][k] = cw; cw *= bw; } } forn(st, LOGN) { rv[st].assign(1 << st, 0); if (st == 0) { rv[st][0] = 0; continue; } int h = (1 << (st - 1)); forn(k, 1 << st) rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h); } } void ntt(vector<Mint> &a, bool inv) { int n = sz(a); int ln = __builtin_ctz(n); forn(i, n) { int ni = rv[ln][i]; if (i < ni) swap(a[i], a[ni]); } forn(st, ln) { int len = 1 << st; for (int k = 0; k < n; k += (len << 1)) { fore(pos, k, k + len){ Mint l = a[pos]; Mint r = a[pos + len] * w[st][pos - k]; a[pos] = l + r; a[pos + len] = l - r; } } } if (inv) { Mint rn = Mint(n).inv(); forn(i, n) a[i] *= rn; reverse(a.begin() + 1, a.end()); } } vector<Mint> mul(vector<Mint> a, vector<Mint> b) { int cnt = 1 << (32 - __builtin_clz(sz(a) + sz(b) - 1)); a.resize(cnt); b.resize(cnt); ntt(a, false); ntt(b, false); vector<Mint> c(cnt); forn(i, cnt) c[i] = a[i] * b[i]; ntt(c, true); return c; } int main() { prepare(); vector<Mint> fact(1, 1), ifact(1, 1); auto C = [&](int n, int k) -> Mint { if (k < 0 || k > n) return 0; while (sz(fact) <= n) { fact.push_back(fact.back() * sz(fact)); ifact.push_back(fact.back().inv()); } return fact[n] * ifact[k] * ifact[n - k]; }; int n; cin >> n; vector<int> a(n), b(n); forn(i, n) cin >> a[i] >> b[i]; vector<Mint> ans(1, 1); forn(i, n) { vector<Mint> Cs; for (int j = b[i] - sz(ans) + 1; j < sz(ans) + a[i]; ++j) Cs.push_back(C(a[i] + b[i], j)); auto res = mul(ans, Cs); int cnt = sz(ans); ans.resize(cnt + a[i] - b[i]); forn(j, sz(ans)) ans[j] = res[cnt + j - 1]; } cout << accumulate(ans.begin(), ans.end(), Mint(0)) << endl; }
1474
A
Puzzle From the Future
In the $2022$ year, Mike found two binary integers $a$ and $b$ of length $n$ (both of them are written only by digits $0$ and $1$) that can have leading zeroes. In order not to forget them, he wanted to construct integer $d$ in the following way: - he creates an integer $c$ as a result of bitwise summing of $a$ and $b$ without transferring carry, so $c$ may have one or more $2$-s. For example, the result of bitwise summing of $0110$ and $1101$ is $1211$ or the sum of $011000$ and $011000$ is $022000$; - after that Mike replaces equal consecutive digits in $c$ by one digit, thus getting $d$. In the cases above after this operation, $1211$ becomes $121$ and $022000$ becomes $020$ (so, $d$ won't have equal consecutive digits). Unfortunately, Mike lost integer $a$ before he could calculate $d$ himself. Now, to cheer him up, you want to find \textbf{any binary} integer $a$ of length $n$ such that $d$ will be \textbf{maximum possible as integer}. Maximum possible as integer means that $102 > 21$, $012 < 101$, $021 = 21$ and so on.
Hint $1$: Should we always make first digit of $d$ not equal to $0$? How can we do it? Hint $2$: Try to choose such $a$ that $d$ will have $n$ digits. At first, we can make the first digit of $d$ not equal to $0$ by setting $1$ to the first digit of $a$. Now we say that $d$ doesn't have leading zeroes. In this case, more digits $d$ has - the larger $d$ is. It turns out, we can always construct $d$ of length $n$ if we make each consecutive pair of digits different. In other words, we want to select $a_i$ in order to make $a_{i-1} + b_{i-1} \neq a_{i} + b_{i}$ for all $i > 1$. Since we want to maximize $a_{i} + b_{i}$, if $a_{i} = 1$ satisfies $a_{i-1} + b_{i-1} \neq a_i + b_i$ we take $a_{i} = 1$. Otherwise, $a_{i} = 0$ satisfies this condition. Time complexity is $\mathcal{O}(n)$.
[ "greedy" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string a; cin >> a; string b = "1"; for (int i = 1; i < n; i++) { if ('1' + a[i] != b[i - 1] + a[i - 1]) b += "1"; else b += "0"; } cout << b << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
1474
B
Different Divisors
Positive integer $x$ is called divisor of positive integer $y$, if $y$ is divisible by $x$ without remainder. For example, $1$ is a divisor of $7$ and $3$ is not divisor of $8$. We gave you an integer $d$ and asked you to find \textbf{the smallest} positive integer $a$, such that - $a$ has at least $4$ divisors; - difference between any two divisors of $a$ is at least $d$.
Hint $1$: Integer have exactly $4$ divisors, if it is of form $pq$ or $p^3$ for some primes $p$ and $q$. In the first case it have divisors $1$, $p$, $q$, $pq$. In the second case it have divisors $1$, $p$, $p^2$, $p^3$. Hint $2$: Instead of finding integer with at least $4$ divisors, find integer with exactly $4$ divisors. Hint $3$: Let $p$ be the smallest prime factor of $a$. Then, $p \geq d + 1$. Solution: Suppose, we have integer $a$ with more than $4$ divisors (and satisfies the other condition). If $a$ has at least two different prime factors, we can throw out all other prime factors and get a smaller number with at least $4$ divisors. Otherwise, $a = p^k$ for some $k > 3$. $p^3$ will also have $4$ divisors and it will be smaller than $a$. When we throw out a prime factor, no new divisors will appear, so the difference between any two of them will be at least $d$. Let's find smallest integers of form $p^3$ and $pq$ $(p<q)$ independently. In the first case, $p^3 - p^2 > p^2 - p > p - 1$, because $p \geq 2$. If we will find the smallest $p \geq d + 1$ all conditions will be satisfied. In the second case, $1 < p < q < pq$. Let's find the smallest $p \geq d + 1$ and the smallest $q \geq d + p$. In this case it is easy to see that $p - 1 \geq d$ and $q - p \geq d$. Also, $pq - q = q(p - 1) \geq qd \geq d$ since $q \geq 2$. It is enough to get OK even without checking case $a = p^3$. Also we should prove that there cannot exist $p'$ and $q'$ such that $p'q' < pq$. It is true because $p'$ should be at least $d+1$ and it should be prime, but $p$ is the smallest prime greater than $d$, so $p' \geq p$. And $q'$ should be at least $p+d$ and we can prove that $q' \geq q$ in the same way. Time complexity is $\mathcal{O}(t \cdot \mathit{gap} \cdot \mathit{primecheck})$, where $\mathit{gap}$ is difference between primes and $\mathcal{O}(\log{a})$ in average and $primecheck$ is complexity of your prime check and usually is $\mathcal{O}(\sqrt{a})$. Answer for $d = 10000$ is near to $2 \cdot 10^8$, so naive solution with factorization of each number shouldn't pass, but it is possible to precompute answers for all values of $d$ by that solution (in this case, you should run solution once for all values of $d$, not once for each value of $d$).
[ "binary search", "constructive algorithms", "greedy", "math", "number theory" ]
1,000
#include <iostream> #include <vector> using namespace std; void solve() { int x; cin >> x; vector<int> p; for (int i = x + 1; ; i++) { int t = 1; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { t = 0; break; } } if (t) { p.push_back(i); break; } } for (int i = p.back() + x; ; i++) { int t = 1; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { t = 0; break; } } if (t) { p.push_back(i); break; } } cout << min(1ll * p[0] * p[1], 1ll * p[0] * p[0] * p[0]) << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
1474
C
Array Destruction
You found a useless array $a$ of $2n$ positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of $a$. It could have been an easy task, but it turned out that you should follow some rules: - In the beginning, you select any positive integer $x$. - Then you do the following operation $n$ times: - select two elements of array with sum equals $x$; - remove them from $a$ and replace $x$ with maximum of that two numbers. For example, if initially $a = [3, 5, 1, 2]$, you can select $x = 6$. Then you can select the second and the third elements of $a$ with sum $5 + 1 = 6$ and throw them out. After this operation, $x$ equals $5$ and there are two elements in array: $3$ and $2$. You can throw them out on the next operation. Note, that you choose $x$ before the start and can't change it as you want between the operations. Determine how should you behave to throw out all elements of $a$.
Hint $1$: How does $x$ changes after each operation? Hint $2$: Suppose, that you know $x$. What pairs of elements can you throw out now? Hint $3$: Suppose, that you did some operations. Note, that if you have integer $b$ that is greater or equal to $x$ and $b$ is still in array $a$, you can't remove $b$ from $a$, thus you can't throw out all elements of $a$. Hint $4$: You don't know $x$ only before the first operation and $n \leq 1000$. Solution: Since all integers are positive, $x = c + d \rightarrow c, d < x$, thus $x$ decreaces after each operation. Suppose that we have integers $a_i \leq a_j \leq a_k$ in our array. If we throw out $a_i + a_j = x$, $x$ becomes equal $a_j \leq a_k$ and we can't throw out $a_k$ any time later. So, we should throw out the biggest element of array on each operation. If we know $x$ and the biggest element of array, we can easily determine the second element we throw out on this operation. We can try all possibilities of the second element of array we throw out on the first operation. $x$ will become equal the biggest element of initial array. After that we put all other elements in multiset $S$ and just simulate opertations by taking $max$ from $S$ and $x - max$ (if it doesn't exists, we can't throw out all elements) and replacing $x$ with $max$. Total time complexity: $\mathcal{O}(n^2 \cdot \log{n})$. There is also a solution without set, that runs in $\mathcal{O}(n^2 + maxA)$. Solution with set Solution without set 1474D - Cleaning
[ "brute force", "constructive algorithms", "data structures", "greedy", "implementation", "sortings" ]
1,700
#include <bits/stdc++.h> using namespace std; const int A = 1e6 + 12; int cnt[A]; void reset(vector<int> a) { for (int i = 0; i < a.size(); i++) { cnt[a[i]] = 0; } } void solve() { int n; cin >> n; vector<int> a(2 * n); for (int i = 0; i < 2 * n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); int t = 0; for (int i = 0; i < 2 * n - 1; i++) { for (int j = 0; j < 2 * n; j++) cnt[a[j]]++; int j = 2 * n - 1; int x = a[i] + a[j]; vector<int> rm; for (int op = 0; op < n; op++) { while (j > 0 && cnt[a[j]] == 0) j--; rm.push_back(a[j]); rm.push_back(x - a[j]); cnt[a[j]]--, cnt[x - a[j]]--; if (cnt[a[j]] < 0 || cnt[x - a[j]] < 0) { cnt[a[j]] = 0; cnt[x - a[j]] = 0; break; } x = max(x - a[j], a[j]); if (op + 1 == n) t = 1; } reset(a); if (t) { cout << "YES\n"; cout << rm[0] + rm[1] << "\n"; for (int i = 0; i < rm.size(); i++) { cout << rm[i] << " \n"[i % 2]; } return; } } cout << "NO\n"; reset(a); } int main(int argc, char* argv[]) { int t; cin >> t; while (t--) { solve(); } }
1474
D
Cleaning
During cleaning the coast, Alice found $n$ piles of stones. The $i$-th pile has $a_i$ stones. Piles $i$ and $i + 1$ are neighbouring for all $1 \leq i \leq n - 1$. If pile $i$ becomes empty, piles $i - 1$ and $i + 1$ \textbf{doesn't} become neighbouring. Alice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to do only the following operation: - Select two \textbf{neighboring} piles and, if both of them are not empty, remove one stone from each of them. Alice understands that sometimes it's impossible to remove all stones with the given operation, so she allowed you to use the following superability: - Before the start of cleaning, you can select two \textbf{neighboring} piles and swap them. Determine, if it is possible to remove all stones using the superability \textbf{not more than once}.
Hint $1$: How to solve the promblem if we are not allowed to use a superabilty (in linear time)? Hint $2$: Look at the first pile. There is only one way to remove stone from the first pile. Hint $3$: If you swap $i$-th and $(i + 1)$-th piles of stones, nothing changes in way you remove stones from $1$-st, $2$-nd, $\ldots$, $(i - 2)$-th piles. Hint $4$: Look at the problem from the both sides: from the beginning of $a$ and from the end of $a$. Solution: We can check, whether we can remove all stones without a supeability using the following algorithm: How can we remove the stones from the $1$-st pile? Only with stones from the second pile! If $a_1 > a_2$, then we can't remove all stones from the $1$-st pile. Now we have $0$ stones in the $1$-st pile and $a_2 - a_1$ stones in the $2$-nd pile. We can apply the idea above and get that we should have $a_2 - a_1$ stones in the $3$-rd pile.... ... In the end we have only $1$ pile. If there are any stones in it, we can't remove all stones. Otherwise, we constructed a solution for removing all stones. Also, we profed that there can be only one way to remove all stones. Now we have to improve this algorithm. Let $p_i$ be a number of stones in the $i$-th pile after cleaning piles $1$, $2$, ..., $i-1$ using this algorithm (and $(i+1)$-th, $(i+2)$-th, ..., $n$-th piles have the initial amount of stones). Now, let $s_i$ be a number of stones in the $i$-th pile, if we removed all stones from the $(i+1)$-th, ..., $n$-th piles (using the same algorithm, but we do operations in reversed order). We compute all $p_i$ and all $s_i$ in $\mathcal{O}(n)$. Now, if we try to swap $i$-th and $(i+1)$-th piles, we should check, that we can remove stones from four piles: $p_{i-1}$, $a_{i + 1}$, $a_{i}$, $s_{i+2}$. If we can do this for any $i$, answer is YES.
[ "data structures", "dp", "greedy", "math" ]
2,200
#include <iostream> #include <vector> using namespace std; int check(vector<long long> a) { for (int i = 0; i + 1 < a.size(); i++) { if (a[i] > a[i + 1]) { return 0; } a[i + 1] -= a[i]; a[i] = 0; } if (a.back() == 0) return 1; return 0; } void solve() { int n; cin >> n; vector<long long> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } if (check(a)) { cout << "YES\n"; return; } if (n == 1) { cout << "NO\n"; return; } swap(a[0], a[1]); if (check(a)) { cout << "YES\n"; return; } swap(a[0], a[1]); swap(a[n - 2], a[n - 1]); if (check(a)) { cout << "YES\n"; return; } swap(a[n - 2], a[n - 1]); vector<long long> p(n), s(n); vector<long long> b = a; p[0] = b[0]; for (int i = 1; i < n; i++) { if (p[i - 1] == -1 || b[i - 1] > b[i]) { p[i] = -1; } else { b[i] -= b[i - 1]; b[i - 1] = 0; p[i] = b[i]; } } b = a; s[n - 1] = b[n - 1]; for (int i = n - 2; i >= 0; i--) { if (s[i + 1] == -1 || b[i + 1] > b[i]) { s[i] = -1; } else { b[i] -= b[i + 1]; b[i + 1] = 0; s[i] = b[i]; } } for (int i = 1; i + 2 < n; i++) { vector<long long> c = {p[i - 1], a[i], a[i + 1], s[i + 2]}; if (p[i - 1] == -1 || s[i + 2] == -1) { continue; } swap(c[1], c[2]); if (check(c)) { cout << "YES\n"; return; } } cout << "NO\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { solve(); } }
1474
E
What Is It?
Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation $p$ of length $n$. Scientists found out, that to overcome an obstacle, the robot should make $p$ an identity permutation (make $p_i = i$ for all $i$). Unfortunately, scientists can't control the robot. Thus the only way to make $p$ an identity permutation is applying the following operation to $p$ multiple times: - Select two indices $i$ and $j$ ($i \neq j$), such that $p_j = i$ and swap the values of $p_i$ and $p_j$. It takes robot $(j - i)^2$ seconds to do this operation. Positions $i$ and $j$ are selected by the robot (scientists can't control it). He will apply this operation while $p$ isn't an identity permutation. We can show that the robot will make no more than $n$ operations regardless of the choice of $i$ and $j$ on each operation.Scientists asked you to find out the maximum possible time it will take the robot to finish making $p$ an identity permutation (i. e. worst-case scenario), so they can decide whether they should construct a new lunar rover or just rest and wait. They won't believe you without proof, so you should build an example of $p$ and robot's operations that maximizes the answer. For a better understanding of the statement, read the sample description.
Hint $1$: How many operations will robot make in the worst case? Hint $2$: How many times can robot spend $(n - 1)^2$ time on $1$ operation? Hint $3$: How many times can robot spend $(n - 2)^2$ time on $1$ operation? It is easyer to think about number of operations with time greater or equal to $(n - 2)^2$. Hint $4$: Instead of operation from the statement we can apply the following operation to $q$ which is initially an identity permutation: Select $i$ such that $q_i = i$ and any $j$ and swap $q_i$ and $q_j$ in $(j - i) ^ 2$ seconds. Then we make $p$ = $q$ and do operations in reversed order. Solution: If we can select $i$ and $j$ for an operation, $p_j \neq j$. After every operation, there is at least one more element with $p_i = i$, so after $n - 1$ operations at least $n - 1$ elements are on their places. The remaining element can be only on its own place, so we can't do more than $n - 1$ operations. Let's now count number of operations that takes $(n - 1)^2$ time. It is only a swap of $1$-st and $n$-th elements. If we did it, $p_1 = 1$ or $p_n = n$ so we can't use it one more time. Let's generalize it. If we are calculating number of operations that takes $(n - k)^2$ time, let's look at the first $k$ elements and at the last $k$ elements. Any operation that takes greater or equal then $(n - k)^2$ seconds, uses two of this elements. So, after $2k - 1$ operations $2k - 1$ of this elements will be on their places and we can't use one more operation of this type. So, $answer \leq (n - 1)^2 + (n - 2)^2 + (n - 2)^2 + (n - 3)^2 + \cdots$. There are $n - 1$ terms, each $(n - k)^2$ appears $2$ times, except $(n - 1)^2$ and last term (depends on parity of $n - 1$). We can construct example, where robot will spend exactly $(n - 1)^2 + (n - 2)^2 + (n - 2)^2 + (n - 3)^2 + \cdots$ second as follows (using idea from hint $4$): If $n$ is even, $answer = (n - 1)^2 + \cdots + (n - n / 2)^2 + (n - n / 2)^2$. Let's look at the example with $n = 6$: Set $q = [1, 2, 3, 4, 5, 6]$. Swap $q_1$ and $q_n$ in $25$ seconds, $q = [6, 2, 3, 4, 5, 1]$. Swap $q_1$ and $q_{n-1}$ in $16$ seconds, $q = [5, 2, 3, 4, 6, 1]$. Swap $q_2$ and $q_n$ in $16$ seconds, $q = [5, 1, 3, 4, 6, 2]$. Swap $q_1$ and $q_{n-2}$ in $9$ seconds, $q = [4, 1, 3, 5, 6, 2]$. Swap $q_3$ and $q_n$ in $9$ second, $q = [4, 1, 2, 5, 6, 3]$. In general, we swap $1$-st and $n$-th elements on the first operation and then move elements $2, n-1, 3, n-2, 4, n-3, ...$ to the further end of $q$. Set $q = [1, 2, 3, 4, 5, 6]$. Swap $q_1$ and $q_n$ in $25$ seconds, $q = [6, 2, 3, 4, 5, 1]$. Swap $q_1$ and $q_{n-1}$ in $16$ seconds, $q = [5, 2, 3, 4, 6, 1]$. Swap $q_2$ and $q_n$ in $16$ seconds, $q = [5, 1, 3, 4, 6, 2]$. Swap $q_1$ and $q_{n-2}$ in $9$ seconds, $q = [4, 1, 3, 5, 6, 2]$. Swap $q_3$ and $q_n$ in $9$ second, $q = [4, 1, 2, 5, 6, 3]$. If $n$ is odd, $answer = (n - 1)^2 + \cdots + (n - \lceil{n/2}\rceil)^2$. The only difference from even case is element in the center. For example, if $n = 7$ we will do the following operations: $q = [1, 2, 3, 4, 5, 6, 7]$. Swap $q_1$ and $q_n$. $q = [7, 2, 3, 4, 5, 6, 1]$. Swap $q_1$ and $q_{n - 1}$. $q = [6, 2, 3, 4, 5, 7, 1]$. Swap $q_2$ and $q_n$. $q = [6, 1, 3, 4, 5, 7, 2]$. Swap $q_1$ and $q_{n - 2}$. $q = [5, 1, 3, 4, 6, 7, 2]$. Swap $q_3$ and $q_n$. $q = [5, 1, 2, 4, 6, 7, 3]$. Finally, swap $q_1$ and $q_{\lceil{n/2}\rceil}$. $q = [4, 1, 2, 5, 6, 7, 3]$. $q = [1, 2, 3, 4, 5, 6, 7]$. Swap $q_1$ and $q_n$. $q = [7, 2, 3, 4, 5, 6, 1]$. Swap $q_1$ and $q_{n - 1}$. $q = [6, 2, 3, 4, 5, 7, 1]$. Swap $q_2$ and $q_n$. $q = [6, 1, 3, 4, 5, 7, 2]$. Swap $q_1$ and $q_{n - 2}$. $q = [5, 1, 3, 4, 6, 7, 2]$. Swap $q_3$ and $q_n$. $q = [5, 1, 2, 4, 6, 7, 3]$. Finally, swap $q_1$ and $q_{\lceil{n/2}\rceil}$. $q = [4, 1, 2, 5, 6, 7, 3]$.
[ "constructive algorithms", "greedy" ]
2,500
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; if (n == 1) { cout << 0 << "\n"; cout << 1 << "\n"; cout << 0 << "\n"; return; } long long ans = 0; long long cnt = 1, st = n - 1, asz = 0; while (asz < n - 1) { if (cnt == 0) { cnt = 2; st--; } ans += st * st; cnt--; asz++; } cout << ans << "\n"; vector<int> p; vector<int> opi, opj; { p.push_back(n / 2 + 1); for (int i = 1; i < n / 2; i++) { p.push_back(i); } for (int i = n / 2 + 2; i <= n; i++) { p.push_back(i); } p.push_back(n / 2); for (int i = n / 2 + 1; i < n; i++) { opi.push_back(i); opj.push_back(1); } for (int i = n / 2; i > 1; i--) { opi.push_back(i); opj.push_back(n); } if (n != 1) { opi.push_back(1); opj.push_back(n); } } for (int i = 0; i < p.size(); i++) { cout << p[i] << " "; } cout << "\n"; cout << opi.size() << "\n"; for (int j = 0; j < opi.size(); j++) { cout << opi[j] << " " << opj[j] << "\n"; } cout << "\n"; return; long long tm = 0; for (int j = 0; j < opi.size(); j++) { opi[j]--; opj[j]--; assert(p[opj[j]] - 1 == opi[j]); swap(p[opi[j]], p[opj[j]]); tm += 1ll * (opi[j] - opj[j]) * (opi[j] - opj[j]); } //cout << "True time = " << tm << "\n"; //cout << "Resulting permutation = "; for (int i = 0; i < n; i++) { ;//cout << p[i] << " "; } //cout << "\n"; assert(tm == ans); for (int i = 0; i < n; i++) { assert(p[i] == i + 1); } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { solve(); } }
1474
F
1 2 3 4 ...
Igor had a sequence $d_1, d_2, \dots, d_n$ of integers. When Igor entered the classroom there was an integer $x$ written on the blackboard. Igor generated sequence $p$ using the following algorithm: - initially, $p = [x]$; - for each $1 \leq i \leq n$ he did the following operation $|d_i|$ times: - if $d_i \geq 0$, then he looked at the last element of $p$ (let it be $y$) and appended $y + 1$ to the end of $p$; - if $d_i < 0$, then he looked at the last element of $p$ (let it be $y$) and appended $y - 1$ to the end of $p$. For example, if $x = 3$, and $d = [1, -1, 2]$, $p$ will be equal $[3, 4, 3, 4, 5]$. Igor decided to calculate the length of the longest increasing subsequence of $p$ and the number of them. A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. A sequence $a$ is an increasing sequence if each element of $a$ (except the first one) is strictly greater than the previous element. For $p = [3, 4, 3, 4, 5]$, the length of longest increasing subsequence is $3$ and there are $3$ of them: $[\underline{3}, \underline{4}, 3, 4, \underline{5}]$, $[\underline{3}, 4, 3, \underline{4}, \underline{5}]$, $[3, 4, \underline{3}, \underline{4}, \underline{5}]$.
Solution describes generalized version of algorigthm, corner cases are described later. It is easy to see that answer doesn't depend on $x$ given in the input, because we can substract $x$ from each element of $p$ and longest incerasing subsequences will remain the same. Let's look at $p$ as a function. If $p_i = x$ and $p_j = y$, for each $z \in [x, y]$ there exists $k \in [i, j]$, such that $p_k = z$ (Integer version of intermediate value theorem). Now look at any longest increasing subsequence $L$. If there are integers $x - 1$ and $x + 1$ in it (but there is no $x$), we can find appearence of $x$ in $p$ between them and add it to $L$, thus making a $L$ longer. So, such $x$ shouldn't exist $\rightarrow$ correct longest increasing sequence contains all integers between $a$ and $b$ for some $a$ and $b$. Let's build array $peaks$ that contains $p_1$, $last(p)$ and all $p_i$ such that $p_{i-1} < p_i > p_{i+1}$ or $p_{i-1} > p_i < p_{i+1}$ in order they appear in $p$. It is easy to see, that $|peaks| \leq n + 1$. Suppose, that the end of $L$ is not a peak. If it lies on increasing interval, than we can take next element into $L$ and increase $|L|$. If it lies on decreasing interval, we can use previous element of $p$ and using previous facts, find $L'$, $|L'| > |L|$. We can apply the same observations to the beginning of $p$. Thus, any $L$ begins and ends in peaks. Now, we can find $|L|$ in $\mathcal{O}(n^2)$. Suppose, we fixed that peaks and got $p'$, such that longest increasing subsequence of $p'$ begins and ends in different ends of $p'$ (we will not care about other longest increasing subsequences). Let's look at the slow algorithm for finding the amount of longest increasing subsequences: Let $ways_i$ be number of ways to build a prefix of longest increasing subsequence, that ends in $p'_i$. Set $ways_1 = 1$. For each $i$ in order $[1..|p'|]$, $ways_i = \sum\limits_{j < i, p'_{j} + 1 = p'_{i}} ways_j$. This is correct because $p'_{j} + 1 = p'_{i}$ means exactly that the length of longest increasing subsequence ends in $p'_j$ is smaller than the length of longest increasing subsequence ends in $p'_i$ by $1$ (because of previous facts). The answer is $ways_{|p'|}$. The time complexity of this approach is $\mathcal{O}(|p'|^2)$ Let's change this algorithm a bit by changing order we iterate over $i$. We will iterate in order of increasing $p'_{i}$. Since each value appears in $p'$ $\mathcal{O}(n)$ times, when calculating values of $ways_i$ for all $i$, such that $p'_i = x$, we will need to check only $\mathcal{O}(n)$ values of $ways_j$ for $p'_j = x - 1$, and we will never use values of $ways_j$ later, we need only $\mathcal{O}(n)$ memory and $\mathcal{O}(|L| \cdot n^2)$ time. We will store this values in array $w$, where $w_{i, j}$ is a number of ways to end prefix of longest increasing subsequence in value $i$ on the $j$-th increasing/decreasing segment of $p'$. Clearly, $w_{i, j}$ is calculated only from $w_{i - 1, *}$. We can write down transitions between them for each $i$ and see, that we use the same transition for almost all values of $i$ between two "consecutive by value" peaks. There are $\mathcal{O}(n)$ intervals between peaks, and almost all transitions on each of this intervals are the same. We can build matrix $G$ of size $\mathcal{O}(n)$ and use matrix exponentiation for doing this transitions fast. Complexity for each $p'$ is $\mathcal{O}(n^4 \cdot \log|d_{max}|)$. We should be careful, because it will take $\mathcal{O}(n^6 * \log|d_{max}|)$ if we will do it for each $p'$ we find. We should group $p'$-s with the same first element into one group and apply the algorithm above for each of the groups. Note, that there can be many groups, but total size (in segments) of all $p'$-s doesn't exceed $n$. It gives the total time complexity $\mathcal{O}(n^4 \cdot \log|d_{max}|)$. We can further optimize this solution to get time complexity $\mathcal{O}(n^3 \cdot \log|d_{max}|)$. Obiviously, we can through out all from matrix all rows and collumns with zeroes. After this, we can show that the matrix will be of the following form: $1$ $1$ $1$ $1$ $1$ $0$ $0$ $1$ $1$ $1$ $0$ $0$ $1$ $1$ $1$ $0$ $0$ $0$ $0$ $1$ $0$ $0$ $0$ $0$ $1$ It happends because ones on the main diagonal correspond to increasing subsegments (between two peaks), and zeroes correspond to decreasing subsegments. Obiviously, we cannot move backwards, so all elements below main diagonal are zeroes. And since this matrix corresponds to placing $x+1$ after $x$ in longest increasing subsequence, all elements above main diagonal are ones (all subsegments contains both $x$ and $x+1$). Matrix exponentiation of this matrix can be done in $\mathcal{O}(n^2 \cdot \log|d_{max}|)$, because we will care only about distance between $i$-th and $j$-th subsegments and parities of $i$ and $j$. There are many tricky cases in this problem, such as: Handling zeroes and same sign elements in a row while building $peaks$. If all $d_i$ are not positive, longest increasing subsequence will have length $1$ (last element = first element), so it don't have to begin in one of peaks and end in one of peaks. Even though all $d_i$ can be stored in $int$, first answer can be up to $5 \cdot 10^{10} + 1$. Also, degree in matrix exponentiation can don't fit in $int$. There can be many groups of $p'$-s. Algorithm without compessing $p'$-s in groups can work $\mathcal{O}(n^6 \cdot \log|d_{max}|)$ in the worst case.
[ "dp", "math", "matrices" ]
3,000
#include <bits/stdc++.h> const long long MOD = 998244353; using namespace std; typedef long long ll; vector<ll> binpow(int len, ll deg) { if (deg == 1) return vector<ll>(len, 1); vector<ll> part = binpow(len, deg / 2); vector<ll> whole(len); auto D = [&](int i, int j){ assert(i <= j); if (i % 2 == 0) return part[j - i]; return j - i - 1 >= 0 ? part[j - i - 1] : 0; }; for (int j = 0; j < len; j++) { for (int i = 0; i <= j; i++) { whole[j] = (whole[j] + D(0, i) * D(i, j)) % MOD; } } if (deg % 2 == 1) { vector<ll> whole2(len); for (int j = 0; j < len; j++) { for (int i = 0; i <= j; i++) { whole2[j] = (whole2[j] + (i != j || j % 2 == 0 ? whole[i] : 0)) % MOD; } } return whole2; } return whole; } void simple_transition(vector<ll> &dp, vector<long long> &L, vector<long long> &R, vector<long long> &fl, long long z) { vector<ll> dp2(dp.size()); for (int i = 0; i < dp.size(); i++) { for (int j = 0; j < i + (fl[i] == 1); j++) { if (L[i] <= z && z <= R[i] && L[j] <= z - 1 && z - 1 <= R[j]) { dp2[i] = (dp2[i] + dp[j]) % MOD; } } } dp = dp2; } long long calls = 0; long long solve(vector<long long> b) { calls += b.size() - 1; vector<long long> c = b; sort(c.begin(), c.end()); int sz = b.size() - 1; vector<long long> L(sz); vector<long long> R(sz); vector<long long> fl(sz, 1); for (int i = 0; i + 1 < b.size(); i++) { L[i] = b[i]; R[i] = b[i + 1]; if (i != 0) { if (L[i] < R[i]) L[i]++; else L[i]--; } if (L[i] > R[i]) swap(L[i], R[i]), fl[i] = -1; } vector<ll> dp(sz); long long fr = c[0], to = c.back(); for (int i = 0; i < sz; i++) { if (L[i] <= fr && fr <= R[i]) { dp[i] = 1; } } long long lst = fr; for (auto p : c) { long long z = p - 2; if (lst < z) { long long d = z - lst; vector<int> act(sz); for (int i = 0; i < sz; i++) { for (int j = 0; j < i + (fl[i] == 1); j++) { if (L[i] <= z && z <= R[i] && L[j] <= z && z <= R[j]) { act[i] = 1; act[j] = 1; } } } int cnt = 0; vector<int> link(sz); for (int i = 0; i < sz; i++) if (act[i]) link[i] = cnt++; vector<ll> fast = binpow(cnt, d); vector<ll> dp2(sz); auto D = [&](int i, int j){ if (i % 2 == 0) return fast[j - i]; return (j - i - 1 >= 0 ? fast[j - i - 1] : 0); }; for (int i = 0; i < sz; i++) { for (int j = 0; j <= i; j++) { dp2[i] = (dp2[i] + dp[j] * D(link[j], link[i])) % MOD; } } dp = dp2; lst = z; } z = p - 1; if (lst < z) { simple_transition(dp, L, R, fl, z); lst = z; } z = p; if (lst < z) { simple_transition(dp, L, R, fl, z); lst = z; } z = p + 1; if (z <= to && lst < z) { simple_transition(dp, L, R, fl, z); lst = z; } } long long res = 0; for (int i = 0; i < sz; i++) { if (L[i] <= to && to <= R[i]) { res = (res + dp[i]) % MOD; } } return res; } int sign(long long x) { if (x > 0) return 1; if (x < 0) return -1; return 0; } int main() { int n = 300; cin >> n; long long x = 0; cin >> x; vector<long long> a; for (int i = 0; i < n; i++) { if (i % 2 == 0) x = 1000000000; else x = -999000000 - i; cin >> x; if (x != 0) { if (a.size() && sign(a.back()) == sign(x)) { a[a.size() - 1] += x; } else { a.push_back(x); } } } vector<long long> peaks; peaks.push_back(1); n = a.size(); for (int i = 0; i < n; i++) { peaks.push_back(a[i] + peaks.back()); } n++; long long max_len = 1; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (peaks[i] < peaks[j]) max_len = max(max_len, peaks[j] - peaks[i] + 1); } } if (max_len == 1) { long long ans = 1; cout << 1 << " "; for (int i = 0; i < a.size(); i++) { ans = (ans + abs(a[i])) % MOD; } cout << ans << endl; return 0; } cout << max_len << " "; long long ans = 0; int i = 0; while (i < n) { int id = -1; for (int j = i + 1; j < n; j++) { if (peaks[j] - peaks[i] + 1 == max_len) { id = j; } } if (id == -1) { i++; continue; } vector<long long> b; for (int k = i; k <= id; k++) { b.push_back(peaks[k]); } i = id; ans = (ans + solve(b)) % MOD; } //cerr << tot << endl; cout << ans << endl; //cout << calls << endl; }
1475
A
Odd Divisor
You are given an integer $n$. Check if $n$ has an \textbf{odd} divisor, greater than one (does there exist such a number $x$ ($x > 1$) that $n$ is divisible by $x$ and $x$ is odd). For example, if $n=6$, then there is $x=3$. If $n=4$, then such a number does not exist.
If the number $x$ has an odd divisor, then it has an odd prime divisor. To understand this fact, we can consider what happens when multiplying even and odd numbers: even $*$ even $=$ even; even $*$ odd $=$ even; odd $*$ even $=$ even; odd $*$ odd $=$ odd. There is only one even prime number - $2$. So, if a number has no odd divisors, then it must be a power of two. To check this fact, for example, you can divide $n$ by $2$ as long as it is divisible. If at the end we got $1$, then $n$ - the power of two. Bonus: You can also use the following condition to check: $n \& (n-1) = 0$
[ "math", "number theory" ]
900
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; void solve() { ll n; cin >> n; if (n & (n - 1)) { cout << "YES\n"; } else { cout << "NO\n"; } } int main() { int t; cin >> t; while (t--) { solve(); } }
1475
B
New Year's Number
Polycarp remembered the $2020$-th year, and he is happy with the arrival of the new $2021$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $n$ as the sum of a certain number of $2020$ and a certain number of $2021$. For example, if: - $n=4041$, then the number $n$ can be represented as the sum $2020 + 2021$; - $n=4042$, then the number $n$ can be represented as the sum $2021 + 2021$; - $n=8081$, then the number $n$ can be represented as the sum $2020 + 2020 + 2020 + 2021$; - $n=8079$, then the number $n$ cannot be represented as the sum of the numbers $2020$ and $2021$. Help Polycarp to find out whether the number $n$ can be represented as the sum of a certain number of numbers $2020$ and a certain number of numbers $2021$.
Let $x$ - the number of $2020$, $y$ - the number of $2021$ ($x, y \geq 0$). Let us write the required decomposition of the number $n$: $n = 2020 \cdot x + 2021 \cdot y = 2020 \cdot (x + y) + y$ $x = \frac{n - y}{2020} - y$
[ "brute force", "dp", "math" ]
900
#include <bits/stdc++.h> #include <utility> using namespace std; using pii = pair<int, int>; int main() { int test; cin >> test; while (test-- > 0) { int n; cin >> n; int cnt2021 = n % 2020; int cnt2020 = (n - cnt2021) / 2020 - cnt2021; if (cnt2020 >= 0 && 2020 * cnt2020 + 2021 * cnt2021 == n) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; }
1475
C
Ball in Berland
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, $a$ boys and $b$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know $k$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if $a=3$, $b=4$, $k=4$ and the couples $(1, 2)$, $(1, 3)$, $(2, 2)$, $(3, 4)$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): - $(1, 3)$ and $(2, 2)$; - $(3, 4)$ and $(1, 3)$; But the following combinations are not possible: - $(1, 3)$ and $(1, 2)$ — the first boy enters two pairs; - $(1, 2)$ and $(2, 2)$ — the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.
We can think that it is given a bipartite graph. Boys and girls are the vertices of the graph. If a boy and a girl are ready to dance together, then an edge is drawn between them. In this graph, you need to select two edges that do not intersect at the vertices. Let $deg(x)$ - the number of edges included in the vertex $x$. Iterate over the first edge - ($a, b$). It will block $deg(a)+deg(b)-1$ of other edges (all adjacent to vertex $a$, to vertex $b$, but the edge ($a, b$) will be blocked twice. All non-blocked edges do not intersect with ($a, b$) at the vertices. So you can add $k-deg(a)-deg(b)+1$ to the answer.
[ "combinatorics", "graphs", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; void solve() { int A, B, k; cin >> A >> B >> k; vector<int> a(A), b(B); vector<pair<int, int>> edges(k); for (auto &[x, y] : edges) { cin >> x; } for (auto &[x, y] : edges) { cin >> y; } for (auto &[x, y] : edges) { x--; y--; a[x]++; b[y]++; } ll ans = 0; for (auto &[x, y] : edges) { ans += k - a[x] - b[y] + 1; } cout << ans / 2 << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
1475
D
Cleaning the Phone
Polycarp often uses his smartphone. He has already installed $n$ applications on it. Application with number $i$ takes up $a_i$ units of memory. Polycarp wants to free at least $m$ units of memory (by removing some applications). Of course, some applications are more important to Polycarp than others. He came up with the following scoring system — he assigned an integer $b_i$ to each application: - $b_i = 1$ — regular application; - $b_i = 2$ — important application. According to this rating system, his phone has $b_1 + b_2 + \ldots + b_n$ convenience points. Polycarp believes that if he removes applications with numbers $i_1, i_2, \ldots, i_k$, then he will free $a_{i_1} + a_{i_2} + \ldots + a_{i_k}$ units of memory and lose $b_{i_1} + b_{i_2} + \ldots + b_{i_k}$ convenience points. For example, if $n=5$, $m=7$, $a=[5, 3, 2, 1, 4]$, $b=[2, 1, 1, 2, 1]$, then Polycarp can uninstall the following application sets (not all options are listed below): - applications with numbers $1, 4$ and $5$. In this case, it will free $a_1+a_4+a_5=10$ units of memory and lose $b_1+b_4+b_5=5$ convenience points; - applications with numbers $1$ and $3$. In this case, it will free $a_1+a_3=7$ units of memory and lose $b_1+b_3=3$ convenience points. - applications with numbers $2$ and $5$. In this case, it will free $a_2+a_5=7$ memory units and lose $b_2+b_5=2$ convenience points. Help Polycarp, choose a set of applications, such that if removing them will free at least $m$ units of memory and lose the minimum number of convenience points, or indicate that such a set does not exist.
Let's say we remove $x$ applications with $b_i=1$ and $y$ applications with $b_i=2$. Obviously, among all the applications with $b_i=1$, it was necessary to take $x$ maximum in memory (so we will clear the most memory). Let's split all the applications into two arrays with $b_i=1$ and $b_i=2$ and sort them. Then you need to take a prefix from each array. Let's iterate over which prefix we take from the first array. For it, we can uniquely find the second prefix (we remove applications until the sum exceeds $m$). If we now increase the first prefix by taking a new application, then we don't need to take any applications in the second array. This means that when the first prefix is increased, the second one can only decrease. To solve the problem, you can use the two-pointer method.
[ "binary search", "dp", "sortings", "two pointers" ]
1,800
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; void solve() { int n, m; cin >> n >> m; vector<int> a, b; vector<int> v(n); for (int &e : v) { cin >> e; } for (int &e : v) { int x; cin >> x; if (x == 1) { a.push_back(e); } else { b.push_back(e); } } sort(a.rbegin(), a.rend()); sort(b.rbegin(), b.rend()); ll curSumA = 0; int r = (int)b.size(); ll curSumB = accumulate(b.begin(), b.end(), 0ll); int ans = INT_MAX; for (int l = 0; l <= a.size(); l++) { while (r > 0 && curSumA + curSumB - b[r - 1] >= m) { r--; curSumB -= b[r]; } if (curSumB + curSumA >= m) { ans = min(ans, 2 * r + l); } if (l != a.size()) { curSumA += a[l]; } } cout << (ans == INT_MAX ? -1 : ans) << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
1475
E
Advertising Agency
Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of $n$ different bloggers. Blogger numbered $i$ has $a_i$ followers. Since Masha has a limited budget, she can only sign a contract with $k$ different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select $k$ bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if $n=4$, $k=3$, $a=[1, 3, 1, 2]$, then Masha has two ways to select $3$ bloggers with the maximum total number of followers: - conclude contracts with bloggers with numbers $1$, $2$ and $4$. In this case, the number of followers will be equal to $a_1 + a_2 + a_4 = 6$. - conclude contracts with bloggers with numbers $2$, $3$ and $4$. In this case, the number of followers will be equal to $a_2 + a_3 + a_4 = 6$. Since the answer can be quite large, \textbf{output it modulo $10^9+7$}.
It is obvious that Masha will enter into agreements only with bloggers that have the most subscribers. You can sort all the bloggers and greedily select the prefix. Let $x$ - be the minimum number of subscribers for the hired blogger. Then we must hire all the bloggers who have more subscribers. Let $m$ - the number of bloggers who have more than $x$ subscribers, $cnt[x]$ - the number of bloggers who have exactly $x$ subscribers. Then we should select $k-m$ bloggers from $cnt[x]$. The number of ways to do this is equal to the binomial coefficient of $cnt[x]$ by $k-m$. You could calculate it by searching for the inverse element modulo. Then you could calculate the factorials and use the equality $\binom n k = \frac{n!}{k! \cdot (n-k)!}$. Alternatively, you can use the equation $\binom n k = \binom {n-1} {k} + \binom {n-1} {k-1}$ and calculate it using dynamic programming. This method is better known as the Pascal triangle.
[ "combinatorics", "math", "sortings" ]
1,600
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; int mod = 1e9 + 7; int fast_pow(int a, int p) { int res = 1; while (p) { if (p % 2 == 0) { a = a * 1ll * a % mod; p /= 2; } else { res = res * 1ll * a % mod; p--; } } return res; } int fact(int n) { int res = 1; for (int i = 1; i <= n; i++) { res = res * 1ll * i % mod; } return res; } int C(int n, int k) { return fact(n) * 1ll * fast_pow(fact(k), mod - 2) % mod * 1ll * fast_pow(fact(n - k), mod - 2) % mod; } void solve() { int n, k; cin >> n >> k; vector<int> cnt(n + 1); for (int i = 0; i < n; i++) { int x; cin >> x; cnt[x]++; } for (int i = n; i >= 0; i--) { if (cnt[i] >= k) { cout << C(cnt[i], k) << "\n"; return; } else { k -= cnt[i]; } } cout << 1; } int main() { int t; cin >> t; while (t--) { solve(); } }
1475
F
Unusual Matrix
You are given two binary square matrices $a$ and $b$ of size $n \times n$. A matrix is called binary if each of its elements is equal to $0$ or $1$. You can do the following operations on the matrix $a$ \textbf{arbitrary} number of times (0 or more): - vertical xor. You choose the number $j$ ($1 \le j \le n$) and for all $i$ ($1 \le i \le n$) do the following: $a_{i, j} := a_{i, j} \oplus 1$ ($\oplus$ — is the operation xor (exclusive or)). - horizontal xor. You choose the number $i$ ($1 \le i \le n$) and for all $j$ ($1 \le j \le n$) do the following: $a_{i, j} := a_{i, j} \oplus 1$. Note that the elements of the $a$ matrix change after each operation. For example, if $n=3$ and the matrix $a$ is: $$ \begin{pmatrix} 1 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 0 \end{pmatrix} $$ Then the following sequence of operations shows an example of transformations: - vertical xor, $j=1$. $$ a= \begin{pmatrix} 0 & 1 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix} $$ - horizontal xor, $i=2$. $$ a= \begin{pmatrix} 0 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 0 \end{pmatrix} $$ - vertical xor, $j=2$. $$ a= \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} $$ Check if there is a sequence of operations such that the matrix $a$ becomes equal to the matrix $b$.
It is clear that the order of operations does not affect the final result, also it makes no sense to apply the same operation more than once (by the property of the xor operation). Let's construct a sequence of operations that will reduce the matrix $a$ to the matrix $b$ (if the answer exists). Let's try iterate over: will we use the operation "horizontal xor". Now, by the each element of the first line ($a_{1,j}$), we can understand whether it is necessary to apply the operation "vertical xor" (if $a_{1,j} \ne b_{1,j}$). Let's apply all necessary operations "vertical xor". It remains clear whether it is necessary to apply the operation "horizontal xor" for $i$ ($2 \le i \le n$). Let's look at each element of the first column ($a_{i,1}$) by it you can understand whether it is necessary to apply the operation "horizontal xor" (if $a_{i, 1} \ne b_{i,1}$).
[ "2-sat", "brute force", "constructive algorithms" ]
1,900
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; bool check(vector<vector<int>> a, vector<vector<int>> const &b) { int n = (int) a.size(); for (int j = 0; j < n; j++) { if (a[0][j] != b[0][j]) { for (int i = 0; i < n; i++) { a[i][j] ^= 1; } } } for (int i = 0; i < n; i++) { int need_xor = (a[i][0] ^ b[i][0]); for (int j = 1; j < n; j++) { if (need_xor != (a[i][j] ^ b[i][j])) { return false; } } } return true; } void solve() { int n; cin >> n; vector<vector<int>> a(n, vector<int>(n)); vector<vector<int>> b(n, vector<int>(n)); for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < n; j++) { a[i][j] = s[j] - '0'; } } for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < n; j++) { b[i][j] = s[j] - '0'; } } for (int times = 0; times < 2; times++) { if (check(a, b)) { cout << "YES\n"; return; } for (int j = 0; j < n; j++) { a[0][j] ^= 1; } } cout << "NO\n"; } int main() { int test; cin >> test; while (test-- > 0) { solve(); } return 0; }
1475
G
Strange Beauty
Polycarp found on the street an array $a$ of $n$ elements. Polycarp invented his criterion for the beauty of an array. He calls an array $a$ beautiful if at least one of the following conditions must be met \textbf{for each different pair of indices} $i \ne j$: - $a_i$ is divisible by $a_j$; - or $a_j$ is divisible by $a_i$. For example, if: - $n=5$ and $a=[7, 9, 3, 14, 63]$, then the $a$ array is not beautiful (for $i=4$ and $j=2$, none of the conditions above is met); - $n=3$ and $a=[2, 14, 42]$, then the $a$ array is beautiful; - $n=4$ and $a=[45, 9, 3, 18]$, then the $a$ array is not beautiful (for $i=1$ and $j=4$ none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array $a$ so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array $a$ beautiful.
Let's calculate for each number $x$ how many times it occurs in the array $a$. Let's denote this number as $cnt_x$. Let's use the dynamic programming method. Let $dp(x)$ be equal to the maximum number of numbers not greater than $x$ such that for each pair of them one of the conditions above is satisfied. More formally, if $dp(x) = k$, then there exists numbers $b_1, b_2, \ldots, b_k$ ($b_i \leq x$) from the array $a$ such that for all $i \ne j$ ($1 \leq i, j \leq k$) one of the conditions above is satisfied. Then to calculate $dp(x)$ you can use the following formula: $dp(x) = cnt(x) + \max \limits_{y = 1, x mod y = 0}^{x-1} dp(y)$ Note that to calculate $dp(x)$ you need to go through the list of divisors of $x$. For this, we use the sieve of Eratosthenes.
[ "dp", "math", "number theory", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = (int) 2e5 + 100; int dp[N]; int cnt[N]; void solve() { int n; cin >> n; fill(dp, dp + N, 0); fill(cnt, cnt + N, 0); for (int i = 0; i < n; i++) { int x; cin >> x; cnt[x]++; } for (int i = 1; i < N; i++) { dp[i] += cnt[i]; for (int j = 2 * i; j < N; j += i) { dp[j] = max(dp[j], dp[i]); } } cout << (n - *max_element(dp, dp + N)) << endl; } int main() { int test; cin >> test; while (test-- > 0) { solve(); } return 0; }
1476
A
K-divisible Sum
You are given two integers $n$ and $k$. You should create an array of $n$ \textbf{positive integers} $a_1, a_2, \dots, a_n$ such that the sum $(a_1 + a_2 + \dots + a_n)$ is divisible by $k$ and maximum element in $a$ is minimum possible. What is the minimum possible maximum element in $a$?
Let's denote $s$ as the sum of array $a$. From one side, since $s$ should be divisible by $k$ then we can say $s = cf \cdot k$. From other side, since all $a_i$ are positive, then $s \ge n$. It's quite obvious that the smaller $s$ - the smaller maximum $a_i$ so we need to find the smallest $cf$ that $cf \cdot k \ge n$. Then $cf = \left\lceil \frac{n}{k} \right\rceil = \left\lfloor \frac{n + k - 1}{k} \right\rfloor$. Now we now that $s = cf \cdot k$ and we need to represent it as $a_1 + \dots + a_n$ with maximum $a_i$ minimized. It's easy to prove by contradiction that maximum $a_i \ge \left\lceil \frac{s}{n} \right\rceil$. Moreover we can always construct such array $a$ that its sum is equal to $s$ and the maximum element is equal to $\left\lceil \frac{s}{n} \right\rceil$. As a result, the answer is $\left\lceil \frac{s}{n} \right\rceil = \left\lfloor \frac{cf \cdot k + n - 1}{n} \right\rfloor$, where $cf = \left\lfloor \frac{n + k - 1}{k} \right\rfloor$.
[ "binary search", "constructive algorithms", "greedy", "math" ]
1,000
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { long long n, k; cin >> n >> k; long long cf = (n + k - 1) / k; k *= cf; cout << (k + n - 1) / n << endl; } return 0; }
1476
B
Inflation
You have a statistic of price changes for one product represented as an array of $n$ positive integers $p_0, p_1, \dots, p_{n - 1}$, where $p_0$ is the initial price of the product and $p_i$ is how the price was increased during the $i$-th month. Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $p_i$ to the price at the start of this month $(p_0 + p_1 + \dots + p_{i - 1})$. Your boss said you clearly that the inflation coefficients must not exceed $k$ %, so you decided to \textbf{increase} some values $p_i$ in such a way, that all $p_i$ remain integers and the inflation coefficients for each month don't exceed $k$ %. You know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes. What's the minimum total sum of changes you need to make all inflation coefficients not more than $k$ %?
Suppose we decided to increase some $p_i$ by $x > 0$. How does it affect all inflation coefficients? Let's the $j$-th inflation coefficient be $cf_j$. We now that $cf_j = \frac{p_j}{p_0 + \dots + p_{j - 1}}$. If $j < i$, then $cf_j$ doesn't change. If $j > i$ then it's denominator increases by $x$ and $cf_j$ decreases. If $j = i$ then it's numerator increases and $cf_j$ increases as well. But, if we increase $p_{i - 1}$ instead of $p_i$ then all decreased $cf_j$ will decrease as well and also $cf_i$ will decrease. Finally, if we increase $p_0$ then all $cf_j$ decrease and there is no $cf_j$ that increases - so it's always optimal to increase only $p_0$. Now we need to calculate what is minimum $x$ we should add to $p_0$. There are two ways: we can either binary search this value $x$ knowing that $x = 100 \cdot 10^9$ is always enough. Then we just need to check that all $cf_j \le \frac{k}{100}$ (that is equivalent to checking that $p_j \cdot 100 \le k \cdot (x + p_0 + \dots + p_{j - 1})$). Or we can note that each $cf_j = \frac{p_j}{(p_0 + \dots + p_{j - 1}) + x}$ and we need to make $cf_j \le \frac{k}{100}$ or that $100 \cdot p_j - k \cdot (p_0 + \dots + p_{j - 1}) \le k \cdot x$ or $x \ge \left\lceil \frac{100 \cdot p_j - k \cdot (p_0 + \dots + p_{j - 1})}{k} \right\rceil$. Since we should fulfill all conditions then we should take $x$ as maximum over all fractions. Since $(p_0 + \dots + p_{j - 1})$ is just a prefix sum, we can check condition for each $cf_j$ in $O(1)$. It total, the time complexity is either $O(n)$ or $O(n \log{n})$ per test case.
[ "binary search", "brute force", "greedy", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; typedef long long li; const int INF = int(1e9); int main() { int t; cin >> t; while(t--) { int n, k; cin >> n >> k; vector<int> p(n); for (int i = 0; i < n; i++) cin >> p[i]; li x = 0; li pSum = p[0]; for (int i = 1; i < n; i++) { x = max(x, (100ll * p[i] - k * pSum + k - 1) / k); pSum += p[i]; } cout << x << endl; } return 0; }
1476
C
Longest Simple Cycle
You have $n$ chains, the $i$-th chain consists of $c_i$ vertices. Vertices in each chain are numbered independently from $1$ to $c_i$ along the chain. In other words, the $i$-th chain is the undirected graph with $c_i$ vertices and $(c_i - 1)$ edges connecting the $j$-th and the $(j + 1)$-th vertices for each $1 \le j < c_i$. Now you decided to unite chains in one graph in the following way: - the first chain is skipped; - the $1$-st vertex of the $i$-th chain is connected by an edge with the $a_i$-th vertex of the $(i - 1)$-th chain; - the last ($c_i$-th) vertex of the $i$-th chain is connected by an edge with the $b_i$-th vertex of the $(i - 1)$-th chain. \begin{center} {\small Picture of the first test case. Dotted lines are the edges added during uniting process} \end{center} Calculate the length of the longest simple cycle in the resulting graph. A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.
Suppose, we've built the graph and chosen any simple cycle. Due to the nature of the graph, any simple cycle right part is part of one of the chains. So, let's for each chain calculate the longest simple path with its right part on this chain and denote it as $len_i$. Obviously, $len_1 = 0$. Now, let's look at chain $i$. If we go along the cycle in both ways, we will step to vertices $a_i$ and $b_i$ of the previous chain. If $a_i = b_i$ then we closed cycle and it's the only possible cycle, so $len_i = c_i + 1$. Otherwise, we can either go from $a_i$ and $b_i$ and meet each other closing the cycle with part of the $(i - 1)$-th chain between $a_i$-th and $b_i$-th vertices - this part has $|a_i - b_i|$ edges and our cycle will have length $c_i + 1 + |a_i - b_i|$. But if we decide to go in different ways, then we will meet the first and the last vertices of the $(i - 1)$-th chain. After that, we'll go to the $a_{i - 1}$-th and the $b_{i - 1}$-th vertices of $(i - 2)$-th chain and will make almost the same choice. But, instead of recurrently solving the same problem, we can note that, in fact, we took a cycle that ends at the $(i - 1)$-th chain, erased the part between vertices $a_i$ and $b_i$, and merged it with our $i$-th chain part, so the length of this merged cycle will be equal to $c_i + 1 + len_{i - 1} - |a_i - b_i|$. Since we maximize $len_i$ we just choose, what part: $|a_i - b_i|$ or $len_{i - 1} - |a_i - b_i|$ is longer and take it. As a result, we can iterate from left to right, calculate all $len_i$ and print the maximum among them.
[ "dp", "graphs", "greedy" ]
1,600
#include<bits/stdc++.h> using namespace std; typedef long long li; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> c(n), a(n), b(n); for (int i = 0; i < n; i++) cin >> c[i]; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; li ans = 0; li lstLen = 0; for (int i = 1; i < n; i++) { li curLen = c[i] + 1ll + abs(a[i] - b[i]); if (a[i] != b[i]) curLen = max(curLen, c[i] + 1ll + lstLen - abs(a[i] - b[i])); ans = max(ans, curLen); lstLen = curLen; } cout << ans << endl; } return 0; };
1476
D
Journey
There are $n + 1$ cities, numbered from $0$ to $n$. $n$ roads connect these cities, the $i$-th road connects cities $i - 1$ and $i$ ($i \in [1, n]$). Each road has a direction. The directions are given by a string of $n$ characters such that each character is either L or R. If the $i$-th character is L, it means that the $i$-th road initially goes from the city $i$ to the city $i - 1$; otherwise it goes from the city $i - 1$ to the city $i$. A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler \textbf{must} go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city $i$ to the city $i + 1$, it is possible to travel from $i$ to $i + 1$, but not from $i + 1$ to $i$. After the traveler moves to a neighboring city, \textbf{all} roads change their directions \textbf{to the opposite ones}. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to. The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $i$, calculate the maximum number of different cities the traveler can visit during \textbf{exactly one journey} if they start in the city $i$.
There are two key observations to this problem: after each pair of moves, the directions go back to the original ones; after each move, we can immediately go back (and combining these observations, we can derive that if we go from city $i$ to some other city $j$, we can always go back). One of the solutions we can write using these observations is to build an undirected graph on $2n+2$ vertices. Each vertex represents a pair $(v, k)$, where $v$ is the city we are currently staying in, and $k$ is the number of moves we made, modulo $2$. Since each move is to a neighboring city, each vertex $(v, 0)$ is unreachable from $(v, 1)$, and vice versa. And since we can always go back, and each pair of steps doesn't change the directions, this graph is actually an undirected one. So, we can find the connected components of this graph using DFS/BFS/DSU, and for each city $v$, print the size of the component the vertex $(v, 0)$ belongs to. Another solution is to find the leftmost and the rightmost city reachable from each city. For example, finding the leftmost reachable city can be done with the following dynamic programming: let $dp_i$ be the leftmost city reachable from $i$. Then, if we can't go left from $i$, $dp_i = i$; if we can make only one step to the left from $i$, $dp_i = i - 1$; and if we can make two steps, we can take the answer from the city $i - 2$: $dp_i = dp_{i - 2}$. The same approach can be used to calculate the rightmost reachable city.
[ "dfs and similar", "dp", "dsu", "implementation" ]
1,700
t = int(input()) for _ in range(t): n = int(input()) s = input() dpl = [i for i in range(n + 1)] dpr = [i for i in range(n + 1)] for i in range(n + 1): if i == 0 or s[i - 1] == 'R': dpl[i] = i elif i == 1 or s[i - 2] == 'L': dpl[i] = i - 1 else: dpl[i] = dpl[i - 2] for i in range(n, -1, -1): if i == n or s[i] == 'L': dpr[i] = i elif i == n - 1 or s[i + 1] == 'R': dpr[i] = i + 1 else: dpr[i] = dpr[i + 2] ans = [(dpr[i] - dpl[i]) + 1 for i in range(n + 1)] print(*ans)
1476
E
Pattern Matching
You are given $n$ patterns $p_1, p_2, \dots, p_n$ and $m$ strings $s_1, s_2, \dots, s_m$. Each pattern $p_i$ consists of $k$ characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string $s_j$ consists of $k$ lowercase Latin letters. A string $a$ matches a pattern $b$ if for each $i$ from $1$ to $k$ either $b_i$ is a wildcard character or $b_i=a_i$. You are asked to rearrange the patterns in such a way that the first pattern the $j$-th string matches is $p[mt_j]$. You are allowed to leave the order of the patterns unchanged. Can you perform such a rearrangement? If you can, then print any valid order.
Let's write down the indices of the pattern that the $j$-th string matches. If $mt_j$ is not among these, then the answer is NO. Otherwise, all the patterns except $mt_j$ should go in the resulting ordering after $mt_j$. Consider that as a graph. Let's add an edge from $mt_j$ to each of the matches. If you add the edges for all the strings, then the topological ordering of the graph will give you the valid result. If the graph has any cycles in it (you can't topsort it), then there is no answer. To find all the patterns we can use the fact that $k$ is rather small. Consider all the $2^k$ binary masks of length $k$. Each mask can correspond to a set of positions in the string that are replaced with wildcards. Now, if there is a pattern that is exactly equal to the string with the fixed set of positions replaced by wildcards, then that pattern is a match. To search for an exact match, you can either store all patterns in a map beforehand (or in a sorted array) or build a trie of them. The second version is faster by a factor of $\log n$ but both solutions should pass easily. Overall complexity: $O(nk \log n + mk \cdot 2^k \log n)$ or $O(nk + m \cdot 2^k)$.
[ "bitmasks", "data structures", "dfs and similar", "graphs", "hashing", "sortings", "strings" ]
2,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct pattern{ string s; int i; }; bool operator <(const pattern &a, const pattern &b){ return a.s < b.s; } vector<vector<int>> g; vector<int> used, ord; bool cyc; void ts(int v){ used[v] = 1; for (int u : g[v]){ if (used[u] == 0) ts(u); else if (used[u] == 1) cyc = true; if (cyc) return; } used[v] = 2; ord.push_back(v); } struct node{ int nxt[28]; int term; node(){ memset(nxt, -1, sizeof(nxt)); term = -1; } }; vector<node> trie; void add(const string &s, int i){ int cur = 0; for (char c : s){ int x = c - '_'; if (trie[cur].nxt[x] == -1){ trie[cur].nxt[x] = trie.size(); trie.push_back(node()); } cur = trie[cur].nxt[x]; } trie[cur].term = i; } bool check(int i, int v, const string &s, int mt){ if (i == int(s.size())){ assert(trie[v].term != -1); if (trie[v].term != mt) g[mt].push_back(trie[v].term); else return true; return false; } bool res = false; if (trie[v].nxt[s[i] - '_'] != -1 && check(i + 1, trie[v].nxt[s[i] - '_'], s, mt)) res = true; if (trie[v].nxt[0] != -1 && check(i + 1, trie[v].nxt[0], s, mt)) res = true; return res; } int main() { cin.tie(0); ios_base::sync_with_stdio(false); trie = vector<node>(1); int n, m, k; cin >> n >> m >> k; g.assign(n, vector<int>()); forn(i, n){ string cur; cin >> cur; add(cur, i); } pattern nw; nw.s = string(k, '_'); forn(i, m){ string cur; int mt; cin >> cur >> mt; if (!check(0, 0, cur, mt - 1)){ cout << "NO\n"; return 0; } } used.assign(n, 0); cyc = false; ord.clear(); forn(i, n) if (!used[i]){ ts(i); if (cyc){ cout << "NO\n"; return 0; } } reverse(ord.begin(), ord.end()); cout << "YES\n"; forn(i, n) cout << ord[i] + 1 << " "; cout << "\n"; return 0; }
1476
F
Lanterns
There are $n$ lanterns in a row. The lantern $i$ is placed in position $i$ and has power equal to $p_i$. Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the $i$-th lantern is turned to the left, it illuminates all such lanterns $j$ that $j \in [i - p_i, i - 1]$. Similarly, if it is turned to the right, it illuminates all such lanterns $j$ that $j \in [i + 1, i + p_i]$. Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.
The main idea of the solution is to calculate the following dynamic programming: $dp_i$ is the maximum prefix we can fully cover with $i$ first lanterns. Let's look at how can we solve it in $O(n^2)$ with this kind of dynamic programming. First of all, let's write it forward. Which transitions from $dp_i$ do we have? iterate on the lantern facing left that will cover the lantern $dp_i + 1$. Let this lantern be $j$. It should cover all lanterns in $[dp_i + 1, j - 1]$, so all lanterns from $[i, j)$ can be turned to the right (and we need a max query to determine the new covered prefix); if $dp_i > i$ (lantern $i$ is already covered), we can just extend the prefix by turning the $i$-th lantern to the right. Note that turning it to the right when it is not covered yet will be modeled by the first transition. It is obviously $O(n^2)$, how can we optimize it? Let's write this dynamic programming backward. The second transition is changed to backward dp easily, what about the first one? Suppose we want to turn some lantern $i$ to the left. Let's iterate on the prefix $j$ that we will "connect" to it; for this prefix, $dp_j$ should be at least $i - p_i - 1$, and we update $dp_i$ with the maximum of $i - 1$ (since it is covered by lantern $i$) and the result of max query on $[j + 1, i - 1]$. In fact, we need only one such prefix - the one with the minimum $j$ among those which have $dp_j \ge i - p_i - 1$. So, we build a minimum segment tree where each pair $(i, dp_i)$ is interpreted as the value of $i$ in position $dp_i$, and with min query on the suffix from $i - p_i - 1$ we find this optimal prefix, from which we should update (and to update, we can use any DS that allows max queries on segment - in my solution, it's another segment tree).
[ "binary search", "data structures", "dp" ]
3,000
#include<bits/stdc++.h> using namespace std; const int INF = int(1e9); struct segTree { int n; bool mx; vector<int> t; void fix(int v) { t[v] = (mx ? max(t[v * 2 + 1], t[v * 2 + 2]) : min(t[v * 2 + 1], t[v * 2 + 2])); } void build(int v, int l, int r) { if(l == r - 1) t[v] = (mx ? -INF : INF); else { int m = (l + r) / 2; build(v * 2 + 1, l, m); build(v * 2 + 2, m, r); fix(v); } } void upd(int v, int l, int r, int pos, int val) { if(l == r - 1) t[v] = (mx ? max(t[v], val) : min(t[v], val)); else { int m = (l + r) / 2; if(pos < m) upd(v * 2 + 1, l, m, pos, val); else upd(v * 2 + 2, m, r, pos, val); fix(v); } } int get(int v, int l, int r, int L, int R) { if(L >= R) return (mx ? -INF : INF); if(l == L && r == R) return t[v]; int m = (l + r) / 2; int lf = get(v * 2 + 1, l, m, L, min(R, m)); int rg = get(v * 2 + 2, m, r, max(m, L), R); return (mx ? max(lf, rg) : min(lf, rg)); } void upd(int pos, int val) { upd(0, 0, n, pos, val); } int get(int L, int R) { return get(0, 0, n, L, R); } void build() { return build(0, 0, n); } segTree() {}; segTree(int n, bool mx) : n(n), mx(mx) { t.resize(4 * n); } }; int main() { int t; scanf("%d", &t); for(int _ = 0; _ < t; _++) { int n; scanf("%d", &n); vector<int> p(n); for(int i = 0; i < n; i++) scanf("%d", &p[i]); vector<int> dp(n + 1, -INF); vector<int> par(n + 1, -2); dp[0] = 0; par[0] = -1; vector<int> lf(n), rg(n); for(int i = 0; i < n; i++) { lf[i] = max(1, i - p[i] + 1); rg[i] = min(n, i + p[i] + 1); } segTree sn(n + 1, false); segTree sx(n, true); sn.build(); sx.build(); for(int i = 0; i < n; i++) sx.upd(i, rg[i]); sn.upd(0, 0); for(int i = 1; i <= n; i++) { int j = i - 1; int k = lf[j] - 1; int m = sn.get(k, n + 1); if(m != INF) { int nval = max(sx.get(m, i - 1), i - 1); if(nval > dp[i]) { dp[i] = nval; par[i] = m; } } if(dp[j] >= i && max(dp[j], rg[j]) > dp[i]) { dp[i] = max(dp[j], rg[j]); par[i] = -1; } if(dp[j] > dp[i]) { dp[i] = dp[j]; par[i] = -1; } sn.upd(dp[i], i); } if(dp[n] != n) puts("NO"); else { puts("YES"); string ans; int cur = n; while(cur != 0) { if(par[cur] == -1) { cur--; ans += "R"; } else { int pcur = par[cur]; int diff = cur - pcur; ans += "L"; for(int j = 0; j < diff - 1; j++) ans += "R"; cur = pcur; } } reverse(ans.begin(), ans.end()); puts(ans.c_str()); } } }
1476
G
Minimum Difference
You are given an integer array $a$ of size $n$. You have to perform $m$ queries. Each query has one of two types: - "$1$ $l$ $r$ $k$" — calculate the minimum value $dif$ such that there are exist $k$ \textbf{distinct} integers $x_1, x_2, \dots, x_k$ such that $cnt_i > 0$ (for every $i \in [1, k]$) and $|cnt_i - cnt_j| \le dif$ (for every $i \in [1, k], j \in [1, k]$), where $cnt_i$ is the number of occurrences of $x_i$ in the subarray $a[l..r]$. If it is impossible to choose $k$ integers, report it; - "$2$ $p$ $x$" — assign $a_{p} := x$.
Let's consider a problem without queries of the second type. Now we can try to solve the problem using Mo's algorithm. Let's maintain array $cnt_i$ - the number of occurrences of $i$ on the current segment and array $ord$ - array $cnt$ sorted in descending order. Let's take a look at how we should handle adding an element equal to $x$. Surely, we should increase $cnt_x$ by $1$, but now we should erase an element equal to $cnt_x-1$ from the array $ord$ and insert an element $cnt_x$ is such a way that the array is still sorted. Instead, we can increase the leftmost element equal to $cnt_x-1$ by $1$. Similarly, we can handle deleting an element (decrease the rightmost element equal to $cnt_x$ by $1$). In order to quickly find the leftmost (rightmost) element equal to $x$, we can store the left and the right bounds of the array $ord$ where all the numbers are equal to $x$. To answer the query of type $1$, we should find two elements in the $ord$ array at distance $k$ whose absolute difference is minimal. Since the size of the array $ord$ (without zero elements) is $O(n)$, we can't look at the whole array. But using the fact that there are no more than $O(\sqrt{n})$ different values in the $ord$ array, we can create an auxiliary array of pairs $(value, cnt)$ (the value from the array $ord$ and the number of occurrences of that value). In such an array, we need to find a subarray where the sum of the second elements in the pairs is at least $k$, and the absolute difference between the first elements in the pairs is minimal. That can be solved using standard two pointers method in $O(\sqrt{n})$. The total complexity of the solution is $O(n\sqrt{n})$. In fact, we can use Mo's algorithm even with updates. But its complexity is $O(n^{\frac{5}{3}} + m\sqrt{n})$. You can read the editorial of the problem 940F on Codeforces or the following blog to learn about processing updates in Mo: https://codeforces.com/blog/entry/72690
[ "data structures", "hashing", "sortings", "two pointers" ]
3,100
#include <bits/stdc++.h> using namespace std; #define x first #define y second #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) typedef pair<int, int> pt; const int N = 100 * 1000 + 13; const int P = 2000; struct query { int t, l, r, k, i; }; int main() { int n, m; scanf("%d%d", &n, &m); vector<int> a(n); forn(i, n) scanf("%d", &a[i]); vector<query> q; vector<array<int, 3>> upd; forn(i, m) { int tp; scanf("%d", &tp); if (tp == 1) { int l, r, k; scanf("%d%d%d", &l, &r, &k); q.push_back({sz(upd), l - 1, r - 1, k, sz(q)}); } else { int p, x; scanf("%d%d", &p, &x); --p; upd.push_back({p, a[p], x}); a[p] = x; } } sort(q.begin(), q.end(), [](const query &a, const query &b) { if (a.t / P != b.t / P) return a.t < b.t; if (a.l / P != b.l / P) return a.l < b.l; if ((a.l / P) & 1) return a.r < b.r; return a.r > b.r; }); for (int i = sz(upd) - 1; i >= 0; --i) a[upd[i][0]] = upd[i][1]; vector<int> cnt(N), ord(N); vector<pt> bounds(N, {N, 0}); bounds[0] = {0, N - 1}; int L = 0, R = -1, T = 0; auto add = [&](int x) { int c = cnt[x]; ++ord[bounds[c].x]; bounds[c + 1].y = bounds[c].x; if (bounds[c + 1].x == N) bounds[c + 1].x = bounds[c].x; if (bounds[c].x == bounds[c].y) bounds[c].x = N - 1; ++bounds[c].x; ++cnt[x]; }; auto rem = [&](int x) { int c = cnt[x]; --ord[bounds[c].y]; if (bounds[c - 1].x == N) bounds[c - 1].y = bounds[c].y; bounds[c - 1].x = bounds[c].y; if (bounds[c].x == bounds[c].y) bounds[c].x = N; --bounds[c].y; --cnt[x]; }; auto apply = [&](int i, int fl) { int p = upd[i][0]; int x = upd[i][fl + 1]; if (L <= p && p <= R) { rem(a[p]); add(x); } a[p] = x; }; vector<int> ans(sz(q)); for (auto qr : q) { int t = qr.t, l = qr.l, r = qr.r, k = qr.k; while (T < t) apply(T++, 1); while (T > t) apply(--T, 0); while (R < r) add(a[++R]); while (L > l) add(a[--L]); while (R > r) rem(a[R--]); while (L < l) rem(a[L++]); int res = N; for (int i = 0, j = 0, sum = 0; i < N && ord[i] > 0; i = bounds[ord[i]].y + 1) { while (j < N && ord[j] > 0 && sum < k) { sum += bounds[ord[j]].y - bounds[ord[j]].x + 1; j = bounds[ord[j]].y + 1; } if (sum >= k) res = min(res, ord[i] - ord[j - 1]); sum -= bounds[ord[i]].y - bounds[ord[i]].x + 1; } if (res == N) res = -1; ans[qr.i] = res; } for (int x : ans) printf("%d\n", x); }
1477
A
Nezzar and Board
$n$ \textbf{distinct} integers $x_1,x_2,\ldots,x_n$ are written on the board. Nezzar can perform the following operation multiple times. - Select two integers $x,y$ (not necessarily distinct) on the board, and write down $2x-y$. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite number $k$ on the board after applying above operation multiple times.
Let's first assume that $x_1=0$ (Otherwise, we could subtract $x_1$ for $x_1,x_2,\ldots,x_n$ and $k$). We will now prove that the answer is "YES" if and only if $k$ can be divided by $g=\gcd(x_2,x_3,\ldots,x_n)$. One direction is straightforward. Note that any number written on the board should be divisible by $g$, which follows from the fact that $g|x, g|y \implies g|2x-y$. It only remains to prove that for any $x$ divisible by $g$, we could write down $x$ on the board. We will prove it by induction on $n$. Base case ($n=2$) is obvious. Let $g_0=\gcd(x_2,x_3,\ldots,x_{n-1})$. By Bézout's Theorem, there exists integers $s,t$ such that $g_0 s-x_n t = g$. By induction, we could write down $g_0$ on the board, and trivially $x_n t$ can be written on the board. Therefore, we could write down $g$ applying operation recursively.
[ "constructive algorithms", "math", "number theory" ]
1,800
#include<bits/stdc++.h> #define int long long using namespace std; const int maxn=200007; int t; int n,k; int x[maxn]; signed main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>t; while (t--){ cin>>n>>k; for (int i=0;i<n;++i) cin>>x[i]; sort(x,x+n); int g=0; for (int i=1;i<n;++i){ g=__gcd(g,x[i]-x[0]); } if ((k-x[0])%g) cout<<"NO\n"; else cout<<"YES\n"; } return 0; }
1477
B
Nezzar and Binary String
Nezzar has a binary string $s$ of length $n$ that he wants to share with his best friend, Nanako. Nanako will spend $q$ days inspecting the binary string. At the same time, Nezzar wants to change the string $s$ into string $f$ during these $q$ days, because it looks better. It is known that Nanako loves consistency so much. On the $i$-th day, Nanako will inspect a segment of string $s$ from position $l_i$ to position $r_i$ inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string. After this inspection, at the $i$-th night, Nezzar can secretly change \textbf{strictly less} than half of the characters in the segment from $l_i$ to $r_i$ inclusive, otherwise the change will be too obvious. Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string $f$ at the end of these $q$ days and nights.
The operations can be described backward: Iterate days in reverse order and start with $f$. In $i$-th day, if there is a strict majority of $0$s or $1$s between $l_i$ and $r_i$, change ALL element inside the range to be the majority. Otherwise, declare that the operation failed. We can see that the "backward" operation is deterministic, so we can compute the source string from destination string alone and check if the source string computed equal to $s$. To simulate the operations, We need to support two kind of operations: range query on sum, and range assignment Which can be simulated using e.g. lazy segment tree. Time complexity: $O((q + n) \log{n})$
[ "data structures", "greedy" ]
1,900
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for (int i=0;i<(int)(n);++i) #define rep1(i,n) for (int i=1;i<=(int)(n);++i) #define range(x) begin(x), end(x) #define sz(x) (int)(x).size() #define pb push_back #define F first #define S second typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; const int maxn=200007; set<int> seg; // segment: [seg[i],seg[i+1]) int n,q,t,prv; int l[maxn],r[maxn]; bool val[maxn]; string s; int main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>t; while (t--){ cin>>n>>q; cin>>s; rep(i,q) cin>>l[i]>>r[i], l[i]--; reverse(l,l+q), reverse(r,r+q); seg.clear(); rep(i,n) seg.insert(i), val[i]=s[i]-'0'; seg.insert(n); auto add=[&](int u){ if (seg.find(u)==seg.end()){ auto ret=*prev(seg.upper_bound(u)); val[u]=val[ret]; seg.insert(u); } }; rep(i,q){ add(l[i]), add(r[i]); vi remv; remv.clear(); int sum[2]; memset(sum,0,sizeof(sum)); auto iter=seg.find(l[i]); while (1){ if (*iter==r[i]) break; int prev=*iter; iter=next(iter); if (*iter<r[i]) remv.pb(*iter); sum[val[prev]]+=*iter-prev; } if (sum[0]==sum[1]){ cout<<"-\n"; goto cont; } if (sum[0]<sum[1]) val[l[i]]=1; else val[l[i]]=0; for (auto c:remv) seg.erase(c); } prv=0; for (auto c:seg){ if (!c) continue; for (int i=prv;i<c;++i) cout<<val[prv]; prv=c; } cout<<"\n"; cont:; } }
1477
C
Nezzar and Nice Beatmap
Nezzar loves the game osu!. osu! is played on beatmaps, which can be seen as an array consisting of \textbf{distinct} points on a plane. A beatmap is called nice if for any three consecutive points $A,B,C$ listed in order, the angle between these three points, centered at $B$, is \textbf{strictly less than} $90$ degrees. \begin{center} {\small Points $A,B,C$ on the left have angle less than $90$ degrees, so they can be three consecutive points of a nice beatmap; Points $A',B',C'$ on the right have angle greater or equal to $90$ degrees, so they cannot be three consecutive points of a nice beatmap.} \end{center} Now Nezzar has a beatmap of $n$ \textbf{distinct} points $A_1,A_2,\ldots,A_n$. Nezzar would like to reorder these $n$ points so that the resulting beatmap is nice. Formally, you are required to find a permutation $p_1,p_2,\ldots,p_n$ of integers from $1$ to $n$, such that beatmap $A_{p_1},A_{p_2},\ldots,A_{p_n}$ is nice. If it is impossible, you should determine it.
There are two different approaches to solve this task. Furthest Points Pick an arbitrary point, and in each iteration, select the furthest point from previously chosen point among all available points. Indeed, we can prove the correctness by contradiction. Insertion Sorting Notice that in any triangle (possibly degenerate), there exists at most one obtuse angle or right angle in this triangle. Therefore, we may build our permutation using modified version of insertion sort (it suffices to substitute comparing operator). We believe that time complexity for the latter approach is better than $O(n^2)$. However, we fail to find a proof or counterexample for it. It would be grateful if someone could figure it out and inform us about it!
[ "constructive algorithms", "geometry", "greedy", "math", "sortings" ]
2,200
#include<bits/stdc++.h> using namespace std; const int maxn=6007; int n; int x[maxn],y[maxn]; vector<int> perm; signed main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>n; for (int i=0;i<n;++i) cin>>x[i]>>y[i]; for (int i=0;i<n;++i){ perm.push_back(i); for (int j=i;j>1;--j){ if (1ll*(x[perm[j]]-x[perm[j-1]])*(x[perm[j-1]]-x[perm[j-2]])+1ll*(y[perm[j]]-y[perm[j-1]])*(y[perm[j-1]]-y[perm[j-2]])>=0){ swap(perm[j],perm[j-1]); } else{ break; } } } for (auto c:perm) cout<<c+1<<" "; }
1477
D
Nezzar and Hidden Permutations
Nezzar designs a brand new game "Hidden Permutations" and shares it with his best friend, Nanako. At the beginning of the game, Nanako and Nezzar both know integers $n$ and $m$. The game goes in the following way: - Firstly, Nezzar hides two permutations $p_1,p_2,\ldots,p_n$ and $q_1,q_2,\ldots,q_n$ of integers from $1$ to $n$, and Nanako secretly selects $m$ unordered pairs $(l_1,r_1),(l_2,r_2),\ldots,(l_m,r_m)$; - After that, Nanako sends his chosen pairs to Nezzar; - On receiving those $m$ unordered pairs, Nezzar checks if there exists $1 \le i \le m$, such that $(p_{l_i}-p_{r_i})$ and $(q_{l_i}-q_{r_i})$ have different signs. If so, Nezzar instantly loses the game and gets a score of $-1$. Otherwise, the score Nezzar gets is equal to the number of indices $1 \le i \le n$ such that $p_i \neq q_i$. However, Nezzar accidentally knows Nanako's unordered pairs and decides to take advantage of them. Please help Nezzar find out two permutations $p$ and $q$ such that the score is maximized.
We can describe the problem in graph theory terms: We are given a graph $G$ of $n$ vertices and $m$ edge. The $i$-th edge connects vertices $l_i$ and $r_i$. We need to write down two numbers on each vertices, on $i$-th vertex we write $p_i$ and $q_i$ on it, so that: $p$ and $q$ forms a permutation from $1$ to $n$, For each edge $(u,v)$, the relative order between $p_u$ and $p_v$ must be the same as between $q_u$ and $q_v$. We want to maximize the number of vertices $u$, so that $p_u \neq q_u$. We can observe the following: For any vertex $u$ with degree $n-1$, $p_u = q_u$. Proof: For such vertex $u$, let $p_u = k$. Then, there are exactly $k - 1$ neighbors of $u$ that has its $p$-number smaller than $u$. Similarly, let $q_u = k'$. Then, there are exactly $k' - 1$ neighbors of $u$ that has its $q$-number smaller than $u$. Since the relative order between $u$ and its neighbors must be the same across $p$ and $q$, $k' - 1 = k - 1$, which leads to $k' = k$. We can assign those numbers with any unused number and delete them from the graph. Now we will consider only vertices with degree $< m-1$, where $m$ is the number of remaining vertices. We claim that the maximum number of differing position to be exactly $m$. As all vertices have degree $< m-1$, it is easier to consider the complement graph $G'$, where $(u,v)$ in $G'$ is connected if and only if $(u,v)$ is not connected in $G$. Notice that $G'$ consists of connected components and each vertex has at least one neighbor. We will focus on a single connected component. Let us find any spanning tree of this particular component. If the spanning tree is astar, Let the center of star be $u$ and the other vertices be $v_1, v_2, \cdots v_k$. Then, the following is a valid assignment: $p_u = 1, q_u = k + 1$ $p_{v_i} = i + 1, q_{v_i} = i$ for $1 \leq i \leq k$ Otherwise, we claim that we can decompose any tree into different connected stars with at least two nodes each. If we can do so, we can assign numbers $1, 2, \cdots k_1$ to first star with $k_1$ nodes, $k_1 + 1, k_1 + 2, \cdots k_1 + k_2$ to second star with $k_2$ nodes and so on. Notice that the relative order between nodes of different stars never change. The remaining part is to decompose tree into stars. There are a lot of algorithms to do so, one of them would be: If any neighbors of $u$ are unassigned, assign $u$ to be the center of new star component along with all unassigned neighbors of $u$. Otherwise, notice that all neighbors of $u$ is now a non-center member of some star component. Pick up any of $u$'s neighbor, $v$. If the star component of $v$ has at least two non-center nodes, remove $v$ from its original star component and make node $u$ and node $v$ a star component centered at $u$. Otherwise, make $v$ to be the center of its star component and add $u$ to it. We can see that the algorithm produces star components of at least two nodes each, and therefore we can apply the assignment of numbers to each stars individually and concat the results. In the end, all nodes will have their $p$ and $q$ assigned differently. It is possible to find all the needed spanning tree in $O((n + m) \log n)$ time. Then, it takes $O(n)$ total time to compute answers for all trees. Therefore, time complexity is $O((n + m) \log n)$.
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,800
#include<bits/stdc++.h> using namespace std; const int maxn=500007; struct info{ int idx,val; friend bool operator<(info u,info v){ return u.val==v.val?u.idx<v.idx:u.val<v.val; } }; struct stars{ int rt; vector<int> leaves; }; set<int> rv; // remained vertices set<int> g[maxn]; // original graph set<int> t[maxn]; // dfs tree set<info> d; int deg[maxn]; int n,m; int perm1[maxn],perm2[maxn]; vector<stars> res; void dfs(int u){ rv.erase(u); int crt=0; while (1){ auto iter=rv.upper_bound(crt); if (iter==rv.end()) break; int v=*iter; crt=v; if (g[u].find(v)!=g[u].end()) continue; t[u].insert(v), t[v].insert(u); dfs(v); } } int main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int tc; cin>>tc; while (tc--){ cin>>n>>m; for (int i=1;i<=n;++i) g[i].clear(), t[i].clear(); rv.clear(), res.clear(), d.clear(); for (int i=1;i<=m;++i){ int u,v; cin>>u>>v; g[u].insert(v), g[v].insert(u); } for (int i=1;i<=n;++i) rv.insert(i); while (rv.size()>0){ int u=*(rv.begin()); dfs(u); } int rem=n; for (int i=1;i<=n;++i){ deg[i]=t[i].size(); if (deg[i]){ d.insert((info){i,deg[i]}); } else{ perm1[i]=perm2[i]=rem; rem--; } } while (d.size()){ int idx=(*(d.begin())).idx; int f=*(t[idx].begin()); vector<int> leaves; leaves.clear(); d.erase((info){f,deg[f]}); for (auto c:t[f]){ d.erase((info){c,deg[c]}); if (deg[c]==1) leaves.push_back(c); else deg[c]--, d.insert((info){c,deg[c]}), t[c].erase(f); } res.push_back((stars){f,leaves}); } int l=0,r=0; for (auto c:res){ perm1[c.rt]=++l; for (auto ls:c.leaves){ perm1[ls]=++l; perm2[ls]=++r; } perm2[c.rt]=++r; } for (int i=1;i<=n;++i) cout<<perm1[i]<<" "; cout<<"\n"; for (int i=1;i<=n;++i) cout<<perm2[i]<<" "; cout<<"\n"; } }
1477
E
Nezzar and Tournaments
In the famous Oh-Suit-United tournament, two teams are playing against each other for the grand prize of precious pepper points. The first team consists of $n$ players, and the second team consists of $m$ players. Each player has a potential: the potential of the $i$-th player in the first team is $a_i$, and the potential of the $i$-th player in the second team is $b_i$. In the tournament, \textbf{all} players will be on the stage in some order. There will be a scoring device, initially assigned to an integer $k$, which will be used to value the performance of all players. The scores for all players will be assigned in the order they appear on the stage. Let the potential of the current player be $x$, and the potential of the previous player be $y$ (\textbf{$y$ equals $x$ for the first player}). Then, $x-y$ is added to the value in the scoring device, Afterwards, if the value in the scoring device becomes negative, \textbf{the value will be reset to $0$}. Lastly, the player's score is assigned to the current value on the scoring device. The score of a team is the sum of the scores of all its members. As an insane fan of the first team, Nezzar desperately wants the biggest win for the first team. He now wonders what is the maximum difference between scores of the first team and the second team. Formally, let the score of the first team be $score_f$ and the score of the second team be $score_s$. Nezzar wants to find the maximum value of $score_f - score_s$ over all possible orders of players on the stage. However, situation often changes and there are $q$ events that will happen. There are three types of events: - $1$ $pos$ $x$ — change $a_{pos}$ to $x$; - $2$ $pos$ $x$ — change $b_{pos}$ to $x$; - $3$ $x$ — tournament is held with $k = x$ and Nezzar wants you to compute the maximum value of $score_f - score_s$. Can you help Nezzar to answer the queries of the third type?
Let's firstly consider a simplified problem where the scoring device will not reset to $0$. For any player, his score will be fully determined by his potential as well as the potential of first player when $k$ is fixed. Indeed, similar property still holds in our setting. Observation 1. For any fixed arrangement of players with potentials $c_1,c_2,\ldots,c_{n+m}$, $score_i=k-c_1+c_i+\max(0,c_1-k-\min(c_1,c_2,\ldots,c_i))$, where $score_i$ is the score of the $i$-th player. Observation 2. If the first player is fixed, it is optimal to place players in second team in descending order of potentials, then place all players in ascending order of potentials. Let $f(t)$ be the difference where $a_x=t$ is selected as the first, and others ordered optimally (and $g(t)$ for sequence $b$ similarly). With some calculation, we may get $f(t) = (n-1) \max(0,t-k-\min) - \sum_{i=1}^m \max(0,t-k-b_i) + (m-n) t + C$ Suppose that we have an oracle of $f$, we are aiming to find out the maximum value of $f(t)$ over sets of values $\{a_1,a_2,\ldots,a_n\}$. It can be seen that maximum values can only be reached on $O(1)$ inputs (which can be found in $O(\log n)$ time). For better understanding, you may refer to the following figure. Here is a figure for $n=3$, $m=3$, $k=2$, $\min=4$, $b_1=6, b_2=8$ and $b_3=10$. It can be seen that in this configuration, function is monotone increasing when $t<10$ and decreasing after. It can be shown that $f$ acts similarly. Therefore, it only remains to calculate $f$ for any given input $t$ efficiently, which can be decomposed to the following queries. minimum value over $a_i$, $b_i$. $\sum_{1 \le i \le m} \max(0,k-t-b_i)$ for given $k$. All those can be done efficiently via segment tree.
[ "data structures", "greedy" ]
3,300
//#pragma GCC optimize("Ofast") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") //#pragma GCC optimize("unroll-loops") #include<bits/stdc++.h> using namespace std; #define rep(i,n) for (int i=0;i<(int)(n);++i) #define rep1(i,n) for (int i=1;i<=(int)(n);++i) #define range(x) begin(x), end(x) #define sz(x) (int)(x).size() #define pb push_back #define F first #define S second typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; namespace internal { // @param n `0 <= n` // @return minimum non-negative `x` s.t. `n <= 2**x` int ceil_pow2(int n) { int x = 0; while ((1U << x) < (unsigned int)(n)) x++; return x; } } template <class S, S (*op)(S, S), S (*e)()> struct segtree { public: segtree() : segtree(0) {} segtree(int n) : segtree(std::vector<S>(n, e())) {} segtree(const std::vector<S>& v) : _n(int(v.size())) { log = internal::ceil_pow2(_n); size = 1 << log; d = std::vector<S>(2 * size, e()); for (int i = 0; i < _n; i++) d[size + i] = v[i]; for (int i = size - 1; i >= 1; i--) { update(i); } } void set(int p, S x) { assert(0 <= p && p < _n); p += size; d[p] = x; for (int i = 1; i <= log; i++) update(p >> i); } S get(int p) { assert(0 <= p && p < _n); return d[p + size]; } S prod(int l, int r) { assert(0 <= l && l <= r && r <= _n); S sml = e(), smr = e(); l += size; r += size; while (l < r) { if (l & 1) sml = op(sml, d[l++]); if (r & 1) smr = op(d[--r], smr); l >>= 1; r >>= 1; } return op(sml, smr); } S all_prod() { return d[1]; } template <bool (*f)(S)> int max_right(int l) { return max_right(l, [](S x) { return f(x); }); } template <class F> int max_right(int l, F f) { assert(0 <= l && l <= _n); assert(f(e())); if (l == _n) return _n; l += size; S sm = e(); do { while (l % 2 == 0) l >>= 1; if (!f(op(sm, d[l]))) { while (l < size) { l = (2 * l); if (f(op(sm, d[l]))) { sm = op(sm, d[l]); l++; } } return l - size; } sm = op(sm, d[l]); l++; } while ((l & -l) != l); return _n; } template <bool (*f)(S)> int min_left(int r) { return min_left(r, [](S x) { return f(x); }); } template <class F> int min_left(int r, F f) { assert(0 <= r && r <= _n); assert(f(e())); if (r == 0) return 0; r += size; S sm = e(); do { r--; while (r > 1 && (r % 2)) r >>= 1; if (!f(op(d[r], sm))) { while (r < size) { r = (2 * r + 1); if (f(op(d[r], sm))) { sm = op(d[r], sm); r--; } } return r + 1 - size; } sm = op(d[r], sm); } while ((r & -r) != r); return 0; } private: int _n, size, log; std::vector<S> d; void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); } }; const int maxn=500007; const int maxm=1000007; int n,m,k,q,t; ll sum; int a[maxn],b[maxn]; struct S{ int cnt; ll sum; }; S e(){ return {0,0}; } S op(S l,S r){ return {l.cnt+r.cnt,l.sum+r.sum}; } signed main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); segtree<S,op,e> seg_a(maxm),seg_b(maxm); auto fa=[&](int x){ if (x>m||x<=0) cerr<<x<<endl; assert(x<=m&&x>0); return seg_a.max_right(0,[&](S l){return l.cnt<x;}); }; auto fb=[&](int x){ assert(x<=n&&x>0); return seg_b.max_right(0,[&](S l){return l.cnt<x;}); }; auto solve=[&](int start,int coef){ // cerr<<"start coef:"<<start<<" "<<coef<<endl; int mn=min(fa(1),fb(1)); if (start<=k+mn) return 1ll*(n-m)*start+sum; auto ret=seg_b.prod(0,start-k); // cerr<<"ret:"<<ret.cnt<<" "<<ret.sum<<endl; return 1ll*coef*(start-k-mn)+1ll*(n-m)*start+sum+ret.sum-1ll*ret.cnt*(start-k); }; cin>>m>>n>>q; rep1(i,m) {cin>>a[i],sum+=a[i]; auto ret=seg_a.get(a[i]); ret.cnt++, ret.sum+=a[i], seg_a.set(a[i],ret);} rep1(i,n) {cin>>b[i],sum-=b[i]; auto ret=seg_b.get(b[i]); ret.cnt++, ret.sum+=b[i], seg_b.set(b[i],ret);} sum+=1ll*(m-n)*k; auto res=[&](){ ll ans=-1e15; ans=max(ans,solve(fb(1),m)); ans=max(ans,solve(fb(n),m)); ans=max(ans,solve(fa(1),m-1)); ans=max(ans,solve(fa(m),m-1)); int threshold=n>1?fb(n-1):0; if (k+threshold<=1e6){ int pos=max(seg_a.prod(0,k+threshold).cnt,1); ans=max(ans,solve(fa(pos),m-1)); int nxt_pos=seg_a.max_right(0,[&](S l){return l.cnt<=pos;}); if (nxt_pos<maxm) ans=max(ans,solve(nxt_pos,m-1)); } cout<<ans<<"\n"; }; while (q--){ int op,idx,x; cin>>op; if (op==1){ cin>>idx>>x; auto ret=seg_a.get(a[idx]); ret.cnt--, ret.sum-=a[idx]; seg_a.set(a[idx],ret); sum-=a[idx]; sum+=x; a[idx]=x; ret=seg_a.get(x); ret.cnt++, ret.sum+=x; seg_a.set(x,ret); } if (op==2){ cin>>idx>>x; auto ret=seg_b.get(b[idx]); ret.cnt--, ret.sum-=b[idx]; seg_b.set(b[idx],ret); sum+=b[idx]; sum-=x; b[idx]=x; ret=seg_b.get(x); ret.cnt++, ret.sum+=x; seg_b.set(x,ret); } if (op==3){ cin>>k; sum+=(m-n)*k; res(); sum-=(m-n)*k; } } return 0; }
1477
F
Nezzar and Chocolate Bars
Nezzar buys his favorite snack — $n$ chocolate bars with lengths $l_1,l_2,\ldots,l_n$. However, chocolate bars might be too long to store them properly! In order to solve this problem, Nezzar designs an interesting process to divide them into small pieces. Firstly, Nezzar puts all his chocolate bars into a black box. Then, he will perform the following operation repeatedly until the maximum length over all chocolate bars does not exceed $k$. - Nezzar picks a chocolate bar from the box with probability proportional to its length $x$. - After step $1$, Nezzar uniformly picks a real number $r \in (0,x)$ and divides the chosen chocolate bar into two chocolate bars with lengths $r$ and $x-r$. - Lastly, he puts those two new chocolate bars into the black box. Nezzar now wonders, what is the expected number of operations he will perform to divide his chocolate bars into small pieces. It can be shown that the answer can be represented as $\frac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \not \equiv 0$ ($\bmod 998\,244\,353$). Print the value of $P\cdot Q^{-1} \mod 998\,244\,353$.
Let's firstly solve an easier version where $n=1$. Part 1 ($n = 1$) Let's firstly rephrase the original task and solve it for case $n=1$. - Let $p_k$ the probability of event that $X_{(i)}-X_{(i-1)} \le K$ for $1 \le i \le k$ and $L - X_{(k)} \le K$. Here, $k$ real numbers $X_1,X_2,\ldots,X_k$ are chosen uniformly from $(0,L)$, and $X_{(1)},X_{(2)},\ldots,X_{(k)}$ is the sorted array of $X_0=0,X_1,X_2,\ldots,X_k$. Then the disire answer would be $\sum_{k=0}^{+\infty} (1-p_k)$. To simplify notations, denote $w=\frac{K}{L}$. We are aiming to calculate $p_n$ from now on. Let $Z_i=X_{(i)}-X_{(i-1)}$,then the pdf(probability density function) of the union distribution of $Z_1,Z_2,\ldots,Z_n$ is $f(z_1,z_2,\ldots,z_n)=n! I_{0<z_i<1,\sum_{i=1}^n z_i < 1}$ Hence, $p_n= n! \int_{0<z_i<w, 1-w < \sum_{i=1}^n z_i < 1} 1 dz_1 dz_2 \ldots dz_n= n! w^n \int_{0<z_i<1, \frac{1}{w}-1<\sum_{i=1}^n z_i<\frac{1}{w}} 1 dz$ Consider $Y_1,Y_2,\ldots,Y_n$ i.i.d, where $Y_i$ follows uniform distribution sampling from $(0,1)$,then the integral above is $Pr[\frac{1}{w}-1<\sum_{i=1}^n Y_i<\frac{1}{w}]$. Note that $\sum_{i=1}^n Y_i$ follows Irwin-Hall distribution whose CDF(cumulative distribution function) is $F(x)={\frac {1}{n!}}\sum _{{k=0}}^{{\lfloor x\rfloor }}(-1)^{k}{\binom {n}{k}}(x-k)^{n}$ Thus,$p_n = n!w^n(F(\frac{1}{w})-F(\frac{1}{w}-1))$. $p_n=1- \left(\sum_{k=0}^x (-1)^k \binom{n}{k} (1-wk)^n - \sum_{k=0}^{x-1} (-1)^k \binom{n}{k}(1-(k+1)w)^n\right) \\ =\sum_{k=1}^x (-1)^{k-1} \left(\binom{n}{k}+\binom{n}{k-1}\right)(1-kw)^n$ where$x=\left[\frac{1}{w}\right]$. using identity $\sum_{n \ge k}\binom{n}{k} x^n=x^k(1-x)^{-(k+1)}$ to finish this task. Main version To avoid confusion, we will let $q_{m,j}$ the probability that $m$ operations are performed on line $j$ but there still exists lines produced by line $j$ with length greater or equal to $K$ (which have been calculated in part 1, with notation $p_n$). Recall that $q_{m,j} = \sum_{k=1}^{\lfloor \frac{L_j}{K} \rfloor} (-1)^{k-1}\binom{m+1}{k} (1-\frac{kK}{L_j})^m$. Therefore, probability $p_m$ that one fails to finish the task within $m$ rounds is $1 - \sum_{j_1+j_2+\ldots+j_n=m} \frac{m!}{j_1!j_2!\ldots j_n!} \prod_{r=1}^n (1-q_{j_r,r})\left(\frac{L_j}{L}\right)^{j_r}$ Let $Q_j$ be EGF of sequence $((1-q_{m,r} )L_j/L)_{m \ge 0}$, that is to say the $m$-th coefficient is $[x^m]Q_j = \frac{1}{m! L}(1-q_{m,r} )L_j.$ Similarly, let $P$ be EGF of sequence $(p_m)_{m \ge 0}$, one may observe that $P = \exp(x) - \prod_{i=1}^n Q_i.$ In the following part, we will calculate $Q_j$. $\begin{aligned} Q_j &= \sum_{m \ge 0} \frac{1}{m!} \left(\frac{L_j}{L} - \sum_{k=1}^{\lfloor \frac{L_j}{K} \rfloor} (-1)^{k-1} \binom{m+1}{k} \left(1-\frac{kK}{L_j}\right)^m \right) x^m\\ &= \exp\left(\frac{L_j}{L}x\right) - \sum_{k=1}^{\lfloor \frac{L_j}{K} \rfloor} (-1)^{k-1} \sum_{m \ge k-1} \frac{(m+1)}{k!(m+1-k)!} \left(\frac{L_j-kK}{L}\right)^m x^m \end{aligned}$ Note that $\sum_{m \ge k-1} \frac{m+1}{k!(m+1-k)!} y^m = \sum_{m \ge k} \frac{y^m}{k!(m-k)!} + \sum_{m \ge k-1} \frac{k y^m}{k!(m+1-k)!} = \frac{y^k}{k!} \exp(y) + \frac{y^{k-1}}{(k-1)!} \exp(y)$. Therefore, $\begin{aligned} Q_j &= \exp(\frac{L_j}{L} x) - \sum_{k=1}^{\lfloor \frac{L_j}{K} \rfloor} (-1)^{k-1} \left(\frac{1}{k!} \left(\frac{L_j-kK}{L}\right)^k x^k + \frac{1}{(k-1)!} \left(\frac{L_j-kK}{L}\right)^{k-1} x^{k-1} \right)\exp\left(\frac{(L_j-kK)x}{L}\right) \end{aligned}$ Note that with NTT and above equalities, we may calculate coefficient of $P$ in $O(nL \log nL)$ (Precisely, we will calculate coefficient of $x^{k-j}\exp{\left(1-\frac{K}{L}k x\right)}$ for each $0 \le k\le L$ and $0 \le j \le \min(n,k)$). Lastly, we should notice that if EGF of sequence $a$ is $x^k \exp(Cx)$, then $a_{k+n} = \frac{(k+n)!}{n!}C^n$, and its OGF is $k!\sum_{n \ge 0}\binom{n+k}{k}C^n x^{n+k} = k!\frac{(x/C)^k}{(1-Cx)^{k+1}}$. Hence, we will be able to calculate OGF $P'$ of sequence $p_m$, and answer is exactly $P'(1)$. It should be noticed that our approach will run in $O(nL \log nL)$ implemented appropriately , where $L=\sum_{i=1}^n l_i$. However, larger time limit is set to allow suboptimal solution to pass(like $O(nL^2)$ or $O(n^2L \log L)$).
[ "combinatorics", "fft", "math", "probabilities" ]
3,500
//#pragma GCC optimize("Ofast") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") //#pragma GCC optimize("unroll-loops") #include<bits/stdc++.h> #define int long long using namespace std; #define rep(i,n) for (int i=0;i<(int)(n);++i) #define rep1(i,n) for (int i=1;i<=(int)(n);++i) #define range(x) begin(x), end(x) #define sz(x) (int)(x).size() #define pb push_back #define F first #define S second typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; const ll mod = (119 << 23) + 1, root = 62; // = 998244353 // For p < 2^30 there is also e.g. 5 << 25, 7 << 26, 479 << 21 // and 483 << 21 (same root). The last two are > 10^9. ll modpow(ll b, ll e) { ll ans = 1; for (; e; b = b * b % mod, e /= 2) if (e & 1) ans = ans * b % mod; return ans; } typedef vector<ll> vl; void ntt(vl &a) { int n = sz(a), L = 31 - __builtin_clz(n); static vl rt(2, 1); for (static int k = 2, s = 2; k < n; k *= 2, s++) { rt.resize(n); ll z[] = {1, modpow(root, mod >> s)}; for(int i=k;i<2*k;++i) rt[i] = rt[i / 2] * z[i & 1] % mod; } vi rev(n); for(int i = 0; i < n; ++i) rev[i] = (rev[i / 2] | (i & 1) << L) / 2; for(int i = 0; i < n; ++i) if (i < rev[i]) swap(a[i], a[rev[i]]); for (int k = 1; k < n; k *= 2) for (int i = 0; i < n; i += 2 * k) for(int j = 0; j < k; ++j) { ll z = rt[j + k] * a[i + j + k] % mod, &ai = a[i + j]; a[i + j + k] = ai - z + (z > ai ? mod : 0); ai += (ai + z >= mod ? z - mod : z); } } vl conv(const vl &a, const vl &b) { if (a.empty() || b.empty()) return {}; int s = sz(a) + sz(b) - 1, B = 32 - __builtin_clz(s), n = 1 << B; int inv = modpow(n, mod - 2); vl L(a), R(b), out(n); L.resize(n), R.resize(n); ntt(L), ntt(R); for (int i = 0; i < n; ++i) out[-i & (n - 1)] = (ll)L[i] * R[i] % mod * inv % mod; ntt(out); return {out.begin(), out.begin() + s}; } const int maxn=1007; int n,k; int l[maxn]; struct polynomial{ int n,m; vector<vi> poly; polynomial(vector<vi> &po):poly(po){ n = sz(poly) - 1, m = sz(poly[0]) - 1; } vi rsz(int nn,int mm){ assert(nn>n&&mm>m); vi ret; ret.resize(nn*mm+1,0); for (int i=0;i<=n;++i){ for (int j=0;j<=m;++j){ ret[i*mm+j]=poly[i][j]; assert(poly[i][j]<mod&&poly[i][j]>=0); } } return ret; } friend polynomial operator*(polynomial l,polynomial r){ vector<vi> po; po.clear(); po.resize(l.n+r.n+1,vi(l.m+r.m+1,0)); auto lpo=l.rsz(l.n+1,l.m+r.m+1),rpo=r.rsz(r.n+1,l.m+r.m+1),res=conv(lpo,rpo); // for (auto c:res) cout<<c<<" "; // cout<<endl; // cout<<sz(lpo)<<" "<<sz(rpo)<<" "<<sz(res)<<endl; for (int i=0;i<=l.n+r.n;++i){ for (int j=0;j<=l.m+r.m;++j){ po[i][j]=res[i*(l.m+r.m+1)+j]; } } // cout<<"hi"<<endl; return po; } }; vector<polynomial> poly; int f[5007]; signed main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>n>>k; f[0]=1; rep1(i,5000) f[i]=f[i-1]*i%mod; int L=0; rep(i,n) cin>>l[i], L+=l[i]; rep(i,n){ vi res0,res1; res0.clear(), res1.clear(); res0.pb(1), res1.pb(0); int sgn=1; rep1(j,l[i]/k){ int tmp0,tmp1; sgn=-sgn; if (l[i]==k*j) { tmp0=tmp1=0; } else{ tmp0=(modpow((l[i]-k*j)*modpow(L,mod-2)%mod,j)%mod)*modpow(f[j],mod-2)%mod, tmp1=(modpow((l[i]-k*j)*modpow(L,mod-2)%mod,j-1)%mod)*modpow(f[j-1],mod-2)%mod; if (sgn<0) tmp0=(tmp0?mod-tmp0:tmp0), tmp1=(tmp1?mod-tmp1:tmp1); } // cerr<<i<<" "<<j<<":"<<tmp0<<" "<<tmp1<<endl; res0.pb(tmp0), res1.pb(tmp1); } vector<vi> p({res0,res1}); polynomial po(p); poly.pb(po); } for (int k=1;k<=n;k<<=1){ for (int i=k;i<n;i+=2*k){ poly[i-k]=poly[i]*poly[i-k]; } } int ans=0; // x^{j-i}exp((1-k*j/L)) -> (j-i)!/((k*j/L)^{j-i+1}) = (j-i)!L^{j-i+1}/(k*j)^{j-i+1} rep(i,poly[0].n+1){ rep(j,poly[0].m+1){ if (i>j) {assert(poly[0].poly[i][j]==0); continue;} if (j==0) {assert(poly[0].poly[i][j]==1); continue;} if (k*j==L) {assert(poly[0].poly[i][j]==0); continue;} int num=f[j-i]*modpow(L,j-i+1)%mod,den=modpow(k*j,j-i+1)%mod; // cerr<<i<<","<<j<<":"<<poly[0].poly[i][j]<<" "<<num<<" "<<den<<endl; ans=(ans+(num*modpow(den,mod-2)%mod)*poly[0].poly[i][j]%mod)%mod; } } if (ans>0) cout<<mod-ans<<endl; else cout<<0<<endl; return 0; }
1478
A
Nezzar and Colorful Balls
Nezzar has $n$ balls, numbered with integers $1, 2, \ldots, n$. Numbers $a_1, a_2, \ldots, a_n$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $a_i \leq a_{i+1}$ for all $1 \leq i < n$. Nezzar wants to color the balls using the minimum number of colors, such that the following holds. - For any color, numbers on balls will form a \textbf{strictly increasing sequence} if he keeps balls with this chosen color and discards all other balls. Note that a sequence with the length at most $1$ is considered as a strictly increasing sequence. Please help Nezzar determine the minimum number of colors.
For positions which numbers are the same, they cannot be colored using same color. Let us color the $i$-th occurrence of any number using color $i$. We can see that: We cannot use fewer colors: if there are $k$ occurrence of any number, at least $k$ color is needed. The assignment of color is valid: Since the sequence was non-increasing, for any subsequence it is also non-increasing. As there are no duplicates in colored subsequence, the subsequence is strictly increasing as well. Therefore, we only need to count the number of occurrence of every number and take the maximum of them. Time complexity: $O(n)$ per test case
[ "brute force", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for (int i=0;i<(int)(n);++i) #define rep1(i,n) for (int i=1;i<=(int)(n);++i) #define range(x) begin(x), end(x) #define sz(x) (int)(x).size() #define pb push_back #define F first #define S second typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int> pii; typedef vector<int> vi; const int maxn=200007; int t,n; int cnt[maxn]; int main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>t; while (t--){ cin>>n; rep1(i,n) cnt[i]=0; rep1(i,n){ int u; cin>>u; cnt[u]++; } int mx=0; rep1(i,n) mx=max(mx,cnt[i]); cout<<mx<<"\n"; } return 0; }
1478
B
Nezzar and Lucky Number
Nezzar's favorite digit among $1,\ldots,9$ is $d$. He calls a \textbf{positive} integer lucky if $d$ occurs at least once in its decimal representation. Given $q$ integers $a_1,a_2,\ldots,a_q$, for each $1 \le i \le q$ Nezzar would like to know if $a_i$ can be equal to a sum of several (one or more) lucky numbers.
For any given $d$, We can observe the following: $10d$ to $10d + 9$ contains $d$ as one of its digit Let $k = 10d + 9$ be the upper bound of such range For every number $x > k$, we can keep reducing $x$ by $d$, $x$ will eventually fall into the range mentioned above, which contains $d$ as digit. Therefore, for numbers $x > k$, they are always achievable. For $x \leq k - 10$, as $k <= 109$, we can run a standard knapsack dynamicprogramming solution, where $dp[x]$ indicates if $x$ is achievable. $dp[x]$ is achievable, if and only if one of the following is true: $x = 0$ For some $y < x$, $dp[y]$ is true and $x - y$ contains $d$ as digit Iterating for every $x$, all $dp[x]$ for $x < k$ can be computed with $O(k)$ per state (as we only need to consider $y < k$. Besides dynamic programming solution, brute force solutions with enough optimization should also pass the test cases easily. Time complexity: $O((10d)^2)$ per test case.
[ "brute force", "dp", "greedy", "math" ]
1,100
#include<bits/stdc++.h> using namespace std; const int maxn=207; int t,d,q; bool dp[maxn]; int main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>t; while (t--){ memset(dp,0,sizeof(dp)); dp[0]=1; cin>>q>>d; if (!d) d+=10; int mx=d*10; for (int i=0;10*i+d<=mx;++i){ for (int j=0;10*i+d+j<=mx;++j){ dp[10*i+d+j]|=dp[j]; } } while (q--){ int u; cin>>u; if (u>=mx||dp[u]) cout<<"YES\n"; else cout<<"NO\n"; } } return 0; }
1478
C
Nezzar and Symmetric Array
Long time ago there was a symmetric array $a_1,a_2,\ldots,a_{2n}$ consisting of $2n$ \textbf{distinct integers}. Array $a_1,a_2,\ldots,a_{2n}$ is called symmetric if for each integer $1 \le i \le 2n$, there exists an integer $1 \le j \le 2n$ such that $a_i = -a_j$. For each integer $1 \le i \le 2n$, Nezzar wrote down an integer $d_i$ equal to the sum of absolute differences from $a_i$ to all integers in $a$, i. e. $d_i = \sum_{j = 1}^{2n} {|a_i - a_j|}$. Now a million years has passed and Nezzar can barely remember the array $d$ and totally forget $a$. Nezzar wonders if there exists any symmetric array $a$ consisting of $2n$ distinct integers that generates the array $d$.
WLOG, we may assume that $0 < a_1 < a_2 < \ldots < a_n$, and $a_{i+n}=-a_i$ for each $1 \le i \le n$. Let's sort array $d$ firstly. It can be observed that the array $d$ satisfied the following property: $d_{2i-1}=d_{2i}$ for each $1 \le i \le n$; $d_{2i} \neq d_{2i+2}$ for each $1 \le i < n$. $d_{2i}$ must be generated for index $i$ or $i+n$. More importantly, we have the following relation: $d_{2n}-d_{2n-2}=\sum_{i=1}^{n} (a_n-a_i)+\sum_{i=1}^n (a_n+a_i) - \sum_{i=1}^n|a_{n-1}-a_i| - \sum_{i=1}^n (a_{n-1}+a_i) = (2n-2)(a_n-a_{n-1})$ And observe that $|a_i-a_n|+|a_i+a_n|=2a_n$ is a constant independent of index $1 \le i\le n$. Therefore, we may remove $a_n$ and $-a_n$ by subtracting some constant for $d_i$ for all $1 \le i \le 2(n-1)$, indicating that we will calculate $a_{i+1}-a_{i}$ for all $1 \le i < n$, which can be done in $O(n)$. Lastly, we should determine if there exists an postivie integer $a_1$ which generates $d_1$, which can be done in $O(n)$.
[ "implementation", "math", "sortings" ]
1,700
#include<bits/stdc++.h> #define int long long using namespace std; const int maxn=200007; int t; int n,a[maxn],b[maxn],d[maxn]; signed main(){ ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); cin>>t; while (t--){ cin>>n; for (int i=0;i<2*n;++i) cin>>a[i]; sort(a,a+2*n,greater<int>()); for (int i=0;i<n;++i){ if (a[i*2]!=a[i*2+1]){ cout<<"NO\n"; goto cont; } b[i]=a[i*2]; } for (int i=1;i<n;++i){ if (b[i-1]==b[i]||(b[i-1]-b[i])%(2*(n-i))){ cout<<"NO\n"; goto cont; } d[i]=(b[i-1]-b[i])/2/(n-i); } for (int i=1;i<n;++i){ b[n-1]-=2*i*d[i]; } if (b[n-1]<=0||b[n-1]%(2*n)) cout<<"NO\n"; else cout<<"YES\n"; cont:; } return 0; }
1479
A
Searching Local Minimum
\textbf{This is an interactive problem}. Homer likes arrays a lot and he wants to play a game with you. Homer has hidden from you a permutation $a_1, a_2, \dots, a_n$ of integers $1$ to $n$. You are asked to find any index $k$ ($1 \leq k \leq n$) which is a local minimum. For an array $a_1, a_2, \dots, a_n$, an index $i$ ($1 \leq i \leq n$) is said to be a local minimum if $a_i < \min\{a_{i-1},a_{i+1}\}$, where $a_0 = a_{n+1} = +\infty$. An array is said to be a permutation of integers $1$ to $n$, if it contains all integers from $1$ to $n$ exactly once. Initially, you are only given the value of $n$ without any other information about this permutation. At each interactive step, you are allowed to choose any $i$ ($1 \leq i \leq n$) and make a query with it. As a response, you will be given the value of $a_i$. You are asked to find any index $k$ which is a local minimum \textbf{after at most $100$ queries}.
We maintain by binary search a range $[l, r]$ which has a local minimum. Moreover, we assume that $a_{l-1} > a_l$ and $a_r < a_{r+1}$. Initially, $[l, r] = [1, n]$. In each iteration, let $m$ be the midpoint of $l$ and $r$. Case 1. If $a_m < a_{m+1}$, then the range becomes $[l, m]$. Case 2. If $a_m > a_{m+1}$, then the range becomes $[m+1, r]$. When $l = r$, we have found a local minimum $a_l$. The number of queries to $a_i$ is at most $2 \lceil \log_2 n \rceil \leq 34 < 100$.
[ "binary search", "interactive", "ternary search" ]
1,700
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; int n; int a[MAXN]; int query(int x) { if (1 <= x && x <= n) { printf("? %d\n", x); fflush(stdout); scanf("%d", &a[x]); } } int main() { scanf("%d", &n); a[0] = a[n + 1] = n + 1; int L = 1, R = n; while (L < R) { int m = (L + R) / 2; query(m); query(m + 1); if (a[m] < a[m + 1]) R = m; else L = m + 1; } printf("! %d\n", L); fflush(stdout); return 0; }
1479
B1
Painting the Array I
\textbf{The only difference between the two versions is that this version asks the maximal possible answer.} Homer likes arrays a lot. Today he is painting an array $a_1, a_2, \dots, a_n$ with two kinds of colors, \textbf{white} and \textbf{black}. A painting assignment for $a_1, a_2, \dots, a_n$ is described by an array $b_1, b_2, \dots, b_n$ that $b_i$ indicates the color of $a_i$ ($0$ for white and $1$ for black). According to a painting assignment $b_1, b_2, \dots, b_n$, the array $a$ is split into two new arrays $a^{(0)}$ and $a^{(1)}$, where $a^{(0)}$ is the sub-sequence of all white elements in $a$ and $a^{(1)}$ is the sub-sequence of all black elements in $a$. For example, if $a = [1,2,3,4,5,6]$ and $b = [0,1,0,1,0,0]$, then $a^{(0)} = [1,3,5,6]$ and $a^{(1)} = [2,4]$. The number of segments in an array $c_1, c_2, \dots, c_k$, denoted $\mathit{seg}(c)$, is the number of elements if we merge all adjacent elements with the same value in $c$. For example, the number of segments in $[1,1,2,2,3,3,3,2]$ is $4$, because the array will become $[1,2,3,2]$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $0$. Homer wants to find a painting assignment $b$, according to which the number of segments in both $a^{(0)}$ and $a^{(1)}$, i.e. $\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$, is as \textbf{large} as possible. Find this number.
Formally, for every sequence $a_1, a_2, \dots, a_n$, and we assume that $a_1, a_2, \dots, a_n$ are positive integers, the number of segments in $a$ is defined to be $\mathit{seg}(a) = \sum_{i=1}^n [ a_{i-1} \neq a_{i} ],$ Let's restate the problem as Problem. Given a sequence $a_1, a_2, \dots, a_n$, divide it into two disjoint subsequences $s$ and $t$ such that $\mathit{seg}(s)+\mathit{seg}(t)$ is as large as possible. Solution. We will construct two disjoint subsequences by scanning through the sequence $a_1, a_2, \dots, a_n$. Initial setting: $s$ and $t$ are two empty sequences, and $a_1, a_2, \dots, a_n$ remains not scanned. Move on: Suppose the last elements of $s$ and $t$ are $x$ and $y$, respectively, and $x = 0$ (resp. $y = 0$) if $s$ (resp. $t$) is empty. Let $z$ be the current element scanning through $a_1, a_2, \dots, a_n$. Our greedy strategy is described in two cases: Greedy Strategy I: If $z$ equals to one of $x$ and $y$, then assign $z$ to the opposite subsequence. That is, if $z = x$, then append $z$ after $y$; and if $z = y$, then append $z$ after $x$. In particular, if $z$ equals to both $x$ and $y$, the assignment could be arbitrary. Greedy Strategy II: If $z$ differs from both $x$ and $y$, then append $z$ after the one with the nearest next same value. That is, let $\mathit{next}(x)$ denote the next position where $x$ appears in $a_1, a_2, \dots, a_n$ after $z$, then append $z$ after $x$ if $\mathit{next}(x) < \mathit{next}(y)$, and after $y$ otherwise. The greedy strategy is intuitive, and with this strategy, an $O(n)$ algorithm is immediately obtained. However, its proof turns out to be complicated. We append its proof for completeness. An Intuitive Proof Consider any optimal assignment $b_1, b_2, \dots, b_n$, we will show that our strategy is not worse than it. Let $a[l \dots r] = a_l, a_{l+1}, \dots, a_r$ be the subarray of $a$. Now suppose we are at some position $p$, where the optimal assignment conflicts with our strategy. We assume that $s = (a[1\dots p])^{(0)} = s' x$ ends with $x$, and $t = (a[1\dots p])^{(1)} = t' y$ ends with $y$, and $a_{p+1} = z$. Greedy Strategy I: If $b$ conflicts with Greedy Strategy I, then we must have $x \neq y$ and without loss of generality, we assume that $x = z$. Greedy Strategy I suggests we append $z$ after $y$ but $b$ suggests we append $z$ after $x$. Suppose $b$ results in the two subarrays $\begin{aligned} & s'xzs^{\prime \prime} \\ & t'yt^{\prime \prime} \end{aligned}$, while there is indeed another optimal assignment that agrees with our strategy and results in $\begin{aligned} & s'xt^{\prime \prime} \\ & t'yzs^{\prime \prime} \end{aligned}$. Greedy Strategy II: If $b$ conflicts with Greedy Strategy II, then we must have $x$, $y$ and $z$ are distinct and without loss of generality, we assume that the next occurrence of $x$ goes in front of that of $y$. Greedy Strategy II suggests we append $z$ after $x$ but $b$ suggests we append $z$ after $y$. Suppose $b$ results in the two subarrays $\begin{aligned} & s'xs^{\prime \prime} \\ & t'yzt^{\prime \prime} \end{aligned}$. Consider two cases. Case 1. If $s^{\prime \prime}$ does not start with $y$, then there is another optimal assignment that agrees with our strategy and results in $\begin{aligned} & s'xzt^{\prime \prime} \\ & t'ys^{\prime \prime} \end{aligned}$. Case 2. If $s^{\prime \prime}$ starts with $y$, i.e. $s^{\prime \prime} = y s_1$, then since the first occurrence of $x$ is in front of that of $y$, we have that $x$ must be in $t^{\prime \prime}$, and assume that $t^{\prime \prime} = t_1 x t_2$. The result of $b$ is restated as $\begin{aligned} & s'x y s_1 \\ & t'yzt_1 x t_2 \end{aligned}$. We find that there is another optimal assignment that agrees with our strategy and results in $\begin{aligned} & s'xz t_1 y s_1 \\ & t'yx t_2 \end{aligned}$ (Note that $t_1$ does not contain any $x$ or $y$ in it). A Formal Proof The number of alternations in a sequence $a$ starting with $x$ is defined to be $\mathit{seg}_x(a) = \sum_{i=1}^n [ a_{i-1} \neq a_{i} ],$ Let $f_{x,y}(a)$ denote the maximal possible sum of numbers of alternations in the two disjoint subsequences $s$ and $t$ of $a$, i.e. $f_{x, y}(a) = \max_{s, t} \{\mathit{seg}_x(s)+\mathit{seg}_y(t)\},$ Let $\mathit{next}(x)$ denote the least index $k$ such that $a_k = x$, i.e. $\mathit{next}(x) = \min\{k \in \mathbb{N}: a_k = x\}$. In case no such index $k$ exists, $\mathit{next}(x)$ is defined to be $\infty$. In fact, our problem can be solved by DP regardless of the time complexity. Proposition 1 (Dynamic Programming). For $n \geq 1$ and every $x, y \in \mathbb{N}$, $f_{x,y}(a_1, a_2, \dots, a_n) = \max \{ f_{a_1, y} (a_2, \dots, a_n) + [a_1 \neq x], f_{x, a_1} (a_2, \dots, a_n) + [a_1 \neq y] \}.$ We can obtain some immediate properties of $f_{x, y}(a)$ by the above DP recurrence. Proposition 2. For every $x, y \in \mathbb{N}$, $f_{x,0}(a) \geq f_{x,y}(a) \geq f_{x,x}(a)$. Moreover, if $\mathit{next}(y) = \infty$, then $f_{x,0}(a) = f_{x,y}(a)$. After some observations, we have Proposition 3. For every $x, y, z \in \mathbb{N}$ and sequence $a$, $f_{z,x}(a)+1 \geq f_{z,y}(a)$. Proof: By induction on the length $n$ of sequence $a$. Basis. It is trivial for the case $n = 0$ since the left hand side is always $1$ and the right hand side is always $0$. Induction. Suppose true for the case $n = k (k \geq 0)$, i.e. $f_{z,x}(a)+1 \geq f_{z,y}(a)$ Case 1. $x = y$. It is trivial that $f_{z,x}(a)+1 \geq f_{z,x}(a)$. Case 2. $z = x \neq y$. We should prove that $f_{x,x}(a)+1 \geq f_{x,y}(a)$. By Proposition 1, we need to prove that $\begin{cases} f_{a_1,x}(a_2,\dots,a_{k+1})+[a_1 \neq x]+1 \geq f_{a_1,y}(a_2,\dots,a_{k+1})+[a_1 \neq x], \\ f_{a_1,x}(a_2,\dots,a_{k+1})+[a_1 \neq x]+1 \geq f_{x,a_1}(a_2,\dots,a_{k+1})+[a_1 \neq y]. \end{cases}$ $f_{a_1,x}(a_2,\dots,a_{k+1})+1 \geq f_{a_1,y}(a_2,\dots,a_{k+1}),$ Case 3. $x \neq y = z$. We should prove that $f_{x,y}(a)+1 \geq f_{x,x}(a)$. By Proposition 1, we only need to prove that $f_{x,a_1}(a_2,\dots,a_{k+1})+[a_1 \neq y]+1 \geq f_{a_1,x}(a_2,\dots,a_{k+1})+[a_1 \neq x],$ Case 4. $x \neq y, z \neq x$ and $z \neq y$. By Proposition 1, $f_{z,x}(a)+1 \geq f_{z,y}(a)$ is equivalent to $\begin{aligned} & \max\{ f_{a_1, x}(a_2,\dots,a_{k+1})+[a_1 \neq z], f_{z, a_1}(a_2,\dots,a_{k+1})+[a_1 \neq x] \} + 1 \\ & \quad \geq \max\{ f_{a_1, y}(a_2,\dots,a_{k+1})+[a_1 \neq z], f_{z, a_1}(a_2,\dots,a_{k+1})+[a_1 \neq y] \}. \end{aligned}$ Case 4.1. $a_1 = z$. The left hand side becomes $\max\{ f_{z, x}(a_2,\dots,a_{k+1}), f_{z, z}(a_2,\dots,a_{k+1})+1 \} + 1 = f_{z, z}(a_2,\dots,a_{k+1})+2$ $\max\{ f_{z, y}(a_2,\dots,a_{k+1}), f_{z, z}(a_2,\dots,a_{k+1})+1 \} = f_{z, z}(a_2,\dots,a_{k+1})+1$ Case 4.2. $a_1 = x$. The left hand side becomes $\max\{ f_{x, x}(a_2,\dots,a_{k+1})+1, f_{z, x}(a_2,\dots,a_{k+1}) \} + 1 = f_{x,x}(a_2,\dots,a_{k+1})+2$ $\max\{ f_{x, y}(a_2,\dots,a_{k+1})+1, f_{z, x}(a_2,\dots,a_{k+1})+1 \}.$ Case 4.3. $a_1 = y$. The left hand side becomes $\max\{ f_{y, x}(a_2,\dots,a_{k+1})+1, f_{z, y}(a_2,\dots,a_{k+1})+1 \} + 1.$ $\max\{ f_{y, y}(a_2,\dots,a_{k+1}), f_{z, y}(a_2,\dots,a_{k+1})+1 \} = f_{z, y}(a_2,\dots,a_{k+1})+1$ Case 4.4. $a_1 \notin \{x,y,z\}$. The left hand side becomes $\max\{ f_{a_1, x}(a_2,\dots,a_{k+1})+1, f_{z, a_1}(a_2,\dots,a_{k+1})+1 \} + 1.$ $\max\{ f_{a_1, y}(a_2,\dots,a_{k+1})+1, f_{z, a_1}(a_2,\dots,a_{k+1})+1 \}.$ The inequality holds for all cases. Therefore, the inequality holds for $n = k+1$. Conclusion. The inequality holds for every $n \geq 0$. $\Box$ Proposition 4. Suppose $a_1, a_2, \dots, a_n$ is a sequence. For every distinct $x, y, z \in \mathbb{N}$, i.e. $x \neq y, y \neq z$ and $z \neq x$, if $\mathit{next}(x) < \mathit{next}(y)$, then $f_{z,y}(a) \geq f_{z,x}(a)$. Proof: By induction on the length $n$ of sequence $a$. Basis. It is trivial for the case $n = 0$ since the both hand sides are $0$. Induction. Suppose true for the case $n = k (k \geq 0)$, i.e. $f_{z,y}(a) \geq f_{z,x}(a).$ Case 1. $a_1 = z$. By Proposition 1 and 3, the left hand side becomes $\max\{ f_{z, y}(a_2,\dots,a_{k+1}), f_{z, z}(a_2,\dots,a_{k+1})+1 \} = f_{z, z}(a_2,\dots,a_{k+1})+1,$ $\max\{ f_{z, x}(a_2,\dots,a_{k+1}), f_{z, z}(a_2,\dots,a_{k+1})+1 \} = f_{z, z}(a_2,\dots,a_{k+1})+1$ Case 2. $a_1 = x$. By Proposition 1, the left hand side becomes $\max\{ f_{x, y}(a_2,\dots,a_{k+1})+1, f_{z, x}(a_2,\dots,a_{k+1})+1 \},$ $\max\{ f_{x, x}(a_2,\dots,a_{k+1})+1, f_{z, x}(a_2,\dots,a_{k+1}) \}.$ $f_{z, x}(a_2,\dots,a_{k+1}) \geq f_{x, x}(a_2,\dots,a_{k+1}),$ Case 3. $a_1 = y$. This is impossible because $\mathit{next}(x) < \mathit{next}(y)$, i.e. there is an element of value $x$ in front of the first element of value $y$. Case 4. $a_1 \notin \{x,y,z\}$. The left hand side becomes $\max\{ f_{a_1, y}(a_2,\dots,a_{k+1})+1, f_{a_1, z}(a_2,\dots,a_{k+1})+1 \}.$ $\max\{ f_{a_1, x}(a_2,\dots,a_{k+1})+1, f_{a_1, z}(a_2,\dots,a_{k+1})+1 \}.$ Case 4.1. If $\mathit{next}(y) > \mathit{next}(z)$, then by induction we have $f_{a_1, y}(a_2,\dots,a_{k+1}) \geq f_{a_1, z}(a_2,\dots,a_{k+1}),$ $f_{a_1, y}(a_2,\dots,a_{k+1}) \geq f_{a_1, x}(a_2,\dots,a_{k+1}).$ Case 4.2. If $\mathit{next}(y) < \mathit{next}(z)$, then by induction we have $f_{a_1, z}(a_2,\dots,a_{k+1}) \geq f_{a_1, y}(a_2,\dots,a_{k+1}),$ $f_{a_1, z}(a_2,\dots,a_{k+1}) \geq f_{a_1, x}(a_2,\dots,a_{k+1}).$ The inequality holds for all cases. Therefore, the inequality holds for $n = k+1$. Conclusion. The inequality holds for every $n \geq 0$. Proposition 5 (Greedy Strategy I). Suppose $a_1, a_2, \dots, a_n$ is a sequence. For every $x, y \in \mathbb{N}$, if $a_1 = x$, then $f_{x,y}(a_1,\dots,a_n) = f_{x,x}(a_2,\dots,a_n)+1.$ Proof: By Proposition 1, we have $f_{x,y}(a_1,\dots,a_n) = \max \{ f_{x, y} (a_2, \dots, a_n), f_{x, x} (a_2, \dots, a_n) + 1 \}.$ $f_{x,x}(a_2, \dots, a_n) + 1 \geq f_{x, y} (a_2, \dots, a_n).$ Proposition 6 (Greedy Strategy II). Suppose $a_1, a_2, \dots, a_n$ is a sequence. For every $x, y \in \mathbb{N}$ with $x \neq y$, if $a_1 \notin \{x,y\}$, then $f_{x,y}(a_1,\dots,a_n) = \begin{cases} f_{a_1,y}(a_2,\dots,a_n)+1 & \mathit{next}(x) < \mathit{next}(y), \\ f_{x,a_1}(a_2,\dots,a_n)+1 & \text{otherwise}. \end{cases}$ $f_{a_1,y}(a_2,\dots,a_n) \geq f_{x,a_1}(a_2,\dots,a_n).$ The same statement holds for $\mathit{next}(x) > \mathit{next}(y)$. $\Box$
[ "constructive algorithms", "data structures", "dp", "greedy", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; int n; int a[MAXN]; int pos[MAXN], nxt[MAXN]; void solve() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 0; i <= n; ++i) pos[i] = n + 1; for (int i = n; i >= 0; --i) { nxt[i] = pos[a[i]]; pos[a[i]] = i; } int x = 0, y = 0; // the last elements of the two subarrays int res = 0; for (int z = 1; z <= n; ++z) { // Greedy Strategy I if (a[x] == a[z]) { res += a[y] != a[z]; y = z; } else if (a[y] == a[z]) { res += a[x] != a[z]; x = z; } // Greedy Strategy II else if (nxt[x] < nxt[y]) { res += a[x] != a[z]; x = z; } else { res += a[y] != a[z]; y = z; } } printf("%d\n", res); } int main() { solve(); return 0; }
1479
B2
Painting the Array II
\textbf{The only difference between the two versions is that this version asks the minimal possible answer.} Homer likes arrays a lot. Today he is painting an array $a_1, a_2, \dots, a_n$ with two kinds of colors, \textbf{white} and \textbf{black}. A painting assignment for $a_1, a_2, \dots, a_n$ is described by an array $b_1, b_2, \dots, b_n$ that $b_i$ indicates the color of $a_i$ ($0$ for white and $1$ for black). According to a painting assignment $b_1, b_2, \dots, b_n$, the array $a$ is split into two new arrays $a^{(0)}$ and $a^{(1)}$, where $a^{(0)}$ is the sub-sequence of all white elements in $a$ and $a^{(1)}$ is the sub-sequence of all black elements in $a$. For example, if $a = [1,2,3,4,5,6]$ and $b = [0,1,0,1,0,0]$, then $a^{(0)} = [1,3,5,6]$ and $a^{(1)} = [2,4]$. The number of segments in an array $c_1, c_2, \dots, c_k$, denoted $\mathit{seg}(c)$, is the number of elements if we merge all adjacent elements with the same value in $c$. For example, the number of segments in $[1,1,2,2,3,3,3,2]$ is $4$, because the array will become $[1,2,3,2]$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $0$. Homer wants to find a painting assignment $b$, according to which the number of segments in both $a^{(0)}$ and $a^{(1)}$, i.e. $\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$, is as \textbf{small} as possible. Find this number.
There are two approaches from different perspectives. DP Approach The first observation is that merging adjacent elements with the same value will not influence the answer. Therefore, without loss of generality, we may assume that there are no adjacent elements with the same value, i.e. $a_{i} \neq a_{i+1}$ for every $1 \leq i < n$. We can solve this problem by a DP approach. Let $f(i)$ denote the minimal possible number of segments for sub-array $a_1, a_2, \dots, a_i$ over all assignments $b_1, b_2, \dots, b_i$ with $b_i \neq b_{i-1}$, where $b_{0} = -1$ for convenience. To obtain the answer, we enumerate the last position $1 \leq i \leq n$ such that $b_{i-1} \neq b_i$, and append all elements $a_{i+1}, a_{i+2}, \dots, a_n$ to the end of $a_i$, which implies an arrangement with $f(i)+n-i$ segments. The minimal number of segments will be the minimum among $f(i)+n-i$ over all $1 \leq i \leq n$. It is straightforward to see that $f(0) = 0$ and $f(1) = 1$. For $2 \leq i \leq n$, $f(i)$ can be computed by enumerating every possible position $1 \leq j < i$ such that $b_{j-1} \neq b_j = b_{j+1} = \dots = b_{i-1} \neq b_i$. That is, $a_j, a_{j+1}, \dots, a_{i-1}$ are assigned to the same sub-sequence, and $a_{j-1}$ and $a_i$ are assigned to the other sub-sequence. Since no adjacent elements has the same value (by our assumption), there are $(i-j)$ segments in $a_j, a_{j+1}, \dots, a_{i-1}$ (we note that the first segment, i.e. the segment of $a_j$, is counted in $f(j)$). Moreover, there will be zero or one new segment when concatenating $a_{j-1}$ and $a_{i}$ depending on whether $a_{j-1} = a_i$ or not. Hence, for every $2 \leq j \leq n$, we have $f(i) = \min_{1 \leq j < i} \{ f(j) + (i-j-1) + [a_{j-1} \neq a_i] \},$ To optimize the DP recurrence, we fix $i$, and let $g(j) = f(j) + (i-j-1) + [a_{j-1} \neq a_i]$, then $f(i) = \max_{1\leq j < i}\{g(j)\}$. We can observe that Lemma 1. For $2 \leq i \leq n$, we have $f(i) = \min\{ g(i-1), g(j^*) \},$ This lemma is very intuitive, which means we need only to consider two cases: one is to just append $a_i$ after $a_{i-1}$ in the same sub-sequence, and the other is to append $a_i$ after the closest $a_{j}$ with the same value, i.e. $a_i = a_j$, and then assign the elements between them (not inclusive) to the other sub-sequence. With this observation, we immediately obtain an $O(n)$ DP solution. The proof is appended below for completeness. Proof: For every $1 \leq j < i$, we have $f(i) \leq g(j) = f(j) + (i-j-1) + [a_{j-1} \neq a_i] \leq f(j) + i - j,$ Now we consider $g(j)$ for every $1 \leq j < i$ in two cases. $a_{j-1} \neq a_i$. We have $\begin{aligned} g(j) & = f(j) + (i-j-1) + 1 \\ & = f(j)-j+i \\ & \geq f(i-1)-(i-1) + i \\ & = f(i-1)+1 \\ & \geq g(i-1).\end{aligned}$ $\begin{aligned} g(j) & = f(j) + (i-j-1) + 1 \\ & = f(j)-j+i \\ & \geq f(i-1)-(i-1) + i \\ & = f(i-1)+1 \\ & \geq g(i-1).\end{aligned}$ $a_{j-1} = a_i$. Suppose there are two different positions $j_1$ and $j_2$ such that $1 \leq j_1 < j_2 < i$ and $a_{j_1-1} = a_{j_2-2} = a_i$, then $\begin{aligned} g(j_1) & = f(j_1) + (i-j_1-1) \\ & = f(j_1) -j_1 +i-1 \\ & \geq f(j_2)-j_2+i-1 \\ & = g(j_2). \end{aligned}$ $\begin{aligned} g(j_1) & = f(j_1) + (i-j_1-1) \\ & = f(j_1) -j_1 +i-1 \\ & \geq f(j_2)-j_2+i-1 \\ & = g(j_2). \end{aligned}$ Greedy Approach Consider we have a computer whose cache has only two registers. Let's suppose the array $a$ is a sequence of memory access to the computer. The problem is then converted to a more intuitive one that asks the optimal cache replacement. Suppose the current two registers contains two memory accesses $x$ and $y$, and the current requirement memory access is $z$. The greedy strategy is simple: If $z$ matches one of $x$ and $y$, just do nothing. Otherwise, the register that contains the memory access whose next occurrence is farther than the other will be replaced by $z$. This strategy is know as Bélády's algorithm or farthest-in-the-future cache/page replacement policy (see here for more information). The complexity is $O(n)$ since we only need to preprocess every element's next occurrence. DP:
[ "constructive algorithms", "data structures", "dp", "greedy", "implementation" ]
2,100
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; int n; int a[MAXN]; int pos[MAXN], nxt[MAXN]; void solve() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 0; i <= n; ++i) pos[i] = n + 1; for (int i = n; i >= 0; --i) { nxt[i] = pos[a[i]]; pos[a[i]] = i; } int x = 0, y = 0; // the last elements of the two subarrays int res = 0; for (int z = 1; z <= n; ++z) { // if one of the two last elements matches a[z], just append a[z] after it. if (a[x] == a[z]) { x = z; } else if (a[y] == a[z]) { y = z; } // otherwise, replace the later one. else if (nxt[x] > nxt[y]) { res += 1; x = z; } else { res += 1; y = z; } } printf("%d\n", res); } int main() { solve(); return 0; }
1479
C
Continuous City
Some time ago Homer lived in a beautiful city. There were $n$ blocks numbered from $1$ to $n$ and $m$ directed roads between them. Each road had a positive length, and each road went from the block with the smaller index to the block with the larger index. For every two (different) blocks, there was at most one road between them. Homer discovered that for some two numbers $L$ and $R$ the city was $(L, R)$-continuous. The city is said to be $(L, R)$-continuous, if - all paths from block $1$ to block $n$ are of length between $L$ and $R$ (inclusive); and - for every $L \leq d \leq R$, there is \textbf{exactly one} path from block $1$ to block $n$ whose length is $d$. A path from block $u$ to block $v$ is a sequence $u = x_0 \to x_1 \to x_2 \to \dots \to x_k = v$, where there is a road from block $x_{i-1}$ to block $x_{i}$ for every $1 \leq i \leq k$. The length of a path is the sum of lengths over all roads in the path. Two paths $x_0 \to x_1 \to \dots \to x_k$ and $y_0 \to y_1 \to \dots \to y_l$ are different, if $k \neq l$ or $x_i \neq y_i$ for some $0 \leq i \leq \min\{k, l\}$. After moving to another city, Homer only remembers the two special numbers $L$ and $R$ but forgets the numbers $n$ and $m$ of blocks and roads, respectively, and how blocks are connected by roads. However, he believes the number of blocks should be no larger than $32$ (because the city was small). As the best friend of Homer, please tell him whether it is possible to find a $(L, R)$-continuous city or not.
The answer is always "YES". For convenience, we write $(x, y, z)$ for a directed road from block $x$ to block $y$ of length $z$. Step 1. We can solve the case $L = 1$ and $R = 2^k$ for $k \geq 0$ inductively. The case for $k = 0$ is trivial, i.e. only one edge $(1, 2, 1)$. Suppose there is a city of $k + 2$ blocks for $L = 1$ and $R = 2^k$ for some $k \geq 0$, and the induced city from block $1$ to block $x$ is $(1, 2^{x-2})$-continuous for every $2 \leq x \leq k + 2$. Let block $k + 3$ be a new block, and add $(1, k+3, 1)$ and $(x, k+3, 2^{x-2})$ for $2 \leq x \leq k+2$. We can see that the new city containing block $k + 3$ is $(1, 2^{k+1})$-continuous. Step 2. Suppose $L = 1$ and $R > 1$. Let $R - 1 = \sum_{i=0}^k R_i 2^i$ be the binary representation of $R - 1$, where $0 \leq R_i \leq 1$. Let $G_k$ be the $(1, 2^k)$-continuous city constructed in Step 1. Let block $k + 3$ be a new block. Connect $(1, k+3, 1)$, and then for every $0 \leq i \leq k$, if $R_i = 1$, then connect $(i+2, k+3, 1+\sum_{j=i+1}^k R_j 2^j)$. We can see that the new city containing block $k + 3$ is $(1, R)$-continuous. Step 3. Suppose $1 < L \leq R$. Consider $H_{R-L+1}$, where $H_R$ denotes the $(1, R)$-continuous city constructed in Step 2 and there are $k$ blocks in $H_{R-L+1}$. Connect $(k, k+1, L-1)$. We can see that the new city containing block $k + 1$ is $(L, R)$-continuous. We note that there is at most $23$ blocks in our constructed city.
[ "bitmasks", "constructive algorithms" ]
2,500
#include <bits/stdc++.h> using namespace std; vector<tuple<int, int, int>> edges; void addedge(int x, int y, int z) { edges.push_back({ x, y, z }); } int solve(int L, int R) { if (L > 1) { int k = solve(1, R - L + 1); addedge(k, k + 1, L - 1); return k + 1; } if ((R & -R) == R) // if L == 1 and R is a power of 2 { int k = __builtin_ctz(R); addedge(1, 2, 1); for (int i = 3; i <= k + 2; ++i) { addedge(1, i, 1); for (int j = 2; j < i; ++j) addedge(j, i, 1 << (j - 2)); } return k + 2; } int k = 0; while (1 << (k + 1) <= R - 1) ++k; solve(1, 1 << k); addedge(1, k + 3, 1); for (int i = 0; i <= k; ++i) if ((R - 1) >> i & 1) addedge(i + 2, k + 3, 1 + ((R - 1) >> (i + 1) << (i + 1))); return k + 3; } int main() { int L, R; scanf("%d%d", &L, &R); puts("YES"); int n = solve(L, R); printf("%d %d\n", n, (int)edges.size()); for (auto [x, y, z] : edges) printf("%d %d %d\n", x, y, z); return 0; }
1479
D
Odd Mineral Resource
In Homer's country, there are $n$ cities numbered $1$ to $n$ and they form a tree. That is, there are $(n-1)$ undirected roads between these $n$ cities and every two cities can reach each other through these roads. Homer's country is an industrial country, and each of the $n$ cities in it contains some mineral resource. The mineral resource of city $i$ is labeled $a_i$. Homer is given the plans of the country in the following $q$ years. The plan of the $i$-th year is described by four parameters $u_i, v_i, l_i$ and $r_i$, and he is asked to find any mineral resource $c_i$ such that the following two conditions hold: - mineral resource $c_i$ appears an \textbf{odd} number of times between city $u_i$ and city $v_i$; and - $l_i \leq c_i \leq r_i$. As the best friend of Homer, he asks you for help. For every plan, find any such mineral resource $c_i$, or tell him that there doesn't exist one.
Let $s(u, v, c)$ denote the number of cities between city $u$ and city $v$, whose mineral resource is $c$. We restate the problem that for each query $u, v, l, r$, find an integer $c$ such that $l \leq c \leq r$ and $s(u, v, c) \not\equiv 0 \pmod 2$. We give a randomized algorithm with success probability extremely high. For every kind of mineral resources $1 \leq i \leq n$, we assign a random variable $X_i$ to it. Those random variables $X_i$ are independent and identically uniformly distributed from $[0, 2^{64}-1]$. For every city $u$, we assign its weight to be $X_{c_u}$. For every query $u, v, l, r$, Let $f(u, v, l, r)$ be the bitwise XOR of all weights of all cities between city $u$ and city $v$, whose mineral resources are in $[l, r]$. We claim that $\Pr\left[\, f(u, v, l, r) = 0 \mid \forall c, s(u, v, c) \equiv 0 \pmod 2 \,\right] = 1$, which means that if a suitable $c$ does not exist then $f(u, v, l, r) = 0$ for certainty, and $\Pr\left[\, f(u, v, l, r) \neq 0 \mid \exists c, s(u, v, c) \not\equiv 0 \pmod 2 \,\right] = 1-2^{-64}$, which means that if a suitable $c$ does exist then $f(u, v, l, r) \neq 0$ with high probability. $\Pr\left[\, \forall c, s(u, v, c) \equiv 0 \pmod 2 \mid f(u, v, l, r) = 0 \,\right] = 1-2^{-64}$, which implies with high probability no suitable mineral resource exists if $f(u, v, l, r) = 0$, and $\Pr\left[\, \exists c, s(u, v, c) \not\equiv 0 \pmod 2 \mid f(u, v, l, r) \neq 0 \,\right] = 1$, which implies with certainty at least one suitable mineral resource exists. to report no solution if $f(u, v, l, r) = 0$, and to find a $c$ ($l \leq c \leq r$) such that $f(u, v, c, c) \neq 0$ if $f(u, v, l, r) \neq 0$. Now consider there are $q$ queries. Let $A_i$ denote the event that the $i$-th query succeeds. The $i$-th query will succeed with probability $\Pr[A_i] \geq 1-2^{-64}$ (however, they may not be independent). Then we have $\begin{aligned} \Pr\left[ \bigwedge_{i=1}^{q} A_i \right] & = 1 - \Pr\left[ \bigvee_{i=1}^q \bar A_i \right] \\ & \geq 1 - \sum_{i=1}^q \Pr[\bar A_i] \\ & = 1 - \sum_{i=1}^q \left( 1 - \Pr[A_i] \right) \\ & \geq 1 - \sum_{i=1}^q \left( 1 - \left( 1 - 2^{-64} \right) \right) \\ & = 1 - 2^{-64}q, \end{aligned}$ To this end, we shall compute $f(u, v, l, r)$ and find a $c$ ($l \leq c \leq r$) such that $f(u, v, c, c) \neq 0$. This can be solved by consistent segment trees. Let's root the tree (by any vertex, say vertex $1$). For every vertex $u$, we maintain a (consistent) segment tree that for each interval $[l, r]$ computes $f(1, u, l, r)$. Let $\mathit{father}(u)$ be the father of vertex $u$, and $\mathit{lca}(u, v)$ be the least common ancestor of vertex $u$ and vertex $v$. Then $f(u, v, l, r) = f(1, u, l, r) \oplus f(1, v, l, r) \oplus f(1, \mathit{lca}(u, v), l, r) \oplus f(1, \mathit{father}(\mathit{lca}(u, v)), l, r).$
[ "binary search", "bitmasks", "brute force", "data structures", "probabilities", "trees" ]
2,900
#include <bits/stdc++.h> using namespace std; const int MAXN = 300010; const int MAXK = 20; mt19937_64 rd(chrono::steady_clock::now().time_since_epoch().count()); int n, q; int a[MAXN]; uint64_t h[MAXN]; vector<int> v[MAXN]; int pre[MAXN][MAXK]; int dis[MAXN]; struct node { node* Lc, * Rc; uint64_t val; node() { Lc = Rc = nullptr; val = 0; } void update() { this->val = this->Lc->val ^ this->Rc->val; } }; int tot; node nodes[MAXN * 22]; node* root[MAXN]; node* new_node() { node* it = &nodes[++tot]; return it; } node* build(int L, int R) { node* it = new_node(); if (L < R) { int m = (L + R) / 2; it->Lc = build(L, m); it->Rc = build(m + 1, R); it->update(); } return it; } node* modify(node* p, int L, int R, int x) { node* it = new_node(); *it = *p; if (L == R) { it->val ^= h[x]; return it; } int m = (L + R) / 2; if (x <= m) it->Lc = modify(p->Lc, L, m, x); else if (x > m) it->Rc = modify(p->Rc, m + 1, R, x); it->update(); return it; } void dfs(int x) { dis[x] = dis[pre[x][0]] + 1; root[x] = modify(root[pre[x][0]], 1, n, a[x]); for (auto y : v[x]) { if (y == pre[x][0]) continue; pre[y][0] = x; dfs(y); } } int getlca(int x, int y) { if (dis[x] < dis[y]) swap(x, y); for (int k = MAXK - 1; k >= 0; --k) if (dis[x] - dis[y] >= 1 << k) x = pre[x][k]; if (x == y) return x; for (int k = MAXK - 1; k >= 0; --k) if (pre[x][k] != pre[y][k]) { x = pre[x][k]; y = pre[y][k]; } return pre[x][0]; } int calc(node* a, node* b, node* c, node* d, int L, int R) { if (L == R) return L; int m = (L + R) / 2; if (a->Lc->val ^ b->Lc->val ^ c->Lc->val ^ d->Lc->val) return calc(a->Lc, b->Lc, c->Lc, d->Lc, L, m); else return calc(a->Rc, b->Rc, c->Rc, d->Rc, m + 1, R); } int query(node* a, node* b, node* c, node* d, int L, int R, int x, int y) { if (L == x && R == y) { if (a->val ^ b->val ^ c->val ^ d->val) return calc(a, b, c, d, L, R); else return -1; } int m = (L + R) / 2; if (y <= m) return query(a->Lc, b->Lc, c->Lc, d->Lc, L, m, x, y); if (x > m) return query(a->Rc, b->Rc, c->Rc, d->Rc, m + 1, R, x, y); int tmp = query(a->Lc, b->Lc, c->Lc, d->Lc, L, m, x, m); if (tmp != -1) return tmp; return query(a->Rc, b->Rc, c->Rc, d->Rc, m + 1, R, m + 1, y); } int main() { scanf("%d%d", &n, &q); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= n; ++i) h[i] = rd(); for (int i = 1; i < n; ++i) { int x, y; scanf("%d%d", &x, &y); v[x].push_back(y); v[y].push_back(x); } root[0] = build(1, n); dfs(1); for (int k = 1; k < MAXK; ++k) for (int i = 1; i <= n; ++i) pre[i][k] = pre[pre[i][k - 1]][k - 1]; while (q--) { int x, y, l, r; scanf("%d%d%d%d", &x, &y, &l, &r); int z = getlca(x, y); int res = query(root[x], root[y], root[z], root[pre[z][0]], 1, n, l, r); printf("%d\n", res); } return 0; }
1479
E
School Clubs
In Homer's school, there are $n$ students who love clubs. Initially, there are $m$ clubs, and each of the $n$ students is in exactly one club. In other words, there are $a_i$ students in the $i$-th club for $1 \leq i \leq m$ and $a_1+a_2+\dots+a_m = n$. The $n$ students are so unfriendly that every day one of them (chosen \textbf{uniformly at random} from all of the $n$ students) gets angry. The student who gets angry will do one of the following things. - With probability $\frac 1 2$, he leaves his current club, then creates a new club himself and joins it. There is only one student (himself) in the new club he creates. - With probability $\frac 1 2$, he does not create new clubs. In this case, he changes his club to a new one (possibly the same club he is in currently) with probability proportional to the number of students in it. Formally, suppose there are $k$ clubs and there are $b_i$ students in the $i$-th club for $1 \leq i \leq k$ (before the student gets angry). He leaves his current club, and then joins the $i$-th club with probability $\frac {b_i} {n}$. We note that when a club becomes empty, students will never join it because any student who gets angry will join an empty club with probability $0$ according to the above statement.Homer wonders the expected number of days until every student is in the same club for the first time. We can prove that the answer can be represented as a rational number $\frac p q$ with $\gcd(p, q) = 1$. Therefore, you are asked to find the value of $pq^{-1} \bmod 998\,244\,353$. It can be shown that $q \bmod 998\,244\,353 \neq 0$ under the given constraints of the problem.
Section 1. The Expected Value of Stopping Time There may be several ways to deal with the expected value of stopping time. Here, we decide to give an elegant way to derive the expected stopping time inspired by MiFaFaOvO's comment. Here, we are going to introduce the mathematical tool we will use in the following description (see here for a Chinese explanation.) Consider a random process $A_0, A_1, A_2, \dots$, where $A_i$ is called the $i$-th event of the process, or the event at time $i$. Let random variable $T \in \mathbb{N}$ be its stopping time. That is, for every $t \in \mathbb{N}$, It can be decided whether $T = t$ as long as $A_0, A_1, \dots, A_t$ are given. If there is a function $\phi(\cdot)$ that maps an event to a real number such that $\mathbb{E}[\,\phi(A_{t+1})-\phi(A_t) \mid A_0, A_1, \dots, A_t \,] = -1$ for every $t \in \mathbb{N}$, and $\mathbb{E}[\phi(A_T)]$ depends on some properties of the events and the stopping time, which is usually a constant in practice. $\mathbb{E}[T] = \phi(A_0) - \phi(A_T).$ To begin our journey, we should first describe an event as something (a number, a tuple, a sequence, or a set) in our problem. We find it naturally to use a (multi-)set $A = \{ a_1, a_2, \dots, a_m \}$ to describe it, where $m$ denotes the number of clubs, the $i$-th of which contains $a_i$ students. We see that the explicit order of the clubs does not matter but the number of students in each club. Furthermore, we notice that every club's status is equal, which implies us to define the potential function as the form $\phi(A) = \sum_{a \in A} f(a) = \sum_{i=1}^m f(a_i),$ $n = \sum_{a \in A} a = \sum_{i=1}^m a_i.$ We first consider the corner case for the value of $f(0)$. Since students will never join an empty club, $A$ and $A \cup \{0\}$ denotes the events with the same property. Therefore, we need $\phi(A) = \phi(A \cup \{0\})$, which immediately yields $f(0) = 0$. We now investigate how the potential function behaves from the $t$-th event $A_t = \{ a_1, a_2, \dots, a_m \}$ to the $(t+1)$-th event $A_{t+1}$. We note that the student who gets angry is in the $i$-th club with probability $\frac {a_i} n$. After that, the angry student will leave and create a new club with probability $\frac 1 2$. In this case, $A_{t+1} = \{ a_1, a_2, \dots, a_{i-1}, a_i-1, a_{i+1}, \dots, a_m, 1 \}$, and we have $\phi(A_{t+1}) = \phi(A_t)-f(a_i)+f(a_i-1)+f(1),$ $\phi(A_{t+1}) = \phi(A_t)-f(a_i)+f(a_i-1)+f(1),$ join the $j$-th club ($j \neq i$) with probability $\frac {a_j} {2n}$. In this case, $A_{t+1} = \{ a_1, a_2, \dots, a_i-1, a_j +1, \dots, a_m\}$, and we have $\phi(A_{t+1}) = \phi(A_t)-f(a_i)-f(a_j)+f(a_i-1)+f(a_j+1),$ $\phi(A_{t+1}) = \phi(A_t)-f(a_i)-f(a_j)+f(a_i-1)+f(a_j+1),$ stay still in the $i$-th club with probability $\frac {a_i} {2n}$. In this case, $A_{t+1} = A_t$, and we have $\phi(A_{t+1}) = \phi(A_t).$ $\phi(A_{t+1}) = \phi(A_t).$ To sum it up, we get that $\begin{aligned} \mathbb{E}[\, \phi(A_{t+1}) \mid A_t \,] = \sum_{i=1}^m \frac {a_i} n \Bigg[ & \frac 1 2 \big(\phi(A_t)-f(a_i)+f(a_i-1)+f(1)\big) \\ &+ \sum_{j \neq i} \frac {a_j} {2n} \big( \phi(A_t)-f(a_i)-f(a_j)+f(a_i-1)+f(a_j+1) \big) + \frac {a_i} {2n} \phi(A_t) \Bigg]. \end{aligned}$ $f(1) + \sum_{i=1}^m \frac {a_i} {n^2} \left[ (2n - a_i) f(a_i-1) + (n - a_i) f(a_i+1) - (3n - 2a_i) f(a_i) \right] + 2 = 0.$ There are several possible ways to assign the value of $f(a)$. We choose the most simple one such that $f(1)+2 = 0$, which removes the constant term. Under this assignment, we have $f(1) = -2$. After this, we have to make that $(2n - a) f(a-1) + (n - a) f(a+1) - (3n - 2a) f(a) = 0,$ $(n-a) \left[ f(a+1)-f(a) \right] = (2n-a) \left[ f(a)-f(a-1) \right].$ We let $g(a) = f(a+1)-f(a)$ for $a \geq 0$. Therefore, $g(0) = f(1)-f(0) = -2$, and $\begin{aligned} g(a) & = \frac {2n-a} {n-a} g(a-1) \\ & = \frac {2n-a} {n-a} \cdot \frac {2n-(a-1)} {n-(a-1)} g(a-1) \\ & = \dots \\ & = \frac {2n-1} {n-1} \cdot \frac {2n-2} {n-2} \cdot \dots \cdot \frac {2n-a} {n-a} g(0). \end{aligned}$ $\begin{aligned} f(a) & = f(0) + g(0) + g(1) + \dots + g(a-1) \\ & = -2 \left[ 1 + \frac {P(1)} {Q(1)} + \frac {P(2)} {Q(2)} + \dots + \frac {P(1)P(2) \dots P(a-1)} {Q(1)Q(2) \dots Q(a-1)} \right], \end{aligned}$ Section 2. The Trick for the Prefix Sum by Generating Functions For convenience, we denote $S(a) = \frac {P(1)} {Q(1)} + \frac {P(2)} {Q(2)} + \dots + \frac {P(1)P(2) \dots P(a)} {Q(1)Q(2) \dots Q(a)},$ Let $N > a$ be a large enough positive integer. Then we have $\begin{aligned} S(a) = \frac 1 {Q(1)Q(2) \dots Q(N)} \Big[ & P(1)Q(2)Q(3)\dots Q(a)Q(a+1) \dots Q(N) + \\ & P(1)P(2)Q(3)\dots Q(a)Q(a+1) \dots Q(N) + \\ & \dots + \\ & P(1)P(2)P(3)\dots P(a)Q(a+1) \dots Q(N) \Big]. \end{aligned}$ $\begin{aligned} R(z) = & P(z+1)Q(z+2)Q(z+3) \dots Q(z+B) + \\ & P(z+1)P(z+2)Q(z+3) \dots Q(z+B) + \\ & \dots + \\ & P(z+1)P(z+2)P(z+3) \dots P(z+B). \end{aligned}$ $\begin{aligned} s(a) = & \sum_{k=0}^{\lfloor{a/B}\rfloor} P(1)\dots P(kB) R(kB) Q((k+1)B+1) \dots Q(N) \\ & + \sum_{i=(\lfloor{a/B}\rfloor+1)B+1}^a P(1)\dots P(i) Q(i+1) \dots Q(N). \end{aligned}$ $\sum_{k=0}^{\lfloor{a/B}\rfloor} \mathfrak{P}(k) R(kB) \mathfrak{Q}(k+1).$ Compute $R(z)$ We deal with $R(z)$ first. We note that $R(z)$ is a polynomial of degree $B$ and we want to compute $R(kB)$ for every $0 \leq k \leq N/B$. If we can obtain the values of $R(0), R(1), \dots, R(B)$, then by Lagrange interpolation, we can recover the polynomial $R(z)$. And then, if we know the exact polynomial $R(z)$, then by multi-point evaluation trick, we can compute the values of $R(kB)$ for every $k \leq N/B$. The total time complexity would be $O(\sqrt{N} \log^2 N)$. We can compute $R(0)$ in $O(B)$ time. And then, we note that $R(z) = \frac {Q(z+B)} {P(z)} R(z-1) - Q(z+1) \dots Q(z+B) + P(z+1) \dots P(z+B).$ Bonus: A "log" in the complexity may be eliminated by some trick similar to min_25's blog? Compute $\mathfrak{P}(k)$ This subproblem is very similar to compute the factorial-like product, which is originally mentioned in min_25's blog. To solve it, we define $f_P(z) = P(z+1)P(z+2) \dots P(z+B).$ compute $\mathfrak{Q}(k)$ This subproblem is more tricky if we are able to compute $\mathfrak{P}(k)$ fast. Similarly, we define $f_Q(z)$ as what we did when computing $\mathfrak{P}(k)$. Let $\mathfrak{Q}'(k)$ be the prefix block products of $Q(x)$ as an analog for $\mathfrak{P}(k)$ and $P(x)$. It can be easily seen that $\mathfrak{Q}(k) = \frac {Q(1)Q(2)\dots Q(N)} {\mathfrak{Q}'(k)}.$ Having computed all values we need in the previous several sections, we are able to compute the value of a single $f(a)$ in $O(\sqrt N)$ time. Therefore, the overall complexity is $O(\sqrt N \log^2 N + m \sqrt N)$. Bonus: Saving $\log n$ in Complexity Moreover, we can save $\log n$ in complexity with an improved interpolation method for shifting evaluation values. See the paper "A. Bostan, P. Gaudry, and E. Schost, Linear recurrences with polynomial coefficients and application to integer factorization and Cartier-Manin operator. SIAM Journal of Computing, 36(6): 1777-1806. 2007". Shifting evaluation values Suppose given are a polynomial $f(x)$ of degree $d$ by a point-value representation $f(0), f(1), \dots, f(d)$ and a shift $\delta$. It is asked to compute an alternative point-value representation $f(\delta), f(\delta+1), \dots, f(\delta+d)$. A straightforward way to solve this problem is to directly make use of Lagrange interpolation and multi-point evaluation, which yields an $O(d \log^2 d)$ arithmetic complexity algorithm. In fact, we can do it better in $O(d \log d)$ time. Recall the formula of Lagrange interpolation that given $n$ points $(x_i, y_i)$ where $y_i = f(x_i)$, then the unique polynomial of degree $(n-1)$ is $f(x) = \sum_{i=1}^n y_{i} \prod_{j \neq i} \frac {x-x_j} {x_i-x_j}.$ $f(x) = \sum_{i=0}^d f(i) \prod_{j \neq i} \frac {x-j} {i-j}.$ $\begin{aligned} f(\delta+k) & = \sum_{i=0}^d f(i) \prod_{j \neq i} \frac {\delta+k-j} {i-j} \\ & = \left( \prod_{j=0}^d (\delta+k-j) \right) \left( \sum_{i=0}^d \frac {(-1)^{d-i} f(i)} {i! (d-i)!} \cdot \frac {1} {\delta+k-i} \right). \end{aligned}$ $A(x) = \sum_{i=0}^d \frac {(-1)^{d-i} f(i)} {i! (d-i)!} x^i,$ $B(x) = \sum_{i=0}^{2d} \frac {1} {\delta+i-d} x^i.$ $f(\delta+k) = \left( \prod_{j=0}^d (\delta+k-j) \right) [x^{d+k}] A(x)B(x).$ Therefore, $f(\delta), f(\delta+1), \dots, f(\delta+d)$ can be computed in $O(d \log d)$ time. Arithmetic sequence shifting Now we consider a modified version: given a polynomial of degree $d$ by a point-value representation $f(0), f(s), f(2s), \dots, f(ds)$ and a shift $\delta$, compute $f(\delta), f(\delta+s), f(\delta+2s), \dots, f(\delta+ds)$. The trick is to let $g(x) = f(xs)$, which is also a polynomial of degree $d$. Then the problem becomes: given $g(0), g(1), \dots, g(s)$ and a shift $\delta' = \delta/s$, compute $g(\delta'), g(\delta'+1), \dots, g(\delta'+d)$. Divide and conquer Let's consider how to compute $R(z)$. For convenience, we denote that $\begin{aligned} R_B(z) = & P(z+1)Q(z+2)Q(z+3) \dots Q(z+B) + \\ & P(z+1)P(z+2)Q(z+3) \dots Q(z+B) + \\ & \dots + \\ & P(z+1)P(z+2)P(z+3) \dots P(z+B), \end{aligned}$ $P_B(z) = P(z+1)P(z+2) \dots P(z+B),$ $Q_B(z) = Q(z+1)Q(z+2) \dots Q(z+B),$ $\begin{matrix} R_B(0), & R_B(s), & \dots, & R_B(sB), \\ P_B(0), & P_B(s), & \dots, & P_B(sB), \\ Q_B(0), & Q_B(s), & \dots, & Q_B(sB). \end{matrix}$ To compute these values recurrently, we should notice that $R_{2B}(z) = R_B(z) Q_B(z+B) + P_B(z) R_B(z+B),$ $P_{2B}(z) = P_B(z) P_B(z+B),$ $Q_{2B}(z) = Q_B(z) Q_B(z+B).$ $\begin{aligned} P_{2B}(0) & = P_B(0) P_B(B), \\ P_{2B}(s) & = P_B(s) P_B(s+B), \\ \dots, \\ P_{2B}(sB) & = P_B(sB) P_B(sB+B), \\ P_{2B}(sB+1) & = P_B(sB+1) P_B(sB+B+1), \\ \dots, \\ P_{2B}(2sB) & = P_B(2sB) P_B(2sB+B). \end{aligned}$ $\begin{matrix} P_B(0), & P_B(s), & \dots, & P_B(sB), \\ P_B(B), & P_B(B+s), & \dots, & P_B(B+sB), \\ P_B(sB), & P_B(sB+s), & \dots, & P_B(sB+sB), \\ P_B(B+sB), & P_B(B+sB+s), & \dots, & P_B(B+sB+sB). \end{matrix}$ $T(d) = T(d/2) + O(d \log d).$ In our case, $d = O(\sqrt N)$, then the complexity is reduced to $O(\sqrt N \log N + m \sqrt N)$. Conclusion We use the trick, SQRT decomposition, to split summations into blocks, and then use Lagrange interpolation and multi-point evaluation to compute the value in each block. We obtain an algorithm with complexity $O(\sqrt N \log^2 N + m \sqrt N)$. A more subtle trick to save a $\log N$ is obtained by the shifting technique, which yields a faster algorithm with complexity $O(\sqrt N \log N + m \sqrt N)$. The constant factor of Lagrange interpolation and multi-point evaluation is very large, so this approach to save a $\log N$ brings a significant improvement. However, we allow suboptimal solutions that directly use Lagrange interpolation and multi-point evaluation to get AC.
[ "dp", "fft", "math", "number theory", "probabilities" ]
3,500
null
1480
A
Yet Another String Game
Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $s = s_1 s_2 \dots s_n$ of length $n$ consisting of lowercase English letters. They move in turns alternatively and \textbf{Alice makes the first move}. In a move, a player \textbf{must} choose an index $i$ ($1 \leq i \leq n$) that has not been chosen before, and change $s_i$ to any other lowercase English letter $c$ that $c \neq s_i$. When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be. A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: - $a$ is a prefix of $b$, but $a \ne b$; - in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
After some observations, we can see that the players should always choose the most significant letter to change, because it coordinates the lexicographical order of the final string most. Therefore, Alice will choose all odd indices while Bob will choose all even indices, and then Alice will change all letters she choose to the smallest possible letters while Bob will change all letters he choose to the largest possible letters. That is, Alice will change letters to "a" if the original letter is not "a" and to "b" otherwise; Bob will change letters to "z" if the original letter is not "z" and to "y" otherwise. The time complexity is $O(n)$.
[ "games", "greedy", "strings" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { string s; cin >> s; for (int i = 0; i < s.size(); ++i) { if (i % 2 == 0) { s[i] = s[i] == 'a' ? 'b' : 'a'; } else { s[i] = s[i] == 'z' ? 'y' : 'z'; } } cout << s << endl; } int main() { int tests; cin >> tests; while (tests--) solve(); return 0; }
1480
B
The Great Hero
The great hero guards the country where Homer lives. The hero has attack power $A$ and initial health value $B$. There are $n$ monsters in front of the hero. The $i$-th monster has attack power $a_i$ and initial health value $b_i$. The hero or a monster is said to be living, if his or its health value is positive (greater than or equal to $1$); and he or it is said to be dead, if his or its health value is non-positive (less than or equal to $0$). In order to protect people in the country, the hero will fight with monsters until either the hero is dead or all the monsters are dead. - In each fight, the hero can select an arbitrary living monster and fight with it. Suppose the $i$-th monster is selected, and the health values of the hero and the $i$-th monster are $x$ and $y$ before the fight, respectively. After the fight, the health values of the hero and the $i$-th monster become $x-a_i$ and $y-A$, respectively. \textbf{Note that the hero can fight the same monster more than once.} For the safety of the people in the country, please tell them whether the great hero can kill all the monsters (even if the great hero himself is dead after killing the last monster).
The hero needs $\lceil b_i/A \rceil$ attacks to kill the $i$-th monster, and he will obtain $\lceil b_i/A \rceil a_i$ damage after that. Suppose the $k$-th monster is the last monster killed by the hero. Then the health value of the hero before the last attack is $h_k = B - \sum_{i=1}^n \left\lceil \frac {b_i} {A} \right\rceil a_i + a_k.$
[ "greedy", "implementation", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; int A, B, n; int a[MAXN], b[MAXN]; void solve() { scanf("%d%d%d", &A, &B, &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i <= n; ++i) scanf("%d", &b[i]); int64_t damage = 0; for (int i = 1; i <= n; ++i) damage += int64_t(b[i] + A - 1) / A * a[i]; for (int i = 1; i <= n; ++i) if (B - (damage - a[i]) > 0) { puts("YES"); return; } puts("NO"); } int main() { int tests; scanf("%d", &tests); while (tests--) solve(); return 0; }
1481
A
Space Navigation
You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces. Space can be represented as the $XY$ plane. You are starting at point $(0, 0)$, and Planetforces is located in point $(p_x, p_y)$. The piloting system of your spaceship follows its list of orders which can be represented as a string $s$. The system reads $s$ from left to right. Suppose you are at point $(x, y)$ and current order is $s_i$: - if $s_i = \text{U}$, you move to $(x, y + 1)$; - if $s_i = \text{D}$, you move to $(x, y - 1)$; - if $s_i = \text{R}$, you move to $(x + 1, y)$; - if $s_i = \text{L}$, you move to $(x - 1, y)$. Since string $s$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, \textbf{you can delete some orders from $s$ but you can't change their positions}. Can you delete several orders (possibly, zero) from $s$ in such a way, that you'll reach Planetforces after the system processes all orders?
Hint 1: You can think of this problem as 2 independent 1D questions (one is up and down , and the other is left and right) instead of 1 2D question. Hint 2: For each 1D part what is the interval of positions that you can reach and see if the end point is in this interval. Hint 3: The interval of up and down is [-The count of D , The count of U] and the interval of left and right is [-The count of L , The count of R].
[ "greedy", "strings" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ int t;cin>>t; while(t--){ int x,y;cin>>x>>y; string s;cin>>s; int u=0,d=0,l=0,r=0; for(int i=0;i<s.length();i++){ if(s[i]=='U')u++; else if(s[i]=='R')r++; else if(s[i]=='D')d++; else l++; } if(x > 0 && r >= x )x = 0; if(x < 0 && l >= -x )x = 0; if(y > 0 && u >= y )y = 0; if(y < 0 && d >= -y )y = 0; cout<<((!x && !y)?"YES":"NO")<<endl; } }
1481
B
New Colony
After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you). You are given an array $h_1, h_2, \dots, h_n$, where $h_i$ is the height of the $i$-th mountain, and $k$ — the number of boulders you have. You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $h_i$): - if $h_i \ge h_{i + 1}$, the boulder will roll to the next mountain; - if $h_i < h_{i + 1}$, the boulder will stop rolling and increase the mountain height by $1$ ($h_i = h_i + 1$); - if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $k$-th boulder or determine that it will fall into the waste collection system.
The two key observation here is that if one boulder fall into the collection system all later boulders will fall into the collection system too and the number of boulders that will end up at any mountain is too small (Hence it will be at most $(n-1) \cdot (100 - 1)$). So we can simulate all boulders throwing until one boulder fall into the collection system, this will take at most $O(100 \cdot n)$.
[ "brute force", "greedy", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() #define fast ios::sync_with_stdio(false);cin.tie(0); typedef long long ll; typedef long double ld; typedef unsigned long long ull; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int main(){ fast int t; cin>>t; while(t--){ int n,k; cin>>n>>k; vector<int> a(n); for(int i=0;i<n;i++)cin>>a[i]; int mx = *max_element(all(a)); if(n * mx < k){ cout << -1 << '\n'; continue; } int ans = n+1; for(int b=0;b<k;b++){ int to = -2; for(int i=0;i<n-1;i++){ if(a[i] < a[i+1]){ to = i; break; } } ans = to + 1; if(to == -2)break; a[to]++; } cout << ans << '\n'; } }
1481
C
Fence Painting
You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it. You have a fence consisting of $n$ planks, where the $i$-th plank has the color $a_i$. You want to repaint the fence in such a way that the $i$-th plank has the color $b_i$. You've invited $m$ painters for this purpose. The $j$-th painter will arrive at the moment $j$ and will recolor \textbf{exactly one} plank to color $c_j$. For each painter you can choose which plank to recolor, but you can't turn them down, i. e. each painter has to color exactly one plank. Can you get the coloring $b$ you want? If it's possible, print for each painter which plank he must paint.
We must first see that the most important painter is the last one (and he will paint plank $x$ where $b_x = c_m$) because of two reasons: when he paints plank $x$ it won't be changed and if some other painter have a color that we don't need we can make him paint plank $x$, which will be repainted later. Now we need to find $x$ where $b_x = c_m$, there are three options: $b_x \ne a_x$. $b_x = a_x$. There are no $b_x = c_m$ this case is impossible and the answer is "NO". If the first two are true we choose $x$ such that $b_x \ne a_x$, then we greedily distribute all painters $j$ $(1 \le j < m)$ such that: There is plank $i$ such that $b_i = c_j$ and $b_i \ne a_i$ then the $j^{th}$ painter will paint plank $i$ (as a result the color of the $i^{th}$ plank will be changed). There is no plank $i$ such that $b_i = c_j$ and $b_i \ne a_i$ then the $j^{th}$ painter will paint plank $x$. At the end there might be some planks that didn't end up as we want so we make a last liner check on all planks $i$ and check if $b_i = a_i$, the total time is $O(n)$.
[ "brute force", "constructive algorithms", "greedy" ]
1,600
#include <bits/stdc++.h> using namespace std; #define mod 1000000007 #define oo 1000000010 const int N = 300010; int n , m; int a[N] , b[N] , c[N] , ans[N]; vector< int > g[N]; void solve(){ scanf("%d%d",&n,&m); for(int i = 1 ;i <= n;i++) g[i].clear(); for(int i = 0 ;i < n;i++) scanf("%d",&a[i]); for(int i = 0 ;i < n;i++){ scanf("%d",&b[i]); if(b[i] != a[i]) g[b[i]].push_back(i); } for(int i = 0; i < m;i++){ scanf("%d",&c[i]); } int last = -1; if((int)g[c[m - 1]].size() > 0){ last = g[c[m - 1]].back(); g[c[m - 1]].pop_back(); } else{ for(int i = 0 ;i < n;i++){ if(b[i] == c[m - 1]){ last = i; break; } } } if(last == -1){ puts("NO"); return; } ans[m - 1] = last; for(int i = 0 ;i < m - 1;i++){ if((int)g[c[i]].size() == 0){ ans[i] = last; } else{ ans[i] = g[c[i]].back(); g[c[i]].pop_back(); } } for(int i = 1;i <= n;i++){ if((int)g[i].size() > 0){ puts("NO"); return; } } puts("YES"); for(int i = 0 ;i < m;i++){ if(i) putchar(' '); printf("%d",ans[i] + 1); } puts(""); } int main(){ int t; cin >> t; while(t--) solve(); return 0; }
1481
D
AB Graph
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $n$ vertices without self-loops. In other words, you have $n$ vertices and each pair of vertices $u$ and $v$ ($u \neq v$) has both directed edges $(u, v)$ and $(v, u)$. Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $(u, v)$ and $(v, u)$ may have different labels). You are also given an integer $m > 0$. You should find a path of length $m$ such that the string obtained by writing out edges' labels when going along the path is a \textbf{palindrome}. The length of the path is the number of edges in it. \textbf{You can visit the same vertex and the same directed edge any number of times}.
If you can find any two nodes $x$, $y$ such that the edge going from $x$ to $y$ has the same value as the edge going from $y$ to $x$, then the answer is obviously YES. If not, if $m$ is odd you can just choose any two nodes $x$ and $y$ and keep going $y \xrightarrow{} x \xrightarrow{} y \xrightarrow{} x \xrightarrow{} y \xrightarrow{} x \xrightarrow{} y$ until you have a string with length $m$, because any alternating string of odd length is a palindrome. If $m$ is even than you should check if there is two consecutive edges with the same value, that is you need to find three different nodes $x$, $y$ and $z$ such that the edge $x \xrightarrow{} y$ has the same value as the edge $y \xrightarrow{} z$. Otherwise any string you can get will be an alternating string and any alternating string with even length is not a palindrome (note that for $(n \geq 3)$ it is always possible to find these three nodes). After finding nodes $x$ $y$, $z$ a way that guarantees you can generate a palindrome string is: if $\frac{m}{2}$ is odd just keep moving $x \xrightarrow{} y \xrightarrow{} z \xrightarrow{} y \xrightarrow{} x \xrightarrow{} y \xrightarrow{} z$ until you have a string of length $m$. The string will look like aabbaabb...aabbaa which is palindrome. if $\frac{m}{2}$ is even then keep moving $y \xrightarrow{} z \xrightarrow{} y \xrightarrow{} x \xrightarrow{} y \xrightarrow{} z \xrightarrow{} y$ until you have a string of length $m$. The string will look like abbaabba...abba which is palindrome. Complexity $O(n^{2} + m)$.
[ "brute force", "constructive algorithms", "graphs", "greedy", "implementation" ]
2,000
#include <bits/stdc++.h> using namespace std; #define mod 998244353 #define oo 1000000010 const int N = 1010; int n , m; char grid[N][N]; int has[N][2]; void solve(){ scanf("%d%d",&n,&m); for(int i = 0 ;i <= n;i++) has[i][0] = has[i][1] = -1; for(int i = 0 ;i < n;i++){ scanf("%s",grid[i]); for(int j = 0 ;j < n;j++){ if(j == i) continue; has[i][grid[i][j] - 'a'] = j; } } if(m & 1){ puts("YES"); for(int i = 0 ;i < m + 1;i++){ if(i) putchar(' '); printf("%d",(i & 1) + 1); } puts(""); return; } for(int i = 0 ;i < n;i++){ for(int j = i + 1;j < n;j++){ if(grid[i][j] == grid[j][i]){ puts("YES"); for(int k = 0 ;k < m + 1;k++){ if(k) putchar(' '); printf("%d",(k & 1 ? i + 1 : j + 1)); } puts(""); return; } } } for(int i = 0 ;i < n;i++){ for(int j = 0;j < n;j++){ if(i == j) continue; if(has[j][grid[i][j] - 'a'] == -1) continue; puts("YES"); int cur = has[j][grid[i][j] - 'a']; if((m / 2) % 2 == 1){ for(int k = 0 ;k < m + 1;k++){ if(k) putchar(' '); if(k % 4 == 0) printf("%d",i + 1); else if(k % 4 == 2) printf("%d",cur + 1); else printf("%d",j + 1); } puts(""); return; } printf("%d",j + 1); for(int k = 0 ;k < m / 2;k++){ if(k & 1) printf(" %d",j + 1); else printf(" %d",cur + 1); } for(int k = 0 ;k < m / 2;k++){ if(k & 1) printf(" %d",j + 1); else printf(" %d",i + 1); } puts(""); return; } } puts("NO"); return; } int main(){ int t; scanf("%d",&t); while(t--) solve(); return 0; }
1481
E
Sorting Books
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. There are $n$ books standing in a row on the shelf, the $i$-th book has color $a_i$. You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other. In one operation you can take one book from any position on the shelf and move it to the right end of the shelf. What is the minimum number of operations you need to make the shelf beautiful?
Lets try to solve the opposite version of the problem where you want to find the maximum number of books that will stay unmoved, so we will choose number of books that will stay unmoved and then move the rest in a way that will make the shelf beautiful. To do that lets first for each color $c$ find the leftmost and rightmost occurrence $l_c$ and $r_c$ and the frequency of this color $f_c$.Then we will use $dp_i$ which will find for each $i$ the maximum number of books that we can leave unmoved in the suffix $[i,n]$. We will go from right to left and for each index $i$ the $dp$ will work as follow : If $i = l_{a_i}$, we leave all occurrences of color $a_i$ unmoved and move everything in between the first and last occurrence of color $a_i$, so between $l_{a_i}$ and $r_{a_i}$ only books with color $a_i$ will stay unmoved, we can see that this will be only true if we are at the first occurrence of color $a_i$ (when $i = l_{a_i}$ because we want to cover the segment $[l_{a_i} , r_{a_i}]$), as a result $dp_i = f_{a_i} + dp_{r_{a_i} + 1}$. If $i \ne l_{a_i}$, we can keep all books with color $a_i$ in range $[i,n]$ unmoved and move everything else, as a result $dp_i = cf_{a_i}$ where $cf_{a_i}$ is the number of books with color $a_i$ in range $[i,n]$ (we can update this array as we move) (note that here we move all books even those after $r_{a_i}$). In either cases we can move the book $a_i$ and get $dp_i = dp_{i+1}$. The answer will be $n - dp_1$ and the time is $O(n)$.
[ "data structures", "dp", "greedy" ]
2,500
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() #define fast ios::sync_with_stdio(false);cin.tie(0); typedef long long ll; typedef long double ld; typedef unsigned long long ull; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int main(){ fast int n; cin>>n; vector<int> a(n),f(n),cf(n); vector<pair<int,int>> at(n,{-1,-1}); for(int i=0;i<n;i++){ cin>>a[i]; a[i]--; f[a[i]]++; if(at[a[i]].first == -1)at[a[i]] = {i,i}; at[a[i]].second = i; } vector<int> dp(n+1); for(int i=n-1;i>=0;i--){ dp[i] = dp[i+1]; cf[a[i]]++; if(i == at[a[i]].first)dp[i] = max(dp[i] , dp[at[a[i]].second + 1] + f[a[i]]); else dp[i] = max(dp[i] , cf[a[i]]); } cout << n - dp[0] << '\n'; }
1481
F
AB Tree
Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd. The problem is: You are given a connected tree rooted at node $1$. You should assign a character a or b to every node in the tree so that the total number of a's is equal to $x$ and the total number of b's is equal to $n - x$. Let's define a string for each node $v$ of the tree as follows: - if $v$ is root then the string is just one character assigned to $v$: - otherwise, let's take a string defined for the $v$'s parent $p_v$ and add to the end of it a character assigned to $v$. You should assign every node a character in a way that \textbf{minimizes the number of distinct strings} among the strings of all nodes.
let the diameter of the tree (the maximum distance between a root and a leaf) be $d$, then the answer couldn't be less than $d+1$ because you will add strings of all lengths between $1$ and $d+1$. In order to have the answer $d+1$, you need all strings with the same length to be equal, so all nodes on the same level must have the same character. Let's define an array $a$ of size $d+1$, such that $a_i$ = (number of nodes at level $i$). So if the answer is $d+1$ there must exist a subset from $a$ with sum $x$, so we assign character a to all the nodes with a level belongs to that subset, and character b to all other nodes. To check if there is a subset with sum $x$ we can use dynamic programming, the complexity of this solution is $O(x \cdot (d+1))$, which is in worst case $O(n^{2})$. But since the sum of array $a$ is equal to $n$, the number of unique values in $a$ will be at most $\sqrt{n}$, so lets have an array of size at most $\sqrt{n}$ having every value with it's frequency. Now let $dp[i][j]$ be true if it is possible to find a subset with sum $j$ in the suffix $i$. So to check if $dp[i][j]$ is true or not we need to check $dp[i+1][j - val[i]], dp[i+1][j - 2 \cdot val[i]] ... , dp[i+1][j - freq[i] \cdot val[i]]$, in another way we need to find a value $k$ such that $dp[i+1][j - k \cdot val[i]]$ is true and $(k \leq freq[i])$, so for every $j$ let's find the minimum possible $k$, if $dp[i + 1][j]$ is true then $k_j$ will be equal to $0$, otherwise it is equal to $k_{j - val[i]} + 1$. So this way we can check if the answer is $d+1$ in $O(n \cdot \sqrt{n})$. Now if the answer is not $d+1$, then it is $d+2$. To find the answer let's start from level $0$ to level $d$, when you are at level $i$ let the number of remaining nodes be $m$ (the number of nodes with depth greater than or equal to $i$) and you have $y$ remaining a's you can still use. If $a_i$ is not greater than $y$ or not greater than $m-y$, you can assign all nodes on the current level with the same character and move on to the next level. If not then you will have to use the two characters on the current level so you are going to add at least one more string on the answer. If you have two nodes on the same level having the same character but the nodes have different prefixes, then the strings will not be considered equal, so to guarantee not adding more than one string to the answer later on, you should make sure to assign the same character to all non-leaf nodes on the current level. Now if we have $l$ non-leaf nodes then $l$ must be less than or equal to $\frac{m}{2}$, because every non-leaf node should have at least one more node in it's sub tree, and we know that for any value $y$ ($\frac{m}{2} \leq max(y , m - y)$), so it is possible to assign the same character to all non-leaf nodes, after assigning all non-leaf nodes with the same character make sure to finish all the remaining copies of this character on the current level so you guarantee on the next levels all nodes will be the same. This way only one string will be added on the current level so the answer will be $d+2$. Total complexity is $O(n \cdot \sqrt{n})$
[ "dp", "greedy", "trees" ]
3,100
#include <bits/stdc++.h> using namespace std; #define mod 998244353 #define oo 1000000010 const int N = 100010; const int SQ = 500; int n , x , p; vector< int > g[N] , cur[N]; char c[N]; int mx; vector< pair<int,int> > v , v2; pair< int , char > a , b; int sz[N]; bool comp(int u,int v){ return (sz[u] < sz[v]); } int DFS(int node,int d){ mx = max(mx,d); cur[d].push_back(node); sz[node] = 1; for(int i = 0 ;i < (int)g[node].size();i++) sz[node] += DFS(g[node][i] , d + 1); return sz[node]; } bool dp[SQ][N]; int f[N]; void build_path(int i,int j){ if(i == (int)v2.size()) return; while(!dp[i + 1][j]){ f[v2[i].first]++; j -= v2[i].first; } build_path(i + 1 , j); } int main(){ scanf("%d%d",&n,&x); a = make_pair(x , 'a'); b = make_pair(n - x , 'b'); if(a > b) swap(a , b); for(int i = 2 ;i <= n;i++){ scanf("%d",&p); g[p].push_back(i); } DFS(1 , 0); for(int i = 0 ;i <= mx;i++) v.push_back(make_pair((int)cur[i].size() , i)); sort(v.begin(),v.end()); for(int i = 0 ;i < (int)v.size();i++){ if(i == 0 || v[i].first != v[i - 1].first) v2.push_back(make_pair(v[i].first , 1)); else v2.back().second++; } dp[(int)v2.size()][0] = true; int val , frq; for(int i = (int)v2.size() - 1;i >= 0;i--){ val = v2[i].first; frq = v2[i].second; vector< int > last(val , -1); for(int j = 0 ;j <= a.first;j++){ if(dp[i + 1][j] == true) last[j % val] = j; if(last[j % val] == -1 || ((j - last[j % val]) / val) > frq) dp[i][j] = false; else dp[i][j] = true; } } if(dp[0][a.first]){ build_path(0 , a.first); for(int i = 1;i <= n;i++) c[i - 1] = b.second; for(int i = 0 ;i <= mx;i++){ if(f[(int)cur[i].size()] == 0) continue; f[(int)cur[i].size()]--; for(int j = 0 ;j < (int)cur[i].size();j++) c[cur[i][j] - 1] = a.second; } printf("%d\n",mx + 1); c[n] = '\0'; puts(c); return 0; } printf("%d\n",mx + 2); for(int i = 0 ;i <= mx;i++){ sort(cur[i].begin(),cur[i].end(),comp); if(a.first < b.first) swap(a , b); while((int)cur[i].size() > 0 && a.first > 0){ c[cur[i].back() - 1] = a.second; cur[i].pop_back(); a.first--; } while((int)cur[i].size() > 0 && b.first > 0){ c[cur[i].back() - 1] = b.second; cur[i].pop_back(); b.first--; } } c[n] = '\0'; puts(c); return 0; }
1482
A
Prison Break
Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple. The prison can be represented as a rectangle $a\times b$ which is divided into $ab$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible. Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.
Each broken wall increases the number of connected regions of the plane at most by one. Since in the end every single cell must be in the same region as the outside of the prison, there has to be only one connected region, hence the answer is at least $nm$ (because there were $nm + 1$ connected regions at the beginning). To achieve the answer, one can, for example, break the upper wall in every cell.
[ "math" ]
800
null
1482
B
Restore Modulo
For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator. This generator takes four non-negative numbers $n$, $m$, $c$, $s$. $n$ and $m$ must be positive, $s$ non-negative and for $c$ it must be true that $0 \leq c < m$. The array $a$ of length $n$ is created according to the following rules: - $a_1 = s \bmod m$, here $x \bmod y$ denotes remainder of the division of $x$ by $y$; - $a_i = (a_{i-1} + c) \bmod m$ for all $i$ such that $1 < i \le n$. For example, if $n = 5$, $m = 7$, $c = 4$, and $s = 10$, then $a = [3, 0, 4, 1, 5]$. Price of such an array is the value of $m$ in this generator. Alex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers $n$, $m$, $c$, $s$ that generate this array. If yes, then maximize $m$.
Handle the case of $c = 0$ separately. For this check whether for every $i$ from $1\leq i < n$ there holds an equality $arr[i] = arr[i + 1]$ (or in other words, all numbers are the same). If this is true then the modulo can be arbitrarily large. Otherwise, if $arr[i] = arr[i + 1]$ holds for at least one $i$, then $c$ must equal zero, but we already know that it's not the case, so the answer is $-1$. Ok, now $c\neq 0$ and no two consecutive numbers coincide. Note that $x + c\pmod{m}$ is either $x + c$ or $x - (m - c)$. So all positive differences (between pairs of consecutive numbers) must be the same, as well as all negative differences. Otherwise the answer is $-1$. If there is no positive difference (or similarly if there is no negative difference) then the modulo can be arbitrarily large. Otherwise the modulo has to equal their sum $c + (m - c) = m$. After we find out $m$ and $c$ it only remains to check if they in fact generate our sequence.
[ "implementation", "math" ]
1,500
null
1482
C
Basic Diplomacy
Aleksey has $n$ friends. He is also on a vacation right now, so he has $m$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $m$ days. On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $\left\lceil\dfrac{m}{2}\right\rceil$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone. Help him to choose teammates so that nobody is chosen strictly more than $\left\lceil\dfrac{m}{2}\right\rceil$ times.
First, for each day we select an arbitrary friend from the list. With this choice, at most one friend will play more than $\left\lceil\dfrac{m}{2}\right\rceil$ times. Let's call him $f$. We want to fix schedule such that $f$ will play exactly $\left\lceil\dfrac{m}{2}\right\rceil$ times. To do this, we go through all the days and, if $f$ is assigned on a certain day and someone else can play this day, then we assign anyone except $f$ for that day. We will make such replacements while $f$ plays more than $\left\lceil\dfrac{m}{2}\right\rceil$ times. There is only one case when this is not possible: if $f$ is the only friend who can play in more than $\left\lceil\dfrac{m}{2}\right\rceil$ days.
[ "brute force", "constructive algorithms", "greedy", "implementation" ]
1,600
null
1482
D
Playlist
Arkady has a playlist that initially consists of $n$ songs, numerated from $1$ to $n$ in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song $1$. The playlist is cycled, i. e. after listening to the last song, Arkady will continue listening from the beginning. Each song has a genre $a_i$, which is a positive integer. Let Arkady finish listening to a song with genre $y$, and the genre of the next-to-last listened song be $x$. If $\operatorname{gcd}(x, y) = 1$, he deletes the last listened song (with genre $y$) from the playlist. After that he continues listening normally, skipping the deleted songs, and \textbf{forgetting} about songs he listened to before. In other words, after he deletes a song, he can't delete the next song immediately. Here $\operatorname{gcd}(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. For example, if the initial songs' genres were $[5, 9, 2, 10, 15]$, then the playlist is converted as follows: [\textbf{5}, 9, 2, 10, 15] $\to$ [\textbf{5}, \textbf{9}, 2, 10, 15] $\to$ [5, 2, 10, 15] (because $\operatorname{gcd}(5, 9) = 1$) $\to$ [5, \textbf{2}, 10, 15] $\to$ [5, \textbf{2}, \textbf{10}, 15] $\to$ [5, 2, \textbf{10}, \textbf{15}] $\to$ [\textbf{5}, 2, 10, \textbf{15}] $\to$ [\textbf{5}, \textbf{2}, 10, 15] $\to$ [5, 10, 15] (because $\operatorname{gcd}(5, 2) = 1$) $\to$ [5, \textbf{10}, 15] $\to$ [5, \textbf{10}, \textbf{15}] $\to$ ... The bold numbers represent the two last played songs. Note that after a song is deleted, Arkady forgets that he listened to that and the previous songs. Given the initial playlist, please determine which songs are eventually deleted and the order these songs are deleted.
Let's call a pair of songs bad if GCD of their genres is $1$. It is easy to check if two songs are bad with Euclid's algorithm in $O(\log{C})$. There are at most $n$ deletions, so simulation is fine in terms of time limit, but we should be able to find the next deleted song quickly. Let's maintain an ordered set of songs on the playlist, and also another ordered set that stores pairs of bad consecutive songs. It is easy to see that after we delete a song, only constant number of changes is needed to these sets. Let the song being deleted be $b$, while the previous song be $a$, and the next song in the playlist be $c$. It is easy to find $a$ and $c$ using the playlist set. Then we should: remove $b$ from the playlist set; remove $(a, b)$ from the bad pairs set; remove $(b, c)$ from the bad pairs set if this pair is bad; add $(a, c)$ to the bad pairs set if this pair is bad. If we store the sets in some fast enough data structure (e. g. balanced binary tree, standard C++'s set is enough), we have fast running time ($O(n (\log{n} + \log{C}))$). It is also possible to solve this problem with double-linked lists or DSU with $O(n \log{C})$ complexity.
[ "data structures", "dsu", "implementation", "shortest paths" ]
1,900
null
1482
E
Skyline Photo
Alice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help. There are $n$ buildings in the city, the $i$-th of them has positive height $h_i$. All $n$ building heights in the city are different. In addition, each building has a beauty value $b_i$. Note that beauty can be positive or negative, as there are ugly buildings in the city too. A set of photos consists of one or more photos of the buildings in the skyline. Each photo includes one or more buildings in the skyline that form a contiguous segment of indices. Each building needs to be in \textbf{exactly one} photo. This means that if a building does not appear in any photo, or if a building appears in more than one photo, the set of pictures is not valid. The beauty of a photo is equivalent to the beauty $b_i$ of the shortest building in it. The total beauty of a set of photos is the sum of the beauty of all photos in it. Help Alice to find the maximum beauty a valid set of photos can have.
We can solve this problem with DP. A trivial $O(n^2)$ algorithm would look like this: Define $dp_i$ as the maximum beauty that can be achieved if we have a set of photos of buildings from $1$ to $i$. We can check every possible splitting point $j \le i$ for the rightmost picture of the set, and keep the biggest answer. $dp_i = max_{j \le i}(dp_{j - 1} + b_{j..i})$. Now we just need to optimize this solution. Assume we are calculating $dp_i$ First important thing we need to realize is that, if we find the position of the closest smaller number to the left of $i$, on position $j$, and we choose to add it in the rightmost photo with building $i$, then the best solution would be on $dp_j$, because all numbers after $j$ are bigger than $h_j$, so they would not change the beauty of the picture (this is assuming that $i$ and $j$ are on the same photo). Note that we had already calculated the max beauty of $dp_j$, so it is not necessary to go back any further, as we have the best answer stored at $dp_j$ Having this observation, we are just left to check numbers between $j$ and $i$ as possible splitting points for the rightmost picture (the case where building $j$ and building $i$ are in different pictures). But we now know that every height from $j + 1$ to $i - 1$ is bigger than $h_i$ ( this is because $j$ is the closets smaller height), so the answer will just be $dp_{k - 1}$ + $b_i$ for any $k$ between $j + 1$ and $i$. We want to maximize the answer, so we just want to look for the max $dp_k$ value in this range. To do this, we can keep a max segment tree with dp values, and query it in $O(lgn)$ time. After we calculate $dp_i$, we insert it to the segment tree. This gives un an $O(n*lgn)$ solution, enough to solve the problem. For the final implementation, we can iterate from 1 to $n$, keeping a stack with height values, to calculate the closest smaller building for each building. We just pop the stack while the current building is smaller than the top value of the stack, and insert the current building on top of the stack. Actually, by using this trick right, a segment tree is not really necessary. We can calculate the minimum answer for the ranges by updating information as we delete or add numbers in the stack. So it is possible to achieve a linear time solution. However, $O(n*lgn)$ is enough to solve the problem, so this optimization is not necessary.
[ "data structures", "divide and conquer", "dp" ]
2,100
null
1482
F
Useful Edges
You are given a weighted undirected graph on $n$ vertices along with $q$ triples $(u, v, l)$, where in each triple $u$ and $v$ are vertices and $l$ is a positive integer. An edge $e$ is called useful if there is at least one triple $(u, v, l)$ and a path (not necessarily simple) with the following properties: - $u$ and $v$ are the endpoints of this path, - $e$ is one of the edges of this path, - the sum of weights of all edges on this path doesn't exceed $l$. Please print the number of useful edges in this graph.
Find all distances between vertices via Floyd's algorithm for $O(n^3)$. Consider all triples with fixed endpoint, say, $v$. Let's find all useful edges corresponding to such triples. An edge $(a, b, w)$ is useful, if there is a triple $(v, u_i, l_i)$ with $dist(v, a) + w + dist(b, u_i)\leq l_i\Leftrightarrow -l_i + dist(u_i, b)\leq -w - dist(v, a).$ Note that the right hand side depends only on the fixed vertex $v$ and the edge itself, so we are going to minimize the left hand side over all possible triples. It can be done using Dijkstra in $O(n^2)$ if we initialize the distance to all $u_i$ with $-l_i$. After we are done for all vertices $v$, there only remains to check for each edge whether it has been marked useful for any vertex $v$.
[ "graphs", "shortest paths" ]
2,400
null
1482
G
Vabank
Gustaw is the chief bank manager in a huge bank. He has unlimited access to the database system of the bank, in a few clicks he can move any amount of money from the bank's reserves to his own private account. However, the bank uses some fancy AI fraud detection system that makes stealing more difficult. Gustaw knows that the anti-fraud system just detects any operation that exceeds some fixed limit $M$ euros and these operations are checked manually by a number of clerks. Thus, any fraud operation exceeding this limit is detected, while any smaller operation gets unnoticed. Gustaw doesn't know the limit $M$ and wants to find it out. In one operation, he can choose some integer $X$ and try to move $X$ euros from the bank's reserves to his own account. Then, the following happens. - If $X \le M$, the operation is unnoticed and Gustaw's account balance raises by $X$ euros. - Otherwise, if $X > M$, the fraud is detected and cancelled. Moreover, Gustaw has to pay $X$ euros from his own account as a fine. If he has less than $X$ euros on the account, he is fired and taken to the police. Initially Gustaw has $1$ euro on his account. Help him find the exact value of $M$ in no more than $105$ operations without getting him fired.
Our solution consists of two parts. First of all find an upper bound for $M$. To achieve this, we try to query $1$, $2$, $4$, $8$ and so on until we fail. After the first unsuccessful query we will have $0$ euro and know that the answer is on some segment $[2^k, 2^{k+1})$. It takes at most 47 queries. Now one could do something like the following binary search: take the left border of our segment of money, then on each query try the left border and then the middle. If the queries are successful then all good, otherwise we lose $L + \frac{R - L}{2}$, where $L$ is taken at the beginning of this iteration, and all $\frac{R - L}{2}$ cannot sum up into something greater than the initial left border we obtained, because initially $R - L = L$, and each time $R - L$ decreases twice. However, this solution requires another $2\log(10^{14})$ queries, which is too much. Let's divide the segment into two non-equal parts sometimes. Note that if the left side of the partition doesn't exceed half of the segment then that extra $L$ we have is enough to cover all our expenses. Also let's use that we actually get extra $M \approx \frac{L + R}{2}$ after successful middle queries. We want our algorithm to look something like the following. Let the current segment equal $[l, r]$. and the current balance is at least $l\cdot y + (r - l)$ for some integer $y$. Then if $y = 0$ then we query $l$, and if $y > 1$ then we query whatever we want on the segment. It is easy to see that after an unsuccessful query our balance is at least $l \cdot (y - 1) + (r - l)$ (for new $l$ and $r$), and after a successful query, we will think that our balance is at least $l \cdot (y + 1) + (r - l)$ (for new $l$ or $r$). The latter is not always the case, we will discuss that later. Now our balance is described by the only integer $y$. Let $dp[x][y]$ equal the maximal $d$ so that it's possible to find the answer on $[l, l + d]$ having $y\cdot l + d$ money initially. Then $dp[x][y] = dp[x - 1][y - 1] + dp[x - 1][y + 1]$, it is easy to compute and follow in the solution. One can show that $dp[k][0] = \binom{k}{[k/2]}$. It implies that $k\leq 49$. This adds up to 97 queries. Now remember that, if we proceed from $(l, r, y)$ to $(m, r, y + 1)$, then our balance was $y\cdot l + (r - l)$ and became $y\cdot l + m$, while we need $(y + 1)\cdot m$ for our estimations. Hence we need some extra cash to cover such "expenses". It can be proven that they don't exceed three of initial $L$-s, which gives the total of 100 queries.
[ "binary search", "interactive" ]
3,200
null
1482
H
Exam
This year a Chunin Selection Exam is held again in Konoha, and taking part in it are $n$ ninjas named $s_1$, $s_2$, ..., $s_n$. All names are distinct. One of the exam stages consists of fights between the participants. This year the rules determining the ninjas for each fight are the following: ninjas $i$ and $j$ fight against each other if the following conditions are held: - $i \neq j$; - $s_{j}$ is a substring of $s_{i}$; - there is no $k$ except $i$ and $j$ that $s_{j}$ is a substring of $s_{k}$, and $s_{k}$ is a substring of $s_{i}$. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Your task is to find out how many fights are going to take place this year.
Fix a particular string $s$ and find all edges outgoing from it. For each position $i$ of the string let's find the value of $left_i$ being the starting position of the longest substring which ends at the position $i$ and is one of the strings $s_j$. It's easy to see that such strings are the only ones where the outgoing edges from $s$ can lead to. What remains is to find out which of them need to be excluded. A string needs to be excluded if there is an occurrence of it into $s$ which is entirely covered by an occurrence of another substring. So let $ind_i = \min\{left_j\,\mid\,j > i\}$. Then the strings to be excluded are precisely the strings among $s_j$'s which are suffixes of the substring $[ind_i, i]$ for some $i$. This can be found via the Aho-Corasick structure. Since its suffix links represent a tree, one can find the vertices corresponding to the substrings $[ind_i, i]$ and mark the way to the root in the suffix links tree. After this one can just check if the vertices of $[left_i, i]$ are marked. To mark paths efficiently one can use segment trees or std::set. The overall complexity is $O(n\log{n})$.
[ "data structures", "string suffix structures", "trees" ]
3,400
null
1485
A
Add and Divide
You have two positive integers $a$ and $b$. You can perform two kinds of operations: - $a = \lfloor \frac{a}{b} \rfloor$ (replace $a$ with the integer part of the division between $a$ and $b$) - $b=b+1$ (increase $b$ by $1$) Find the minimum number of operations required to make $a=0$.
Suppose that you can use $x$ operations of type $1$ and $y$ operations of type $2$. Try to reorder the operations in such a way that $a$ becomes the minimum possible. You should use operations of type $2$ first, then moves of type $1$. How many operations do you need in the worst case? ($a = 10^9$, $b = 1$) You need at most $30$ operations. Iterate over the number of operations of type $2$. Notice how it is never better to increase $b$ after dividing ($\lfloor \frac{a}{b+1} \rfloor \le \lfloor \frac{a}{b} \rfloor$). So we can try to increase $b$ to a certain value and then divide $a$ by $b$ until it is $0$. Being careful as not to do this with $b<2$, the number of times we divide is going to be $O(\log a)$. In particular, if you reach $b \geq 2$ (this requires at most $1$ move), you need at most $\lfloor \log_2(10^9) \rfloor = 29$ moves to finish. Let $y$ be the number of moves of type $2$; we can try all values of $y$ ($0 \leq y \leq 30$) and, for each $y$, check how many moves of type $1$ are necessary. Complexity: $O(\log^2 a)$. If we notice that it is never convenient to increase $b$ over $6$, we can also achieve a solution with better complexity.
[ "brute force", "greedy", "math", "number theory" ]
1,000
#include <iostream> using namespace std; void solve(){ long long A,B,a,b,res,i,ans; cin>>A>>B; if(!A){ cout<<0<<endl; return; } res=A+3; for(i=(B<2?2-B:0); i<res; ++i){ b=B+i; a=A; ans=i; while(a){ a/=b; ++ans; } if(ans<res)res=ans; } cout<<res<<endl; } int main(){ int t; cin>>t; while(t--)solve(); return 0; }
1485
B
Replace and Keep Sorted
Given a positive integer $k$, two arrays are called $k$-similar if: - they are \textbf{strictly increasing}; - they have the same length; - all their elements are positive integers between $1$ and $k$ (inclusive); - they differ in \textbf{exactly} one position. You are given an integer $k$, a \textbf{strictly increasing} array $a$ and $q$ queries. For each query, you are given two integers $l_i \leq r_i$. Your task is to find how many arrays $b$ exist, such that $b$ is $k$-similar to array $[a_{l_i},a_{l_i+1}\ldots,a_{r_i}]$.
You can make a $k$-similar array by assigning $a_i = x$ for some $l \leq i \leq r$ and $1 \leq x \leq k$. How many $k$-similar arrays can you make if $x$ is already equal to some $a_i$ ($l \leq i \leq r$)? How many $k$-similar arrays can you make if either $x < a_l$ or $x > a_r$? How many $k$-similar arrays can you make if none of the previous conditions holds? Let's consider each value $x$ from $1$ to $k$. If $x < a_l$, you can replace $a_l$ with $x$ (and you get $1$ $k$-similar array). There are $a_l-1$ such values of $x$. If $x > a_r$, you can replace $a_r$ with $x$ (and you get $1$ $k$-similar array). There are $k-a_r$ such values of $x$. If $a_l < x < a_r$, and $x \neq a_i$ for all $i$ in $[l, r]$, you can either replace the rightmost $b_i$ which is less than $x$, or the leftmost $b_i$ which is greater than $x$ (and you get $2$ $k$-similar arrays). There are $(a_r - a_l + 1) - (r - l + 1)$ such values of $x$. If $x = a_i$ for some $i$ in $[l, r]$, no $k$-similar arrays can be made. The total count is $(a_l-1)+(k-a_r)+2((a_r - a_l + 1) - (r - l + 1))$, which simplifies to $k + (a_r - a_l + 1) - 2(r - l + 1)$. Complexity: $O(n + q)$.
[ "dp", "implementation", "math" ]
1,200
#include <bits/stdc++.h> using namespace std; int main(){ cin.tie(0); ios_base::sync_with_stdio(NULL); int N,Q,K; cin >> N >> Q >> K; vector<int> v(N); for(int &x: v)cin >> x; int l,r; while(Q--){ cin >> l >> r; cout << K + v[r-1] - v[l-1] - 2*(r - l) - 1 << "\n"; } return 0; }
1485
C
Floor and Mod
A pair of positive integers $(a,b)$ is called \textbf{special} if $\lfloor \frac{a}{b} \rfloor = a \bmod b$. Here, $\lfloor \frac{a}{b} \rfloor$ is the result of the integer division between $a$ and $b$, while $a \bmod b$ is its remainder. You are given two integers $x$ and $y$. Find the number of special pairs $(a,b)$ such that $1\leq a \leq x$ and $1 \leq b \leq y$.
Let $\lfloor \frac{a}{b} \rfloor = a~\mathrm{mod}~b = k$. Is there an upper bound for $k$? $k \leq \sqrt x$. For a fixed $k$, can you count the number of special pairs such that $a \leq x$ and $b \leq y$ in $O(1)$? We can notice that, if $\lfloor \frac{a}{b} \rfloor = a~\mathrm{mod}~b = k$, then $a$ can be written as $kb+k$ ($b > k$). Since $b > k$, we have that $k^2 < kb+k = a \leq x$. Hence $k \leq \sqrt x$. Now let's count special pairs for any fixed $k$ ($1 \leq k \leq \sqrt x$). For each $k$, you have to count the number of $b$ such that $b > k$, $1 \leq b \leq y$, $1 \leq kb+k \leq x$. The second condition is equivalent to $1 \leq b \leq x/k-1$. Therefore, for any fixed $k > 0$, the number of special pairs ($a\leq x$; $b \leq y$) is $max(0, min(y,x/k-1) - k)$. The result is the sum of the number of special pairs for each $k$. Complexity: $O(\sqrt x)$.
[ "binary search", "brute force", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve(){ ll x, y; cin >> x >> y; ll ans = 0; for(ll i = 1; i*i < x; i++)ans+=max(min(y,x/i-1)-i,0LL); cout << ans << endl; return; } int main(){ int T = 1; cin >> T; while(T--){ solve(); } return 0; }
1485
D
Multiples and Power Differences
You are given a matrix $a$ consisting of positive integers. It has $n$ rows and $m$ columns. Construct a matrix $b$ consisting of positive integers. It should have the same size as $a$, and the following conditions should be met: - $1 \le b_{i,j} \le 10^6$; - $b_{i,j}$ is a multiple of $a_{i,j}$; - the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in $b$ is equal to $k^4$ for some integer $k \ge 1$ ($k$ is not necessarily the same for all pairs, it is own for each pair). We can show that the answer always exists.
Brute force doesn't work (even if you optimize it): there are relatively few solutions. There may be very few possible values of $b_{i,j}$, if $b_{i-1,j}$ is fixed. The problem arises when you have to find a value for a cell with, e.g., $4$ fixed neighbors. Try to find a possible property of the neighbors of $(i, j)$, such that at least a solution for $b_{i,j}$ exists. The least common multiple of all integers from $1$ to $16$ is less than $10^6$. Build a matrix with a checkerboard pattern: let $b_{i, j} = 720720$ if $i + j$ is even, and $720720+a_{i, j}^4$ otherwise. The difference between two adjacent cells is obviously a fourth power of an integer. We choose $720720$ because it is $\operatorname{lcm}(1, 2, \dots, 16)$. This ensures that $b_{i, j}$ is a multiple of $a_{i, j}$, because it is either $720720$ itself or the sum of two multiples of $a_{i, j}$. Complexity: $O(nm)$.
[ "constructive algorithms", "graphs", "math", "number theory" ]
2,200
#include <iostream> using namespace std; int main(){ unsigned h,w,x,y,t; cin>>h>>w; for(y=0; y<h; ++y){ for(x=0; x<w; ++x){ cin>>t; if((x^y)&1) cout<<"720720 "; else cout<<720720+t*t*t*t<<' '; } cout<<'\n'; } return 0; }
1485
E
Move and Swap
You are given $n - 1$ integers $a_2, \dots, a_n$ and a tree with $n$ vertices rooted at vertex $1$. The leaves are all at the same distance $d$ from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree $1$ are leaves. If vertices $s$ and $f$ are connected by an edge and the distance of $f$ from the root is greater than the distance of $s$ from the root, then $f$ is called a child of $s$. Initially, there are a red coin and a blue coin on the vertex $1$. Let $r$ be the vertex where the red coin is and let $b$ be the vertex where the blue coin is. You should make $d$ moves. A move consists of three steps: - Move the red coin to any child of $r$. - Move the blue coin to any vertex $b'$ such that $dist(1, b') = dist(1, b) + 1$. Here $dist(x, y)$ indicates the length of the simple path between $x$ and $y$. Note that $b$ and $b'$ are not necessarily connected by an edge. - You can optionally swap the two coins (or skip this step). Note that $r$ and $b$ can be equal at any time, and there is no number written on the root. After each move, you gain $|a_r - a_b|$ points. What's the maximum number of points you can gain after $d$ moves?
What happens if you can't swap coins? Let $dp_i$ be the maximum score that you can reach after $dist(1, i)$ moves if there is a red coin on node $i$ after step $3$. However, after step $2$, the coin on node $i$ may be either red or blue. Try to find transitions for both cases. If you consider only the first case, you solve the problem if there are no swaps. You can greedily check the optimal location for the blue coin: a node $j$ such that $dist(1,i) = dist(1,j)$ and $a_j$ is either minimum or maximum. Instead, if the coin on node $i$ is blue after step $2$, the red coin is on node $j$ and you have to calculate $\max(dp_{parent_j} + |a_j - a_i|)$ for each $i$ with a fixed $dist(1, i)$. How? Divide the nodes in groups based on the distance from the root. Then, for each $dist(1, i)$ in increasing order, calculate $dp_i$ - the maximum score that you can reach after $dist(1, i)$ moves if there is a red coin on node $i$ after step $3$. You can calculate $dp_i$ if you know $dp_j$ for each $j$ that belongs to the previous group. There are two cases: if after step $2$ the coin on node $i$ is red, the previous position of the red coin is fixed, and the blue coin should reach either the minimum or the maximum $a_j$ among the $j$ that belong to the same group of $i$; if after step $2$ the coin on node $i$ is red, the previous position of the red coin is fixed, and the blue coin should reach either the minimum or the maximum $a_j$ among the $j$ that belong to the same group of $i$; if after step $2$ the coin on node $i$ is blue, there is a red coin on node $j$ ($dist(1, i) = dist(1, j)$), so you have to maximize the score $dp_{parent_j} + |a_j - a_i|$. This can be done efficiently by sorting the $a_i$ in the current group and calculating the answer separately for $a_j \leq a_i$ and $a_j > a_i$; for each $i$ in the group, the optimal node $j$ either doesn't change or it's the previous node. Alternatively, you can notice that $dp_{parent_j} + |a_j - a_i| = \max(dp_{parent_j} + a_j - a_i, dp_{parent_j} + a_i - a_j)$, and you can maximize both $dp_{parent_j} + a_j - a_i$ and $dp_{parent_j} + a_i - a_j$ greedily (by choosing the maximum $dp_{parent_j} + a_j$ and $dp_{parent_j} - a_j$, respectively). In this solution, you don't need to sort the $a_i$. if after step $2$ the coin on node $i$ is blue, there is a red coin on node $j$ ($dist(1, i) = dist(1, j)$), so you have to maximize the score $dp_{parent_j} + |a_j - a_i|$. This can be done efficiently by sorting the $a_i$ in the current group and calculating the answer separately for $a_j \leq a_i$ and $a_j > a_i$; for each $i$ in the group, the optimal node $j$ either doesn't change or it's the previous node. Alternatively, you can notice that $dp_{parent_j} + |a_j - a_i| = \max(dp_{parent_j} + a_j - a_i, dp_{parent_j} + a_i - a_j)$, and you can maximize both $dp_{parent_j} + a_j - a_i$ and $dp_{parent_j} + a_i - a_j$ greedily (by choosing the maximum $dp_{parent_j} + a_j$ and $dp_{parent_j} - a_j$, respectively). In this solution, you don't need to sort the $a_i$. The answer is $\max(dp_i)$. Complexity: $O(n)$ or $O(n\log n)$.
[ "dfs and similar", "dp", "greedy", "trees" ]
2,500
#include <bits/stdc++.h> using namespace std; #define endl "\n" #define ll long long #define INF (ll)1e18 ll i, i1, j, k, k1, t, n, m, res, check1, a[200010], a1, b, d, v, dist[200010], dp[200010], s, s1, s2; vector<ll> adj[200010]; vector<array<ll, 3>> dadj[200010]; bool visited[200010]; void dfs(ll s) { for (auto u : adj[s]) { if (!visited[u]) { visited[u] = true; dist[u] = dist[s] + 1; dadj[dist[u]].push_back({-1, s, u}); d = max(d, dist[u]); dfs(u); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); //ifstream cin("input.txt"); //ofstream cout("output.txt"); cin >> t; while (t--) { cin >> n; for (i = 0; i <= n; i++) { adj[i].clear(); dadj[i].clear(); visited[i] = false; dist[i] = 0; dp[i] = 0; } for (i = 2; i <= n; i++) { cin >> v; adj[v - 1].push_back(i - 1); adj[i - 1].push_back(v - 1); } for (i = 1; i < n; i++) { cin >> a[i]; } d = 0; visited[0] = true; dfs(0); dadj[0].push_back({0, -1, 0}); for (i = 1; i <= d; i++) { for (auto& u : dadj[i]) { u[0] = a[u[2]]; // cout << u[0] << ' ' << u[1] << ' ' << u[2] << endl; } // cout << endl; sort(dadj[i].begin(), dadj[i].end()); s = dadj[i].size(); s1 = dadj[i][0][0]; s2 = dadj[i][dadj[i].size() - 1][0]; // cout << s1 << ' ' << s2 << endl; for (auto& u : dadj[i]) { a1 = a[u[2]]; dp[u[2]] = max({dp[u[2]], dp[u[1]] + a1 - s1, dp[u[1]] + s2 - a1}); } k = 0; for (j = 0; j < s; j++) { if (dp[dadj[i][j][1]] - dadj[i][j][0] > dp[dadj[i][k][1]] - dadj[i][k][0]) { k = j; } dp[dadj[i][j][2]] = max(dp[dadj[i][j][2]], dadj[i][j][0] - dadj[i][k][0] + dp[dadj[i][k][1]]); } k = s - 1; for (j = s - 1; j >= 0; j--) { if (dp[dadj[i][j][1]] + dadj[i][j][0] > dp[dadj[i][k][1]] + dadj[i][k][0]) { k = j; } dp[dadj[i][j][2]] = max(dp[dadj[i][j][2]], dadj[i][k][0] - dadj[i][j][0] + dp[dadj[i][k][1]]); } } res = 0; for (i = 1; i < n; i++) { // cout << dp[i] << ' '; res = max(res, dp[i]); } // cout << endl; cout << res << endl; } return 0; }
1485
F
Copy or Prefix Sum
You are given an array of integers $b_1, b_2, \ldots, b_n$. An array $a_1, a_2, \ldots, a_n$ of integers is \textbf{hybrid} if for each $i$ ($1 \leq i \leq n$) at least one of these conditions is true: - $b_i = a_i$, or - $b_i = \sum_{j=1}^{i} a_j$. Find the number of hybrid arrays $a_1, a_2, \ldots, a_n$. As the result can be very large, you should print the answer modulo $10^9 + 7$.
Why isn't the answer $2^{n-1}$? What would you overcount? Find a dp with time complexity $O(n^2\log n)$. Let $dp_{i, j}$ be the number of hybrid prefixes of length $i$ and sum $j$. The transitions are $dp_{i, j} \rightarrow dp_{i+1, j+b_i}$ and $dp_{i,j} \rightarrow dp_{i+1,b_i}$. Can you optimize it to $O(n\log n)$? For each $i$, you can choose either $a_i = b_i$ or $a_i = b_i - \sum_{k=1}^{i-1} a_k$. If $\sum_{k=1}^{i-1} a_k = 0$, the two options coincide and you have to avoid overcounting them. This leads to an $O(n^2\log n)$ solution: let $dp_i$ be a map such that $dp_{i, j}$ corresponds to the number of ways to create a hybrid prefix $[1, i]$ with sum $j$. The transitions are $dp_{i, j} \rightarrow dp_{i+1, j+b_i}$ (if you choose $b_i = a_i$, and $j \neq 0$), $dp_{i,j} \rightarrow dp_{i+1,b_i}$ (if you choose $b_i = \sum_{k=1}^{i} a_k$). Let's try to get rid of the first layer of the dp. It turns out that the operations required are move all $dp_j$ to $dp_{j+b_i}$ calculate the sum of all $dp_j$ in some moment change the value of a $dp_j$ and they can be handled in $O(n\log n)$ with "Venice technique". $dp$ is now a map such that $dp_j$ corresponds to the number of ways to create a hybrid prefix $[1, i]$ such that $\sum_{k=1}^{i} a_k - b_k = j$. Calculate the dp for all prefixes from left to right. if $b_i = a_i$, you don't need to change any value of the dp; if $b_i = \sum_{k=1}^{i} a_k$, you have to set $dp_{\sum_{k=1}^{i} -b_k}$ to the total number of hybrid arrays of length $i-1$. Complexity: $O(n\log n)$.
[ "combinatorics", "data structures", "dp", "sortings" ]
2,400
#include <bits/stdc++.h> using namespace std; #define nl "\n" #define nf endl #define ll long long #define pb push_back #define _ << ' ' << #define INF (ll)1e18 #define mod 1000000007 #define maxn 200010 ll i, i1, j, k, k1, t, n, m, res, flag[10], a, b[maxn], tt; map<ll, ll> mp; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> t; while (t--) { cin >> n; mp.clear(); for (i = 1; i <= n; i++) { cin >> b[i]; } mp[0] = 1; tt = 1; k = 0; for (i = 1; i <= n; i++) { a = mp[k]; mp[k] = tt; k -= b[i]; tt = (2 * tt - a + mod) % mod; } cout << tt << nl; } return 0; }
1486
A
Shifting Stacks
You have $n$ stacks of blocks. The $i$-th stack contains $h_i$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $i$-th stack (if there is at least one block) and put it to the $i + 1$-th stack. Can you make the sequence of heights strictly increasing? Note that the number of stacks always remains $n$: stacks don't disappear when they have $0$ blocks.
What's the lower bound for the amount of blocks for the answer to be $\texttt{YES}$? Check the predicate for every prefix. Let's consider the smallest amount of blocks we need to make the first $i$ heights ascending. As heights are non-negative and ascending the heights should look like $0, 1, 2, 3, ..., i - 1$, so the minimum sum is $\frac{(i - 1) \cdot i}{2}$. It turns out that this is the only requirement. If it's not the case for every prefix the answer is $\texttt{NO}$ because we can't make some prefix ascending. Otherwise the answer is $\texttt{YES}$ because you can move the blocks right till there is at least $i$ blocks in the $i$-th stack and this would make the heights ascending.
[ "greedy", "implementation" ]
900
t = int(input()) for i in range(t): n = int(input()) need = 0 have = 0 ans = True a = [int(i) for i in input().split()] for j in range(n): need += j have += a[j] if have < need: ans = False if ans: print("YES") else: print("NO")
1486
B
Eastern Exhibition
You and your friends live in $n$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$, where $|x|$ is the absolute value of $x$.
Is problem really two dimensional? How to solve the problem if $y = 0$? At first let's see that the problem is not two dimensional. If we change the $x$ coordinate the sum of distances by $y$ is not changed at all. So we just need to calculate the number of good points on a line with points having coordinates $x$ and then $y$ and multiply the answers. Now to calculate the answer on a line we could use a known fact: point with the smallest summary distance is between left and right median. So now we only need to sort the array and find the elements on positions $\lfloor\frac{n + 1}{2} \rfloor$ and $\lfloor \frac{n + 2}{2} \rfloor$ and return their difference plus one.
[ "binary search", "geometry", "shortest paths", "sortings" ]
1,500
t = int(input()) def solve(x): x.sort() return x[len(x) // 2] - x[(len(x) - 1) // 2] + 1 for i in range(t): n = int(input()) x, y = [], [] for j in range(n): px, py = map(int, input().split()) x.append(px) y.append(py) print(solve(x) * solve(y))
1486
C1
Guessing the Greatest (easy version)
\textbf{The only difference between the easy and the hard version is the limit to the number of queries}. \textbf{This is an interactive problem.} There is an array $a$ of $n$ \textbf{different} numbers. In one query you can ask the position of the second maximum element in a subsegment $a[l..r]$. Find the position of the maximum element in the array in no more than \textbf{40} queries. A subsegment $a[l..r]$ is all the elements $a_l, a_{l + 1}, ..., a_r$. After asking this subsegment you will be given the position of the second maximum from this subsegment \textbf{in the whole} array.
Binary search? How to check if the maximum element is in the left or the right part of the array in two queries? Let's solve for some subsegment $[l, r)$ and $mid = (l + r) / 2$. Now let's check if the max element is in $[l, mid)$ or $[mid, r)$. Let's find the second max element in $[l, r)$ and call it $smax$. Now let's think that $smax$ is less than $mid$ (for symmetrical reasons). Now if we ask $[l, mid)$ and second max is still $smax$ it means that maximum element is in $[l, mid)$, otherwise it's in $[mid, r)$. Now we've shrunk the segment by a factor of two. So the resulting number of queries is $2 \cdot \lceil log_2 10^5 \rceil = 34$.
[ "binary search", "interactive" ]
1,600
from sys import stdout def ask(l, r): if l == r: return -1 print('?', l, r) stdout.flush() return int(input()) l = 1 r = int(input()) + 1 while r - l > 1: mid = (r + l) // 2 was = ask(l, r - 1) if was < mid: if ask(l, mid - 1) == was: r = mid else: l = mid else: if ask(mid, r - 1) == was: l = mid else: r = mid print('!', l) stdout.flush()
1486
C2
Guessing the Greatest (hard version)
\textbf{The only difference between the easy and the hard version is the limit to the number of queries}. \textbf{This is an interactive problem.} There is an array $a$ of $n$ \textbf{different} numbers. In one query you can ask the position of the second maximum element in a subsegment $a[l..r]$. Find the position of the maximum element in the array in no more than \textbf{20} queries. A subsegment $a[l..r]$ is all the elements $a_l, a_{l + 1}, ..., a_r$. After asking this subsegment you will be given the position of the second maximum from this subsegment \textbf{in the whole} array.
Kudos to Aleks5d for proposing a solution to this subproblem. Binary search AGAIN? How to solve the problem if the second maximum element is at position $1$? How to check if the maximum element is to the left or the right of the second maximum in two queries? Let's find second max $smax$. Now let's check if the max element is to the left, or to the right. Just ask $[1, smax]$ and see if the answer is different to $smax$. Now let's suppose that the max element is to the right (for symmetrical reasons). Now we only need to find the smallest $m$ such that the answer to the query $[smax, m]$ is $smax$. The smallest such $m$ is obviously the position of the maximum element. Now we need to use binary search to find such $m$. So the resulting number of queries is $2 + \lceil log_2 10^5 \rceil = 19$.
[ "binary search", "interactive" ]
1,900
from sys import stdout def ask(l, r): if l == r: return -1 print('?', l, r) stdout.flush() return int(input()) n = int(input()) smax = ask(1, n) if smax == 1 or ask(1, smax) != smax: l = smax r = n while r - l > 1: mid = (l + r) // 2 if ask(smax, mid) == smax: r = mid else: l = mid print('!', r) else: l = 1 r = smax while r - l > 1: mid = (l + r) // 2 if ask(mid, smax) == smax: l = mid else: r = mid print('!', l) stdout.flush()
1486
D
Max Median
You are a given an array $a$ of length $n$. Find a subarray $a[l..r]$ with length at least $k$ with the largest median. A median in an array of length $n$ is an element which occupies position number $\lfloor \frac{n + 1}{2} \rfloor$ after we sort the elements in non-decreasing order. For example: $median([1, 2, 3, 4]) = 2$, $median([3, 2, 1]) = 2$, $median([2, 1, 2, 1]) = 1$. Subarray $a[l..r]$ is a contiguous part of the array $a$, i. e. the array $a_l,a_{l+1},\ldots,a_r$ for some $1 \leq l \leq r \leq n$, its length is $r - l + 1$.
How to solve the problem if all the values are $-1$ and $1$? Binary search ONCE MORE? How to check if the answer is at least $x$? Let's binary search the answer. Now let's check if the answer is at least $x$. Replace all values that are at least $x$ with 1 and values that are less than $x$ with $-1$. Now if for some segment the median is at least $x$ if the sum on this subsegment is positive! Now we only need to check if the array consisting of $-1$ and $1$ has a subsegment of length at least $k$ with positive sum. So let's just calculate prefix sums of this array and for prefix sum at position $i$ choose the minimum prefix sum amongst positions $0, 1, ..., i - k$, which can be done using prefix minimum in linear time. So the resulting complexity is $O(nlogn)$.
[ "binary search", "data structures", "dp" ]
2,100
n, k = map(int, input().split()) a = [int(i) for i in input().split()] l = 1 r = n + 1 while r - l > 1: mid = (r + l) // 2 b = [1 if i >= mid else -1 for i in a] for i in range(1, len(b)): b[i] += b[i - 1] ans = False if b[k - 1] > 0: ans = True mn = 0 for i in range(k, len(b)): mn = min(mn, b[i - k]) if b[i] - mn > 0: ans = True if ans: l = mid else: r = mid print(l)
1486
E
Paired Payment
There are $n$ cities and $m$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph \textbf{is not guaranteed to be connected}. Each road has it's own parameter $w$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $a$ to city $b$ and then from city $b$ to city $c$) and you will have to pay $(w_{ab} + w_{bc})^2$ money to go through those roads. Find out whether it is possible to travel from city $1$ to every other city $t$ and what's the minimum amount of money you need to get from $1$ to $t$.
Did you read that $w$ is at most $50$? How to change the graph for dijkstra algorithm to work with this rule? Add some fake vertices and edges to make things work. Let's think about it this way. For a middle vertex we only care what are the weights of the edges that pass through it. Now for every vertex $v$ let's create some fake vertices $(v, w)$, where $w$ is the weight of the last edge. This would add at most $O(M)$ new vertices. Now for each starting edge $(u, v, w)$ let's make an edge $u \rightarrow (v, w)$ of weight $0$ and for each vertex $(u, was)$ and edge $(u, v, w)$ let's create an edge $(u, was) \rightarrow v$ with weight $(was + w)^2$. Now running Dijkstra's algorithm from vertex $1$ will result for correct answers for all vertices (as we've simulated the paired edge situation with fake vertices and edges). Also we wouldn't create more than $O(M \cdot maxW)$ edges cause if some vertex has degree $t$ we would create no more than $t \cdot maxW$ edges and sum of all $t$ is $2 \cdot M$. Carefully implemented this would result in $O(M \cdot maxW \cdot logM)$ or $O(M \cdot maxW + MlogM)$ time and $O(M \cdot maxW)$ or $O(M)$ memory. All of those were fine.
[ "binary search", "brute force", "constructive algorithms", "dp", "flows", "graphs", "shortest paths" ]
2,200
#include <bits/stdc++.h> using namespace std; signed main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int n, m; cin >> n >> m; vector<vector<pair<int, int>>> G(n * 51); auto addedge = [&](int u, int v, int w) { G[u * 51].push_back({v * 51 + w, 0}); for (int was = 1; was <= 50; ++was) { G[u * 51 + was].push_back({v * 51, (was + w) * (was + w) }); } }; for (int i = 0; i < m; ++i) { int u, v, w; cin >> u >> v >> w; --u, --v; addedge(u, v, w); addedge(v, u, w); } set<pair<int, int>> st; int inf = 1e9 + 7; vector<int> d(G.size(), inf); d[0] = 0; st.insert({d[0], 0}); while (st.size()) { auto f = *st.begin(); st.erase(st.begin()); for (auto i : G[f.second]) { if (d[i.first] > d[f.second] + i.second) { st.erase({d[i.first], i.first}); d[i.first] = d[f.second] + i.second; st.insert({d[i.first], i.first}); } } } for (int i = 0; i < n; ++i) { int ans = d[i * 51]; if (ans == inf) cout << "-1 "; else cout << ans << ' '; } return 0; }
1486
F
Pairs of Paths
You are given a tree consisting of $n$ vertices, and $m$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $(i, j)$ $(1 \leq i < j \leq m)$ such that $path_i$ and $path_j$ have exactly one vertex in common.
Root the tree. After rooting the tree, how does the intersection of two paths look? After rooting the tree, what are the two types of intersection? Let's root the tree at some vertex. Now the intersection vertex is lca for at least one path. If the vertex wasn't lca for both paths it would mean that there are either two edges going up (which is impossible in a rooted tree) or they are going up by the same edge, but this would mean that this vertex parent is also an intersection point, so the paths are intersecting in at least $2$ points, so this is impossible too. Now there are two types of intersections: with the same lca and different lca. Let's count them independently. For each path and it's lca let's find the subtrees that path goes to from lca. This would result in a triplet $(lca, subtree1, subtree2)$ (replace subtree with $-1$ if there is none) with $subtree1 < subtree2$ or both of them are $-1$. Now to count the intersections of the first type let's use inclusion-exclusion principle. Remember all paths that have same lca. Now we need to calculate the number of pairs so that they have different $subtree1$ and $subtree2$ (or $-1$). The formula is going to be $cntpath \cdot (cntpath - 1) / 2 - \sum \left(cnt(subtree1, x) + cnt(x, subtree2) - (cnt(subtree1, subtree2) + 1) \right) / 2$ (from inclusion-exclusion principle) where cntpath is the number of paths with this lca and $cnt(x, y)$ is the number of paths with triplet $(lca, x, y)$. The situation with $-1$ is pretty similar, left as an exercise to the reader. Finding the number of intersections of second type is a bit easier. We just need to calculate the number of all intersections between a path with fixed lca and a vertical path which crosses this lca (the path is not neccessarily vertical, but it contains both lca and it's parent) and then subtract $cnt(subtree1)$ and $cnt(subtree2)$, where $cnt(x)$ is the number of vertical paths that go into subtree $x$. After that we just have to print out the sum of this two numbers. Counting all the needed functions can be done using some data structure (small-to-large for example) or some subtree dynamic programming. The resulting complexity is $O(Mlog^2M)$ or $O(MlogM)$ or even $O(M)$ if you're strong enough.
[ "combinatorics", "data structures", "dfs and similar", "dp", "trees" ]
2,600
#include <bits/stdc++.h> using namespace std; #define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define FIXED cout << fixed << setprecision(12) #define ll long long #define pii pair<int, int> #define graph vector<vector<int>> #define pb push_back #define f first #define s second #define sz(a) signed((a).size()) #define all(a) (a).begin(), (a).end() void flush() { cout << flush; } void flushln() { cout << endl; } void println() { cout << '\n'; } template<class T> void print(const T &x) { cout << x; } template<class T> void read(T &x) { cin >> x; } template<class T, class ...U> void read(T &x, U& ... u) { read(x); read(u...); } template<class T, class ...U> void print(const T &x, const U& ... u) { print(x); print(u...); } template<class T, class ...U> void println(const T &x, const U& ... u) { print(x); println(u...); } graph G; vector<vector<int>> up; vector<int> h; int LOG; void orient(int v, int p, int he = 0) { up[0][v] = p; h[v] = he; for (auto i : G[v]) if (i != p) { orient(i, v, he + 1); } } int lca(int u, int v) { if (h[u] > h[v]) swap(u, v); int d = h[v] - h[u]; for (int l = 0; l < LOG; ++l) if (d >> l & 1) v = up[l][v]; if (u == v) { return u; } for (int l = LOG - 1; l >= 0; --l) { if (up[l][u] != up[l][v]) { u = up[l][u]; v = up[l][v]; } } return up[0][u]; } int getup(int v, int dist) { for (int l = 0; l < LOG; ++l) if (dist >> l & 1) v = up[l][v]; return v; } vector<pii> paths; vector<map<pii, vector<int>>> samelca; vector<vector<int>> bylca; vector<vector<int>> addvertex; vector<set<int>> sets; vector<int> link; set<int>& at(int v) { return sets[link[v]]; } bool count(const vector<int> &v, int x) { return binary_search(all(v), x); } ll ans = 0; template<class T, class U> U get(map<T, U> &mp, T k) { auto it = mp.find(k); if (it != mp.end()) return it->s; return T(); } void process(int v, int p = -1) { int bigson = -1; map<int, int> sonvert, sonhere; for (auto i : G[v]) if (i != p) { process(i, v); if (bigson == -1 || sz(at(bigson)) < sz(at(i))) { bigson = i; } sonvert[i] = sz(at(i)); // number of paths that cross v and i both, but lca is not i } for (auto &p : samelca[v]) { sonvert[p.f.f] -= sz(p.s); sonvert[p.f.s] -= sz(p.s); sonhere[p.f.f] += sz(p.s); sonhere[p.f.s] += sz(p.s); } sonvert.erase(-1); sonhere.erase(-1); if (bigson != -1) { link[v] = link[bigson]; } for (auto i : G[v]) if (i != bigson) { for (auto path : at(i)) at(v).insert(path); } for (auto path : addvertex[v]) at(v).insert(path); // at(v) - all paths that cross v // bylca[v] - all paths that have v as lca ll vertical = sz(at(v)) - sz(bylca[v]); ll here = sz(bylca[v]); ans += vertical * here + here * (here - 1) / 2; ll add1 = 0, add2 = 0; for (auto &p : samelca[v]) { add1 += sz(p.s) * (ll)(get(sonvert, p.f.f) + get(sonvert, p.f.s)); if (p.f.f >= 0) { add2 += sz(p.s) * (ll)(get(sonhere, p.f.f) + get(sonhere, p.f.s)); add2 -= (sz(p.s) * (ll)(sz(p.s) + 1) / 2) * 2; } else if (p.f.s >= 0) { add2 += sz(p.s) * (ll)(get(sonhere, p.f.s)); add2 -= sz(p.s); } } ans -= add1 + add2 / 2; for (auto path : bylca[v]) at(v).erase(path); } signed main() { FAST; FIXED; int n; read(n); G = graph(n); for (int i = 1; i < n; ++i) { int u, v; read(u, v); --u, --v; G[u].pb(v); G[v].pb(u); } LOG = ceil(log2(max(2, n))); up = vector<vector<int>>(LOG, vector<int>(n)); h = vector<int>(n); orient(0, 0); for (int l = 1; l < LOG; ++l) { for (int i = 0; i < n; ++i) up[l][i] = up[l - 1][up[l - 1][i]]; } int m; read(m); auto getsub = [&](int v, int l) { if (v == l) return -1; return getup(v, h[v] - h[l] - 1); }; paths.resize(m); samelca.resize(n); bylca.resize(n); addvertex.resize(n); for (int i = 0; i < m; ++i) { int u, v; read(u, v); --u, --v; paths[i] = {u, v}; int l = lca(u, v); pii sons; sons.f = getsub(u, l); sons.s = getsub(v, l); if (sons.f > sons.s) swap(sons.f, sons.s); samelca[l][sons].pb(i); bylca[l].pb(i); addvertex[u].pb(i); addvertex[v].pb(i); } sets.resize(n); link.resize(n); iota(all(link), 0); process(0); println(ans); return 0; }
1487
A
Arena
$n$ heroes fight against each other in the Arena. Initially, the $i$-th hero has level $a_i$. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (\textbf{it's even possible that it is the same two heroes that were fighting during the last minute}). When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $1$. The winner of the tournament is the first hero that wins in at least $100^{500}$ fights \textbf{(note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner)}. A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament. Calculate the number of possible winners among $n$ heroes.
If for some hero $i$, no other hero is weaker than $i$, then the $i$-th hero cannot win any fights and is not a possible winner. Otherwise, the hero $i$ is a possible winner - he may fight the weakest hero $100^{500}$ times and be declared the winner. So the solution to the problem is calculating the number of minimum elements in the array $a$, since all other elements denote possible winners of the tournament.
[ "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int& x : a) cin >> x; cout << n - count(a.begin(), a.end(), *min_element(a.begin(), a.end())) << endl; } }
1487
B
Cat Cycle
Suppose you are living with two cats: A and B. There are $n$ napping spots where both cats usually sleep. Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically: - Cat A changes its napping place in order: $n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$ In other words, at the first hour it's on the spot $n$ and then goes in decreasing order cyclically; - Cat B changes its napping place in order: $1, 2, 3, \dots, n - 1, n, 1, 2, \dots$ In other words, at the first hour it's on the spot $1$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $x$ then the A takes this place and B moves to the next place in its order (if $x < n$ then to $x + 1$, but if $x = n$ then to $1$). Cat B follows his order, so \textbf{it won't return to the skipped spot $x$ after A frees it, but will move to the spot $x + 2$ and so on}. Calculate, where cat B will be at hour $k$?
If $n$ is even, then each hour A and B are on the spots with different parity, so they will never meet. Otherwise, let's look closely what happens. At the start, A in $n$ and B in $1$. But since we can form a cycle from spots then it means that $n$ and $1$ in reality are neighbors. After that, A and B (starting from neighboring positions) just go in opposite directions and meet each other in the opposite spot after exactly $\left\lfloor \frac{n}{2} \right\rfloor$ steps. After meeting B "jumps over" A making $1$ extra step and the situation become practically the same: A and B are neighbors and move in the opposite direction. In other words, each $f = \left\lfloor \frac{n}{2} \right\rfloor$ steps B makes one extra step, so the answer (if both $k$ and spots are $0$-indexed) is $(k + (n \bmod 2) \cdot \left\lfloor \frac{k}{f} \right\rfloor) \bmod n$
[ "math", "number theory" ]
1,200
fun main() { repeat(readLine()!!.toInt()) { var (n, k) = readLine()!!.split(' ').map { it.toInt() } k-- val floor = n / 2 println((k + (n % 2) * k / floor) % n + 1) } }
1487
C
Minimum Ties
A big football championship will occur soon! $n$ teams will compete in it, and each pair of teams will play exactly one game against each other. There are two possible outcomes of a game: - the game may result in a tie, then both teams get $1$ point; - one team might win in a game, then the winning team gets $3$ points and the losing team gets $0$ points. The score of a team is the number of points it gained during all games that it played. You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well. Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.
If $n$ is odd, then we can solve the problem without any ties: each team should win exactly $\lfloor\frac{n}{2}\rfloor$ matches and lose the same number of matches. Finding which matches each team wins and which matches each team loses can be done with some graph algorithms (like Eulerian cycles or circulations), or with a simple construction: place all teams in a circle in any order, and let the $i$-th team win against the next $\lfloor\frac{n}{2}\rfloor$ teams after it in the circle, and lose to all other teams. Unfortunately, if $n$ is even, we need to use some ties since the total sum of scores over all teams is exactly $\frac{3n(n-1)}{2}$ when there are no ties, and this number is not divisible by $n$ when $n$ is even. Each tie reduces the total sum by $1$, and the minimum number of ties to make $\frac{3n(n-1)}{2} - t$ divisible by $n$ is $t = \frac{n}{2}$ (since $\frac{3n(n-1)}{2} \bmod n = \frac{n}{2}$). So, if we find an answer with exactly $\frac{n}{2}$ ties, it is optimal. And it's easy to find one: once again, place all teams in a circle in any order; make the $i$-th team win against $\frac{n - 2}{2}$ next teams in the circle, lose against $\frac{n - 2}{2}$ previous teams in the circle, and tie with the opposite team in the circle.
[ "brute force", "constructive algorithms", "dfs and similar", "graphs", "greedy", "implementation", "math" ]
1,500
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int i = 0; i < t; i++) { int n; cin >> n; if(n % 2 == 1) { for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) if(j - i <= n / 2) cout << 1 << " "; else cout << -1 << " "; cout << endl; } else { for(int i = 0; i < n; i++) for(int j = i + 1; j < n; j++) if(j - i < n / 2) cout << 1 << " "; else if(j - i == n / 2) cout << 0 << " "; else cout << -1 << " "; cout << endl; } } }
1487
D
Pythagorean Triples
A Pythagorean triple is a triple of integer numbers $(a, b, c)$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $a$, $b$ and $c$, respectively. An example of the Pythagorean triple is $(3, 4, 5)$. Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $c = a^2 - b$. Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $(3, 4, 5)$: $5 = 3^2 - 4$, so, according to Vasya's formula, it is a Pythagorean triple. When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $(a, b, c)$ with $1 \le a \le b \le c \le n$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.
We have to find the number of triples ($a, b, c$) such that equations $a^2+b^2=c^2$ and $a^2-b=c$ are satisfied. Let's subtract one equation from another and get that $b^2+b=c^2-c \implies b(b+1)=c(c-1)$. So we know that $c=b+1$ and after substituting, we get that $a^2=2b+1$. We can see that there is only one correct value of $b$ (and $c$) for every odd value of $a$ (greater than $1$). So we can iterate over the value of $a$ and check that the corresponding value of $c$ doesn't exceed $n$. This solution works in $O(\sqrt{n})$ because $a \approx \sqrt{c} \le \sqrt{n}$, but you can also solve it in $O(1)$.
[ "binary search", "brute force", "math", "number theory" ]
1,500
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans = 0; for (int i = 3; i * i <= 2 * n - 1; i += 2) ++ans; cout << ans << '\n'; } }
1487
E
Cheap Dinner
Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert. There are $n_1$ different types of first courses Ivan can buy (the $i$-th of them costs $a_i$ coins), $n_2$ different types of second courses (the $i$-th of them costs $b_i$ coins), $n_3$ different types of drinks (the $i$-th of them costs $c_i$ coins) and $n_4$ different types of desserts (the $i$-th of them costs $d_i$ coins). Some dishes don't go well with each other. There are $m_1$ pairs of first courses and second courses that don't go well with each other, $m_2$ pairs of second courses and drinks, and $m_3$ pairs of drinks and desserts that don't go well with each other. Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!
The main solution is dynamic programming: let $dp_i$ for every possible dish $i$ be the minimum cost to assemble a prefix of a dinner ending with the dish $i$ (here, $i$ can be a dish of any type: first course, second course, drink, or dessert). Then, the answer to the problem is the minimum value among all desserts. The number of transitions in this dynamic programming is too big, since, for example, when transitioning from first courses to second courses, we need to check $O(n_1 n_2$) options. To speed this up, we need some sort of data structure built over the values of $dp_i$ for all first courses $i$ that allows to recalculate $dp_j$ for a second course $j$ quickly. There are two main approaches to this: build any version of RMQ over the values of dynamic programming for the first courses. Then, when we want to calculate the answer for some second course $j$, sort all types of first courses which don't go well with it, and make several RMQ queries to find the minimum value over all non-forbidden first courses; store all values of $dp_i$ in a data structure that supports adding an element, deleting an element, and finding the minimum element (this DS should allow duplicate elements as well). When we want to calculate the answer for some second course $j$, remove all values of $dp_i$ corresponding to the first courses that don't go well with it from the data structure, query the minimum in it, and insert the removed elements back. The same approach can be used to advance from second courses to drinks and from drinks to desserts (you can even use the same code in a for-loop with $3$ iterations, so the resulting solution is actually short and simple).
[ "brute force", "data structures", "graphs", "greedy", "implementation", "sortings", "two pointers" ]
2,000
#include<bits/stdc++.h> using namespace std; int main() { vector<int> ns(4); for(int i = 0; i < 4; i++) scanf("%d", &ns[i]); vector<vector<int>> cs(4); for(int i = 0; i < 4; i++) { cs[i].resize(ns[i]); for(int j = 0; j < ns[i]; j++) scanf("%d", &cs[i][j]); } vector<vector<vector<int>>> bad(3); for(int i = 0; i < 3; i++) { bad[i].resize(ns[i + 1]); int m; scanf("%d", &m); for(int j = 0; j < m; j++) { int x, y; scanf("%d %d", &x, &y); x--; y--; bad[i][y].push_back(x); } } vector<vector<int>> dp(4); dp[0] = cs[0]; for(int i = 0; i < 3; i++) { dp[i + 1].resize(ns[i + 1]); multiset<int> s; for(int j = 0; j < ns[i]; j++) s.insert(dp[i][j]); for(int j = 0; j < ns[i + 1]; j++) { for(auto k : bad[i][j]) s.erase(s.find(dp[i][k])); if(s.empty()) dp[i + 1][j] = int(4e8 + 43); else dp[i + 1][j] = *s.begin() + cs[i + 1][j]; for(auto k : bad[i][j]) s.insert(dp[i][k]); } } int ans = *min_element(dp[3].begin(), dp[3].end()); if(ans > int(4e8)) ans = -1; cout << ans << endl; }
1487
F
Ones
You are given a positive (greater than zero) integer $n$. You have to represent $n$ as the sum of integers (possibly negative) consisting only of ones (digits '1'). For example, $24 = 11 + 11 + 1 + 1$ and $102 = 111 - 11 + 1 + 1$. Among all possible representations, you have to find the one that uses the minimum number of ones in total.
Let's build the number from the lowest digit to the highest digit with the following dynamic programming: $dp_{i,carry,cp,cn}$ - the minimum number of ones, if $i$ least significant digits are already fixed, the carry to the next digit is $carry$ (can be negative), there are $cp$ positive numbers (of the form $111 \cdots 111$) of length greater than or equal to $i$ and $cn$ negative numbers of length greater than or equal to $i$. First, consider the transitions when we reduce the values of $cp$ and/or $cn$. Such transitions correspond to the fact that in the optimal answer there were several numbers of length exactly $i$, and they should not be considered further. If the value of $(cp-cn+carry) \mod 10$ matches the $i$-th least significant digit in $n$, then we can use transition to $(i+1)$-th state with the new value of $carry$ and the number of ones in the answer increased by $cp+cn$. It remains to estimate what the maximum value of $cp$ ($cn$) and $carry$ we need. The value of $cp$ doesn't exceed the total number of numbers that we use in the answer. Using at most $5$ numbers we can decrease the length of $n$ by at least $1$. Thus, the maximum value of $cp$ and $cn$ is at most $5|n|$ (where |n| is the length of the number $n$). For the value of $carry$, the condition $carry \ge \frac{carry+cp}{10}$ should be met (similarly for a negative value). Thus, we can assume that the absolute value of $carry$ doesn't exceed $\frac{5|n|}{9}$. The total complexity of this solution is $O(|n|^4)$, yet with a high constant factor.
[ "dp", "greedy", "shortest paths" ]
2,900
#include <bits/stdc++.h> using namespace std; #define sz(a) int((a).size()) #define forn(i, n) for (int i = 0; i < int(n); ++i) const int N = 250; const int M = 28; const int INF = 1e9; int dp[2][M * 2 + 1][N][N]; int main() { string s; cin >> s; reverse(s.begin(), s.end()); s += "0"; forn(carry, M * 2 + 1) forn(cp, N) forn(cn, N) dp[0][carry][cp][cn] = INF; dp[0][M][N - 1][N - 1] = 0; forn(i, sz(s)) { forn(carry, M * 2 + 1) forn(cp, N) forn(cn, N) dp[1][carry][cp][cn] = INF; forn(carry, M * 2 + 1) for (int cp = N - 1; cp >= 0; --cp) for (int cn = N - 1; cn >= 0; --cn) if (dp[0][carry][cp][cn] != INF) { if (cp > 0) dp[0][carry][cp - 1][cn] = min(dp[0][carry][cp - 1][cn], dp[0][carry][cp][cn]); if (cn > 0) dp[0][carry][cp][cn - 1] = min(dp[0][carry][cp][cn - 1], dp[0][carry][cp][cn]); int rcarry = carry - M; int val = rcarry + cp - cn; int digit = val % 10; if (digit < 0) digit += 10; int ncarry = val / 10; if (val < 0 && digit != 0) --ncarry; if (digit == s[i] - '0') dp[1][ncarry + M][cp][cn] = min(dp[1][ncarry + M][cp][cn], dp[0][carry][cp][cn] + cp + cn); } swap(dp[0], dp[1]); } int ans = INF; forn(i, N) forn(j, N) ans = min(ans, dp[0][M][i][j]); cout << ans << endl; }
1487
G
String Counting
You have $c_1$ letters 'a', $c_2$ letters 'b', ..., $c_{26}$ letters 'z'. You want to build a beautiful string of length $n$ from them (obviously, you cannot use the $i$-th letter more than $c_i$ times). \textbf{Each $c_i$ is greater than $\frac{n}{3}$}. A string is called beautiful if there are no palindromic contiguous substrings of odd length greater than $1$ in it. For example, the string "abacaba" is not beautiful, it has several palindromic substrings of odd length greater than $1$ (for example, "aca"). Another example: the string "abcaa" is beautiful. Calculate the number of different strings you can build, and print the answer modulo $998244353$.
Suppose there is no constraint on the number of letters used. Then this problem can be solved with the following dynamic programming: let $dp_{i, j, k}$ be the number of strings of length $i$ ending with characters $j$ and $k$ that don't contain palindromes of odd length greater than $1$ (obviously, each forbidden palindrome contains a subpalindrome of length $3$, so we only need to ensure that there are no palindromes of length $3$). The thing we are going to use in order to ensure that all the constraints on the number of characters are met is inclusion-exclusion. Since each $c_i > \frac{n}{3}$, at most two characters can violate their constraints in a single string, so we will iterate on some character of the alphabet and subtract the number of strings violating the constraint on this character from the answer, then iterate on a pair of characters and add the number of strings violating the constraints on these two characters to the answer. Okay, how to calculate the number of strings violating the constraint on some fixed character? Let's use dynamic programming $f_{i, j, k, l}$ - the number of strings such that they contain $i$ characters, $j$ of them have the same type that we fixed, the previous-to-last character is $k$ and the last character is $l$. The number of states here seems to be something about $n^2 \cdot 26^2$, but in fact, $k$ and $l$ can be optimized to have only two different values since we are interested in two types of characters: the ones that coincide with the character we fixed, and the ones that don't. Okay, what about violating the constraints on two characters? The same method can be used here: let $g_{i, j, k, l, m}$ be the number of strings consisting of $i$ characters such that the number of occurrences of the first fixed character is $j$, the number of occurrences of the second fixed character is $k$, the previous-to-last character is $l$ and the last character is $m$. Again, at first it seems that there are up to $n^3 \cdot 26^2$ states, but $l$ and $m$ can be optimized to have only $3$ different values, so the number of states is actually $n^3 \cdot 3^2$. It seems that we have to run this dynamic programming for each pair of characters, right? In fact, no, it is the same for every pair of characters, the only difference is which states violate the constraints and which don't. We can run this dp only once, and when we need an answer for the pair of characters $(x, y)$, we can use two-dimensional prefix sums to query the sum over $g_{i, j, k, l, m}$ with $i = n$, $j > c_x$ and $k > c_y$ in $O(1)$. In fact, this dynamic programming can also be used for the first and the second part of the solution (calculating the strings that don't violate any constraints and the strings that violate the constraints on one character), so the hardest part of the solution runs in $O(n^3)$, though with a pretty big constant factor.
[ "combinatorics", "dp", "fft", "math" ]
2,700
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 402; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int sub(int x, int y) { return add(x, -y); } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int c[26]; int dp[2][N][N][3][3]; int sumDp[N][N]; int p1[N][N]; int p2[N][N]; int n; int main() { cin >> n; for(int i = 0; i < 26; i++) cin >> c[i]; for(int i = 0; i < 26; i++) for(int j = 0; j < 26; j++) for(int k = 0; k < 26; k++) if(i != k) { multiset<int> s = {i, j, k}; dp[1][s.count(0)][s.count(1)][min(2, j)][min(2, k)]++; } for(int i = 4; i <= n; i++) { for(int j = 0; j < N; j++) for(int k = 0; k < N; k++) for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++) { dp[0][j][k][x][y] = dp[1][j][k][x][y]; dp[1][j][k][x][y] = 0; } for(int j = 0; j < N; j++) for(int k = 0; k < N; k++) for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++) { int cur = dp[0][j][k][x][y]; if(cur == 0) continue; for(int z = 0; z < 3; z++) { int& nw = dp[1][j + (z == 0 ? 1 : 0)][k + (z == 1 ? 1 : 0)][y][z]; nw = add(nw, mul(cur, (z == 2 ? 24 : 1) - (z == x ? 1 : 0))); } } } for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) for(int k = 0; k < 3; k++) for(int l = 0; l < 3; l++) sumDp[i][j] = add(sumDp[i][j], dp[1][i][j][k][l]); for(int i = 0; i < N; i++) { p1[i][N - 1] = sumDp[i][N - 1]; for(int j = N - 2; j >= 0; j--) p1[i][j] = add(sumDp[i][j], p1[i][j + 1]); } for(int j = 0; j < N; j++) { p2[N - 1][j] = p1[N - 1][j]; for(int i = N - 2; i >= 0; i--) p2[i][j] = add(p1[i][j], p2[i + 1][j]); } int ans = p2[0][0]; for(int i = 0; i < 26; i++) { for(int j = 0; j < N; j++) for(int k = c[i] + 1; k < N; k++) ans = sub(ans, sumDp[k][j]); } for(int i = 0; i < 26; i++) for(int j = 0; j < i; j++) ans = add(ans, p2[c[i] + 1][c[j] + 1]); cout << ans << endl; }
1490
A
Dense Array
Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $i$ ($1 \le i \le n-1$), this condition must be satisfied: $$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$ For example, the arrays $[1, 2, 3, 4, 3]$, $[1, 1, 1]$ and $[5, 10]$ are dense. And the arrays $[5, 11]$, $[1, 4, 2]$, $[6, 6, 1]$ are \textbf{not} dense. You are given an array $a$ of $n$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added. For example, if $a=[4,2,10,1]$, then the answer is $5$, and the array itself after inserting elements into it may look like this: $a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1]$ (there are other ways to build such $a$).
Note that adding elements between positions $i$ ($1 \le i \le n - 1$) and $i + 1$ will not change the ratio of the adjacent elements, except for the ones just added. Therefore, for each pair of adjacent numbers, the problem can be solved independently. Let us solve the problem for a adjacent pair of numbers $a_i$ and $a_{i+1}$ for which the inequality from the statements does not hold. Suppose that $2a_i \le a_{i+1}$ (if not, we will swap them). Then between $a_i$ and $a_{i+1}$ it requires to insert $\left\lceil log_2 \left(\frac{a_{i+1}}{a_i}\right) - 1 \right\rceil$ elements of the form: $2a_i, 4a_i, ..., 2^{\left\lceil log_2 \left(\frac{a_{i+1}}{a_i}\right) - 1 \right\rceil} a_i$ It is better not to use explicit formula, but to use the following cycle:
[ "greedy", "math" ]
800
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { int n; cin >> n; int last; cin >> last; int ans = 0; for (int i = 1; i < n; i++) { int nw; cin >> nw; int a = min(last, nw), b = max(last, nw); while (a * 2 < b) { ans++; a *= 2; } last = nw; } cout << ans << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
1490
B
Balanced Remainders
You are given a number $n$ (\textbf{divisible by $3$}) and an array $a[1 \dots n]$. In one move, you can increase any of the array elements by one. Formally, you choose the index $i$ ($1 \le i \le n$) and \textbf{replace} $a_i$ with $a_i + 1$. You can choose the same index $i$ multiple times for different moves. Let's denote by $c_0$, $c_1$ and $c_2$ the number of numbers from the array $a$ that have remainders $0$, $1$ and $2$ when divided by the number $3$, respectively. Let's say that the array $a$ has balanced remainders if $c_0$, $c_1$ and $c_2$ are equal. For example, if $n = 6$ and $a = [0, 2, 5, 5, 4, 8]$, then the following sequence of moves is possible: - initially $c_0 = 1$, $c_1 = 1$ and $c_2 = 4$, these values are not equal to each other. Let's increase $a_3$, now the array $a = [0, 2, 6, 5, 4, 8]$; - $c_0 = 2$, $c_1 = 1$ and $c_2 = 3$, these values are not equal. Let's increase $a_6$, now the array $a = [0, 2, 6, 5, 4, 9]$; - $c_0 = 3$, $c_1 = 1$ and $c_2 = 2$, these values are not equal. Let's increase $a_1$, now the array $a = [1, 2, 6, 5, 4, 9]$; - $c_0 = 2$, $c_1 = 2$ and $c_2 = 2$, these values are equal to each other, which means that the array $a$ has balanced remainders. Find the minimum number of moves needed to make the array $a$ have balanced remainders.
Note that the numbers in the $a$ array are not important to us, so initially we will calculate the values of $c_0$, $c_1$, $c_2$. Now applying a move for the number $a_i$ is equivalent to: decreasing $c_{a_i\ mod\ 3}$ by $1$; and increasing $c_{(a_i + 1)\ mod\ 3}$ by $1$; We will perform the following greedy algorithm: while the array $a$ have no balanced remainders, find any $i$ ($0 \le i \le 2$) such that $c_i > \frac{n}{3}$; we apply the move for $c_i$, that is, replace $c_i$ with $c_i-1$, and $c_{(i+1)\ mod\ 3}$ with $c_{(i+1)\ mod\ 3}+1$. It is easy to prove the correctness of this greedy algorithm by cyclically shifting the values $c_0$, $c_1$, and $c_2$ so that the first element is equal to the maximum of them.
[ "brute force", "constructive algorithms", "math" ]
1,000
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int &x : a) { cin >> x; } int res = 0; vector<int> cnt(3); for (int x = 0; x <= 2; x++) { for (int i = 0; i < n; i++) { if (a[i] % 3 == x) { cnt[x]++; } } } while (*min_element(cnt.begin(), cnt.end()) != n / 3) { for (int i = 0; i < 3; i++) { if (cnt[i] > n / 3) { res++; cnt[i]--; cnt[(i + 1) % 3]++; } } } cout << res << endl; } int main() { int t; cin >> t; while (t--) { solve(); } }
1490
C
Sum of Cubes
You are given a positive integer $x$. Check whether the number $x$ is representable as the sum of the cubes of two positive integers. Formally, you need to check if there are two integers $a$ and $b$ ($1 \le a, b$) such that $a^3+b^3=x$. For example, if $x = 35$, then the numbers $a=2$ and $b=3$ are suitable ($2^3+3^3=8+27=35$). If $x=4$, then no pair of numbers $a$ and $b$ is suitable.
In this problem, we need to find $a$ and $b$ such that $x=a^3+b^3$ and $a \ge 1, b \ge 1$. Since $a$ and $b$ are positive, $a^3$ and $b^3$ are also positive. Hence $a^3 \le a^3 + b^3 \le x$. Therefore, the number $a$ can be iterated from $1$ to $\sqrt[3]{x}$. Since in all tests $x \le 10^{12}$, then $a \le 10^4$. For each $a$ , you can find $b$ by the formula $b=\sqrt[3]{x-a^3}$. This is a positive number. It remains to check that $b$ is an integer.
[ "binary search", "brute force", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; const ll N = 1'000'000'000'000L; unordered_set<ll> cubes; void precalc() { for (ll i = 1; i * i * i <= N; i++) { cubes.insert(i * i * i); } } void solve() { ll x; cin >> x; for (ll i = 1; i * i * i <= x; i++) { if (cubes.count(x - i * i * i)) { cout << "YES\n"; return; } } cout << "NO\n"; } int main() { precalc(); int t; cin >> t; while (t--) { solve(); } }
1490
D
Permutation Transformation
A permutation — is a sequence of length $n$ integers from $1$ to $n$, in which all the numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ — permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ — no. Polycarp was recently gifted a permutation $a[1 \dots n]$ of length $n$. Polycarp likes trees more than permutations, so he wants to transform permutation $a$ into a rooted binary tree. He transforms an array of different integers into a tree as follows: - the maximum element of the array becomes the root of the tree; - all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child; - all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation $a=[3, 5, 2, 1, 4]$, then the root will be the element $a_2=5$, and the left subtree will be the tree that will be built for the subarray $a[1 \dots 1] = [3]$, and the right one — for the subarray $a[3 \dots 5] = [2, 1, 4]$. As a result, the following tree will be built: \begin{center} {\small The tree corresponding to the permutation $a=[3, 5, 2, 1, 4]$.} \end{center} Another example: let the permutation be $a=[1, 3, 2, 7, 5, 6, 4]$. In this case, the tree looks like this: \begin{center} {\small The tree corresponding to the permutation $a=[1, 3, 2, 7, 5, 6, 4]$.} \end{center} Let us denote by $d_v$ the depth of the vertex $a_v$, that is, the number of edges on the path from the root to the vertex numbered $a_v$. Note that the root depth is zero. Given the permutation $a$, for each vertex, find the value of $d_v$.
We will construct the required tree recursively. Let us describe the state of tree construction by three values $(l, r, d)$, where $[l, r]$ - is the segment of the permutation, and $d$ - is the current depth. Then the following transitions can be described: find the position $m$ of the maximum element on the segment $[l, r]$, that is, $a_m = \max\limits_{i=l}^{r} a_i$; the depth of the vertex $a_m$ is equal to $d$; if $l<m$, then make the transition to the state $(l, m-1, d + 1)$; if $m<r$, then make the transition to the state $(m + 1, r, d + 1)$; Then, in order to construct the required tree, it is necessary to take $(1, n, 0)$ as the initial state.
[ "dfs and similar", "divide and conquer", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; void build(int l, int r, vector<int> const &a, vector<int> &d, int curD = 0) { if (r < l) { return; } if (l == r) { d[l] = curD; return; } int m = l; for (int i = l + 1; i <= r; i++) { if (a[m] < a[i]) { m = i; } } d[m] = curD; build(l, m - 1, a, d, curD + 1); build(m + 1, r, a, d, curD + 1); } void solve() { int n; cin >> n; vector<int> a(n); for (int &x : a) { cin >> x; } vector<int> d(n); build(0, n - 1, a, d); for (int x :d) { cout << x << " "; } cout << endl; } int main() { int t; cin >> t; while (t--) { solve(); } }